body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<pre><code>$(document).ready(function() {
$('#state-list, #major-list').hide();
$('#state').bind('click', function() {
$('#state-list').toggle();
});
$('#major').bind('click', function() {
$('#major-list').toggle();
});
});
</code></pre>
<p>All links and lists will follow the naming convention of:</p>
<p>link, link-list, like seen below:</p>
<pre><code><a href="#" id="link">Link</a>
<div id="link-list">
...
</div>
</code></pre>
<p>Is there a way listen for all links and toggle their respective lists, instead of creating a bind click for every link?</p>
|
[] |
[
{
"body": "<pre><code> <a href=\"#\" id=\"link\" class=\"linksToWatch\">Link</a>\n <div id=\"link-list\" class=\"listsToToggle\">\n\n $('.listsToToggle').hide();\n\n $('.linksToWatch').bind('click', function() {\n var id = $(this).attr('id');\n $('#' + id + '-list').toggle();\n });\n</code></pre>\n\n<p>May be, something like this?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-16T21:12:36.573",
"Id": "10933",
"ParentId": "10931",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "10933",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-16T20:50:52.063",
"Id": "10931",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "need to refactor multiple toggle lists"
}
|
10931
|
<p>I've written a quick little helper for event & call debounce/throttling. Since I'm at home and none of my regular code review friends are on-line I figured I'd turn to the great folks here! Would love any feedback you might have.</p>
<pre><code>/**
* debounce
* @param {integer} milliseconds This param indicates the number of milliseconds
* to wait after the last call before calling the original function .
* @return {function} This returns a function that when called will wait the
* indicated number of milliseconds after the last call before
* calling the original function.
*/
Function.prototype.debounce = function (milliseconds) {
var baseFunction = this,
timer = null,
wait = milliseconds;
return function () {
var self = this,
args = arguments;
function complete() {
baseFunction.apply(self, args);
timer = null;
}
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(complete, wait);
};
};
/**
* throttle
* @param {integer} milliseconds This param indicates the number of milliseconds
* to wait between calls before calling the original function.
* @return {function} This returns a function that when called will wait the
* indicated number of milliseconds between calls before
* calling the original function.
*/
Function.prototype.throttle = function (milliseconds) {
var baseFunction = this,
lastEventTimestamp = null,
limit = milliseconds;
return function () {
var self = this,
args = arguments,
now = Date.now();
if (!lastEventTimestamp || now - lastEventTimestamp >= limit) {
lastEventTimestamp = now;
baseFunction.apply(self, args);
}
};
};
</code></pre>
<p>To help understand what the point of these helpers are I've prepared this demo: <a href="http://jsfiddle.net/zR5jV/1/" rel="nofollow">http://jsfiddle.net/zR5jV/1/</a></p>
<p>GitHub project can be found here: <a href="https://github.com/m-gagne/limit.js" rel="nofollow">https://github.com/m-gagne/limit.js</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T19:46:58.670",
"Id": "18015",
"Score": "0",
"body": "Honestly, you'd probably be better off just using [underscore.js](http://documentcloud.github.com/underscore/), rather than reinventing the wheel (unless you're doing it for fun). At just around 4K minified, it's a very powerful library that includes more refined versions of both of these methods and is complimentary to almost every other JavaScript library."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T15:20:46.840",
"Id": "18086",
"Score": "0",
"body": "Cool hadn't heard of underscore.js before, thanks. Yes this was more of a \"do it for fun\" / \"try creating a project & associated website\" project. It was also more to bring to light the issue of frequency of events that people might not know of. Rarely as a developer do we ever get to create something truly unique, but I've learned a lot and gotten some great feedback in producing this simple snippet of code :)"
}
] |
[
{
"body": "<p>The key differences between a throttled function and a debounced function are that the throttled function can return a value because it is called synchronously and the debounced version cannot because it is used asynchronously.</p>\n\n<p>You have lost that on your throttle implementation. I would at least make the following change:</p>\n\n<pre><code>Function.prototype.throttle = function (milliseconds) {\n var baseFunction = this,\n lastEventTimestamp = null,\n limit = milliseconds,\n lastresult;\n\n return function () {\n var self = this,\n args = arguments,\n now = Date.now();\n\n if (!lastEventTimestamp || now - lastEventTimestamp >= limit) {\n lastEventTimestamp = now;\n lastresult = baseFunction.apply(self, args);\n }\n return lastresult;\n };\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T12:22:11.460",
"Id": "17800",
"Score": "0",
"body": "Good point, I've only used throttle in scenarios where I don't care about the return value. I'll integrate this into my library, thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T20:27:58.833",
"Id": "11144",
"ParentId": "10932",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "11144",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-16T21:05:27.880",
"Id": "10932",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "limit.js Code Review"
}
|
10932
|
<p>I have an HTML form being populated by a table of customer requests. The user reviews each request, sets an operation, and submits. The operation gets set into a post arg as follow</p>
<pre><code>$postArray = array_keys($_POST);
</code></pre>
<p>[1]=>Keep [2]=>Reject [3]=>Reject [4]=>Ignore ["item id"]=>"operation"</p>
<p>This is how I am parsing my Post args... it seems awkward, the unused $idx. I am new to PHP, is there a smoother way to do this?</p>
<pre><code>$postArray = array_keys($_POST);
foreach($postArray as $idx => $itemId) {
$operation = $_POST[$itemId];
echo "$itemId $operation </br>";
...perform operation...
}
</code></pre>
|
[] |
[
{
"body": "<p>It looks like you may want to unset the 'item id' entry in your post array before you do the processing:</p>\n\n<p><code>unset($_POST['item id']);</code></p>\n\n<p>Then you can use foreach to loop over the key (idx) and value (operation).</p>\n\n<pre><code>foreach ($_POST as $idx => $operation)\n{\n echo $idx . ' ' . $operation . '</br>';\n // perform operation.\n}\n</code></pre>\n\n<p>The <code>array_keys</code> function was unnecessary because foreach can be used with associative arrays handling both their keys and values.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T02:55:01.787",
"Id": "10936",
"ParentId": "10934",
"Score": "1"
}
},
{
"body": "<p>You dont need to grab the the keys separately.</p>\n\n<pre><code>foreach($_POST as $key => $value) { \n echo \"$key $value </br>\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T11:55:43.427",
"Id": "17402",
"Score": "0",
"body": "My answer already covered this. Adding another answer with the same information does not seem helpful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T08:39:45.080",
"Id": "10948",
"ParentId": "10934",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "10936",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-16T22:53:16.790",
"Id": "10934",
"Score": "0",
"Tags": [
"php",
"html"
],
"Title": "Parsing unknown POST Args in PHP"
}
|
10934
|
<p>I'm just writing my first PHP-Mysqli sample (think about a Wiki 0.0.1) and I would like to ask you if this example is <strong>secure</strong> or not or if there are any other <strong>problems/suggestions</strong> you might recommend?</p>
<p>I would like to use <strong>prepared statements</strong> and <strong>not care about sanitizing the input</strong> from $_GET, but I don't know if this code is considered secure and OK?</p>
<p>Also, any comments regarding how this functionality (reading a latest revision from a database) should be done is welcome.</p>
<pre><code>require_once 'connect.php';
$id = $_GET['id'];
if ( $stmt = $mysqli->prepare("SELECT text, rev FROM wiki WHERE id = ? ORDER BY rev DESC LIMIT 0,1") ) {
$stmt->bind_param( "s", $id );
$stmt->execute();
$stmt->bind_result( $text, $rev );
$stmt->fetch();
echo "rev: " . $rev . ": " . $text;
echo '<br>';
$stmt->close();
}
$mysqli->close();
</code></pre>
<p><strong>connect.php</strong></p>
<pre><code>$mysqli = new mysqli("localhost", "xxx", "yyy", "zzz");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
</code></pre>
<p>Is it safe to keep connect.php at the <strong>same folder as the other php files</strong>? </p>
<p>Is there any chance <strong>someone could read the plain password</strong> in connect.php file?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T00:33:32.913",
"Id": "17391",
"Score": "0",
"body": "Don't print errors out so they are visible. 1) It has no meaning to a user (my mum has no idea what a connect failure is nor how to resolve the problem) and makes your site look bad. 2) It provides information to attackers that they do not need. Errors messages should be placed in the log file. The only error message you should display to a user an apology (with an optional guid (that you generate)) and a potential solution (like pleas try latter). If they complain you can use the guid to look up the real error in the log and then resolve the issue."
}
] |
[
{
"body": "<p>Yes, that looks good.</p>\n\n<p>Minor comment: Normally an id is an integer. Should it have been \"i\" in your bind_param?</p>\n\n<p><strong>Connection Details</strong></p>\n\n<p>First, I am not a security expert. However, I would recommend storing the connection details in a location that is not served by your web-server. It should be somewhere in your PHP include_path or accessible from your autoloader.</p>\n\n<p>Having the file in a directory accessible from your web-server could open up the connection details if you had an incorrectly configured web-server.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T05:03:38.380",
"Id": "10943",
"ParentId": "10935",
"Score": "1"
}
},
{
"body": "<p>Verify the id to be an integer. One way to do that is like</p>\n\n<pre><code>$id = (int)$_GET['id'];\nif($id > 0) {\n .... //proceed\n}\n</code></pre>\n\n<p>Next, the parameter should be bind using <code>i</code> not <code>s</code></p>\n\n<pre><code>$stmt->bind_param( \"1\", $id );\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T08:34:08.973",
"Id": "10947",
"ParentId": "10935",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "10943",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T00:10:49.727",
"Id": "10935",
"Score": "1",
"Tags": [
"php",
"mysql",
"security",
"mysqli"
],
"Title": "PHP-Mysqli example secure?"
}
|
10935
|
<p>I wrote this program for the Google Code Jam problem, "Recycled numbers."</p>
<p>It took around 2 and half minutes to solve the small input set on my dual core, 1GB RAM system. But for the large input set it took around 25 minutes(processor usage was 100% for those 25 mins) to solve the problem.</p>
<p><strong>Problem</strong></p>
<blockquote>
<p>Let's say a pair of distinct positive integers (\$n\$, \$m\$) is recycled if
you can obtain m by moving some digits from the back of n to the front
without changing their order.</p>
<p>For example, (12345, 34512) is a recycled pair since you can obtain
34512 by moving 345 from the end of 12345 to the front. Note that n
and m must have the same number of digits in order to be a recycled
pair. Neither n nor m can have leading zeros.</p>
<p>Given integers \$A\$ and \$B\$ with the same number of digits and no leading
zeros, how many distinct recycled pairs (\$n\$, \$m\$) are there with \$A ≤ n <
> m ≤ B\$?</p>
</blockquote>
<p>How can I make my program fast enough to solve the large input set within 8 minutes?</p>
<pre><code>f=open('C-large.in')
noi=int(f.readline().rstrip('\r\n'))
i=1
ou=open('jam.out','w')
while i<=noi:
re=f.readline().rstrip('\r\n')
rs=re.split()
a=int(rs[0])
b=int(rs[1])
ans=0
c=[x for x in range(a,b+1)]
for ind,x in enumerate(c):
for y in c[ind+1:]:
n=str(x)
m=str(y)
if len(n)==len(m) and len(n)>1 and len(m)>1:
ki=1
while ki <len(n):
temp=n[-1:-(ki)-1:-1][::-1]+n[:-(ki)]
if temp[0]!='0':
if temp==m:
ans+=1
break
ki+=1
else :
break
print("Case #%s:"%(i),ans,file=ou)
i+=1
ou.close()
f.close()
</code></pre>
<p><strong>Small input:</strong></p>
<blockquote>
<pre><code>50
156 927
167 978
484 954
160 990
135 916
160 939
103 914
173 958
100 101
124 945
181 976
101 932
101 935
170 928
171 984
126 973
283 788
667 667
384 750
153 934
173 993
185 930
100 100
178 993
21 31
178 970
168 958
170 992
104 989
34 70
162 935
289 289
185 993
10 99
120 953
184 917
179 936
108 967
6 7
160 958
115 925
137 972
188 921
10 99
118 966
100 972
167 944
136 983
107 926
118 996
</code></pre>
</blockquote>
<p><strong>Large input:</strong></p>
<blockquote>
<pre><code>50
10000 10001
1781 7688
1007465 1919027
100000 100000
1032122 1995680
1216257 1504628
1216908 1951709
1021619 1930030
15048 53617
1007458 1962726
388 869
1067361 1995135
46739 73395
1077614 1958584
1031957 1958036
72634 74120
1063961 1954135
274937 720742
1 8
1057393 1928164
28 93
1000000 2000000
1032073 1940559
1089798 1970754
100000 999999
1434814 1780702
1072799 1964898
1059864 1967119
155569 345355
2578 4229
72 95
552 553
601415 711929
1275115 1433162
688042 856983
594203 673506
1172008 1490273
180289 925799
354653 354653
1195595 1669305
5908 5967
2083 7987
339 670
1015539 1982001
29229 96206
1006167 1522491
1117646 1117646
1021936 1950412
41215 83080
1033077 1969448
</code></pre>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T03:21:31.440",
"Id": "17392",
"Score": "0",
"body": "Sometimes the biggest gains come from changing the logic. Are you sure that you want to keep the logic? You need more laziness with the help of http://docs.python.org/library/itertools.html, in particular - islice. Generating an actual slice would be a bit expensive."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T02:44:19.277",
"Id": "17530",
"Score": "0",
"body": "Have you tried *[this method?](http://stackoverflow.com/questions/4295799/how-to-improve-performance-of-this-code/4299378#4299378)* At least it will prove to you what's taking the most time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-29T14:45:07.233",
"Id": "18157",
"Score": "0",
"body": "`if len(m) == len(n) and len(m) > 1 and len(n) > 1` ... If the first 2 expressions are true, the last one MUST be true."
}
] |
[
{
"body": "<pre><code> f=open('C-large.in')\n</code></pre>\n\n<p>Don't sue single letter variable names, its really hard to read</p>\n\n<pre><code> noi=int(f.readline().rstrip('\\r\\n'))\n</code></pre>\n\n<p>Since the default is already to remove whitespace, why both with the <code>\\r\\n</code> parameter?</p>\n\n<pre><code> i=1\n ou=open('jam.out','w')\n while i<=noi:\n</code></pre>\n\n<p>Use for loops, not while loops to count</p>\n\n<pre><code> re=f.readline().rstrip('\\r\\n')\n</code></pre>\n\n<p>re is a really bad name because its the same as the regular expression module</p>\n\n<pre><code> rs=re.split()\n a=int(rs[0])\n b=int(rs[1])\n</code></pre>\n\n<p>I'd use <code>a,b = map(int, re.split())</code></p>\n\n<pre><code> ans=0\n c=[x for x in range(a,b+1)]\n</code></pre>\n\n<p>Use <code>c = list(range(a,b+1))</code></p>\n\n<pre><code> for ind,x in enumerate(c):\n for y in c[ind+1:]:\n</code></pre>\n\n<p>That's gonna be inefficient. Firstly, you can easily express it using simple ranges</p>\n\n<pre><code>for x in range(a, b+ 1):\n for y in range(x + 1, b + 1):\n</code></pre>\n\n<p>and therefore avoid the slices. </p>\n\n<p>But you can do much better. You are only interested in values of y which are recyclings of x. Instead of generating the rather large number of possible second numbers, try just generating the fairly small number of possible ways to recycle x. </p>\n\n<pre><code> n=str(x)\n m=str(y)\n</code></pre>\n\n<p>Converting all your numbers to strings will be expensive. See if you can keep them as integers and just do math operations on them</p>\n\n<pre><code> if len(n)==len(m) and len(n)>1 and len(m)>1:\n ki=1 \n while ki <len(n):\n</code></pre>\n\n<p>Again, use for loops to count</p>\n\n<pre><code> temp=n[-1:-(ki)-1:-1][::-1]+n[:-(ki)]\n</code></pre>\n\n<p>temp should be banned variable name. All variables are temporary, use a more helpful name.</p>\n\n<pre><code> if temp[0]!='0':\n if temp==m:\n ans+=1\n break\n ki+=1 \n else :\n break\n\n\n\n print(\"Case #%s:\"%(i),ans,file=ou)\n</code></pre>\n\n<p>Normally, we use <code>%d</code> for numbers</p>\n\n<pre><code> i+=1\n ou.close()\n f.close()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T07:51:25.073",
"Id": "17545",
"Score": "0",
"body": "I applied all the changes you mentioned above and my program became faster by 15-20 seconds, but still not enough for the large input set."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T13:46:29.003",
"Id": "17584",
"Score": "0",
"body": "@AshwiniChaudhary, my versions solves the large data set in two minutes. I'm going to guess that you didn't actually make all the changes I suggested."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-29T14:28:40.043",
"Id": "18156",
"Score": "0",
"body": "In general, you're right about using cryptic/confusing variable names. However, `f` is a commonly used and widely accepted variable for a file object. If I saw `f` independent of it's context, my first assumption would be that it represented a file object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-04T04:12:10.110",
"Id": "18381",
"Score": "0",
"body": "@JoelCornett, I personally still don't like `f`, but its common enough you can get away with it. The way I see it, its still preferable to use a longer name. Nevertheless, I should have picked on some of the other examples"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T04:16:05.273",
"Id": "10939",
"ParentId": "10938",
"Score": "7"
}
},
{
"body": "<p>The correct solution here <em>is</em> to change the logic. Your code runs in O(n^2) (where n is b-a), but the correct solution runs in O(n d) (where d is the number of digits). Because d is most likely much smaller than n, this is much faster.</p>\n\n<p>For more details, see <a href=\"http://code.google.com/codejam/contest/1460488/dashboard#s=a&a=2\">the official analysis of the problem</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T21:06:25.230",
"Id": "17420",
"Score": "0",
"body": "I suspect the authors means that he needs to get the same answer when he says that he doesn't want to change the logic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T07:42:55.770",
"Id": "17543",
"Score": "0",
"body": "@svick can you give me pythonic version of the solution provided by the codejam team for the large input set, because I don't know C much. I guess the logic I used for the my solution is exactly the same they mentioned for the small input set."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T08:49:58.447",
"Id": "10949",
"ParentId": "10938",
"Score": "5"
}
},
{
"body": "<p>Not sure if my comparison method is as efficient - I've not benchmarked the tow against each other, but I'd expect the rest of this code to be better. It would be more efficient to avoid the convenience function (extra function calls), however I've split it out this way to enhance readability, and make it easier to switch your comparison method.</p>\n\n<p>As I say - the comparison is completely unoptimised, but then again I usually find that standard library objects are fairly efficient.</p>\n\n<pre><code>def main():\n \"\"\" Conventionally this it the function run when the script starts \"\"\"\n from collections import Counter\n with open('C-large.in') as input_file: \n # using 'with' is recommended as it will cause the file to be closed automatically\n # when you exit this block (think try/catch/finally)\n def is_recyclable(x,y):\n \"\"\" Convenience function for readability \"\"\"\n X,Y = str(x), str(y)\n if len(X) == len(Y) and len(X) > 1:\n return Counter(X) == Counter(Y)\n return False\n with open('jam.out','w') as output_file:\n line_ending = '\\r\\n'\n i = 1\n for line in input_file: #This will do your readline calls for you. Not sure what your 'noi' was doing, it crashed for me...\n (a,b) = (int(x) for x in line.rstrip(line_ending).split())\n ans = 0\n for x in range(a, b+1): # In python 3.x this is a generator\n for y in range(x+1, b+1): # In python 2.x use xrange\n # You should now have a <= x < y <= b\n if is_recyclable(x,y):\n ans += 1\n output = \"Case #%s: %s%s\"%(i, ans, line_ending)\n #print output debug line\n output_file.write(output)\n i += 1\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T18:33:24.510",
"Id": "17608",
"Score": "0",
"body": "ah I see I missinterpretted the comparisson - I'll have a look at that tomorrow"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T11:42:15.023",
"Id": "11031",
"ParentId": "10938",
"Score": "1"
}
},
{
"body": "<p>You're calculating <code>n</code> and <code>len(n)</code> more times than you need to. I got a 25% speed increase simply by:</p>\n\n<ul>\n<li>moving <code>n=str(x)</code> up into the <code>for idx,x...</code> loop</li>\n<li>storing <code>n</code>'s length\nin that same loop (eg. <code>length_n = len(n)</code>) </li>\n<li>replacing all the\ninstaces of <code>len(n)</code> with <code>length_n</code>.</li>\n</ul>\n\n<p>I'm sure that principle will apply to whichever solution you end up going with.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T05:57:41.090",
"Id": "17863",
"Score": "0",
"body": "the `len(n)>1` can also be pushed up on level."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T16:36:44.557",
"Id": "11140",
"ParentId": "10938",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "10939",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T03:12:04.447",
"Id": "10938",
"Score": "2",
"Tags": [
"python",
"performance",
"programming-challenge"
],
"Title": "\"Recycled numbers\" challenge"
}
|
10938
|
<p>Here are two ways for writing this sample code (one using multi-threading, one without using multi-threading) - The original code (friend wrote it) uses multi-threading. I would like to know which method is better, and was there a motivation for using multi-threading in this situation?</p>
<p><strong>1) First way (multi-threading):</strong></p>
<p>main Class:</p>
<pre><code>public class main
{
public static void main(String[] args)
{
MyWorker worker1 = new MyWorker();
}
}
</code></pre>
<p>MyWorker Classs:</p>
<pre><code>import java.util.HashMap;
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyWorker
{
HashMap<String, Integer> HM_1, HM_2, HM_both;
ExecutorService threadExecutor;
LinkedList<String> myStrings_1;
LinkedList<String> myStrings_2;
public MyWorker()
{
myStrings_1 = new LinkedList<String>();
myStrings_1.add("Letter A");
myStrings_1.add("Letter B");
myStrings_1.add("Letter C");
myStrings_2 = new LinkedList<String>();
myStrings_2.add("Letter D");
myStrings_2.add("Letter E");
myStrings_2.add("Letter F");
threadExecutor = Executors.newFixedThreadPool(10);
HM_1= new HashMap<String, Integer>();
HM_2 = new HashMap<String, Integer>();
HM_both = new HashMap<String, Integer>();
for(Object o_1: myStrings_1.toArray())
{
// multi-threading
String f_1 = (String)o_1;
threadExecutor.execute(new Helper(this, f_1, true));
}
for(Object o_2: myStrings_2.toArray())
{
// multi-threading
String f_2 = (String)o_2;
threadExecutor.execute(new Helper(this, f_2, false));
}
threadExecutor.shutdown();
}
public void getWorkerData(String f, boolean b, int currNum)
{
if(b)
{
HM_1.put(f, currNum);
HM_both.put(f, currNum);
}
else
{
HM_2.put(f, currNum);
HM_both.put(f, currNum);
}
}
}
</code></pre>
<p>Helper Class:</p>
<pre><code>public class Helper implements Runnable
{
public MyWorker currWorker1;
public String s;
public boolean b;
public Helper(MyWorker _currWorker1, String _s, boolean _b)
{
s = _s;
currWorker1 = _currWorker1;
b = _b;
}
public void run()
{
currWorker1.getWorkerData(s, b, 12);
}
}
</code></pre>
<p><strong>2) Second way (no multi-threading):</strong></p>
<p>main_noThreading Class:</p>
<pre><code>public class main_noThreading
{
public static void main(String[] args)
{
MyWorker_noThreading worker1 = new MyWorker_noThreading();
}
}
</code></pre>
<p>MyWorker_noThreading:</p>
<pre><code>import java.util.HashMap;
import java.util.LinkedList;
public class MyWorker_noThreading
{
HashMap<String, Integer> HM_1, HM_2, HM_both;
LinkedList<String> myStrings_1;
LinkedList<String> myStrings_2;
public MyWorker_noThreading()
{
myStrings_1 = new LinkedList<String>();
myStrings_1.add("Letter A");
myStrings_1.add("Letter B");
myStrings_1.add("Letter C");
myStrings_2 = new LinkedList<String>();
myStrings_2.add("Letter E");
myStrings_2.add("Letter F");
myStrings_2.add("Letter G");
HM_1 = new HashMap<String, Integer>();
HM_2 = new HashMap<String, Integer>();
HM_both = new HashMap<String, Integer>();
for(Object o_1: myStrings_1.toArray())
{
// no multi-threading
String f_1 = (String)o_1;
new Helper_noThreading(this, f_1, true);
}
for(Object o_2: myStrings_2.toArray())
{
// no multi-threading
String f_2 = (String)o_2;
new Helper_noThreading(this, f_2, false);
}
}
public void getWorkerData(String f, boolean b, int currNum)
{
if(b)
{
HM_1.put(f, currNum);
HM_both.put(f, currNum);
}
else
{
HM_2.put(f, currNum);
HM_both.put(f, currNum);
}
}
}
</code></pre>
<p>MyHelper_noThreading Class:</p>
<pre><code>public class Helper_noThreading
{
public MyWorker_noThreading currWorker1;
public String s;
public boolean b;
public Helper_noThreading(MyWorker_noThreading _currWorker1, String _s, boolean _b)
{
s = _s;
currWorker1 = _currWorker1;
b = _b;
currWorker1.getWorkerData(s, _b, 12);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-07-09T22:12:58.780",
"Id": "320639",
"Score": "0",
"body": "As an aside, why are you using `Object` in your for-each loop? For that matter, why are you calling `toArray()`?"
}
] |
[
{
"body": "<p>I'm only commenting the threading part of the code you posted and regarding those parts I would say that the multithreaded code is not correctly written. None of the data structures written to by the threads are thread safe and no locking mechanism for maintaining thread safety is in place.</p>\n\n<p>Performance wise there is also absolutely no reason for multithreading this code. There are no system calls or complex calculations present that might benefit from being run in parallell.</p>\n\n<p>As for your question I would say that the non multithreaded solution is better (although you could surely simplify that code quite a bit).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T07:31:45.793",
"Id": "17395",
"Score": "0",
"body": "Can you give me a scenario where the multi-threaded code would break, or fail? For example, would it be a problem if the `myStrings_1` and `myStrings_2` were super long? I'm asking this question because I am getting weird results sometimes and was wondering if it was because of the multi-threaded code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T07:58:29.817",
"Id": "17397",
"Score": "3",
"body": "The problem is in the calls to HM_x.put(..). HashSet is not thread safe and the methods cannot be guaranteed to function properly when called by multiple threads. See: [javadoc for HashSet](http://docs.oracle.com/javase/6/docs/api/java/util/HashSet.html)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T07:17:43.253",
"Id": "10944",
"ParentId": "10940",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "10944",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T04:22:07.823",
"Id": "10940",
"Score": "2",
"Tags": [
"java",
"multithreading"
],
"Title": "What's the motivation for multi-threading in this code?"
}
|
10940
|
<p>To learn and practice coding in C++, I wrote an implementation of <a href="http://en.wikipedia.org/wiki/Kosaraju%27s_algorithm" rel="nofollow">Kosaraju's two-pass algorithm</a> for computing the strongly connected components in a directed graph, using depth-first search.</p>
<p>This was my first time touching any C++ code in a while (I mainly program in Python or C#). As such, any critique or advice on style, layout, readability, maintainability, and best practice would be greatly appreciated. And, although performance wasn't a primary goal, I am highly interested in any optimizations that could be made (currently it can process about 800 thousand nodes with 5 million edges in around 10 seconds).</p>
<pre><code>#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <list>
using std::vector;
using std::map;
using std::list;
using std::ifstream;
using std::cout;
using std::endl;
// Constants
//-------------------------------
const char FILENAME[] = "SCC.txt";
// Prototypes
//-------------------------------
long get_node_count(const char filename[]);
vector< vector<long> > parse_file(const char filename[]);
map< long, vector<long> > compute_scc(vector< vector<long> > &graph);
vector< vector<long> > reverse_graph(const vector< vector<long> > &graph);
void dfs_loop(const vector< vector<long> > &graph, vector<long> &finishTime, vector<long> &leader);
long dfs(const vector< vector<long> > &graph, long nodeIndex, vector<bool> &expanded, vector<long> &finishTime, long t, vector<long> &leader, long s);
list<unsigned long> get_largest_components(const map< long, vector<long> > scc, long size);
/**
* Main
*/
int main() {
// Get the sequential graph representation from the file
vector< vector<long> > graph = parse_file(FILENAME);
// Compute the strongly-connected components
map< long, vector<long> > scc = compute_scc(graph);
// Compute the largest 5 components and print them out
list<unsigned long> largestComponents = get_largest_components(scc, 5);
list<unsigned long>::iterator it;
for (it = largestComponents.begin(); it != largestComponents.end(); it++) {
cout << *it << ' ';
}
cout << endl;
return 0;
}
/**
* Parse an input file as a graph, and return the graph.
*/
vector< vector<long> > parse_file(const char filename[]) {
// Get the node count and prepare the graph
long nodeCount = get_node_count(filename);
vector< vector<long> > graph(nodeCount);
// Open file and extract the data
ifstream graphFile(filename);
long nodeIndex;
long outIndex;
while (graphFile) {
graphFile >> nodeIndex;
graphFile >> outIndex;
// Add the new outgoing edge to the node
graph[nodeIndex - 1].push_back(outIndex - 1);
}
return graph;
}
/**
* Get the count of nodes from a graph file representation
*/
long get_node_count(const char filename[]) {
// Open file and keep track of how many times the value changes
ifstream graphFile(filename);
long maxNodeIndex = 0;
long nodeIndex = 0;
while (graphFile) {
// Check the node index
graphFile >> nodeIndex;
if (nodeIndex > maxNodeIndex) {
maxNodeIndex = nodeIndex;
}
// Check the outgoing edge
graphFile >> nodeIndex;
if (nodeIndex > maxNodeIndex) {
maxNodeIndex = nodeIndex;
}
}
return maxNodeIndex;
}
/**
* Compute all of the strongly-connected components of a graph
* using depth-first search, Kosaraju's 2-pass method
*/
map< long, vector<long> > compute_scc(vector< vector<long> > &graph) {
// Create finishing time and leader vectors to record the data
// from the search
vector<long> finishTime(graph.size(), 0);
vector<long> leader(graph.size(), 0);
// Initialize the finish time initially to be the numbers of the graph
vector<long>::iterator it;
long index = 0;
for (it = finishTime.begin(); it != finishTime.end(); it++) {
*it = index;
index++;
}
// Reverse the graph, to compute the 'magic' finishing times
vector< vector<long> > reversed = reverse_graph(graph);
dfs_loop(reversed, finishTime, leader);
// Compute the SCC leaders using the finishing times
dfs_loop(graph, finishTime, leader);
// Distribute nodes to SCCs
map< long, vector<long> > scc;
vector<long>::iterator lit;
for (lit = leader.begin(); lit != leader.end(); lit++) {
long nodeIndex = lit - leader.begin();
// Append node to SCC
scc[*lit].push_back(nodeIndex);
}
return scc;
}
/**
* Reverse a directed graph by looping through each node/edge pair
* and recording the reverse
*/
vector< vector<long> > reverse_graph(const vector< vector<long> > &graph) {
// Create new graph
vector< vector<long> > reversed(graph.size());
// Loop through all elements and fill new graph with reversed endpoints
vector< vector<long> >::const_iterator it;
for (it = graph.begin(); it != graph.end(); it++) {
long nodeIndex = it - graph.begin();
// Loop through all outgoing edges, and reverse them in new graph
vector<long>::const_iterator eit;
for (eit = graph[nodeIndex].begin(); eit != graph[nodeIndex].end(); eit++) {
reversed[*eit].push_back(nodeIndex);
}
}
return reversed;
}
/**
* Compute a depth-first search through all nodes of a graph
*/
void dfs_loop(const vector< vector<long> > &graph, vector<long> &finishTime, vector<long> &leader) {
// Create expanded tracker and copied finishing time tracker
vector<bool> expanded(graph.size(), 0);
vector<long> loopFinishTime = finishTime;
long t = 0;
vector<long>::reverse_iterator it;
// Outer loop through all nodes in order to cover disconnected
// sections of the graph
for (it = loopFinishTime.rbegin(); it != loopFinishTime.rend(); it++) {
// Compute a depth-first search if the node hasn't
// been expanded yet
if (!expanded[*it]) {
t = dfs(graph, *it, expanded, finishTime, t, leader, *it);
}
}
}
/**
* Search through a directed graph recursively, beginning at node 'nodeIndex',
* until no more node can be searched, recording the finishing times and the
* leaders
*/
long dfs(
const vector< vector<long> > &graph,
long nodeIndex,
vector<bool> &expanded,
vector<long> &finishTime,
long t,
vector<long> &leader,
long s
) {
// Mark the current node as explored
expanded[nodeIndex] = true;
// Set the leader to the given leader
leader[nodeIndex] = s;
// Loop through outgoing edges
vector<long>::const_iterator it;
for (it = graph[nodeIndex].begin(); it != graph[nodeIndex].end(); it++) {
// Recursively call DFS if not explored
if (!expanded[*it]) {
t = dfs(graph, *it, expanded, finishTime, t, leader, s);
}
}
// Update the finishing time
finishTime[t] = nodeIndex;
t++;
return t;
}
/**
* Computes the largest 'n' of a strongly-connected component list
* and return them
*/
list<unsigned long> get_largest_components(const map< long, vector<long> > scc, long size) {
// Create vector to hold the largest components
list<unsigned long> largest(size, 0);
// Iterate through map and keep track of largest components
map< long, vector<long> >::const_iterator it;
for (it = scc.begin(); it != scc.end(); it++) {
// Search through the current largest list to see if there exists
// an SCC with less elements than the current one
list<unsigned long>::iterator lit;
for (lit = largest.begin(); lit != largest.end(); lit++) {
// Compare size and change largest if needed, inserting
// the new one at the proper position, and popping off the old
if (*lit < it->second.size()) {
largest.insert(lit, it->second.size());
largest.pop_back();
break;
}
}
}
return largest;
}
</code></pre>
<p>An example input file (<code>SCC.txt</code>) is composed of edges represented by begin-end node numbers. It could look like this:</p>
<pre><code>1 2
2 3
3 1
4 3
4 5
5 6
6 4
7 6
7 8
8 9
9 10
10 7
</code></pre>
|
[] |
[
{
"body": "<p>Fair enough. Lazy but OK I suppose. Personally when using <code>using</code> like this I bind it to the tightest scope possible.</p>\n\n<pre><code>using std::vector;\nusing std::map;\nusing std::list;\nusing std::ifstream;\nusing std::cout;\nusing std::endl;\n</code></pre>\n\n<p>The idea of making it <code>std</code> and not <code>standard</code> was so that it would not be too obnoxious when going <code>std::cout</code> in the code.</p>\n\n<p>This is very obnoxious to read. A bit of work formatting these lines to make it easy to read would have gone a long way:</p>\n\n<pre><code>long get_node_count(const char filename[]);\nvector< vector<long> > parse_file(const char filename[]);\nmap< long, vector<long> > compute_scc(vector< vector<long> > &graph);\nvector< vector<long> > reverse_graph(const vector< vector<long> > &graph);\nvoid dfs_loop(const vector< vector<long> > &graph, vector<long> &finishTime, vector<long> &leader);\nlong dfs(const vector< vector<long> > &graph, long nodeIndex, vector<bool> &expanded, vector<long> &finishTime, long t, vector<long> &leader, long s);\nlist<unsigned long> get_largest_components(const map< long, vector<long> > scc, long size);\n</code></pre>\n\n<p>Nothing wrong with this:</p>\n\n<pre><code>// Get the sequential graph representation from the file\nvector< vector<long> > graph = parse_file(FILENAME);\n</code></pre>\n\n<p>But you don' think it would have been more intuitive to read as:</p>\n\n<pre><code>MyGraph graph(FILENAME);\n</code></pre>\n\n<p>A tiny bit of work wrapping your data into a class goes a long way to make the code more readable. Your style you are using the classes available in C++ but really your style is more C than C++.</p>\n\n<p>Learn to use the standard algorithms:</p>\n\n<pre><code>list<unsigned long>::iterator it;\nfor (it = largestComponents.begin(); it != largestComponents.end(); it++) {\n cout << *it << ' ';\n}\ncout << endl;\n\n// Easier to write as\n\nstd::copy(largestComponents.begin(), largestComponents.end(),\n std::ostream_iterator<unsigned long>(std::cout, \" \");\nstd::cout << std::endl;\n</code></pre>\n\n<p>Main is special (you don't actually need to return anything. If there is no return in main() it is equivalent to return 0).</p>\n\n<pre><code>return 0;\n</code></pre>\n\n<p>If you're code never returns anything but 0 then I would not return anything (let the language do it stuff). Do this to distinguish it from code that can return an error code.</p>\n\n<p>I hope you profiled to make sure it was worth reading the file twice.</p>\n\n<pre><code>long nodeCount = get_node_count(filename);\nvector< vector<long> > graph(nodeCount);\n</code></pre>\n\n<p>The vector automatically re-sizes as required. It uses a heuristic to prevent it re-sizing too many times. If you are using a C++11 compiler then the cost of resizing will be minimized as it will be using move rather than copy to reduce the cost.</p>\n\n<p>This is almost always wrong:</p>\n\n<pre><code>while (graphFile) {\n</code></pre>\n\n<p>The last successfull read will read <code>up-to</code> but not past the end of file. Thus leaving the stream in a good state even though there is no data left to read from the stream. Thus the loop will be enetered but the first read will fail. But inside your loop you don't check for failure. As a result you push_back() one more node than exists in the file (though the last node is a copy of the previous node).</p>\n\n<p>The correct way to write the loop is:</p>\n\n<pre><code>while(graphFile >> nodeIndex >> outIndex)\n{\n // Read of both values was successful\n // Add it to the graph.\n graph[nodeIndex - 1].push_back(outIndex - 1);\n}\n</code></pre>\n\n<p>Learn the standard functions:</p>\n\n<pre><code> if (nodeIndex > maxNodeIndex) {\n maxNodeIndex = nodeIndex;\n }\n\n // Easier to read as:\n\n maxNodeIndex = std::max(maxNodeIndex, nodeIndex);\n</code></pre>\n\n<p>There is no point in calculating <code>nodeIndex</code>. Either use the iterators, or use the index into the array the combination of both techniques is untidy.</p>\n\n<pre><code>for (it = graph.begin(); it != graph.end(); it++) {\n long nodeIndex = it - graph.begin();\n\n // Loop through all outgoing edges, and reverse them in new graph\n vector<long>::const_iterator eit;\n for (eit = graph[nodeIndex].begin(); eit != graph[nodeIndex].end(); eit++) {\n reversed[*eit].push_back(nodeIndex);\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T08:21:28.650",
"Id": "10946",
"ParentId": "10942",
"Score": "8"
}
},
{
"body": "<p>I have a few comments.</p>\n\n<ol>\n<li><p>In the parse_file function, you need to close the file before you return the graph by using </p>\n\n<pre><code>graphFile.close()\n</code></pre></li>\n<li><p>Your <code>reverse_graph</code> function could be better. I think you can parse the file again but this time reverse the head and tail of the node to get a reversed graph. For example, instead of read in head first, you can read in the tail and then the head.</p></li>\n<li><p>Your graph is big (with 800 thousand nodes). It would be better to use pass by reference extensively. For example, in your <code>parse_file</code> function, you construct a very big graph in the function, and return it. It would be better if you pass in a graph by reference and construct it while you read file. In this way, you create fewer temporary objects (graph in this case) and it saves you some memory. The same idea applies in other functions like compute_scc and, if you want, <code>get_largest_component</code>. For example:</p>\n\n<pre><code>void parse_file(const char filename[], Graph & graph);\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-25T20:28:59.060",
"Id": "82605",
"ParentId": "10942",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "10946",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T04:43:31.557",
"Id": "10942",
"Score": "8",
"Tags": [
"c++",
"algorithm",
"graph",
"search"
],
"Title": "Implementation of Kosaraju's algorithm for strongly connected components"
}
|
10942
|
<p>The following code detects if the system is idling. It approaches the problem by using the <code>Robot</code> class to take a screenshot, waits for a while, and then takes another screenshot. It then compares screenshot 1 with screenshot 2. If a certain amount of change is detected, it presumes the system is idling, else the system is active.</p>
<p>Please suggest code changes or even a different solution!</p>
<pre><code>package base;
import java.awt.AWTException;
import java.awt.DisplayMode;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
public class CheckIdle extends Thread {
private Robot robot;
private double threshHold = 0.05;
private int activeTime;
private int idleTime;
private boolean idle;
private Rectangle screenDimenstions;
public CheckIdle(int activeTime, int idleTime) {
this.activeTime = activeTime;
this.idleTime = idleTime;
// Get the screen dimensions
// MultiMonitor support.
int screenWidth = 0;
int screenHeight = 0;
GraphicsEnvironment graphicsEnv = GraphicsEnvironment
.getLocalGraphicsEnvironment();
GraphicsDevice[] graphicsDevices = graphicsEnv.getScreenDevices();
for (GraphicsDevice screens : graphicsDevices) {
DisplayMode mode = screens.getDisplayMode();
screenWidth += mode.getWidth();
if (mode.getHeight() > screenHeight) {
screenHeight = mode.getHeight();
}
}
screenDimenstions = new Rectangle(0, 0, screenWidth, screenHeight);
// setup the robot.
robot = null;
try {
robot = new Robot();
} catch (AWTException e1) {
e1.printStackTrace();
}
idle = false;
}
public void run() {
while (true) {
BufferedImage screenShot = robot
.createScreenCapture(screenDimenstions);
try {
Thread.sleep(idle ? idleTime : activeTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
BufferedImage screenShot2 = robot
.createScreenCapture(screenDimenstions);
if (compareScreens(screenShot, screenShot2) < threshHold) {
idle = true;
} else {
idle = false;
}
}
}
private double compareScreens(BufferedImage screen1, BufferedImage screen2) {
int counter = 0;
boolean changed = false;
// Count the amount of change.
for (int i = 0; i < screen1.getWidth() && !changed; i++) {
for (int j = 0; j < screen1.getHeight(); j++) {
if (screen1.getRGB(i, j) != screen2.getRGB(i, j)) {
counter++;
}
}
}
return (double) counter
/ (double) (screen1.getHeight() * screen1.getWidth()) * 100;
}
public static void main(String[] args) {
CheckIdle idleChecker = new CheckIdle(20000, 1000);
idleChecker.run();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T12:04:13.287",
"Id": "17403",
"Score": "0",
"body": "If, for instance, a Flash animation is being played in foreground, it wouldn't be detected as idling."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T12:31:56.247",
"Id": "17405",
"Score": "0",
"body": "Yes, I agree. Monitoring input (mouse/keyboard) will bypass that problem, but to my knowledge it will require 3d party libraries to capture the global inputs? Any other suggestion to avoid that problem?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T12:39:30.903",
"Id": "17406",
"Score": "0",
"body": "The solution is very system-dependant. For instance, in Windows you have to hook into mouse/keyboard events using JNI and the system API. Why are you avoiding 3rd party libraries? If there are any that solve your problem, why would you complicate yourself?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T12:57:12.143",
"Id": "17408",
"Score": "0",
"body": "In this case I am trying to find a Java only solution. It seems that I will require both a Linux and Windows 3rd party library to solve this problem. At first glace that seems more complicated, wouldn't you agree?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T03:57:30.863",
"Id": "17434",
"Score": "2",
"body": "Superficially: use `final` for `threshold`. Do not do `if (a < b) return true else false` but do `return (a < b);` or `return (a >= b);` - whichever you need. `boolean changed` needs to go. Use fractions, not percents - get rid of `* 100`. Rename counter to something like `pixelDifferenceCount`. Also, first half of `CheckIdle` should be its own method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T09:28:55.430",
"Id": "17486",
"Score": "0",
"body": "One problem with this approach is the clock. If there is an analogue clock with a second hand on screen then the program will never detect an idle state."
}
] |
[
{
"body": "<p>In</p>\n\n<pre><code> if (compareScreens(screenShot, screenShot2) < threshHold) {\n idle = true;\n } else {\n idle = false;\n }\n</code></pre>\n\n<p>Isn't this better as </p>\n\n<pre><code> idle = compareScreens(screenShot, screenShot2) < threshHold;\n</code></pre>\n\n<p>Here, why initialize robot to null first? Isn't this given in the constructor? And why do you continue if there is an AWT exception? Doesn't it mean no GUI? perhaps your constructor should throw that exception. Otherwise, perhaps it is better to have a larger block for try catch. The reason is that the exception handling code is better away from the main sequence. You use robot in the run code. So in order for that to run, robot has to be non null. So catching the exception here is not correct.</p>\n\n<pre><code> // setup the robot.\n robot = null;\n try {\n robot = new Robot();\n } catch (AWTException e1) {\n e1.printStackTrace();\n }\n</code></pre>\n\n<p>You also set idle to false, which is not really needed because it is initialized to false by java.</p>\n\n<p>Why do you take an extra screen shot? Isn't this what you mean?</p>\n\n<pre><code>public void run() {\n try {\n BufferedImage screenShot = null;\n BufferedImage screenShotPrev \n = robot.createScreenCapture(screenDimenstions);\n while (true) {\n Thread.sleep(idle ? idleTime : activeTime);\n screenShot = robot.createScreenCapture(screenDimenstions);\n idle = compareScreens(screenShotPrev, screenShot) < threshHold;\n screenShotPrev = screenShot;\n }\n } catch (InterruptedException e) {\n ...\n }\n</code></pre>\n\n<p>Here, where do you use the changed? (as noted in comment to the question.)</p>\n\n<pre><code>private double compareScreens(BufferedImage screen1, BufferedImage screen2) {\n int counter = 0;\n boolean changed = false;\n\n // Count the amount of change.\n for (int i = 0; i < screen1.getWidth() && !changed; i++) {\n for (int j = 0; j < screen1.getHeight(); j++) {\n if (screen1.getRGB(i, j) != screen2.getRGB(i, j)) {\n counter++;\n }\n }\n }\n\n return (double) counter\n / (double) (screen1.getHeight() * screen1.getWidth()) * 100;\n}\n</code></pre>\n\n<p>The for loop may be better as</p>\n\n<pre><code> int[] s1 = ((DataBufferInt) screen1.getRaster().getDataBuffer()).getData(); \n int[] s2 = ((DataBufferInt) screen2.getRaster().getDataBuffer()).getData(); \n for(int i = 0; i < s1.length; i++)\n if (s1[i] != s2[i]) counter++;\n</code></pre>\n\n<p>Since it avoids multiple calls to getRGB.</p>\n\n<p>And is there any chance of getHeight or getWidth returning 0?\nAlso, I assume that you are calling .run instead of .start only because you are testing?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T06:01:39.237",
"Id": "17482",
"Score": "0",
"body": "Hi, thank you very mush for the feedback. I agree with comments, and will make the changes likewise."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T23:53:22.710",
"Id": "10995",
"ParentId": "10952",
"Score": "4"
}
},
{
"body": "<p>You can use the following code to globally detect the current mouse location:</p>\n\n<pre><code>// prevent HeadlessException\nif (GraphicsEnvironment.isHeadless()) {\n System.err.println(\"headless graphics environment detected\");\n return;\n}\nPointerInfo info = MouseInfo.getPointerInfo();\nPoint point = info.getLocation();\n</code></pre>\n\n<p>However, you would still need to use a third party library such as <a href=\"http://melloware.com/products/jintellitype/index.html\" rel=\"nofollow\">JIntellitype</a> to detect keyboard activity.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T05:58:49.707",
"Id": "17481",
"Score": "0",
"body": "Thank you! I wasn't aware of this! I will change the implementation around this."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T05:08:22.960",
"Id": "10999",
"ParentId": "10952",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "10995",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T09:48:15.453",
"Id": "10952",
"Score": "4",
"Tags": [
"java"
],
"Title": "Detecting if the system is idling"
}
|
10952
|
<p>I have an abstract class implementing some concrete functionality for its child classes:</p>
<pre><code>abstract class Function {
def eval: Double = some_concrete_functionality_which_calls_fEval
def simplify: Funcion = more_concrete_calling_fSimplify
protected def fEval: Double
protected def fSimplify: Funcion
}
</code></pre>
<p>The child classes should implement <code>fEval</code> and <code>fSimplify</code> themselves, while <code>eval</code> and <code>simplify</code> act like a public proxy between them to provide common functionality before calling the actual implementation.</p>
<p><code>f</code> stands for function but, although I feel <code>fName</code> is not very expressive, I can't think of any good alternatives (besides <code>concreteEval</code> which seems very bloated.)</p>
<p>Any suggestions? Should I stick to <code>concreteEval</code>? Maybe keep it like it is?</p>
|
[] |
[
{
"body": "<p>I think that it's more a matter of taste. If I were to come along behind you, I wouldn't have any particular problem with <code>fEval</code> and <code>fSimplify</code>.</p>\n\n<p>I'm not sure that I would like <code>concreteEval</code>.</p>\n\n<p>In my own code I tend to use <code>doEval</code>, but I could also imagine using <code>evalImpl</code> or <code>myEval</code>, depending on what it is exactly that is being done by these functions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T12:41:37.000",
"Id": "17407",
"Score": "0",
"body": "I thought about `myEval` too but it looks very meaningless. Why it it 'yours'? Like `fEval` it doesn't explain why it is not just `eval`. `doEval` and `evalImpl` look good, they show that it's where you actuall **do** the eval and that it's an **impl**, respectively. I'll think of them. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T11:58:11.767",
"Id": "10955",
"ParentId": "10954",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "10955",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T11:46:30.237",
"Id": "10954",
"Score": "1",
"Tags": [
"scala"
],
"Title": "Which name should I choose for private abstract functionality with a public proxy?"
}
|
10954
|
<p>I'm an experienced developer myself but for a current project I am working on I have decided to hire some developers to develop a mobile app which requires some supporting web services (developed in PHP).</p>
<p>I know myself that the code I have pasted below is worse than what I would expect a 5 year old to produce after spending 5 minutes reading <em>Dummy's Guide to Programming PHP Badly</em>. However, this is meant to be a professional software development company!</p>
<p>After a quick perusal I can see that it is wide open to basic SQL injection attacks, conforms to no web services standard I know of, barely uses any sound principles of software design or architecture and quite frankly I think it must be some kind of practical joke.</p>
<p>I was wondering if anyone else could help me out by pointing out the problems in this code and/or just generally tearing it apart and having a good laugh at it. </p>
<p>I might then show this page to our developers in the hope that they can take on some of this feedback and hopefully end up producing some code that I would dare to put into a production environment.</p>
<p>Note: The code I have pasted below is not doctored. It includes all the useful comments and descriptions that the developers have kindly left for us to make it easy to maintain.</p>
<p>This is the 'Front Controller':</p>
<pre><code><?php
include "includes/dbconnect.php";
include "user_class.php";
$userval = new userinfo();
switch($_POST['action'])
{
//****** User profile Class *******//
case "login":
$user=$userval->emailsign($_POST);
break;
case "emailsignstp2":
$user=$userval->emailsignstp2($_POST);
break;
case "usersignIN":
$user=$userval->usersignIN($_POST);
break;
/*case "register":
$user=$userval->user_registration($_REQUEST, $_FILES);
break;
case "logout":
$user=$userval->logout($_REQUEST);
break;*/
}
echo json_encode($user);
//print_r($user);
?>
</code></pre>
<p>And the API class itself:</p>
<pre><code><?php
ini_set("display_errors", 1);
if($_SERVER['HTTP_HOST'] == "localhost/whatittext/") {
//define('DOMAIN', "http://localhost/nglcc/profile_img/");
} else {
define('DOMAIN', "http://myapi.com/");
}
class userinfo
{
function emailsign($email)
{
$whatittext['emaillogin'] = array();
$uemail = $email['uemail'];
if (!preg_match("/^[^@]{1,64}@[^@]{1,255}$/", $uemail)) {
$whatittex["emaillogin"]["result"]="false";
$whatittex["emaillogin"]["error"]="Inalid email";
}else{
$sql=mysql_query("select count(*) AS `cct`, t1.* from `users` AS t1 where t1.`uemail`='".$uemail."' AND t1.`status`= '1'") or die(mysql_error());
$row = mysql_fetch_array($sql);
if($row['cct'] > 0)
{
$whatittex["emaillogin"]["result"]="true";
$whatittex["emaillogin"]["uname"]=$row['uname'];
$whatittex["emaillogin"]["uemail"]=$row['uemail'];
$whatittex["emaillogin"]["create_dt"]=$row['create_dt'];
$whatittex["emaillogin"]["ucountry"]=$row['ucountry'];
}
else
{
$whatittex["emaillogin"]["result"]="false";
$whatittex["emaillogin"]["error"]="Email address dose not exist.";
}
}
return $whatittex["emaillogin"];
}
function emailsignstp2($emailpass)
{
$whatittext['emaillogin'] = array();
$uemail = $emailpass['uemail'];
$upass = $emailpass['upass'];
if (!preg_match("/^[^@]{1,64}@[^@]{1,255}$/", $uemail)) {
$whatittex["emaillogin"]["result"]="false";
$whatittex["emaillogin"]["error"]="Inalid Email";
}else{
$sql=mysql_query("select count(*) AS `cct`, t1.* from `users` AS t1 where t1.`uemail`='".$uemail."' AND t1.`upassword`='".$upass."' AND t1.`status`= '1'") or die(mysql_error());
$row = mysql_fetch_array($sql);
if($row['cct'] > 0)
{
$whatittex["emaillogin"]["result"]="true";
$whatittex["emaillogin"]["uname"]=$row['uname'];
$whatittex["emaillogin"]["uemail"]=$row['uemail'];
$whatittex["emaillogin"]["create_dt"]=$row['create_dt'];
$whatittex["emaillogin"]["ucountry"]=$row['ucountry'];
}
else
{
$whatittex["emaillogin"]["result"]="false";
$whatittex["emaillogin"]["error"]="Invalid email or password.";
}
}
return $whatittex["emaillogin"];
}
function usersignIN($signin)
{
$whatittext['emaillogin'] = array();
$uemail = $signin['uemail'];
$upass = $signin['upass'];
$uname = $signin['uname'];
$ucountry = $signin['ucountry'];
if (!preg_match("/^[^@]{1,64}@[^@]{1,255}$/", $uemail)) {
$whatittex["emaillogin"]["result"]="false";
$whatittex["emaillogin"]["error"]="Inalid email";
}else{
$sql=mysql_query("select count(*) AS `cct` from `users` where `uemail`='".$uemail."'") or die(mysql_error());
$row = mysql_fetch_array($sql);
if($row['cct'] > 0)
{
$whatittex["emaillogin"]["result"]="false";
$whatittex["emaillogin"]["error"]="Email address already exist.";
}
else
{
if($uemail=='' || $upass=='' || $uname=='' || $ucountry=='')
{
$whatittex["emaillogin"]["result"]="false";
$whatittex["emaillogin"]["error"]="Please fill all of the following option properly.";
}
else
{
$sql2=mysql_query("select count(*) AS `cct2` from `users` where `uname`='".$uname."'") or die(mysql_error());
$row2 = mysql_fetch_array($sql2);
if($row2['cct2'] > 0)
{
$whatittex["emaillogin"]["result"]="false";
$whatittex["emaillogin"]["error"]="User name already exist.";
}
else
{
$sql=mysql_query("insert into `users` set `uemail`='".$uemail."', `uname`='".$uname."', `upassword`='".$upass."', `ucountry`='".$ucountry."'");
$whatittex["emaillogin"]["result"]="true";
$whatittex["emaillogin"]["uname"]=$uname;
$whatittex["emaillogin"]["uemail"]=$uemail;
$whatittex["emaillogin"]["ucountry"]=$ucountry;
}
}
}
}
return $whatittex["emaillogin"];
}
/*function user_login($arr) //LOGIN//
{
$login["whatittext"] = array();
$email=$arr['email'];
$password=$arr['pass'];
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email))
{
$login["nglcc"]["result"]="false";
$login["nglcc"]["error"]="Inalid Email";
}
else if(trim($password)!="")
{
$sql=mysql_query("select * from `user` where `email`='".$email."' AND password='".$password."' AND `status`= '1'");
$rows=@mysql_num_rows($sql);
if($rows == 1)
{
$row = mysql_fetch_assoc($sql);
$r[0] = $row;
mysql_query("update `user` set `login_status`='1' where uid=".$row['uid']);
$login["nglcc"]["result"]="true";
$login["nglcc"]["login_info"] = $r;
}
else
{
$login["nglcc"]["result"]="false";
$login["nglcc"]["error"] = "Invalid email/password";
}
}
else
{
$login["nglcc"]["result"]="false";
$login["nglcc"]["error"]="Email/password should not blank";
}
return $login;
}*/
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T09:21:22.730",
"Id": "71752",
"Score": "0",
"body": "If this is the server code, I don't want to see the mobile code. I bet 5/2 that they misuse ssl in at least one way"
}
] |
[
{
"body": "<h2>In order of badness.</h2>\n\n<ol>\n<li><strong>SQL injection</strong> (as you pointed out).</li>\n<li>Plaintext <strong>passwords</strong>, hold the salt. Obviosuly no investigation was done on how to deal with passwords.</li>\n<li><strong>mysql_*</strong> is <strike>softly deprecated</strike> now <a href=\"http://www.php.net/manual/en/migration55.deprecated.php\" rel=\"nofollow\">deprecated</a>.</li>\n<li>Horrible <strong>double line-spacing</strong> (Choose every second line and start again. I'd choose the blanks.)</li>\n<li><strong>Item by item setting of an array.</strong> Build the whole thing in a single statement.</li>\n<li><strong>Lowercase is not a valid choice for naming methods and variables</strong> (e.g $whatitext, ->emailsignstp2), use pascal or camel case.</li>\n<li>Horrible variable name <strong>$whatitex (probably mispelt)</strong> also $whatitext.</li>\n<li>The User class is completely pointless, it is a group of functions. <strong>Fake OO sucks.</strong> Seriously, just use a namespace and normal functions.</li>\n<li><strong>Validation of the email</strong> is woeful. See: <a href=\"http://php.net/manual/en/filter.examples.validation.php\" rel=\"nofollow\">filter_var</a></li>\n<li><strong>No useful comments.</strong></li>\n<li><strong>Pointless abbreviation</strong> of method emailsignstp2.</li>\n<li><strong>Randomly commented code</strong> shouldn't exist when using a revision control system.</li>\n</ol>\n\n<p>I'm sure I have missed a few things. This was unprofessional work. They will need to learn very quickly. I wouldn't want them doing any serious work (especially if they were trying to write it with classes in an OO style).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T08:25:41.157",
"Id": "17484",
"Score": "0",
"body": "Item by item setting of an array, double line-spacing, pointless classes and randomly commented code are sound signatures of \"by lines of code\" payment agreement....\nNaive attempts to get rich quick. Next try are things like `if(true){ some verifiable code} else {coder's net profit}`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T13:31:13.097",
"Id": "10987",
"ParentId": "10956",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "10987",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T14:56:00.987",
"Id": "10956",
"Score": "2",
"Tags": [
"php5",
"authentication"
],
"Title": "User login and signup system"
}
|
10956
|
<p>I'm a big fan of David Allen's <a href="http://rads.stackoverflow.com/amzn/click/0142000280" rel="nofollow noreferrer">Getting Things Done</a>, but the myriad software tools and sites I've tried haven't impressed me that much. That's why I've decided to write my own.</p>
<h2>The concept</h2>
<p>This app (I don't have a name for it yet.) pulls in your twitter stream, Facebook news feeds, email, RSS feeds, and more and treats them like items in your GTD inbox, sorted by importance, dependent on who sent you the message. Once everything has been gathered, it's your job to look at each item and decide what to do with it.</p>
<pre><code>SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL';
CREATE SCHEMA IF NOT EXISTS `DoneBox` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
USE `DoneBox` ;
-- -----------------------------------------------------
-- Table `DoneBox`.`users`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `DoneBox`.`users` (
`id` CHAR(16) BINARY NOT NULL ,
`username` VARCHAR(50) NULL ,
`password` VARCHAR(150) NULL ,
`email` VARCHAR(100) NULL ,
`recovery_answer_1` TEXT NULL ,
`recovery_answer_2` TEXT NULL ,
`phone` VARCHAR(45) NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
CREATE UNIQUE INDEX `username_UNIQUE` ON `DoneBox`.`users` (`username` ASC) ;
-- -----------------------------------------------------
-- Table `DoneBox`.`Imap`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `DoneBox`.`Imap` (
`id` CHAR(16) BINARY NOT NULL ,
`host` VARCHAR(100) NULL ,
`port` INT NULL ,
`ssl` TINYINT(1) NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `DoneBox`.`smtp`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `DoneBox`.`smtp` (
`id` CHAR(16) BINARY NOT NULL ,
`host` VARCHAR(100) NULL ,
`port` INT NULL ,
`ssl` TINYINT(1) NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `DoneBox`.`pop3`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `DoneBox`.`pop3` (
`id` CHAR(16) BINARY NOT NULL ,
`host` VARCHAR(100) NULL ,
`port` INT NULL ,
`ssl` TINYINT(1) NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `DoneBox`.`email_provider`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `DoneBox`.`email_provider` (
`id` CHAR(16) NOT NULL ,
`domain` VARCHAR(100) NULL ,
`long_domain` VARCHAR(100) NULL ,
`Imap_id` CHAR(16) BINARY NOT NULL ,
`pop3_id` CHAR(16) BINARY NOT NULL ,
`smtp_id` CHAR(16) BINARY NOT NULL ,
PRIMARY KEY (`id`, `Imap_id`, `pop3_id`, `smtp_id`) ,
CONSTRAINT `fk_email_provider_Imap1`
FOREIGN KEY (`Imap_id` )
REFERENCES `DoneBox`.`Imap` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_email_provider_pop31`
FOREIGN KEY (`pop3_id` )
REFERENCES `DoneBox`.`pop3` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_email_provider_smtp1`
FOREIGN KEY (`smtp_id` )
REFERENCES `DoneBox`.`smtp` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE INDEX `fk_email_provider_Imap1` ON `DoneBox`.`email_provider` (`Imap_id` ASC) ;
CREATE INDEX `fk_email_provider_pop31` ON `DoneBox`.`email_provider` (`pop3_id` ASC) ;
CREATE INDEX `fk_email_provider_smtp1` ON `DoneBox`.`email_provider` (`smtp_id` ASC) ;
-- -----------------------------------------------------
-- Table `DoneBox`.`email_account`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `DoneBox`.`email_account` (
`id` CHAR(16) BINARY NOT NULL ,
`email` VARCHAR(100) NULL ,
`password` VARCHAR(150) NULL ,
`signature` VARCHAR(45) NULL ,
`email_provider_id` CHAR(16) NOT NULL ,
`users_id` CHAR(16) BINARY NOT NULL ,
PRIMARY KEY (`id`, `email_provider_id`, `users_id`) ,
CONSTRAINT `fk_email_account_email_provider1`
FOREIGN KEY (`email_provider_id` )
REFERENCES `DoneBox`.`email_provider` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_email_account_users1`
FOREIGN KEY (`users_id` )
REFERENCES `DoneBox`.`users` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE INDEX `fk_email_account_email_provider1` ON `DoneBox`.`email_account` (`email_provider_id` ASC) ;
CREATE INDEX `fk_email_account_users1` ON `DoneBox`.`email_account` (`users_id` ASC) ;
-- -----------------------------------------------------
-- Table `DoneBox`.`contexts`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `DoneBox`.`contexts` (
`id` CHAR(16) BINARY NOT NULL ,
`name` VARCHAR(100) NULL ,
`users_id` CHAR(16) BINARY NOT NULL ,
PRIMARY KEY (`id`, `users_id`) ,
CONSTRAINT `fk_contexts_users1`
FOREIGN KEY (`users_id` )
REFERENCES `DoneBox`.`users` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE INDEX `fk_contexts_users1` ON `DoneBox`.`contexts` (`users_id` ASC) ;
-- -----------------------------------------------------
-- Table `DoneBox`.`projects`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `DoneBox`.`projects` (
`id` CHAR(16) BINARY NOT NULL ,
`name` VARCHAR(100) NULL ,
`description` LONGTEXT NULL ,
`contexts_id` CHAR(16) BINARY NOT NULL ,
`users_id` CHAR(16) BINARY NOT NULL ,
PRIMARY KEY (`id`, `contexts_id`, `users_id`) ,
CONSTRAINT `fk_projects_contexts1`
FOREIGN KEY (`contexts_id` )
REFERENCES `DoneBox`.`contexts` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_projects_users1`
FOREIGN KEY (`users_id` )
REFERENCES `DoneBox`.`users` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE INDEX `fk_projects_contexts1` ON `DoneBox`.`projects` (`contexts_id` ASC) ;
CREATE INDEX `fk_projects_users1` ON `DoneBox`.`projects` (`users_id` ASC) ;
-- -----------------------------------------------------
-- Table `DoneBox`.`email_messages`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `DoneBox`.`email_messages` (
`id` CHAR(16) NOT NULL ,
`sender` VARCHAR(100) NULL ,
`sent_on` DATETIME NULL ,
`subject` VARCHAR(45) NULL ,
`body` LONGTEXT NULL ,
`is_unread` TINYINT(1) NULL ,
`email_account_id` CHAR(16) BINARY NOT NULL ,
`users_id` CHAR(16) BINARY NOT NULL ,
`projects_id` CHAR(16) BINARY NOT NULL ,
`contexts_id` CHAR(16) BINARY NOT NULL ,
PRIMARY KEY (`id`, `email_account_id`, `users_id`, `projects_id`, `contexts_id`) ,
CONSTRAINT `fk_email_messages_email_account1`
FOREIGN KEY (`email_account_id` )
REFERENCES `DoneBox`.`email_account` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_email_messages_users1`
FOREIGN KEY (`users_id` )
REFERENCES `DoneBox`.`users` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_email_messages_projects1`
FOREIGN KEY (`projects_id` )
REFERENCES `DoneBox`.`projects` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_email_messages_contexts1`
FOREIGN KEY (`contexts_id` )
REFERENCES `DoneBox`.`contexts` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE INDEX `fk_email_messages_email_account1` ON `DoneBox`.`email_messages` (`email_account_id` ASC) ;
CREATE INDEX `fk_email_messages_users1` ON `DoneBox`.`email_messages` (`users_id` ASC) ;
CREATE INDEX `fk_email_messages_projects1` ON `DoneBox`.`email_messages` (`projects_id` ASC) ;
CREATE INDEX `fk_email_messages_contexts1` ON `DoneBox`.`email_messages` (`contexts_id` ASC) ;
-- -----------------------------------------------------
-- Table `DoneBox`.`social_account`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `DoneBox`.`social_account` (
`id` CHAR(16) BINARY NOT NULL ,
`service` VARCHAR(100) NULL ,
`username` VARCHAR(100) NULL ,
`send` INT(11) NULL ,
`receive` INT(11) NULL ,
`key` VARCHAR(200) NULL ,
`json` LONGTEXT NULL ,
`users_id` CHAR(16) BINARY NOT NULL ,
PRIMARY KEY (`id`, `users_id`) ,
CONSTRAINT `fk_social_account_users1`
FOREIGN KEY (`users_id` )
REFERENCES `DoneBox`.`users` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE INDEX `fk_social_account_users1` ON `DoneBox`.`social_account` (`users_id` ASC) ;
-- -----------------------------------------------------
-- Table `DoneBox`.`social_messages`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `DoneBox`.`social_messages` (
`id` CHAR(16) BINARY NOT NULL ,
`sender` VARCHAR(200) NULL ,
`messaage_id` VARCHAR(200) NULL ,
`operation` TEXT NULL ,
`transient` TEXT NULL ,
`stream` VARCHAR(45) NULL ,
`time` TIME NULL ,
`from_me` INT(11) NULL ,
`to_me` VARCHAR(45) NULL ,
`json` VARCHAR(45) NULL ,
`social_account_id` CHAR(16) BINARY NOT NULL ,
`users_id` CHAR(16) BINARY NOT NULL ,
`projects_id` CHAR(16) BINARY NOT NULL ,
`contexts_id` CHAR(16) BINARY NOT NULL ,
PRIMARY KEY (`id`, `social_account_id`, `users_id`, `projects_id`, `contexts_id`) ,
CONSTRAINT `fk_social_messages_social_account1`
FOREIGN KEY (`social_account_id` )
REFERENCES `DoneBox`.`social_account` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_social_messages_users1`
FOREIGN KEY (`users_id` )
REFERENCES `DoneBox`.`users` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_social_messages_contexts1`
FOREIGN KEY (`contexts_id` )
REFERENCES `DoneBox`.`contexts` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_social_messages_projects1`
FOREIGN KEY (`projects_id` )
REFERENCES `DoneBox`.`projects` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE INDEX `fk_social_messages_social_account1` ON `DoneBox`.`social_messages` (`social_account_id` ASC) ;
CREATE INDEX `fk_social_messages_users1` ON `DoneBox`.`social_messages` (`users_id` ASC) ;
CREATE INDEX `fk_social_messages_contexts1` ON `DoneBox`.`social_messages` (`contexts_id` ASC) ;
CREATE INDEX `fk_social_messages_projects1` ON `DoneBox`.`social_messages` (`projects_id` ASC) ;
-- -----------------------------------------------------
-- Table `DoneBox`.`syndicate_feeds`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `DoneBox`.`syndicate_feeds` (
`id` CHAR(16) BINARY NOT NULL ,
`name` VARCHAR(100) NULL ,
`url` VARCHAR(200) NULL ,
`users_id` CHAR(16) BINARY NOT NULL ,
PRIMARY KEY (`id`, `users_id`) ,
CONSTRAINT `fk_syndicate_feeds_users1`
FOREIGN KEY (`users_id` )
REFERENCES `DoneBox`.`users` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE INDEX `fk_syndicate_feeds_users1` ON `DoneBox`.`syndicate_feeds` (`users_id` ASC) ;
-- -----------------------------------------------------
-- Table `DoneBox`.`syndicate_items`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `DoneBox`.`syndicate_items` (
`id` CHAR(16) BINARY NOT NULL ,
`title` VARCHAR(100) NULL ,
`date` DATE NULL ,
`url` VARCHAR(200) NULL ,
`body` LONGTEXT NULL ,
`syndicate_feeds_id` CHAR(16) BINARY NOT NULL ,
`users_id` CHAR(16) BINARY NOT NULL ,
`projects_id` CHAR(16) BINARY NOT NULL ,
`contexts_id` CHAR(16) BINARY NOT NULL ,
PRIMARY KEY (`id`, `syndicate_feeds_id`, `users_id`, `projects_id`, `contexts_id`) ,
CONSTRAINT `fk_syndicate_items_syndicate_feeds1`
FOREIGN KEY (`syndicate_feeds_id` )
REFERENCES `DoneBox`.`syndicate_feeds` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_syndicate_items_users1`
FOREIGN KEY (`users_id` )
REFERENCES `DoneBox`.`users` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_syndicate_items_projects1`
FOREIGN KEY (`projects_id` )
REFERENCES `DoneBox`.`projects` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_syndicate_items_contexts1`
FOREIGN KEY (`contexts_id` )
REFERENCES `DoneBox`.`contexts` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE INDEX `fk_syndicate_items_syndicate_feeds1` ON `DoneBox`.`syndicate_items` (`syndicate_feeds_id` ASC) ;
CREATE INDEX `fk_syndicate_items_users1` ON `DoneBox`.`syndicate_items` (`users_id` ASC) ;
CREATE INDEX `fk_syndicate_items_projects1` ON `DoneBox`.`syndicate_items` (`projects_id` ASC) ;
CREATE INDEX `fk_syndicate_items_contexts1` ON `DoneBox`.`syndicate_items` (`contexts_id` ASC) ;
-- -----------------------------------------------------
-- Table `DoneBox`.`activation_profile`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `DoneBox`.`activation_profile` (
`id` CHAR(16) BINARY NOT NULL ,
`activation_code` VARCHAR(40) NULL ,
`date` DATE NULL ,
`users_id` CHAR(16) BINARY NOT NULL ,
PRIMARY KEY (`id`, `users_id`) ,
CONSTRAINT `fk_activation_profile_users1`
FOREIGN KEY (`users_id` )
REFERENCES `DoneBox`.`users` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE INDEX `fk_activation_profile_users1` ON `DoneBox`.`activation_profile` (`users_id` ASC) ;
CREATE USER `levi` IDENTIFIED BY '<snip>';
grant DELETE on TABLE `DoneBox`.`Imap` to levi;
grant INSERT on TABLE `DoneBox`.`Imap` to levi;
grant SELECT on TABLE `DoneBox`.`Imap` to levi;
grant UPDATE on TABLE `DoneBox`.`Imap` to levi;
grant DELETE on TABLE `DoneBox`.`social_messages` to levi;
grant INSERT on TABLE `DoneBox`.`social_messages` to levi;
grant SELECT on TABLE `DoneBox`.`social_messages` to levi;
grant UPDATE on TABLE `DoneBox`.`social_messages` to levi;
grant DELETE on TABLE `DoneBox`.`contexts` to levi;
grant SELECT on TABLE `DoneBox`.`contexts` to levi;
grant UPDATE on TABLE `DoneBox`.`contexts` to levi;
grant INSERT on TABLE `DoneBox`.`contexts` to levi;
grant DELETE on TABLE `DoneBox`.`pop3` to levi;
grant INSERT on TABLE `DoneBox`.`pop3` to levi;
grant SELECT on TABLE `DoneBox`.`pop3` to levi;
grant UPDATE on TABLE `DoneBox`.`pop3` to levi;
grant DELETE on TABLE `DoneBox`.`syndicate_feeds` to levi;
grant SELECT on TABLE `DoneBox`.`syndicate_feeds` to levi;
grant UPDATE on TABLE `DoneBox`.`syndicate_feeds` to levi;
grant INSERT on TABLE `DoneBox`.`syndicate_feeds` to levi;
grant DELETE on TABLE `DoneBox`.`email_account` to levi;
grant SELECT on TABLE `DoneBox`.`email_account` to levi;
grant UPDATE on TABLE `DoneBox`.`email_account` to levi;
grant INSERT on TABLE `DoneBox`.`email_account` to levi;
grant DELETE on TABLE `DoneBox`.`projects` to levi;
grant INSERT on TABLE `DoneBox`.`projects` to levi;
grant SELECT on TABLE `DoneBox`.`projects` to levi;
grant UPDATE on TABLE `DoneBox`.`projects` to levi;
grant DELETE on TABLE `DoneBox`.`syndicate_items` to levi;
grant INSERT on TABLE `DoneBox`.`syndicate_items` to levi;
grant SELECT on TABLE `DoneBox`.`syndicate_items` to levi;
grant UPDATE on TABLE `DoneBox`.`syndicate_items` to levi;
grant DELETE on TABLE `DoneBox`.`email_messages` to levi;
grant INSERT on TABLE `DoneBox`.`email_messages` to levi;
grant SELECT on TABLE `DoneBox`.`email_messages` to levi;
grant UPDATE on TABLE `DoneBox`.`email_messages` to levi;
grant DELETE on TABLE `DoneBox`.`smtp` to levi;
grant INSERT on TABLE `DoneBox`.`smtp` to levi;
grant SELECT on TABLE `DoneBox`.`smtp` to levi;
grant UPDATE on TABLE `DoneBox`.`smtp` to levi;
grant DELETE on TABLE `DoneBox`.`users` to levi;
grant INSERT on TABLE `DoneBox`.`users` to levi;
grant SELECT on TABLE `DoneBox`.`users` to levi;
grant UPDATE on TABLE `DoneBox`.`users` to levi;
grant DELETE on TABLE `DoneBox`.`email_provider` to levi;
grant INSERT on TABLE `DoneBox`.`email_provider` to levi;
grant SELECT on TABLE `DoneBox`.`email_provider` to levi;
grant UPDATE on TABLE `DoneBox`.`email_provider` to levi;
grant DELETE on TABLE `DoneBox`.`social_account` to levi;
grant INSERT on TABLE `DoneBox`.`social_account` to levi;
grant SELECT on TABLE `DoneBox`.`social_account` to levi;
grant UPDATE on TABLE `DoneBox`.`social_account` to levi;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
</code></pre>
<p>MySQL workbench file I used to generate <a href="http://dl.dropbox.com/u/19871021/Database.mwb" rel="nofollow noreferrer">this code</a>.</p>
<ul>
<li>This database will be deployed to Amazon RDS.</li>
<li>I'm using a <a href="http://www.clojure.org" rel="nofollow noreferrer">clojure</a> library called <a href="http://www.sqlkorma.com" rel="nofollow noreferrer">korma</a> to run queries.</li>
<li>The Imap, smtp, pop3, and email_provider tables are used to keep a local email configuration cache, these could probably be merged.</li>
<li>I'm using a GUID as the primary key for all my tables.</li>
</ul>
<p>Does this design make sense? Are there any places I can make improvements? Are the permissions I have set enough? This is my first attempt at trying to design a database for a web app, so any suggestions and advice are greatly appreciated. Thank you for your time and consideration.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T01:55:50.060",
"Id": "17429",
"Score": "0",
"body": "don't store plaintext passwords"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T02:00:06.467",
"Id": "17430",
"Score": "0",
"body": "why do you have so many composite pk's? why not 0?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T03:18:29.973",
"Id": "17432",
"Score": "0",
"body": "@Ron first, I'm using the BCrypt algorithm for the User table and AES for the email_account table, second, I used MySQL workbench to design the database and used an identifying 1:1 and 1:n relationship, is there anything I should have done differently?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-31T15:50:29.820",
"Id": "53801",
"Score": "1",
"body": "why use a GUID for the Primary Keys? why not just use an `INT` that `AUTO_INCREMENT`'s ????"
}
] |
[
{
"body": "<ul>\n<li>consider utf8 charset and collation for your international users</li>\n<li><p>maximum length of an email address is 320 characters</p></li>\n<li><p>maximum length of a phone number is 15 characters, plus 11 for extension (plus 1 for a separator if you want to go that way)</p></li>\n<li><p>your user's password should be hashed before it is stored in the database, so should have a fixed length</p></li>\n<li><p>email provider passwords should be encrypted </p></li>\n<li><p>why nullable for username and password?</p></li>\n<li><p>recovery text might be problematic due to celebrities (Sarah Palin had an issue with this)</p></li>\n<li><p>consider implications of having to enter 16 digit (GUID) identifiers in urls, or over the phone</p></li>\n<li><p>host name can be 255 chars</p></li>\n<li><p>signature seems kinda short - I would go with TEXT</p></li>\n<li><p>I would use table inheritance pattern for email provider, email/social message</p></li>\n<li><p>What does json field mean in <code>social_account</code>?</p></li>\n<li><p>I guess you could hash the <code>activation_profile.activation_code</code> , and shorten it to code</p></li>\n<li><p>What does <code>activation_profile.date</code> mean?</p></li>\n<li><p>url maximum length is 2083 characters</p></li>\n<li><p>What about email attachments or Facebook message attachments?</p></li>\n<li><p>How are you going to deal with multi-part emails that have an HTML body and a plain-text body, or both or neither?</p></li>\n<li><p>E-mail subject maximum length is 78</p></li>\n<li><p>You might want to put your index declarations all in one file so that you can drop and add them in one operation (in case of bulk load)</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T17:38:37.157",
"Id": "17465",
"Score": "0",
"body": "two things, first, I've answered your questions in my original question, second, what's table inheritance? Google has been less then helpful here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T17:50:23.193",
"Id": "17466",
"Score": "0",
"body": "duh me on the social passwords. was late at night :)\n\nregarding inheritance, it looks like messages are pretty similar and providers are pretty similar. you might consider a supertype for each that holds common fields, to ease maintenance over time. i was referring to these patterns:\n\nhttp://martinfowler.com/eaaCatalog/singleTableInheritance.html\n\nhttp://martinfowler.com/eaaCatalog/classTableInheritance.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T18:08:16.917",
"Id": "17467",
"Score": "0",
"body": "Ah, thank you very much for your time and effort, I really appreciate it. Now all I have to do is commit the update SQL file to git and I'll be good to go!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T06:23:38.213",
"Id": "10981",
"ParentId": "10958",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T17:05:37.190",
"Id": "10958",
"Score": "3",
"Tags": [
"mysql",
"sql"
],
"Title": "Database design for an online organization tool"
}
|
10958
|
<p>I've been building a coloring book for kids: <a href="http://coloringbook.core.ba.lightburncloud.com/" rel="nofollow">http://coloringbook.core.ba.lightburncloud.com/</a></p>
<p>It's got to work on an iPad, so I decided to try out Raphaël JS. I want to try and make this as efficient as possible, and was wondering if anybody had any suggestions on how to tighten things up.</p>
<p>I'm just kind of flying by the seat of my pants here, so if anybody has any best practices/general tips for Raphaël (or jQuery, or JavaScript), it'd help me out a lot.</p>
<pre><code>// Primes the page, gets the scene via JSON
// -------------------------------------------------------------------
var engine = {
paper : Object,
prime : function(){
// Makes new instance of scalable raphael
engine.paper = new ScaleRaphael("stage", 960, 525);
engine.handleResize();
$(window).resize(engine.handleResize);
},
load : function(json){
$.getJSON(json, function(data){
// Collects Scene Elements
scene.set(data.elements);
// Collects Colors
color.set(data.colors);
// Collects Audio Elements
audio.set(data.audio);
// Collects Save State Elements
save.set(data.state);
// Sets up ui
engine.uiAudio();
engine.uiControls();
});
},
handleResize : function(){
// Resizes stage
var win = $(window);
engine.paper.changeSize(win.width(), win.height(), true, false);
},
handleClick : function(elem){
if(elem.attr('fill') != color.active){
// Saves the previous state to the history stack
history.save(elem.id, elem.attr('fill'));
// Fill with active color
elem.attr('fill', color.active);
//Save ID & Color, eg:
//$.post("[url of save function]", { id : elem.id, color : color.active });
//console.log(elem.id + ' ' + color.active)
}
// Gets name, checks to see if there's audio associated with it
audio.check(elem.data("name"));
},
uiAudio : function(){
$('body').append('<div id="uiPop"></div>');
$('#uiPop').jPlayer({
ready : function(){
$(this).jPlayer('setMedia', {
wav: "cogs/audio/ui/pop.wav",
mp3: "cogs/audio/ui/pop.mp3"
});
},
swfPath: "cogs/scripts",
supplied: "wav, mp3",
wmode: "window"
});
},
uiControls : function(){
var buttonStyle = {
'stroke-width' : '5px',
'stroke' : '#d1d2d3',
'fill' : '#0082c8'
},
shadowStyle = {
'stroke-width' : '0',
'stroke' : 'transparent',
'fill' : 'r#666666-#73afdf'
},
iconStyle = {
'stroke-width' : '0',
'stroke' : 'transparent',
'fill' : '#fff'
}
// Home Button -----------------------------------------------
var homeButton = engine.paper.set();
// shadow
engine.paper.ellipse(895, 96, 40, 15).attr(shadowStyle);
// button
homeButton.push(engine.paper.ellipse(895, 60, 35, 35).attr(buttonStyle).attr('href','http://www.google.com'));
homeButton.push(engine.paper.path("M895.025,41.46L875,60.962h4.536v15.383c0,1.213,1.311,2.195,2.927,2.195h25.152 c1.617,0,2.928-0.982,2.928-2.195V60.962H915L895.025,41.46z").attr(iconStyle).attr('href','http://www.google.com'));
// events
homeButton.hover(function(){
homeButton[0].attr('stroke','#fff');
},function(){
homeButton[0].attr('stroke','#d1d2d3');
});
// -----------------------------------------------------------
// Sound Button ----------------------------------------------
var soundButton = engine.paper.set();
// shadow
engine.paper.ellipse(895, 296, 40, 15).attr(shadowStyle);
// button
soundButton.push(engine.paper.ellipse(895, 260, 35, 35).attr(buttonStyle));
soundButton.push(engine.paper.path("M920.156,260c0-13.871-11.284-25.156-25.156-25.156c-7.395,0-14.057,3.21-18.664,8.31 c-0.012,0.012-0.028,0.021-0.041,0.034c-0.07,0.07-0.134,0.147-0.186,0.228c-3.895,4.431-6.266,10.235-6.266,16.584 c0,13.871,11.286,25.156,25.156,25.156c6.294,0,12.053-2.328,16.47-6.164c0.132-0.068,0.26-0.149,0.368-0.261 c0.074-0.072,0.137-0.152,0.189-0.233C917.022,273.897,920.156,267.309,920.156,260z M917.283,260 c0,6.107-2.472,11.648-6.467,15.678l-31.494-31.494c4.03-3.994,9.57-6.466,15.678-6.466 C907.287,237.717,917.283,247.713,917.283,260z M872.718,260c0-5.146,1.759-9.884,4.697-13.66l31.246,31.245 c-3.775,2.938-8.517,4.698-13.661,4.698C882.714,282.283,872.718,272.286,872.718,260z").attr(iconStyle).hide());
soundButton.push(engine.paper.path("M904.188,255.004c-1.183-2.239-3.318-3.446-5.036-5.218c-1.323-1.365-2.391-2.973-2.918-4.813 c-0.073-0.261-0.371-1.102-0.391-1.632v-0.102c0.005-0.103,0.022-0.19,0.06-0.25c0,0-0.023,0.037-0.06,0.095v-0.095 c0-0.341-0.276-0.618-0.617-0.618s-0.618,0.276-0.618,0.618v27.036c-1.332-0.96-3.544-1.144-5.729-0.32 c-2.979,1.125-4.77,3.693-3.998,5.736c0.77,2.044,3.811,2.789,6.791,1.665c2.449-0.924,4.09-2.822,4.171-4.604 c0-0.001,0-0.002,0-0.002v-22.568l0.059,0.073c0.676,1.572,2.831,2.661,2.831,2.661c2.147,1.083,4.159,3.058,4.864,5.38 c0.625,2.059,0.271,4.383-0.497,6.356c-0.353,0.905-0.795,2.041-1.464,2.776c1.349-1.483,2.639-3.338,3.256-5.26 C905.643,259.583,905.321,257.152,904.188,255.004z").attr(iconStyle));;
// events
soundButton.hover(function(){
soundButton[0].attr('stroke','#fff');
},function(){
soundButton[0].attr('stroke','#d1d2d3');
}).click(function(){
if(audio.isOn){
audio.isOn = false;
soundButton[1].show();
}else{
audio.isOn = true;
soundButton[1].hide();
}
});
// -----------------------------------------------------------
// Clear Button ----------------------------------------------
var clearButton = engine.paper.set();
// shadow
engine.paper.ellipse(895, 396, 40, 15).attr(shadowStyle);
//button
clearButton.push(engine.paper.ellipse(895, 360, 35, 35).attr(buttonStyle))
clearButton.push(engine.paper.path("M899.326,343.448c0-2.286-1.989-2.286-1.989-2.286h-3.38c-2.585,0-2.286,2.286-2.286,2.286 H899.326z M906.085,344.84c0,0-18.49,0-22.565,0c-4.076,0-3.878,3.877-3.878,3.877h30.718 C910.359,344.542,906.085,344.84,906.085,344.84z M883.966,374.961c0.497,3.777,4.474,3.877,4.474,3.877h12.525 c4.672,0,5.069-4.075,5.069-4.075l2.784-24.355h-27.637C881.182,350.407,883.47,371.184,883.966,374.961z M901.411,353.741 c0.035-0.591,0.539-1.044,1.132-1.007c0.59,0.034,1.041,0.541,1.007,1.131l-1.158,19.947c-0.033,0.569-0.505,1.01-1.068,1.01 c-0.021,0-0.042-0.002-0.063-0.002c-0.59-0.034-1.041-0.541-1.007-1.132L901.411,353.741z M893.93,353.787 c0-0.592,0.479-1.071,1.071-1.071c0.591,0,1.07,0.479,1.07,1.071v19.98c0,0.591-0.479,1.071-1.07,1.071 c-0.593,0-1.071-0.48-1.071-1.071V353.787z M887.533,352.734c0.586-0.036,1.097,0.416,1.13,1.007l1.159,19.947 c0.034,0.591-0.416,1.098-1.007,1.132c-0.021,0-0.042,0.002-0.063,0.002c-0.563,0-1.035-0.44-1.068-1.01l-1.159-19.947 C886.491,353.275,886.942,352.769,887.533,352.734z").attr(iconStyle));
// events
clearButton.hover(function(){
clearButton[0].attr('stroke','#fff');
},function(){
clearButton[0].attr('stroke','#d1d2d3');
}).click(function(){
scene.colorable.attr('fill','#fff');
history.clear();
});
// -----------------------------------------------------------
// Undo Button -----------------------------------------------
var undoButton = engine.paper.set();
// shadow
engine.paper.ellipse(895, 496, 40, 15).attr(shadowStyle);
// button
undoButton.push(engine.paper.ellipse(895, 460, 35, 35).attr(buttonStyle));
undoButton.push(engine.paper.path("M917.962,441.608l-15.218-1.075l-1.074,15.219l6.732-5.843c2.508,3.128,3.88,6.97,3.88,11.048 c0,9.78-7.956,17.736-17.736,17.736c-9.779,0-17.736-7.956-17.736-17.736c0-4.736,1.846-9.189,5.195-12.541l-3.374-3.374 c-4.252,4.251-6.593,9.905-6.593,15.915c0,12.412,10.097,22.51,22.508,22.51c12.41,0,22.509-10.098,22.509-22.51 c0-5.244-1.776-10.189-5.038-14.186L917.962,441.608z").attr(iconStyle));
// events
undoButton.hover(function(){
undoButton[0].attr('stroke','#fff');
},function(){
undoButton[0].attr('stroke','#d1d2d3');
}).click(function(){
history.recall();
});
// -----------------------------------------------------------
}
}
// -------------------------------------------------------------------
// Handles colors
// -------------------------------------------------------------------
var color = {
active : Object,
list : Object,
set : function(array){
color.list = engine.paper.set();
var shadowStyle = {
'stroke-width' : '0',
'stroke' : 'transparent',
'fill' : 'r#666666-#73afdf'
}
// Displays Colors
for(var i = 0; i < array.length; i++){
// Shadows
var x = 96+(100*i);
engine.paper.ellipse(65, x, 40, 15).attr(shadowStyle)
var y = 60+(100*i);
color.list.push(
engine.paper.ellipse(65, y, 35, 35).attr({
'stroke-width' : '5px',
'stroke' : '#d1d2d3',
'fill' : '#'+array[i].hex
}).hover(function(){
this.attr('stroke','#fff')
}, function(){
if(!this.data('active')){
this.attr('stroke','#d1d2d3');
}
}).click(function(){
color.handleClick(this);
})
);
}
// Sets Active Color
color.active = '#'+array[0].hex
color.list[0].attr('stroke','#fff').data('active',true);
},
handleClick : function(elem){
color.active = elem.attr('fill');
color.list.attr('stroke','#d1d2d3').removeData('active');
elem.attr('stroke','#fff').data('active',true);
}
}
// -------------------------------------------------------------------
// Handles scene
// -------------------------------------------------------------------
var scene = {
outlines : Object,
colorable : Object,
set : function(array){
// Initializes the sets
scene.outlines = engine.paper.set();
scene.colorable = engine.paper.set();
// Draws Objects, puts outlines in one set, colorable items in the other
for(var i = 0; i < array.length; i++){
if(array[i].colorable == 'true'){
scene.colorable.push(
eval('engine.paper.' + array[i].type +'('+array[i].coords+').data("name","'+array[i].name+'")')
);
}else{
scene.outlines.push(
eval('engine.paper.' + array[i].type +'('+array[i].coords+')')
);
}
}
// Colors the outlines
scene.outlines.attr({
'fill' : '#000',
'stroke' : 'transparent',
'stroke-width' : 0
});
// Colors the colorable items
scene.colorable.attr({
'fill' : '#fff',
'stroke' : 'transparent',
'stroke-width' : 0
});
// Listens for clicks on the colorable items
scene.colorable.forEach(function(e){
e.click(function(){
engine.handleClick(this);
});
});
// Shifts elements over
engine.paper.forEach(function(elem){
elem.translate(130,0);
});
}
}
// -------------------------------------------------------------------
// Sets up audio
// -------------------------------------------------------------------
var audio = {
collection : [],
isOn : true,
set : function(array){
for(var i = 0; i < array.length; i++){
var a = array[i].wav,
b = array[i].mp3,
id = 'audio_'+i,
rel = array[i].rel;
$('body').append('<div id='+id+'></div>');
$('#'+id).jPlayer({
ready : function(){
$(this).jPlayer('setMedia', {
wav: a,
mp3: b
});
},
play : function(){
$(this).jPlayer("pauseOthers");
},
swfPath: "cogs/scripts",
supplied: "wav, mp3",
wmode: "window"
});
audio.collection.push({
"rel" : rel,
"id" : id
});
}
},
check : function(name){
var audID,
play = false;
for(var i = 0; i < audio.collection.length; i++){
if(audio.collection[i].rel == name){
audID = audio.collection[i].id;
play = true;
}
}
if(play && audio.isOn){
$('#'+audID).jPlayer('play');
}else if(audio.isOn){
$('#uiPop').jPlayer('play');
}
}
}
// -------------------------------------------------------------------
// Handles Saved data
// -------------------------------------------------------------------
var save = {
set : function(array){
for(var i = 0; i < array.length; i++){
// Gets elements by saved ID, sets color to saved color
engine.paper.getById(array[i].id).attr('fill',array[i].color)
}
}
}
// -------------------------------------------------------------------
// History
// -------------------------------------------------------------------
var history = {
stack : [],
save : function(id, color){
// Pushes state onto the stack
history.stack.push({
"id" : id,
"color" : color
});
},
recall : function(){
// Recalls previous state
if(history.stack.length){
var prev = history.stack.pop()
engine.paper.getById(prev.id).attr({
fill : prev.color
})
}
},
clear : function(){
// Clears history
history.stack.length = 0;
}
}
// -------------------------------------------------------------------
// Start
// -------------------------------------------------------------------
$(function(){
engine.prime();
engine.load('cogs/scenes/choking2.json');
})
// -------------------------------------------------------------------
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T21:07:45.333",
"Id": "17421",
"Score": "0",
"body": "please put the code inline in the question (as per the faq)"
}
] |
[
{
"body": "<p>First of all, the best way to optimize any code is to run it through a profiler to find the bottlenecks.</p>\n\n<p>Assuming you've already done that, here are a couple <em>very</em> minor things:</p>\n\n<ol>\n<li><p>This code:</p>\n\n<pre><code>for(var i = 0; i < array.length; i++){\n</code></pre>\n\n<p>results in the <code>length</code> property being queried on each iteration. Obviously this won't amount to much difference if the number of iterations is small, but as a general rule I try to always cache the value:</p>\n\n<pre><code>for(var i = 0, len = array.length; i < len; i++){\n</code></pre>\n\n<p>And you should be caching property accesses on any objects if you use them in multiple places. For example, instead of using <code>array[i]</code> in several places within a loop, store it in a variable and use the variable instead.</p></li>\n<li><p>I'm not sure how expensive multiplication is compared to addition in JS (and again, if <code>array.length</code> is a small value this won't make a difference), but instead of calculating this value every iteration:</p>\n\n<pre><code>var x = 96+(100*i);\n</code></pre>\n\n<p>You could just increment it within the loop:</p>\n\n<pre><code>var len = array.length;\nfor(var i = 0, j = 0; i < len; i++, j += 100){\n var x = 96 + j;\n var y = 60 + j;\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T14:46:15.500",
"Id": "17447",
"Score": "1",
"body": "Thanks a lot for the suggestions! I ran this test for multiplication vs. addition: http://jsperf.com/addition-vs-multiplication, look like multiplication is faster, at least in Chrome."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T15:05:44.007",
"Id": "17451",
"Score": "0",
"body": "Nice! Very interesting..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T22:01:04.673",
"Id": "10968",
"ParentId": "10959",
"Score": "1"
}
},
{
"body": "<p>I agree with seand above, I would also add:</p>\n\n<pre><code>$(window).resize(engine.handleResize); \n</code></pre>\n\n<p>This might results in more resize events then you would expect, as the user resizes the window many events will be triggered causing needless updates. Coincidently I just released a helper to solve this exact problem, you can see it in action here: <a href=\"http://limit.gotsomething.com\" rel=\"nofollow\">http://limit.gotsomething.com</a></p>\n\n<p>Another (and this is really a preference) is rather than have various colors sprinkled through your code it might be best to declare them all in one spot. Making updating the UI much easier (especially for non developers)</p>\n\n<p>Lastly, your stack for history is a nice feature, however you might consider future proofing it a bit by not only storing the colour but the attribute/method itself. This way should you introduce the ability to change stroke, opacity etc. it will be supported. Just a thought.</p>\n\n<p>Regardless, neat app and the code overall is very good!</p>\n\n<p>Marc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T14:51:17.270",
"Id": "17448",
"Score": "0",
"body": "Thanks a lot for your suggestions. Your limit helper is pretty slick, I'm sharing it with my coworkers!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T22:52:12.677",
"Id": "10969",
"ParentId": "10959",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T19:05:47.810",
"Id": "10959",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"optimization",
"svg",
"raphael.js"
],
"Title": "Optimize coloring book built with Raphaël and jQuery"
}
|
10959
|
<p>I've been working on a lightweight XML schema parser, and have what I think is a moderately clean solution (some parts helped out by previous questions I posted here) so far for obtaining all schema details, but would like any criticism at all that could help further improve this code.</p>
<p>Below I have supplied the schema class I wrote, and then an example schema.txt file that the schema class will open if run as main. The schema class calls under "main" can be modified if you want to get a better look at the schema data structure, and I have some accompanying functions I have written for the class to pull out specific details that I haven't put here because I still need to do some work on them.</p>
<p><strong>schema.py:</strong></p>
<pre class="lang-python prettyprint-override"><code>from lxml import etree
INDICATORS = ["all", "sequence", "choice"]
TYPES = ["simpleType", "complexType"]
class schema:
def __init__(self, schemafile):
if schemafile is None:
print "Error creating Schema: Invalid schema file used"
return
self.schema = self.create_schema(etree.parse(schemafile))
def create_schema(self, schema_data):
def getXSVal(element): #removes namespace
return element.tag.split('}')[-1]
def get_simple_type(element):
return {
"name": element.get("name"),
"restriction": element.getchildren()[0].attrib,
"elements": [ e.get("value") for e in element.getchildren()[0].getchildren() ]
}
def get_simple_content(element):
return {
"simpleContent": {
"extension": element.getchildren()[0].attrib,
"attributes": [ a.attrib for a in element.getchildren()[0].getchildren() ]
}
}
def get_elements(element):
if len(element.getchildren()) == 0:
return element.attrib
data = {}
ename = element.get("name")
tag = getXSVal(element)
if ename is None:
if tag == "simpleContent":
return get_simple_content(element)
elif tag in INDICATORS:
data["indicator"] = tag
elif tag in TYPES:
data["type"] = tag
else:
data["option"] = tag
else:
if tag == "simpleType":
return get_simple_type(element)
else:
data.update(element.attrib)
data["elements"] = []
data["attributes"] = []
children = element.getchildren()
for child in children:
if child.get("name") is not None:
data[getXSVal(child)+"s"].append(get_elements(child))
elif tag in INDICATORS and getXSVal(child) in INDICATORS:
data["elements"].append(get_elements(child))
else:
data.update(get_elements(child))
if len(data["elements"]) == 0:
del data["elements"]
if len(data["attributes"]) == 0:
del data["attributes"]
return data
schema = {}
root = schema_data.getroot()
children = root.getchildren()
for child in children:
c_type = getXSVal(child)
if child.get("name") is not None and not c_type in schema:
schema[c_type] = []
schema[c_type].append(get_elements(child))
return schema
def get_Types(self, t_name):
types = []
for t in self.schema[t_name]:
types.append(t["name"])
return types
def get_simpleTypes(self):
return self.get_Types("simpleType")
def get_complexTypes(self):
return self.get_Types("complexType")
if __name__ == '__main__':
fschema = open("schema.txt")
schema = schema(fschema)
print schema.get_simpleTypes()
print schema.get_complexTypes()
</code></pre>
<p><strong>schema.txt:</strong></p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" version="3.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="main_object">
<xs:complexType>
<xs:choice maxOccurs="unbounded">
<xs:element minOccurs="1" maxOccurs="1" name="source">
<xs:complexType>
<xs:all>
<xs:element name="name" type="xs:string" />
<xs:element name="group_id" type="xs:integer" />
<xs:element minOccurs="0" name="description" type="xs:string" />
</xs:all>
<xs:attribute name="id" type="xs:integer" use="required" />
</xs:complexType>
</xs:element>
<xs:element minOccurs="1" maxOccurs="1" name="event">
<xs:complexType>
<xs:all>
<xs:element name="date" type="xs:date" />
<xs:element minOccurs="0" name="event_type" type="xs:string" />
<xs:element minOccurs="0" name="event_hours" type="xs:string" />
</xs:all>
<xs:attribute name="id" type="xs:integer" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="state">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
</xs:sequence>
<xs:attribute name="id" type="xs:integer" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="location">
<xs:complexType>
<xs:all>
<xs:element name="address" type="simpleAddressType" />
<xs:element minOccurs="0" name="directions" type="xs:string" />
<xs:element minOccurs="0" name="hours" type="xs:string" />
</xs:all>
<xs:attribute name="id" type="xs:integer" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="selection_item">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs="0" name="selection_type_id" type="xs:integer" />
<xs:element minOccurs="0" maxOccurs="unbounded" name="option_id">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:integer">
<xs:attribute name="sort_order" type="xs:integer" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="id" type="xs:integer" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="custom_selection">
<xs:complexType>
<xs:choice maxOccurs="unbounded">
<xs:element name="heading" type="xs:string" />
<xs:sequence maxOccurs="unbounded">
<xs:element name="response_id">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:integer">
<xs:attribute name="sort_order" type="xs:integer" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:choice>
<xs:attribute name="id" type="xs:integer" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="response">
<xs:complexType>
<xs:all>
<xs:element name="text" type="xs:string" />
<xs:element minOccurs="0" name="sort_order" type="xs:integer" />
</xs:all>
<xs:attribute name="id" type="xs:integer" use="required" />
</xs:complexType>
</xs:element>
</xs:choice>
<xs:attribute fixed="3.0" name="schemaVersion" type="xs:decimal" use="required" />
</xs:complexType>
</xs:element>
<xs:complexType name="simpleAddressType">
<xs:all>
<xs:element minOccurs="0" name="location_name" type="xs:string"/>
<xs:element name="line1" type="xs:string"/>
<xs:element minOccurs="0" name="line2" type="xs:string"/>
<xs:element minOccurs="0" name="line3" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="state" type="xs:string"/>
<xs:element name="zip" type="xs:string"/>
</xs:all>
</xs:complexType>
<xs:complexType name="certified">
<xs:simpleContent>
<xs:extension base="xs:integer">
<xs:attribute name="certification" type="certificationEnum" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<xs:simpleType name="certificationEnum">
<xs:restriction base="xs:string">
<xs:enumeration value="unofficial_partial"/>
<xs:enumeration value="unofficial_complete"/>
<xs:enumeration value="certified"/>
<xs:enumeration value="Unofficial_partial"/>
<xs:enumeration value="Unofficial_complete"/>
<xs:enumeration value="Unofficial_Partial"/>
<xs:enumeration value="Unofficial_Complete"/>
<xs:enumeration value="Certified"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="yesNoEnum">
<xs:restriction base="xs:string">
<xs:enumeration value="yes"/>
<xs:enumeration value="no"/>
<xs:enumeration value="Yes"/>
<xs:enumeration value="No"/>
<xs:enumeration value="YES"/>
<xs:enumeration value="NO"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T02:10:02.910",
"Id": "18109",
"Score": "0",
"body": "You're kind of reinventing the wheel, IMO. Have you seen http://www.aaronsw.com/2002/xmltramp/ ?"
}
] |
[
{
"body": "<p>Well, your code is amazing in that it proves you can handle the most commonly used 10% subset of XML Schema in a few dozen lines of code. But where are you planning to go with this? As you try to increase your coverage of XSD features, your design won't scale. Perhaps that doesn't matter - there's no harm in starting small and being prepared to refactor as it grows.</p>\n\n<p>From my own experience of writing a schema processor, I would recommend keeping a close correspondence between the architecture of your code and the architecture of the spec. That is, implement a data structure corresponding to the schema component model described in the spec; have a process that constructs the SCM from the raw XML representation, and that enforces all the XML representation constraints; have another process that examines the SCM for consistency (enforcing the SCM component constraints), and then another process that's concerned with using the SCM for validation, including generating a finite state automaton or whatever. You can still do it incrementally, of course (e.g leave out named model groups, attribute groups, substitution groups, etc initially) but it's probably a good idea to get the overall structure in place early.</p>\n\n<p>I would follow the XSD 1.1 spec rather than XSD 1.0, partly because the new features are nice for users, but also because the spec is much clearer - still dense, but now penetrable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T15:13:10.513",
"Id": "17455",
"Score": "0",
"body": "I think I am following a similar approach to what you are mentioning. I am writing a class and series of helper method to parse the schema itself, and then quickly access all underlying attributes. This is for a personal project, but I would like to try to make this go farther, so I think I might need to introduce classes for simpleContent, and other types for this to scale better. I think I am somewhat following your approach, I use this to parse XML docs, produce flat files from them, validate database data according to the schema, and a few other tasks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T08:08:09.857",
"Id": "10983",
"ParentId": "10960",
"Score": "2"
}
},
{
"body": "<pre><code>from lxml import etree\n\nINDICATORS = [\"all\", \"sequence\", \"choice\"]\nTYPES = [\"simpleType\", \"complexType\"]\n\nclass schema:\n</code></pre>\n\n<p>Python convention is to name classes using CamelCase.</p>\n\n<pre><code> def __init__(self, schemafile):\n if schemafile is None:\n print \"Error creating Schema: Invalid schema file used\"\n return\n</code></pre>\n\n<p>Use exceptions report errors in python. Don't print problems to standard output and then try to continue. Nothing good will come of it. Actually, you don't even need to check for None, because it'll fail on the next line anyways.</p>\n\n<pre><code> self.schema = self.create_schema(etree.parse(schemafile))\n\n def create_schema(self, schema_data):\n def getXSVal(element): #removes namespace\n return element.tag.split('}')[-1]\n</code></pre>\n\n<p>Shouldn't you at least verify that the namespace was correct?</p>\n\n<pre><code> def get_simple_type(element):\n return {\n \"name\": element.get(\"name\"),\n \"restriction\": element.getchildren()[0].attrib,\n \"elements\": [ e.get(\"value\") for e in element.getchildren()[0].getchildren() ]\n }\n</code></pre>\n\n<p>It looks like you are using a dictionary like an object. Perhaps you should actually be creating a SimpleType object with these attributes.</p>\n\n<pre><code> def get_simple_content(element):\n return {\n \"simpleContent\": {\n \"extension\": element.getchildren()[0].attrib,\n \"attributes\": [ a.attrib for a in element.getchildren()[0].getchildren() ]\n }\n }\n\n def get_elements(element):\n</code></pre>\n\n<p>I've go no idea what this function is trying to do</p>\n\n<pre><code> if len(element.getchildren()) == 0:\n return element.attrib\n\n data = {}\n\n ename = element.get(\"name\")\n tag = getXSVal(element)\n\n if ename is None:\n</code></pre>\n\n<p>It seems strange that you check for the name, but don't do anything with it</p>\n\n<pre><code> if tag == \"simpleContent\":\n return get_simple_content(element)\n</code></pre>\n\n<p>Its confusing the way you sometimes return something, other times you add into a dictionary. </p>\n\n<pre><code> elif tag in INDICATORS:\n data[\"indicator\"] = tag\n elif tag in TYPES:\n data[\"type\"] = tag\n else:\n data[\"option\"] = tag\n\n else:\n if tag == \"simpleType\":\n return get_simple_type(element)\n else: \n data.update(element.attrib)\n</code></pre>\n\n<p>I don't really follow what the theory for this condition is. I do see the same code showing up multiple times which makes me wonder if it can be refactored to be cleaner.</p>\n\n<pre><code> data[\"elements\"] = []\n data[\"attributes\"] = []\n children = element.getchildren() \n\n for child in children:\n</code></pre>\n\n<p>Combine the last two lines</p>\n\n<pre><code> if child.get(\"name\") is not None:\n data[getXSVal(child)+\"s\"].append(get_elements(child))\n elif tag in INDICATORS and getXSVal(child) in INDICATORS:\n data[\"elements\"].append(get_elements(child))\n else:\n data.update(get_elements(child))\n\n if len(data[\"elements\"]) == 0:\n del data[\"elements\"]\n if len(data[\"attributes\"]) == 0:\n del data[\"attributes\"]\n</code></pre>\n\n<p>Do you really want to do this? It seems to me that it'll make code harder to write that uses the data</p>\n\n<pre><code> return data\n</code></pre>\n\n<p>These long function as inner functions smell bad. The suggest perhaps they should be in another class or something.</p>\n\n<pre><code> schema = {}\n root = schema_data.getroot()\n children = root.getchildren()\n for child in children:\n c_type = getXSVal(child)\n if child.get(\"name\") is not None and not c_type in schema:\n schema[c_type] = []\n</code></pre>\n\n<p>If the name is None, won't that cause the next line to have an error?</p>\n\n<pre><code> schema[c_type].append(get_elements(child))\n</code></pre>\n\n<p>Instead use <code>schema.setdefault(c_type,[]).append(get_elements(child))</code> it'll take care adding the list the first time you append.</p>\n\n<pre><code> return schema\n\n def get_Types(self, t_name):\n</code></pre>\n\n<p>Python convetion is lowercase_with_underscores for method names</p>\n\n<pre><code> types = []\n for t in self.schema[t_name]:\n types.append(t[\"name\"])\n return types\n</code></pre>\n\n<p>I'd use <code>return [t[\"name\"] for t in self.schema[t_name]]</code></p>\n\n<pre><code> def get_simpleTypes(self):\n return self.get_Types(\"simpleType\")\n\n def get_complexTypes(self):\n return self.get_Types(\"complexType\")\n\n\nif __name__ == '__main__':\n fschema = open(\"schema.txt\")\n</code></pre>\n\n<p>I suggest using with to make sure it gets closed</p>\n\n<pre><code> schema = schema(fschema)\n\n print schema.get_simpleTypes()\n print schema.get_complexTypes()\n</code></pre>\n\n<p>My overall problem with your approach is that you are converting the xml schema into a bunch of unstructured dictionaries. The result isn't going to be much easier to work then the original XML objects. It's gonna be a real pain writing code to work with the schema representation you've produced. Without knowing the overall goal of why you are parsing the schema, I can't really suggest how to improve it.</p>\n\n<p>On your new vesrion</p>\n\n<pre><code> try:\n self.schema = self.create_schema(etree.parse(schemafile))\n except:\n print \"Error creating Schema: Invalid schema file used\"\n</code></pre>\n\n<p>NO! Don't catch the exception. Let the program just die. Never ever ever ever just print to the screen where an error happens. </p>\n\n<p>Here my version of what you've done. </p>\n\n<pre><code>from lxml import etree\nfrom copy import copy\nSCHEMA_SPACE = \"{http://www.w3.org/2001/XMLSchema}\"\n\nclass Schema:\n\n def __init__(self, schemafile):\n self.root = etree.parse(schemafile)\n\n def findall(self, path):\n return self.root.findall( path.replace(\"xs:\", SCHEMA_SPACE) )\n\n def find(self, path):\n return self.root.find( path.replace(\"xs:\", SCHEMA_SPACE) )\n\n def names_of(self, nodes):\n return [node.get(\"name\") for node in nodes]\n\n def get_Types(self, t_name):\n return self.names_of( self.findall(t_name) ) \n\n def get_simpleTypes(self):\n return self.get_Types(\"xs:simpleType\")\n\n def get_complexTypes(self):\n return self.get_Types(\"xs:complexType\")\n\n def get_elements_of_attribute(self, attribute):\n return self.names_of(self.findall(\".//xs:element/xs:complexType/xs:\" + attribute + \"/../..\"))\n\n def get_element_attributes(self, name): \n\n node = self.find(\".//xs:element[@name='\" + name + \"']\")\n if node is None:\n node = self.find(\".//xs:complexType[@name='\" + name + \"']\")\n\n if node is None:\n return None\n else:\n return node.attrib\n\n\nif __name__ == '__main__':\n with open(\"schema.txt\") as f:\n\n schema = Schema(f)\n\n print schema.get_simpleTypes()\n print schema.get_complexTypes()\n print schema.get_elements_of_attribute(\"all\")\n\n print schema.get_element_attributes(\"source\")\n print schema.get_element_attributes(\"contact_id\")\n</code></pre>\n\n<p>Copying all the data into python dictionaries is not helping. It is much easier to extract this information directly from the XML. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T15:38:09.047",
"Id": "17459",
"Score": "0",
"body": "Thanks for all your suggestions. Stuff I agree and changed: camel case class names, starting exception, all code consolidation suggestions, probably classes for simpleType and simpleContent objects. Stuff I should explain more: This is the core data structure, I wrote a bunch of helper methods to quickly access all properties contained within to parse XML docs, produce flat files from them, validate database data according to the schema, and some other stuff. The dictionary/sometime distinction is done based on whether the object is a property of the root element or is a new element itself"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T15:45:49.210",
"Id": "17460",
"Score": "0",
"body": "Hopefully that explains most of the conditions, also why frequently \"name\" is ignored. The inner class function get_element had to be recursive and check all conditions but you are right, I could parse out some of the logic. You mentioned repeated code but I couldn't find another place where I use that conditional logic in this code segment, am I missing something obvious? I changed \"get_Type\" to \"get_type\", original used because the xsd standards for \"simpleType\" and \"complexType\" are written like that. Given this, do you have other suggestions on how I could better handle the parsing logic?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T15:49:36.897",
"Id": "17461",
"Score": "0",
"body": "@MikeJ, re code-duplication: upon a second look, I just can't read. To give any better suggestions, I'd have to see how you are using this data structure you are constructing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T19:29:48.120",
"Id": "17475",
"Score": "0",
"body": "I added in more of the helper functions I had written and more example function calls to hopefully show a better idea of the how I'm using this data structure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T17:37:52.197",
"Id": "17604",
"Score": "0",
"body": "@MikeJ, see edit. Basically, your data structure isn't helping you perform any of those tasks. Its actually easy to extract from the original xml document."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T14:46:02.223",
"Id": "10989",
"ParentId": "10960",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "10989",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T21:11:22.230",
"Id": "10960",
"Score": "3",
"Tags": [
"python",
"parsing",
"xml",
"xsd"
],
"Title": "XML schema parser"
}
|
10960
|
RaphaëlJS is a cross-browser JavaScript library that draws vector graphics for web sites. It uses SVG for most browsers and VML for older versions of Internet Explorer.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T21:32:39.297",
"Id": "10963",
"Score": "0",
"Tags": null,
"Title": null
}
|
10963
|
<p>SVG is a platform for two-dimensional graphics. It has two parts: an XML-based file format and a programming API for graphical applications. Key features include shapes, text and embedded raster graphics, with many different painting styles. It supports scripting through languages such as ECMAScript and has comprehensive support for animation.</p>
<p>SVG is used in many business areas including Web graphics, animation, user interfaces, graphics interchange, print and hardcopy output, mobile applications and high-quality design. All major modern web browsers have at least some degree of support and render SVG markup directly, including Mozilla Firefox, Internet Explorer 9, Google Chrome, Opera, and Safari. Earlier versions of Microsoft Internet Explorer (IE) do not support SVG natively.</p>
<p><a href="http://www.w3.org/Graphics/SVG/About.html" rel="nofollow">More about SVG from W3C</a></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial" rel="nofollow">Mozilla Developer Network SVG tutorial</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T21:35:55.440",
"Id": "10964",
"Score": "0",
"Tags": null,
"Title": null
}
|
10964
|
XML Schema Document (XSD) is a document written in the XML Schema language, typically containing the "xsd" XML namespace prefix and stored with the ".xsd" filename extension. It can be used to express a set of rules to which an XML document must conform in order to be considered 'valid' according to that schema.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T21:38:19.117",
"Id": "10967",
"Score": "0",
"Tags": null,
"Title": null
}
|
10967
|
<p>A best practice is a method or technique that is generally considered to be superior to other methods in achieving the same result. In the context of Code Review, questions with the <a href="/questions/tagged/best-practice" class="post-tag" title="show questions tagged 'best-practice'" rel="tag">best-practice</a> tag generally involve a short excerpt of code with a question of general interest, usually focused more on maintainability concerns than the algorithm to solve the task at hand.</p>
<p>Note, however, that questions must include a real code excerpt (as per the <a href="http://meta.codereview.stackexchange.com/help/on-topic">site rules</a>) and sufficient context for reviewers to make specific recommendations relevant to your situation. Questions in which the code has been stripped down to a hypothetical situation will likely be closed as off-topic.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T00:43:23.083",
"Id": "10971",
"Score": "0",
"Tags": null,
"Title": null
}
|
10971
|
Best-practice questions generally involve a short excerpt of code with a question of general interest, usually focused more on maintainability concerns than the algorithm to solve the task at hand. Note that questions must include a real code excerpt and sufficient context for reviewers to make specific recommendations relevant to your situation; hypothetical questions are off-topic for Code Review.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T00:43:23.083",
"Id": "10972",
"Score": "0",
"Tags": null,
"Title": null
}
|
10972
|
<p>I've built this two classes for a Poker game on Android and I would appreciate some feedback on my code.</p>
<p>Have no mercy. The harsher you are, the better.</p>
<p>Feel free to add your number of WTFs/minute.</p>
<p><strong>PokerHand.java</strong></p>
<pre><code>package com.poker.util;
import java.util.Arrays;
import java.util.Collections;
public class PokerHand implements Comparable<PokerHand> {
public static final int NUM_CARDS = 5;
public enum Strength {
HIGH_CARD, ONE_PAIR, TWO_PAIR, THREE_OF_A_KIND, STRAIGHT, FLUSH, FULL_HOUSE, FOUR_OF_A_KIND, STRAIGHT_FLUSH
}
/**
* array of cards sorted descending
*/
public Card[] cards;
protected Strength strength = null;
/**
* <b>int strenghtValue</b> has 4 bits per relevant card<br>
* <br>
* It is used to differentiate between two hands of the same strength<br>
* <br>
* For example if the hand strength == TWO_PAIR<br>
* c0 will be the top pair and c1 will be the bottom pair
* <table border="0" bordercolor="#FFCC00" style="background-color:#FFFFCC" width="400" cellpadding="3" cellspacing="3">
* <tr>
* <td>strenghtValue</td>
* <td>0000</td>
* <td>0000</td>
* <td>0000</td>
* <td>0000</td>
* <td>0000</td>
* <td>0000</td>
* <td>0000</td>
* <td>0000</td>
* </tr>
* <tr>
* <td>index</td>
* <td></td>
* <td></td>
* <td></td>
* <td>c0</td>
* <td>c1</td>
* <td>c2</td>
* <td>c3</td>
* <td>c4</td>
* </tr>
* </table>
* <br>
* Where c0 is the most important rank
*/
private int strengthValue = 0;
private static final int[] MASK_CARD = { 0x000F0000, 0x0000F000,
0x00000F00, 0x000000F0, 0x0000000F };
public PokerHand(Card c1, Card c2, Card c3, Card c4, Card c5) {
cards = new Card[NUM_CARDS];
this.cards[0] = c1;
this.cards[1] = c2;
this.cards[2] = c3;
this.cards[3] = c4;
this.cards[4] = c5;
Arrays.sort(cards,Collections.reverseOrder());
evaluateSrenght();
}
public PokerHand(int c1, int c2, int c3, int c4, int c5) {
cards = new Card[NUM_CARDS];
this.cards[0] = new Card(c1);
this.cards[1] = new Card(c2);
this.cards[2] = new Card(c3);
this.cards[3] = new Card(c4);
this.cards[4] = new Card(c5);
Arrays.sort(cards,Collections.reverseOrder());
evaluateSrenght();
}
public int compareTo(PokerHand hand) {
if (this.getStrength().compareTo(hand.getStrength()) > 0)
return 1;
if (this.getStrength().compareTo(hand.getStrength()) < 0)
return -1;
if (strengthValue > hand.strengthValue)
return 1;
if (strengthValue < hand.strengthValue)
return -1;
return 0;
}
public static int compare(PokerHand h1, PokerHand h2) {
return h1.compareTo(h2);
}
public Strength getStrength() {
return strength;
}
public int getStrenghtValue(int index)
throws IndexOutOfBoundsException{
if (!( index>=0 && index<=4) )
throw new IndexOutOfBoundsException("Index should be between 0 and 4");
return (strengthValue | MASK_CARD[index]) >> ((5 - index) * 4);
}
/**
* should be called only once per index
*
* @param index
* <br>
* <table border="0" bordercolor="#FFCC00" style="background-color:#FFFFCC" width="400" cellpadding="3" cellspacing="3">
* <tr>
* <td>strenghtValue</td>
* <td>0000</td>
* <td>0000</td>
* <td>0000</td>
* <td>0000</td>
* <td>0000</td>
* <td>0000</td>
* <td>0000</td>
* <td>0000</td>
* </tr>
* <tr>
* <td>index</td>
* <td></td>
* <td></td>
* <td></td>
* <td>0</td>
* <td>1</td>
* <td>2</td>
* <td>3</td>
* <td>4</td>
* </tr>
* </table>
* @param value
* 4-bit value to set
*/
private void setSrengthValue(int index, int value)
throws IndexOutOfBoundsException,RuntimeException{
if (!( index>=0 && index<=4) )
throw new IndexOutOfBoundsException("Index should be between 0 and 4");
if (value > 0xF)
throw new RuntimeException("Value should be between 0 and 15");
strengthValue |= (value << ((5 - index) * 4));
}
private void evaluateSrenght() {
int numPairs=0;
//assumes cards[] are sorted descending
if (isStraightFlush()) {
strength = Strength.STRAIGHT_FLUSH;
//check for 5-high straight A-5-4-3-2
if (cards[1].rank == Card.Ranks.FIVE.rank)
setSrengthValue(0, cards[1].rank);
else
setSrengthValue(0, cards[0].rank);
}
else if (isFourOfAKind()) {
strength = Strength.FOUR_OF_A_KIND;
setSrengthValue(0, cards[1].rank);
}
else if (isFullHouse()) {
strength = Strength.FULL_HOUSE;
setSrengthValue(0, cards[2].rank);
if (cards[2].rank == cards[0].rank)
setSrengthValue(1, cards[3].rank);
else
setSrengthValue(1, cards[0].rank);
}
else if (isFlush()){
strength = Strength.FLUSH;
for (int i=0; i>NUM_CARDS; i++)
setSrengthValue(i, cards[i].rank);
}
else if (isStraight()){
strength = Strength.STRAIGHT;
//check for 5-high straight A-5-4-3-2
if (cards[1].rank == Card.Ranks.FIVE.rank)
setSrengthValue(0, cards[1].rank);
else
setSrengthValue(0, cards[0].rank);
}
else if (isThreeOfAKind()){
strength = Strength.THREE_OF_A_KIND;
setSrengthValue(0, cards[2].rank);
}
else if ( ( numPairs = getNumPairs()) == 2 ) {
strength = Strength.TWO_PAIR;
setSrengthValue(0, cards[1].rank);
setSrengthValue(1, cards[3].rank);
}
else if (numPairs == 1){
strength = Strength.ONE_PAIR;
for (int i=0; i < NUM_CARDS-1; i++)
if (cards[i].rank == cards[i+1].rank){
setSrengthValue(0, cards[i].rank);
break;
}
}
else{
strength = Strength.HIGH_CARD;
for (int i=0; i>NUM_CARDS; i++)
setSrengthValue(i, cards[i].rank);
}
}
/*
* All methods bellow should be called only after the cards array was sorted
*/
private int getNumPairs() {
int pairs = 0;
for (int i = 0; i < NUM_CARDS; i++)
if (cards[i].rank == cards[i + 1].rank)
pairs++;
return pairs;
}
private boolean isThreeOfAKind() {
for (int i = 0; i < NUM_CARDS - 2; i++)
if (cards[i].rank == cards[i+1].rank &&
cards[i].rank == cards[i+2].rank)
return true;
return false;
}
private boolean isStraight() {
//check for 5=high straight A-5-4-3-2
int start = (cards[0].rank==Card.Ranks.ACE.rank &&
cards[1].rank==Card.Ranks.FIVE.rank)
? 1 : 0;
for(int i=start; i< NUM_CARDS - 1; i++){
if ( cards[i].rank - cards[i+1].rank != 1)
return false;
}
return true;
}
private boolean isFlush() {
for (int i = 0; i < NUM_CARDS - 1; i++)
if (cards[i].suit != cards[i + 1].suit)
return false;
return true;
}
private boolean isFullHouse( ) {
if (cards[1].rank == cards[2].rank)
return ( cards[0].rank == cards[1].rank &&
cards[1].rank == cards[2].rank &&
cards[3].rank == cards[4].rank );
else
return ( cards[0].rank == cards[1].rank &&
cards[2].rank == cards[3].rank &&
cards[3].rank == cards[4].rank );
}
private boolean isFourOfAKind( ) {
if (cards[0].rank != cards[1].rank)
return ( cards[1].rank == cards[2].rank &&
cards[2].rank == cards[3].rank &&
cards[3].rank == cards[4].rank );
else
return ( cards[0].rank == cards[1].rank &&
cards[1].rank == cards[2].rank &&
cards[2].rank == cards[3].rank );
}
private boolean isStraightFlush( ) {
return isStraight() && isFlush();
}
}
</code></pre>
<p><strong>Card.java</strong></p>
<pre><code>package com.poker.util;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
public class Card implements Comparable<Card> {
public enum Suit {
HEARTS, SPADES, DIAMONS, CLUBS;
public static Suit fromCode(int c) {
int i = c / 4;
return ((i >= 2) ? (i == 3 ? CLUBS : DIAMONS) : (i == 1 ? SPADES : HEARTS));
}
}
public enum Ranks {
DEUCE(0),
THREE(1),
FOUR(2),
FIVE(3),
SIX(4),
SEVEN(5),
EIGHT(6),
NINE(7),
TEN(8),
JACK(9),
QUEEN(10),
KING(11),
ACE(12);
private static final Map<Integer, Ranks> lookup = new HashMap<Integer, Ranks>();
static {
for (Ranks s : EnumSet.allOf(Ranks.class))
lookup.put(s.rank, s);
}
public final int rank;
private Ranks(int rank) {
this.rank = rank;
}
public static Ranks fromCode(int code) {
return lookup.get(code%13);
}
public static Ranks fromRank(int rank) {
return lookup.get(rank);
}
}
/**
* int from 0 to 51 inclusive represinting a card
*/
public final int code;
public final int rank;
public final Suit suit;
public Card(int code) {
this.code = code;
this.rank = (code % 13);
this.suit = Suit.fromCode(code);
}
public String toString() {
return Ranks.fromCode(code) + " of " + suit;
}
public int compareTo(Card card) {
return this.rank - card.rank;
}
}
</code></pre>
<p>Also let me know if I should remove the long Javadoc comments from the source. I figured if anyone wants to copy paste in Eclipse, it would be helpful. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T09:27:48.183",
"Id": "17437",
"Score": "1",
"body": "No Royal Flush? :)"
}
] |
[
{
"body": "<p>You could try drying it a little bit,</p>\n\n<pre><code>public init(Card c1, Card c2, Card c3, Card c4, Card c5) {\n cards = new Card[NUM_CARDS];\n this.cards[0] = c1;\n this.cards[1] = c2;\n this.cards[2] = c3;\n this.cards[3] = c4;\n this.cards[4] = c5;\n Arrays.sort(cards,Collections.reverseOrder());\n evaluateSrenght();\n}\n\n\npublic PokerHand(Card c1, Card c2, Card c3, Card c4, Card c5) {\n init(c1, c2, c3, c4, c5);\n}\npublic PokerHand(int c1, int c2, int c3, int c4, int c5) {\n init(new Card(c1), new Card(c2), new Card(c3), new Card(c4), new Card(c5));\n}\n</code></pre>\n\n<p>And this avoids it a little more,</p>\n\n<pre><code>public int compareTo(PokerHand hand) {\n int i = this.getStrength().compareTo(hand.getStrength());\n if (i != 0)\n return i;\n return (new Integer(strengthValue)).compareTo(new Integer(hand.strengthValue));\n}\n</code></pre>\n\n<p>Is n't this off by 1?</p>\n\n<pre><code>private int getNumPairs() {\n int pairs = 0;\n for (int i = 0; i < NUM_CARDS; i++)\n if (cards[i].rank == cards[i + 1].rank)\n pairs++;\n\n return pairs;\n}\n</code></pre>\n\n<p>And here, condition is bad</p>\n\n<pre><code>private void evaluateSrenght() {\n...\n else{\n strength = Strength.HIGH_CARD;\n for (int i=0; i>NUM_CARDS; i++)\n setSrengthValue(i, cards[i].rank);\n }\n}\n</code></pre>\n\n<p>Also note that your spelling of strength varies. </p>\n\n<p>A little more drying up here</p>\n\n<pre><code>private boolean cmpAllranks(int[] c1, int[] c2) {\n for(int i = 0; i < c1.length; i++)\n if (cards[c1[i]].rank != cards[c2[i]].rank) \n return false;\n}\nprivate boolean isFullHouse( ) {\n if (cards[1].rank == cards[2].rank) {\n return cmpAllranks(new Integer[] {0,1,3}, new Integer[] {1,2,4});\n } else {\n return cmpAllranks(new Integer[] {0,2,3}, new Integer[] {1,3,4});\n }\n}\n// Choose the style you like\nprivate boolean isFourOfAKind( ) {\n Integer[] c1, c2;\n if (cards[0].rank != cards[1].rank) {\n c1 = new Integer[] {1,2,3};\n c2 = new Integer[] {2,3,4}\n } else {\n c1 = new Integer[] {0,1,2};\n c2 = new Integer[] {1,2,3}\n }\n return cmpAllranks(c1, c2);\n}\n</code></pre>\n\n<p>Now, these are probably better off in a case structure</p>\n\n<pre><code>private void evaluateSrenght() {\n ...\n if (isStraightFlush()) {\n else if (isFourOfAKind()) {\n else if (isFullHouse()) {\n else if (isFlush()){\n else if (isStraight()){\n else if (isThreeOfAKind()){\n else if ( ( numPairs = getNumPairs()) == 2 ) {\n else if (numPairs == 1){\n else{\n}\n</code></pre>\n\n<p>That is, </p>\n\n<pre><code>private void evaluateSrenght() {\n ...\n swtich (typeOfHand()) {\n straightFlush:...\n fullHouse: ...\n flush: ...\n etc.\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T11:59:56.880",
"Id": "17439",
"Score": "0",
"body": "Thank you, all great suggestions, only one thing i don't get: why is the condition bad in `evaluateStrength()` -properly spelled now-"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T14:39:44.743",
"Id": "17446",
"Score": "2",
"body": "`for(int i=0; i>NUM_CARDS; i++)` This will never be true (direction of the comparison symbol)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T05:53:43.803",
"Id": "10980",
"ParentId": "10973",
"Score": "6"
}
},
{
"body": "<ul>\n<li><p>Check access modifiers. You have few fields in your <code>Card</code> and <code>PokerHand</code> classes which should be <code>private</code> but they are not. </p></li>\n<li><p>I don't quite understand the diff between <code>IndexOutBoundsException</code> and <code>RuntimeException</code> in this case:</p>\n\n<pre><code>private void setSrengthValue(int index, int value) \nthrows IndexOutOfBoundsException,RuntimeException{\n\nif (!( index>=0 && index<=4) )\n throw new IndexOutOfBoundsException(\"Index should be between 0 and 4\");\nif (value > 0xF)\n throw new RuntimeException(\"Value should be between 0 and 15\");\n</code></pre>\n\n<p>There should be only one <code>IllegalArgumentException</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T08:10:00.747",
"Id": "17436",
"Score": "0",
"body": "why not keep setStrengthValue private? Seems quite reasonable to only expose functionality for inspecting state and keep functionality for modifying state private."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T12:08:55.397",
"Id": "17441",
"Score": "0",
"body": "In `Card` I chose to make everything public and final because getters have overhead on android. In `PokerHand`i don't see anything public that needs to be private."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T12:09:32.510",
"Id": "17442",
"Score": "0",
"body": "Also, you are right about the `IllegalArgumentException`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T07:55:50.907",
"Id": "10982",
"ParentId": "10973",
"Score": "4"
}
},
{
"body": "<p>Additionally to the other suggestions: Write utility functions like <code>boolean haveSameRank(Card ... cards)</code>, which could be used in several places.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T14:03:46.660",
"Id": "10988",
"ParentId": "10973",
"Score": "1"
}
},
{
"body": "<p>You have misspelled Strength in several places. I think the lookup method for Suites look rather messy with those nested ternary operators. Why divide by four (one wtf)? =)</p>\n\n<p>Your most complex part is how to calculate what kind of hand the player has. I once did saw some code of 'Risk' PC board game in which they evaluate the strength of the cards you trade in. I could not help but wonder whether you cant make the comparison of hand strength smarter than just start checking from the most powerful hand towards the least.</p>\n\n<p>Maybe its possible to use collections and checking their size somehow? Atleast for Risk that would make sense.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T18:51:19.513",
"Id": "18220",
"ParentId": "10973",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "10980",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T00:49:45.290",
"Id": "10973",
"Score": "8",
"Tags": [
"java",
"classes",
"android",
"playing-cards"
],
"Title": "Poker game classes"
}
|
10973
|
<p>I supplied the following code as an answer to <a href="https://stackoverflow.com/q/10207890/698590">this question on SO</a>, but I was wondering if there was a better way to write out all those array loops (i.e. perhaps using a Collection/Dictionary?) It seems clunky/cumbersome as-is.</p>
<pre><code>Function ContainedInMonth(OriginalStartDate As String, _
OriginalEndDate As String) As Boolean
Dim MonthSet As Variant
Dim AryCounter As Integer, ISOOffset As Integer
Dim StartYear As Integer, EndYear As Integer
Dim StartWeek As Integer, EndWeek As Integer
Dim StartDay As Integer, EndDay As Integer
Dim FormattedStartDate As Date, FormattedEndDate As Date
' This section may (will) vary, depending on your data.
' I'm assuming "YYYY-WW" is passed...
' Also, error/formatting checking for these values is needed
' and wil differ depending on that format.
StartYear = Val(Left(OriginalStartDate, 4))
StartWeek = Val(Right(OriginalStartDate, 2))
EndYear = Val(Left(OriginalEndDate, 4))
EndWeek = Val(Right(OriginalEndDate, 2))
If StartYear <> EndYear Or StartWeek > EndWeek Then
ContainedInMonth = False
ElseIf StartWeek = EndWeek Then
ContainedInMonth = True
Else
' Using the calculation from wikipedia. Honestly, I'm not sure that
' I understand this bit, but it seemed to work for my test cases.
ISOOffset = Weekday(CDate("1/4/" & StartYear), vbMonday) + 3
StartDay = (StartWeek * 7) - ISOOffset ' Adding 0 for start of week
EndDay = (EndWeek * 7) + 6 - ISOOffset ' Adding 6 for end of week
' Set the starting day for each month, depending on leap year.
If StartYear Mod 4 = 0 Then
MonthSet = Array(0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335)
Else
MonthSet = Array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334)
End If
FormattedStartDate = 0:FormattedEndDate = 0
For AryCounter = 11 To 0 Step -1
If StartDay > MonthSet(AryCounter) And FormattedStartDate = 0 Then
' Using MM/DD/YYYY format - this may be different for you
FormattedStartDate = CDate(AryCounter + 1 & _
"/" & StartDay - MonthSet(AryCounter) & "/" & StartYear)
End If
If EndDay > MonthSet(AryCounter) And FormattedEndDate = 0 Then
FormattedEndDate = CDate(AryCounter + 1 & _
"/" & EndDay - MonthSet(AryCounter) & "/" & EndYear)
End If
Next AryCounter
ContainedInMonth = IIf(Month(FormattedStartDate) = Month(FormattedEndDate), True, False)
End If
End Function
</code></pre>
<p>I had considered something like: </p>
<pre><code>If StartYear Mod 4 = 0 Then
TempArray = LeapSet
Else
TempArray = NonLeapSet
End If
'Now do loops
</code></pre>
|
[] |
[
{
"body": "<p>This is the final result of what was done with this code, though the code pertaining to the root question remained unchanged.</p>\n\n<pre><code>Function ContainsWhatMonths(OriginalStartDate As String, _\n OriginalEndDate As String) As Variant\n\n Dim MonthSet As Variant\n Dim AryCounter As Integer, ISOOffset As Integer\n Dim StartYear As Integer, EndYear As Integer\n Dim StartWeek As Integer, EndWeek As Integer\n Dim StartDay As Integer, EndDay As Integer\n Dim StartWeekStartDate As Date, StartWeekEndDate As Date\n Dim EndWeekStartDate As Date, EndWeekEndDate As Date\n Dim FormattedStartDate As Date, FormattedEndDate As Date\n Dim TotalMonths As Integer, OutputMonths As String\n\n StartYear = Val(Right(OriginalStartDate, 4))\n StartWeek = Val(Left(OriginalStartDate, 2))\n EndYear = Val(Right(OriginalEndDate, 4))\n EndWeek = Val(Left(OriginalEndDate, 2))\n\n If StartYear <= EndYear Then\n\n ' Using the calculation from wikipedia. Honestly, I'm not sure that\n ' I understand this bit, but it seemed to work for my test cases.\n ISOOffset = Weekday(CDate(\"1/4/\" & StartYear), vbMonday) + 3\n StartDay = (StartWeek * 7) - ISOOffset ' Adding 0 for start of week\n EndDay = (EndWeek * 7) + 6 - ISOOffset ' Adding 6 for end of week\n\n ' Set the starting day for each month, depending on leap year.\n If StartYear Mod 4 = 0 Then\n MonthSet = Array(0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335)\n Else\n MonthSet = Array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334)\n End If\n\n For AryCounter = 11 To 0 Step -1\n If StartDay > MonthSet(AryCounter) Then\n ' Using MM/DD/YYYY format - this may be different for you\n StartWeekStartDate = CDate(AryCounter + 1 & _\n \"/\" & StartDay - MonthSet(AryCounter) & \"/\" & StartYear)\n StartWeekEndDate = StartWeekStartDate + 6\n\n If Month(StartWeekStartDate) <> Month(StartWeekEndDate) Then\n FormattedStartDate = DateSerial(StartYear, Month(StartWeekEndDate), 1)\n Else\n FormattedStartDate = DateSerial(StartYear, Month(StartWeekEndDate) + 1, 1)\n End If\n\n Exit For\n End If\n Next AryCounter\n\n If EndYear Mod 4 = 0 Then\n MonthSet = Array(0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335)\n Else\n MonthSet = Array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334)\n End If\n\n For AryCounter = 11 To 0 Step -1\n If EndDay > MonthSet(AryCounter) Then\n EndWeekStartDate = CDate(AryCounter + 1 & _\n \"/\" & EndDay - MonthSet(AryCounter) & \"/\" & EndYear)\n EndWeekEndDate = EndWeekStartDate + 6\n\n If Month(EndWeekStartDate) <> Month(EndWeekEndDate) Then\n FormattedEndDate = CDate(Month(EndWeekEndDate) & \"/1/\" & EndYear) - 1\n Else\n FormattedEndDate = CDate(Month(EndWeekEndDate) & \"/1/\" & EndYear)\n End If\n\n Exit For\n End If\n Next AryCounter\n\n ' Switch the commenting on these two lines to return the string\n 'ContainsWhatMonths = Array()\n ContainsWhatMonths = vbNullString\n\n TotalMonths = (Year(FormattedEndDate) - Year(FormattedStartDate)) * 12 + _\n Month(FormattedEndDate) - Month(FormattedStartDate)\n\n If TotalMonths >= 0 Then\n\n For AryCounter = 0 To TotalMonths\n OutputMonths = OutputMonths & \",\" & _\n Format(DateAdd(\"m\", AryCounter, FormattedStartDate), \"MM/YYYY\")\n Next\n\n OutputMonths = Right(OutputMonths, Len(OutputMonths) - 1)\n\n ' Switch the commenting on these two lines to return the string\n 'ContainsWhatMonths = Split(OutputMonths, \",\")\n ContainsWhatMonths = OutputMonths\n End If\n\n End If\n\nEnd Function\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-05T17:13:57.480",
"Id": "13362",
"ParentId": "10990",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "13362",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T15:30:19.157",
"Id": "10990",
"Score": "3",
"Tags": [
"array",
"vba"
],
"Title": "Looping through arrays in VBA"
}
|
10990
|
<p>I'm having trouble accessing variables throughout multiple functions. For example, I need to use <em>userinput</em> throughout many other functions, but do not have access to it with my current code. I am pretty sure that I need to change the parameters of my functions, so that I can pass the value of those functions by reference, but I'm having trouble doing that. </p>
<p>Here's what my code looks like right now: </p>
<pre><code>#include <cstdlib>
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
double fahrtocels();
double celstofahr();
double celstokelv();
double kelvtocels();
int main()
{
do { int userinput=0;
cout << " 1) Fahr to Cels" << endl;
cout << " 2) Cels to Fahr" << endl;
cout << " 3) Cels to Kelv" << endl;
cout << " 4) Kelv to Cels" << endl;
cin >> userinput;
if(userinput=1)
fahrtocels();
if(userinput=2)
celstofahr();
if(userinput=3)
celstokelv();
if(userinput=4)
kelvtocels(); } while(userinput=0);
}
double fahrtocels()
{
int input;
int tempinput;
double finaloutput;
cout <<" Please Enter the Temp in Fahrenheit"<<endl;
cin >> input;
userinput= 1;
tempinput = input - 32;
finaloutput = tempinput/1.8;
cout<<input<< " degrees fahrenheit is equivalent to " << finaloutput<< " celsius"<< endl;
userinput = 0;
}
double celstofahr()
{
int inputcels;
int tempinputcels;
double finaloutputcels;
cout <<" Please Enter the Temp in Celsius"<<endl;
cin >> inputcels;
tempinputcels = inputcels * 1.8;
finaloutputcels = tempinputcels + 32;
cout<<inputcels<< " degrees celsius is equivalent to " << finaloutputcels<< " fahrenheit"<< endl;
}
double celstokelv()
{
int inputcelskelv;
double finaloutputcelskelv;
cout <<" Please Enter the Temp in Celsius for Kelvin Conversion"<<endl;
cin >> inputcelskelv;
finaloutputcelskelv = inputcelskelv + 273.15;
cout<<inputcelskelv<< " degrees celsius is equivalent to " << finaloutputcelskelv<< " kelvin"<< endl;
}
double kelvtocels()
{
int inputkelvcels;
double finaloutputkelvcels;
cout <<" Please Enter the Temp in Kelvin for Celsius conversion"<<endl;
cin >> inputkelvcels;
finaloutputkelvcels = inputkelvcels - 273.15;
cout<<inputkelvcels<< " degrees kelvin is equivalent to " << finaloutputkelvcels<< " celsius"<< endl;
}
</code></pre>
|
[] |
[
{
"body": "<p>Your problem is completely unrelated to smart pointers.</p>\n\n<p>The keyword here is <strong>separation of concerns</strong>. You have a function (well, several of them) who try to do everything: create a prompt, control user input, convert a value, and output the result.</p>\n\n<p>This is bad. You should separate these concerns rigorously.</p>\n\n<p>At the heart of your program is a conversion function with the prototype</p>\n\n<pre><code>double convert(double input);\n</code></pre>\n\n<p>Of course, you have several of them – one for each unit-to-unit conversion (this can be done differently by first converting to a common unit but we’ll omit this for now).</p>\n\n<p>Then you need an input and an output routine, which may look as follows:</p>\n\n<pre><code>double read_number(std::string const& unit) {\n std::cout << \"Please enter the temperature in \" << unit << std::flush;\n double value;\n std::cin >> value;\n return value;\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>void print_result(std::string const& from_unit, std::string const& to_unit, double from, double to) {\n std::cout << from << \" \" << from_unit << \" is equivalent to \"\n << to << \" \" << to_unit << \"\\n\";\n}\n</code></pre>\n\n<p>The conversions are then straightforward one-liners, for instance:</p>\n\n<pre><code>double celsius_to_kelvin(double value) {\n return value + 273.15;\n}\n</code></pre>\n\n<p>(Furthermore, note that while it’s “degrees celsius”, it’s simply “kelvin” – not “degrees kelvin”.)</p>\n\n<p>You could even use the same function for <em>all</em> conversions and merely store the scaling factor and offset. Such as:</p>\n\n<pre><code>typedef std::pair<double, double> coefficients_t;\n\nstd::vector<coefficients_t> conversions = {\n { 273.15, 1 }, // °C => K\n { -32, 0.5556 }, // °F => °C\n …\n};\n\nenum conversion_type {\n CtoK,\n FtoC,\n …\n};\n\ndouble convert(conversion_type conversion, double input) {\n coefficients_t coef = conversions[conversion];\n return (input + coeffs.first) * coeffs.second;\n}\n</code></pre>\n\n<p>(This syntax requires C++11, C++03 is more verbose.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T20:52:26.187",
"Id": "10994",
"ParentId": "10993",
"Score": "2"
}
},
{
"body": "<p>First, the code is technically off-topic, since it has a pretty clear bug (in <code>main</code>):</p>\n\n<pre><code>} while(userinput=0);\n</code></pre>\n\n<p>This is almost certainly intended to be <code>userinput==0</code>. As-is, it's an assignment, which yields 0, which is treated as false, so the loop only ever executes once, regardless of input from the user.</p>\n\n<p>While I agree with the basic approach @Konrad has advocated, putting together a table of the data needed for the conversions, I think I'd implement it just a bit differently. I would <em>not</em> use <code>std::pair</code>. I'd explicitly define a struct so the values would have meaningful names:</p>\n\n<pre><code>struct conversion {\n double offset;\n double coefficient;\n};\n</code></pre>\n\n<p>Then your conversion would look like:</p>\n\n<pre><code>double convert(conversion_type conversion, double input) { \n conversion c = conversions[conversion];\n return (input+c.offset)*c.coefficient;\n}\n</code></pre>\n\n<p>...which seems more readable, at least to me. If you do want to maintain separate functions for each conversion, I'd still break things up into one function doing input. another doing the conversion itself, and a third to display the result. I'd still make it largely table drive, using a vector (or array) of pointers to functions, using the number entered by the user to to index into that (after assuring that it's within range, of course).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T13:09:41.723",
"Id": "17496",
"Score": "0",
"body": "I agree that yours is cleaner. Mine is kind of like the Python approach in C++. I’d even think about inheritance to model this (have a base class taking care of the conversion and child classes to populate the offset & coeff in the constructor). That way, the classes can also take care of holding the scale’s names."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T04:18:07.843",
"Id": "10998",
"ParentId": "10993",
"Score": "3"
}
},
{
"body": "<pre><code>if(userinput==1)\n...\nif(userinput=2)\n...\n</code></pre>\n\n<p>consider to use either <code>switch</code> or <code>else if</code> constructions in such cases</p>\n\n<pre><code>if (userinput==1)\n...\nelse if(userinput==2)\n...\n</code></pre>\n\n<p>also consider to play this trick</p>\n\n<pre><code>double(*)(void) fp[] = {fahrtocels, celstofahr, celstokelv, kelvtocels}\nfp[userinput]() // calling function depends on the input number\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T12:40:08.000",
"Id": "11012",
"ParentId": "10993",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T19:51:53.927",
"Id": "10993",
"Score": "1",
"Tags": [
"c++"
],
"Title": "Temperature Conversion Program"
}
|
10993
|
<p>I want to know why Java is accepted over Python when it comes to runtime. On performing the following Euler problem, Python takes up less lines and runs faster (Python ~0.05s, Java ~0.3s on my machine).</p>
<p>Could I optimize this Java code in any way? The problem is here (<a href="http://projecteuler.net/problem=22" rel="nofollow">http://projecteuler.net/problem=22</a>)</p>
<p>Python:</p>
<pre><code>def main():
names = open("names.txt", "r").read().replace("\"", "").split(",")
names.sort()
print sum((i + 1) * sum(ord(c) - ord('A') + 1 for c in n) for i, n in enumerate(names))
if __name__ == "__main__":
main()
</code></pre>
<p>Java:</p>
<pre><code>import java.util.Arrays;
import java.lang.StringBuilder;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class euler22
{
public static String readFileAsString(String path) throws IOException
{
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(
new FileReader(path));
String buffer = null;
while((buffer = reader.readLine()) != null)
{
builder.append(buffer);
}
reader.close();
return builder.toString();
}
public static void main(String[] args) throws IOException
{
String[] names = fileAsString("names.txt").replace("\"", "").split(",");
int total = 0;
Arrays.sort(names);
for(int i = 0; i < names.length; ++i)
{
int sum = 0;
for(char c : names[i].toCharArray())
{
sum += c - 'A' + 1;
}
total += (i + 1) * sum;
}
System.out.println(total);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T04:07:00.150",
"Id": "17479",
"Score": "2",
"body": "How exactly are you compiling your java code? Try deleting the pyc file and timing the Python piece twice in a row. Also, time the io-bound piece and the cpu-bound piece for Python and Java separately. The computation is in theory parralelizable, but not in Java version. I do not know enough to be sure though. I suggest that you use `with open('file.txt', 'r') as fin: names = fin.read()...` for better safety. You also probably can speed up the Java reading piece a bit if you tokenize things manually. Java's and Python's io library must differ, and one is taking more advantage of hardware maybe"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T03:27:14.087",
"Id": "17491",
"Score": "8",
"body": "It might just be JVM startup time...hard to compare when runtimes are so short."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T03:32:45.040",
"Id": "17492",
"Score": "1",
"body": "Profile your code, but I think most of the time is spent on reading the input files. You read the file line by line in Java which is slower than reading all at once in Python."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T03:37:55.630",
"Id": "17493",
"Score": "4",
"body": "You simply cannot benchmark a Java program without running the code being benchmarked at least ten thousand times -- enough for the JIT to kick in. Anything else isn't a fair comparison."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T05:42:04.543",
"Id": "17494",
"Score": "1",
"body": "There are many solutions on the forum for this problem. Did none of them help? BTW: Add to the run time, the time it took you to write the code, to get the total time from when you started to when you had a solution and you might see the runtime doesn't matter in this case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T13:12:36.413",
"Id": "17497",
"Score": "2",
"body": "@Louis? Not fair? Why? This code is short enough that it *doesn’t need* the JIT to kick in. Furthermore, Python hasn’t got one either. The comparison is fair – it’s just not very meaningless precisely because the problem is too small to make a difference in practice."
}
] |
[
{
"body": "<p>So, what exactly do you want to know, what is your question? I do not think you have to refactor anything here. Maybe you can push the limits, but first read this (and you should know why java is choosen):</p>\n\n<ol>\n<li>Are you counting just the time of program execution (your code does not show this), or the total time of jvm startup, program execution and jvm shutdown (the same for python startup, exec, shutdown). You have to remember that this time differs between different interpreters/jvm's. And it can influence your computation. For such a small problem it will be the main factor. </li>\n</ol>\n\n<p>If you have a bigger problem, that runs for a longer period of time, then the jvm startup does not matter. If your program has to run for a month it does not matter if jvm starts in 1 ms, 1 second or even 1 hour.</p>\n\n<p>Be sure that you know what you want to measure.</p>\n\n<ol>\n<li>Java starts by interpreting, which is not the fastest way of runnig programs, and after some time, and hot-spots analysis the Java HotSpot JIT compiler kicks in, and the you will see that the program speeds up. </li>\n</ol>\n\n<p>I have taken your example, and run it a few times (counting the time of each execution). It starts from about 130ms, and after a few cycles it runs in less than <strong>8ms</strong>. And I know that file read and access time is a factor also, but after first read the file should be in Operating System cache.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T09:22:58.960",
"Id": "11002",
"ParentId": "10997",
"Score": "1"
}
},
{
"body": "<p>Broadly speaking try creating less objects. ;)</p>\n\n<p>You can</p>\n\n<ul>\n<li>read the entire file as a series of lines or as a string with FileUtils.</li>\n<li>iterate through each character rather than building an array which you iterate.</li>\n<li>as the program is so short, try using <code>-client</code> which has shorter start time.</li>\n</ul>\n\n<p>To maximise the performance</p>\n\n<pre><code>long start = System.nanoTime();\nlong sum = 0;\nint runs = 10000;\nfor (int r = 0; r < runs; r++) {\n FileChannel channel = new FileInputStream(\"names.txt\").getChannel();\n ByteBuffer bb = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());\n TLongArrayList values = new TLongArrayList();\n\n long wordId = 0;\n int shift = 63;\n while (true) {\n int b = bb.remaining() < 1 ? ',' : bb.get();\n if (b == ',') {\n values.add(wordId);\n wordId = 0;\n shift = 63;\n if (bb.remaining() < 1) break;\n\n } else if (b >= 'A' && b <= 'Z') {\n shift -= 5;\n long n = b - 'A' + 1;\n wordId = (wordId | (n << shift)) + n;\n\n } else if (b != '\"') {\n throw new AssertionError(\"Unexpected ch '\" + (char) b + \"'\");\n }\n }\n\n values.sort();\n\n sum = 0;\n for (int i = 0; i < values.size(); i++) {\n long wordSum = values.get(i) & ((1 << 8) - 1);\n sum += (i + 1) * wordSum;\n }\n}\nlong time = System.nanoTime() - start;\nSystem.out.printf(\"%d took %.3f ms%n\", sum, time / 1e6);\n</code></pre>\n\n<p>prints</p>\n\n<pre><code>XXXXXXXXX took 27.817 ms\n</code></pre>\n\n<p>Its pretty obtuse, but works around the fact its not warmed up. </p>\n\n<p>You can tell this is the case because if you repeat the code in a loop 10000 times, the time taken is only 8318 ms or 0.83 ms per run.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T05:42:48.847",
"Id": "11010",
"ParentId": "10997",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T03:24:20.513",
"Id": "10997",
"Score": "4",
"Tags": [
"java",
"python",
"programming-challenge"
],
"Title": "Python vs. Java Runtime on Euler 22 - Name Scores"
}
|
10997
|
<p>I made a stack monad that lets one manipulate and control values on a stack.</p>
<p>I want to know if it's correct (it seems correct), how to make it faster, and how I could detect stack overflows without carrying around the stack size and checking against it (I've heard about guard pages but I have no idea how I'd use them with Haskell).</p>
<pre><code>{-# LANGUAGE RankNTypes #-}
module Main where
import Data.IORef
import Foreign.Ptr
import Foreign.Storable
import Foreign.Marshal.Alloc
import Control.Exception ( bracket )
import System.IO.Unsafe
newtype StackRef s a = StackRef (Ptr a)
data Stack = Stack (Ptr ())
newtype StackMonad s a = StackMonad (Stack -> IO (Stack, a))
instance Monad (StackMonad s) where
return x = ioToStackMonad (return x)
(StackMonad m) >>= f = StackMonad $ \stack -> do
(newStack, x) <- m stack
let (StackMonad g) = f x
g newStack
runStackWithSize :: Int -> (forall s. StackMonad s a) -> a
runStackWithSize stackSize (StackMonad f) = unsafePerformIO $
bracket (mallocBytes stackSize) free $ \theStack -> do
(_, a) <- f (Stack theStack)
return a
-- | 1024 bytes is the usual size for a stack
runStack :: (forall s. StackMonad s a) -> a
runStack = runStackWithSize 1024
newStackRef :: Storable a => a -> StackMonad s (StackRef s a)
newStackRef value = StackMonad $ \(Stack topOfStack) -> do
let ptr = castPtr (alignPtr topOfStack (alignment value))
poke ptr value
return (Stack (plusPtr ptr (sizeOf value)), StackRef ptr)
ioToStackMonad :: IO a -> StackMonad s a
ioToStackMonad action = StackMonad $ \ptr -> do
a <- action
return (ptr, a)
writeStackRef :: Storable a => StackRef s a -> a -> StackMonad s ()
writeStackRef (StackRef p) val = ioToStackMonad (poke p val)
readStackRef :: Storable a => StackRef s a -> StackMonad s a
readStackRef (StackRef p) = ioToStackMonad (peek p)
{- |
The type hackery means that pointers to the old stuff isn't reachable,
therefore it's okay to pop the stack pointer.
-}
stack :: (forall s. (forall b. StackRef t b -> StackRef s b) -> StackMonad s a) -> StackMonad t a
stack f = let (StackMonad s) = f (\(StackRef p) -> StackRef p) in StackMonad $ \old_ptr -> do
(_, state) <- s old_ptr
return (old_ptr, state)
stack_ :: (forall s. (forall b. StackRef t b -> StackRef s b) -> StackMonad s ()) -> StackMonad t ()
stack_ f = let (StackMonad s) = f (\(StackRef p) -> StackRef p) in StackMonad $ \old_ptr -> do
_ <- s old_ptr
return (old_ptr, ())
x :: Int
x = runStack $ do
a <- newStackRef 5
c <- stack $ \lift1 -> do
b <- newStackRef 1
let liftedA = lift1 a
aValue <- readStackRef liftedA
writeStackRef liftedA 6
bValue <- readStackRef b
return (aValue + bValue)
newAValue <- readStackRef a
return (c + newAValue)
main = print x
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-05T19:57:19.303",
"Id": "18459",
"Score": "5",
"body": "Did you tried out an implementation where the stack is just a plain list? Letting the runtime do the work for you is usually faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T13:29:20.327",
"Id": "38482",
"Score": "0",
"body": "Actually, a list *is* a stack: it's biased toward accessing the first element. And, `[]` is a Monad... and likely heavily optimized, although it is not as fast as, say a `Vector`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-02T19:04:58.703",
"Id": "48789",
"Score": "0",
"body": "Performance is only a side point. The point is semi-deterministic allocation of memory (which will also be neat for debugging.) For that reason just using a list is incorrect."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T06:55:15.013",
"Id": "72238",
"Score": "1",
"body": "I don't know Haskell, but I know if I were approaching this problem in a language I'm familiar with, I would write tests whether it be unit tests or integration tests to determine if it works as expected. Run it through its paces and assert that you don't get overflows and the stack responds properly."
}
] |
[
{
"body": "<p>This code is simply incorrect. It is even not a stack (because it lacks\n<code>pop</code> operation and it is impossible to implement it in a type-safe way).\nHere is an example:</p>\n\n<pre><code>runStack $ do\n newStackRef (5:: Int)\n newStackRef False\n newStackRef 'x'\n</code></pre>\n\n<p>according to the definition of the <code>newStackRef</code> it just pokes <code>Storable</code>\nrepresentation of the value into the memory block and advances the pointer.\nAny information about the type of that value is lost.</p>\n\n<p>To pop a value from such a stack you need to specify correct type and\ncompiler (or RTS) is not able to warn you if the type is not correct.</p>\n\n<p>To the monad part of the question. From the <code>instance Monad</code>\ndefinition it is easy to see that it almost the same as the <code>State</code> monad (here is how it defined in \n<a href=\"http://hackage.haskell.org/package/transformers-0.3.0.0/docs/src/Control-Monad-Trans-State-Lazy.html#StateT\">Control.Monad.State.Trans.State.Lazy</a>)</p>\n\n<pre><code>instance (Monad m) => Monad (StateT s m) where\n return a = state $ \\s -> (a, s)\n m >>= k = StateT $ \\s -> do\n ~(a, s') <- runStateT m s\n runStateT (k a) s'\n</code></pre>\n\n<p>The only difference is that it operates on top of <code>IO</code> an has fixed type of state. So it is actually <code>StateT (Ptr ()) IO</code>.</p>\n\n<p>It is even not clear what it is for a stack to be an instance of <code>Monad</code>.\nE.g. list monad allows nondeterministic computations (in prolog-like\nstyle), <code>Maybe</code> monad allows computations that fail.</p>\n\n<p>To enable computation to access and operate stack it is easier to use existing <code>State</code> monad with some stack implementation as a state. I see no reason to implement your own <code>Stack</code> monad.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T07:13:45.460",
"Id": "47854",
"ParentId": "11000",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T05:13:59.110",
"Id": "11000",
"Score": "27",
"Tags": [
"optimization",
"performance",
"haskell",
"stack",
"monads"
],
"Title": "How can I make my stack monad faster?"
}
|
11000
|
<p>This is my rspec integration test for user, it always breaks when my teammate change something, how do i improve this?</p>
<pre><code>describe "Users" do
before(:each) do
populate_role
end
describe "GET /users/sign_in" do
#it "should redirect to redirect to user sign in page for user that is not sign in" do
# get root_path
# response.should redirect_to(new_user_session_url)
#end
it "should sign in the admin with correct user id and password" do
login_user(@admin_role)
page.should have_content("Sign out")
end
end
describe "DELETE /users/sign_out" do
it "shoud sign out the admin" do
login_user(@admin_role)
page.should have_content("Sign out")
visit root_url
click_link "Sign out"
page.should have_content("Signed out successfully.")
end
end
describe "GET /users/new" do
it "should allow admin to create a new owner with only user_id and generate the password" do
owner = FactoryGirl.build(:user, role: @owner_role, unit: FactoryGirl.create(:unit))
admin = login_user(@admin_role)
visit new_user_path
fill_in_admin_user_creation_form_for(owner)
click_button("Add")
page!
#page.should have_content("User was successfully created.")
should_have_content_for_admin_user_creation(owner)
end
it "should allow owner to create resident" do
owner = login_user(@owner_role, FactoryGirl.create(:unit))
resident = FactoryGirl.build(:user, role: @resident_role)
visit new_user_path
fill_in_owner_user_creation_form_for(resident)
click_button("Add")
should_have_content_for_owner_user_creation(resident)
end
it "should not allow owner to create admin and change unit" do
login_user(@owner_role, FactoryGirl.create(:unit))
visit new_user_path
page.should have_no_selector('select#user_role_id')
page.should have_no_selector('select#user_unit_id')
end
end
# print user info
describe "GET /user/:id/print" do
it "should allow admin to print the user information include self generated password after admin created the owner" do
login_user(@admin_role)
owner = FactoryGirl.build( :user, role: @owner_role, unit: FactoryGirl.create(:unit) )
visit new_user_path
fill_in_admin_user_creation_form_for(owner)
click_button("Add")
find("#user_password").should have_content(owner.user_id)
end
it "should print the user information include password before user activate it" do
login_user(@admin_role)
owner = FactoryGirl.create( :user, :without_password, role: @owner_role, unit: FactoryGirl.create(:unit))
visit user_print_path(owner)
find("#user_password").should have_content(owner.user_id)
end
it "should print the user information of resident that is under the owner" do
owner = login_user(@owner_role, FactoryGirl.create(:unit))
resident = FactoryGirl.create( :user, :without_password, role: @resident_role, unit: owner.unit)
visit user_print_path(resident)
current_path.should == user_print_path(resident)
end
it "should not print the user information of resident that is not under the owner" do
owner = login_user(@owner_role, FactoryGirl.create(:unit))
resident = FactoryGirl.create( :user, :without_password, role: @resident_role, unit: FactoryGirl.create(:unit))
visit user_print_path(resident)
current_path.should == root_path
end
it "should print the user information of owner that is not activated" do
admin = login_user(@admin_role)
owner = FactoryGirl.create( :user, :without_password, role: @owner_role, unit: FactoryGirl.create(:unit),active: false)
visit user_print_path(owner)
current_path.should == user_print_path(owner)
end
it "should not print the user information of owner that is activated" do
admin = login_user(@admin_role)
owner = FactoryGirl.create( :user, :without_password, role: @owner_role, unit: FactoryGirl.create(:unit),active: true)
visit user_print_path(owner)
current_path.should == root_path
end
end
def fill_in_admin_user_creation_form_for(user)
fill_in("user[user_id]", :with => user[:user_id])
select(user.role.name, :from => "user[role_id]")
select(user.unit.to_string, :from => "user[unit_id]")
select(user[:title], :from => "user_title")
fill_in("user[name]", :with => user[:name])
fill_in("user[dob]", :with => user[:dob])
fill_in("user[nric]", :with => user[:nric])
fill_in("user[phone]", :with => user[:phone])
fill_in("user[email]", :with => user[:email])
end
def fill_in_owner_user_creation_form_for(user)
fill_in('user[user_id]', :with => user[:user_id])
select(user[:title], :from => "user[title]")
fill_in("user[name]", :with => user[:name])
fill_in("user[dob]", :with => user[:dob])
fill_in("user[nric]", :with => user[:nric])
fill_in("user[phone]", :with => user[:phone])
fill_in("user[email]", :with => user[:email])
end
def should_have_content_for_admin_user_creation(user)
page.should have_content(user[:user_id])
page.should have_content(user.unit.to_string)
page.should have_content(user[:title])
page.should have_content(user[:name])
page.should have_content(user[:dob])
page.should have_content(user[:nric])
page.should have_content(user[:phone])
page.should have_content(user[:email])
end
def should_have_content_for_owner_user_creation(user)
page.should have_content(user[:user_id])
page.should have_content(user.unit.to_string)
page.should have_content(user[:title])
page.should have_content(user[:name])
page.should have_content(user[:dob])
page.should have_content(user[:nric])
page.should have_content(user[:phone])
page.should have_content(user[:email])
end
end
</code></pre>
|
[] |
[
{
"body": "<p>Your specs look OK (I have a few comments, but none that would address your main question of why your specs break when your teammates push code). I suspect the problem lies not with your code, but with the team - sounds like you're trying to test drive, and they're not on-board?</p>\n\n<p>If everyone followed the process, that shouldn't happen. Specifically, if:</p>\n\n<ul>\n<li>Everyone Test Drove and followed the principle of not writing code unless there was a failing spec: First write a spec, watch it fail, then write the minimum amount of code to fix the failure, repeat.</li>\n<li>Everyone ran all the specs before pushing code to make sure they didn't break anything</li>\n</ul>\n\n<p>Then this wouldn't happen. You should evangelize TDD and get your teammates to appreciate the benefits!</p>\n\n<p>My comments, FWIW:</p>\n\n<ul>\n<li><p>You're mixing contexts a little bit with your descriptions: \"GET /users/sign_in\" and \"DELETE /users/sign_out\" type descriptions belong in Controller specs and not Request specs. (The request spec simulates an actual user, who has no knowledge of HTTP methods, etc. I would write it more like so:</p>\n\n<pre><code>context \"admin logging in\" do\n describe \"when an admin signs in successfully\" do\n it \"should indicate that he is signed in by displaying the sign-out button\" do\n ....\n end\n end\n describe \"when and admin signs out\" do \n it \"should show a success message\" do\n ....\n end\n end\nend\n</code></pre></li>\n<li><p>FactoryGirl has an option to allow using just <code>create(:unit)</code> instead of <code>FactoryGirl.create(:unit)</code>. Makes things a bit more readable.</p></li>\n<li>Delete commented out code - it clutters things up, you can always retrieve it from git.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-10T16:31:23.253",
"Id": "12445",
"ParentId": "11001",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T09:21:42.503",
"Id": "11001",
"Score": "0",
"Tags": [
"ruby",
"unit-testing",
"ruby-on-rails",
"rspec"
],
"Title": "Rspec Request break when teammate pushes some changes"
}
|
11001
|
<p>Explained what I'm doing in the comments:</p>
<pre><code>class User {
public $id;
public $email;
public $username;
public $password;
public $rep;
public function __constructor($id, $email, $username, $password, $rep) { // Assign all 'required' fields for our object upon instantiation
$this->id = $id;
$this->email = $email;
$this->username = $username;
$this->password = $password;
$this->rep = $rep;
}
public static function getUsers($query, $mysqli) { // Pass the query to select desired users and the mysqli connection object
$all_users = $mysqli->query($query);
$user = array();
while($users = $all_users->fetch_assoc()) {
$temp_user = new User($users['id'], $users['email'], $users['username'], $users['password'], $users['rep']);
$user[] = $temp_user;
}
return $user;
}
}
</code></pre>
<p>Which allows me to do something like this:</p>
<pre><code>$users = User::getUsers("SELECT * FROM users", $mysqli); // Returns an array of user objects containing each users details
</code></pre>
<p>Which I can loop through at will.</p>
<p>Is using a static function like this a good idea? What might be the pitfalls to my design? One that just occurred to me when writing this is that I might not always needs every user field, but it wouldn't be hard to customize the constructor to allow only desired fields to be assigned values.</p>
<p>Here is what I was doing BEFORE the previous example. Is this technically better? The thing that was bothering me is there are several occasions where I'm duplicating the block of code below to instantiate an array of objects. Should I create another class to take care of this process, or am I still going about this the wrong way?</p>
<pre><code>$all_users = $mysqli->query($query);
$user = array();
while($users = $all_users->fetch_assoc()) {
$temp_user = new User($users['id'], $users['email'], $users['username'], $users['password'], $users['rep']);
$user[] = $temp_user;
}
class User {
private $id;
private $email;
private $username;
private $password;
private $rep;
public function __constructor($id, $email, $username, $password, $rep) { // Assign all 'required' fields for our object upon instantiation
$this->id = $id;
$this->email = $email;
$this->username = $username;
$this->password = $password;
$this->rep = $rep;
}
public function getID() {
// etc
}
public function setPassword($password) {
// etc
}
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>No, this is not OO code.</strong></p>\n\n<p>You are missing some of the key parts of OO.</p>\n\n<h2>Data Hiding</h2>\n\n<p>All of the class properties are public. Use protected for id, email, username etc. This stops outsiders from modifying the object without your control. The object should only be modified using the public interface that you provide for it.</p>\n\n<h2>Encapsulation</h2>\n\n<p>Did you implement a public interface for your object, while hiding implementation details away from the programmer who will use your object?</p>\n\n<p>I think the answer is that you haven't really provided a complete interface here. Unfortunately your one method is misleading. Your class is a User class, however it returns Users (plural). This class actually looks like a DataMapper for users rather than a User class. This also leads me to think that you don't need the properties in the object as you will likely just want to be returning the results.</p>\n\n<h2>Static</h2>\n\n<p><strong>OO and static methods do not mix</strong>. You kind of hit it with your usage example. It will work without you having any object created. </p>\n\n<p><code>$users = User::getUsers(\"SELECT * FROM users\", $mysqli);</code></p>\n\n<p>Observe how this is really just calling a function. None of the class properties are used within the method.</p>\n\n<p>I don't believe there is any place for static methods in OO. Also, static causes a tight coupling in your code. Look at your usage, what will you need in place to run that code? See if you come up with the same answer as me before you read on.</p>\n\n<p>The things you will need to run the static code are: A class named User with a method named getUsers.</p>\n\n<p>Now, look at the following call to an object method and tell me what you need:</p>\n\n<p><code>$user->getUsers(\"SELECT * FROM users\", $mysqli);</code></p>\n\n<p>Answer: An object with a getUsers method. You have just removed your dependency on the User class. Now if you want to you can pass in a SuperUser object and get super users. This is an example of polymorphism which is one of the key concepts of OOP.</p>\n\n<h2>Testability</h2>\n\n<p>By calling <code>User::getUsers</code> in your code you have a hard-coded break out of the unit, making the code very difficult to test as a unit. Using an object allows you to pass in a special object to help you test.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T10:40:53.107",
"Id": "17488",
"Score": "0",
"body": "Hey Paul, thanks for taking the time to answer. Please see the part I added to the bottom of the question in light of what you said."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T10:53:08.053",
"Id": "17489",
"Score": "0",
"body": "Yes, I think the one you just posted (your previous version) was good OO. Its a bit hard to know what will be best without knowing the full details of what you are trying to achieve. An important thing will be that you match the objects in your solution to the problem at hand. Also, staying clear of static will definitely be beneficial. Good luck!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T10:56:39.487",
"Id": "17490",
"Score": "0",
"body": "Thinking about it a bit more, maybe a Data Mapper class to retrieve all of the users is what you want. Search for Data Mapper pattern."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T13:14:26.740",
"Id": "17498",
"Score": "2",
"body": "Static methods don’t contradict OOP, and both can be used in conjunction. Having a static method here is totally fine. Saying that there is no place for static methods in OOP is simply wrong. This would preclude constructors which are just static methods in disguise. Put differently, OP’s `getUsers` is a constructor in disguise. Again: this is a totally valid pattern."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T14:47:39.400",
"Id": "17501",
"Score": "0",
"body": "@KonradRudolph If you can avoid tight coupling and can unit test easily with static methods then let me know. I am in the PHP chat room frequently."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T14:52:04.950",
"Id": "17503",
"Score": "0",
"body": "@Paul You can’t but it’s horrible overkill. Unit testing isn’t problematic by the way, only mocking is. And I find that seriously overrated. Not because it’s not useful, but it makes the architecture much more complex and consequently has a very bad cost/benefit ratio so I only use it when it’s actually required."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T10:32:08.737",
"Id": "11006",
"ParentId": "11004",
"Score": "6"
}
},
{
"body": "<p>I think you'd benefit from taking a look at the documentation for the 2 major PHP ORMs (Object Relational Mapping) <a href=\"http://www.doctrine-project.org/\" rel=\"nofollow\">Doctrine</a> and <a href=\"http://www.propelorm.org/\" rel=\"nofollow\">Propel</a> to get some ideas on how to approach it.</p>\n\n<p>They both provide classes that map to a record (row) and classes for interacting with the db tables (Doctrine call theirs \"Table\" classes, Propel calls them \"Peer\" classes).</p>\n\n<p>When you need data, you call a method in the table/peer class, and that returns a collection of objects containing your data.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T12:05:40.223",
"Id": "11007",
"ParentId": "11004",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T09:39:55.383",
"Id": "11004",
"Score": "5",
"Tags": [
"php",
"object-oriented"
],
"Title": "User class design"
}
|
11004
|
<p>I have the following query which works as it should, but I'd like to know how I can make it run faster.</p>
<p>For <code>info</code>, tables <code>cl</code>, <code>jo</code> and <code>mi</code> all have column <code>ref</code> as the <code>auto_inc</code> <code>primary key</code> and <code>ID</code> as the main identification number. Therefore, I use the <code>ref</code>s to keep a history of changes for <code>ID</code>. So, I use <code>SELECT MAX(ref) FROM [xx] GROUP BY ID</code> to get the most recent <code>cl</code> <code>jo</code> and <code>mi</code>.</p>
<pre><code>SELECT mi.ref, jo.ID, mi.ID AS mID, mt.mi_type, jo.ref, jt.jo_type, cl.cl_name
FROM mi
INNER JOIN mt ON mt.ref = mi.mi_type
INNER JOIN jo ON jo.ID = mi.job
INNER JOIN cl ON cl.ID = jo.cl
INNER JOIN jt ON jt.ref = jo.jo_type
WHERE mi.ref IN (SELECT MAX(ref)
FROM mi
GROUP BY ID)
AND jo.ref IN (SELECT MAX(ref)
FROM jo
GROUP BY ID)
AND cl.ref IN (SELECT MAX(ref)
FROM cl
GROUP BY ID)
ORDER BY cl.cl_name, jt.jo_type, mt.mi_type ASC
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T13:43:08.060",
"Id": "17500",
"Score": "0",
"body": "Have you tried selecting the MAX from each of three tables first then using those values in the where clause?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T16:28:47.207",
"Id": "17506",
"Score": "0",
"body": "No but I'll give it a go. Thanks"
}
] |
[
{
"body": "<p>Moving your subqueries to the <em>from</em> clause may improve performance. </p>\n\n<p>Additional indexes may help too. Add a clustered index on <em>ID</em> or (<em>ID, ref</em>) for tables <em>mi</em>, <em>jo</em> and <em>cl</em> to speed up the <em>group by</em> and <em>max</em> operations. You may also benefit from a clustered index on each of your <em>order by</em> columns.</p>\n\n<pre><code>SELECT mi.ref, jo.ID, mi.ID AS mID, mt.mi_type, jo.ref, jt.jo_type, cl.cl_name \nFROM mi \nINNER JOIN mt ON mt.ref = mi.mi_type\nINNER JOIN jo ON jo.ID = mi.job\nINNER JOIN cl ON cl.ID = jo.cl\nINNER JOIN jt ON jt.ref = jo.jo_type\nINNER JOIN (SELECT MAX(ref) AS ref FROM mi GROUP BY ID) mi2 ON mi2.ref = mi.ref\nINNER JOIN (SELECT MAX(ref) AS ref FROM jo GROUP BY ID) jo2 ON jo2.ref = jo.ref\nINNER JOIN (SELECT MAX(ref) AS ref FROM cl GROUP BY ID) cl2 ON cl2.ref = cl.ref\nORDER BY cl.cl_name, jt.jo_type, mt.mi_type\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T16:35:46.573",
"Id": "17509",
"Score": "0",
"body": "Thanks Anthony. Unfortunately it doesn't appear to be any quicker. Can I ask you to explain why matching on `ID` as well as on `ref` (the primary key) improves the performance?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T09:15:37.703",
"Id": "17551",
"Score": "0",
"body": "Quite right. I overlooked that `ref` is the primary key. I've updated my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-21T08:16:30.120",
"Id": "17628",
"Score": "0",
"body": "Thanks Anthony, but it hasn't made the query any quicker."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T14:18:50.977",
"Id": "11013",
"ParentId": "11005",
"Score": "1"
}
},
{
"body": "<p>Thanks to Anthony for pointing me in the right direction, I then realised that I had unnecessary joins so here's the much quicker final version, for reference:</p>\n\n<pre><code>SELECT mi2.ref, jo2.ID, mi2.ID AS mID, mt.mi_type, jo2.ref, jt.jo_type, cl2.cl_name\nFROM (SELECT ID, MAX(ref) AS ref, mi_type, job FROM mi GROUP BY ID) mi2\nINNER JOIN mt ON mt.ref = mi2.mi_type\nINNER JOIN (SELECT ID, MAX(ref) AS ref, cl, jo_type FROM jo GROUP BY ID) jo2 ON jo2.ID = mi2.job\nINNER JOIN (SELECT ID, MAX(ref) AS ref, cl_name FROM cl GROUP BY ID) cl2 ON cl2.ID = jo2.cl\nINNER JOIN jt ON jt.ref = jo2.jo_type\nORDER BY cl2.cl_name, jt.jo_type, mt.mi_type ASC\n</code></pre>\n\n<p>Hope this helps someone else.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T15:23:10.667",
"Id": "11167",
"ParentId": "11005",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "11167",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T09:58:06.017",
"Id": "11005",
"Score": "0",
"Tags": [
"sql",
"mysql",
"join"
],
"Title": "Make a MySQL SELECT and INNER JOIN faster"
}
|
11005
|
<p>I am implementing Dijkstra's Algorithm using Min Heap to speed up the code.</p>
<p>For a small number of nodes, the code is really running very fast. But for a large number of nodes, my code is throwing <em>java.lang.OutOfMemoryError: Java heap space</em> exception. My Min heap implementation is based on the code, given <a href="https://stackoverflow.com/a/2657086/1175065">here</a> in C++. I changed this code into Java.</p>
<p>Below is my min heap code (I am not putting Dijkstra's algorithm code, as it is same as described in the above link).</p>
<pre><code>public class Heap {
private static int[] data;
private static int[] index;
public static int[] cost;
public static boolean[] eval;
private static int size;
public Heap(int s) {
data = new int[s];
index = new int[s];
cost = new int[s];
eval = new boolean[s];
}
public void init(int s) {
for (int i = 0; i < s; i++) {
index[i] = -1;
eval[i] = false;
}
size = 0;
}
public boolean isEmpty() {
return (size == 0);
}
private void shiftUp(int i) {
int j;
while (i > 0) {
j = (i - 1) / 2;
if (cost[data[i]] < cost[data[j]]) {
int temp = index[data[i]];
index[data[i]] = index[data[j]];
index[data[j]] = temp;
temp = data[i];
data[i] = data[j];
data[j] = temp;
i = j;
} else
break;
}
}
private void shiftDown(int i) {
int j, k;
while (2 * i + 1 < size) {
j = 2 * i + 1;
k = j + 1;
if (k < size && cost[data[k]] < cost[data[j]]
&& cost[data[k]] < cost[data[i]]) {
int temp = index[data[k]];
index[data[k]] = index[data[i]];
index[data[i]] = temp;
temp = data[k];
data[k] = data[i];
data[i] = temp;
i = k;
} else if (cost[data[j]] < cost[data[i]]) {
int temp = index[data[j]];
index[data[j]] = index[data[i]];
index[data[i]] = temp;
temp = data[j];
data[j] = data[i];
data[i] = temp;
i = j;
} else
break;
}
}
public int pop() {
int res = data[0];
data[0] = data[size - 1];
index[data[0]] = 0;
size--;
shiftDown(0);
return res;
}
public void push(int x, int c) {
if (index[x] == -1) {
cost[x] = c;
data[size] = x;
index[x] = size;
size++;
shiftUp(index[x]);
} else {
if (c < cost[x]) {
cost[x] = c;
shiftUp(index[x]);
shiftDown(index[x]);
}
}
}
}
</code></pre>
<p>As far as the code is concerned, it is working fine for small <code>s</code>. How can I optimize this code for a large value of nodes?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-21T13:45:09.173",
"Id": "178596",
"Score": "0",
"body": "I was able to solve this question TSHPATH in spoj with your code... I think maybe you are not taking the Graph as a adjacency list... I am attaching the link to the code here: http://ideone.com/951QAJ"
}
] |
[
{
"body": "<p>The only memory that you are allocating is the four arrays: <code>data</code>, <code>index</code>, <code>cost</code>, and <code>eval</code>. That means that if you are running out of memory then you probably need to allocate more memory. An array of primitives is just about as compact a structure as you're going to get.</p>\n\n<p>You don't say what you mean by \"large value of nodes\", but you can figure that you will be allocating approximately 13 bytes (less because the boolean array will be packed) times the value of <code>s</code> passed into the constructor. I think the default heap is 64 MB, and some of that is allocated to other things, but you should be able to allocate at something in the millions range.</p>\n\n<p>I added this main to your code and it showed that an array of 100,000 entries used just over 1.2 MB.</p>\n\n<pre><code>public static void main(String[] args) {\n Runtime r = Runtime.getRuntime();\n\n long t = r.totalMemory();\n long f = r.freeMemory();\n System.out.println(\"[Heap.main] \" + t + \",\" + f);\n\n Heap h = new Heap(100000);\n h.init(0);\n h.push(1,2);\n System.out.println(\"[Heap.main] isEmpty returns: \" + h.isEmpty());\n\n t = r.totalMemory();\n f = r.freeMemory();\n System.out.println(\"[Heap.main] \" + t + \",\" + f);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T16:29:40.963",
"Id": "17507",
"Score": "0",
"body": "Thank you. Can you please suggest me some ways? My aim is to speed up `Dijkstra's Algorithm`. That is why i am using `Min Heap` as it is suggested by [StackOverflow](http://stackoverflow.com/a/2657086/1175065) also. How can I get more speed up with higher number of nodes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T16:34:50.107",
"Id": "17508",
"Score": "0",
"body": "The amount of memory that the program is allowed to use is specified by Java runtime parameters (-Xmx specifically - see the documentation for the Java runtime you are using, such as http://docs.oracle.com/javase/1.5.0/docs/tooldocs/solaris/java.html)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T17:55:17.237",
"Id": "17519",
"Score": "0",
"body": "Ya.. I know about it. java -Xmx1024M will work. but is there any possible way to optimize this code? I can ignore `boolean array eval` for the time being. But what can be done with `int array data index and cost`? If anyhow i can change play with their size or is there any other optimized min heap code in java? Would be very helpful to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T07:00:38.723",
"Id": "17540",
"Score": "0",
"body": "1. You can have a look at different dijkstra implementations how they did it and compare yours e.g. my own ;) http://karussell.github.com/GraphHopper/ 2. a minor change could be to use BitSet instead of boolean array (saves a bit memory but is probably slower) 3. you can use speed up technics (bidirectional dijkstra, contraction hierarchie, guided dijkstras like a star, using heuristics, ...) 4. instead of an own heap for 'smaller' datasets I've seen that the normal java heap (PriorityQueue) is sufficient and could be even faster"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T07:02:14.523",
"Id": "17541",
"Score": "0",
"body": "a minor btw: be sure that you understand that a star is NOT a heuristic. although it is often used as one"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T08:12:22.817",
"Id": "17546",
"Score": "0",
"body": "@Karussell: I can't go for `A* algorithm`. I have to strict on `Dijkstra's Algorithm`. However google suggest me to make use of `fibonacci heap` instead of `binary heap.` So right now i am implementing `febonacci heap.`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T08:19:31.687",
"Id": "17547",
"Score": "0",
"body": "@Karussell: I downloaded (Graphhopper)[http://karussell.github.com/GraphHopper/] and checked `Dijkstra's Algorithm`. It's beautiful. It also uses `Priority Queue`. Thank you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T15:48:45.763",
"Id": "17593",
"Score": "0",
"body": "yes, but prioqueue != fibonacci but as I said it shouldn't be that much faster. also have a look into DijkstraBidirection which should be twice as fast. why can't you use a*?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T17:05:20.740",
"Id": "17751",
"Score": "0",
"body": "@Karussell: A* is not suiting in my case as there is no heuristics for my case. And speed is also fine of the above program, the only thing which i am suffering from this code is `OutOfMemoryError Exception`. If somehow i can make some changes in the code,then that would be best for me."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T15:35:54.890",
"Id": "11016",
"ParentId": "11015",
"Score": "3"
}
},
{
"body": "<p>I'm with @DonaldMcLean, in that I don't see a possibility of memory leak here.\nSo if you run out of memory that must be because given the size of the heap you want to create, you didn't give enough memory to the JVM to contain all your arrays.</p>\n\n<p>There's something to save you some memory though:\nthe <code>eval</code> array is completely unused,\nit's just taking up memory for no reason, so delete that.</p>\n\n<hr>\n\n<p>In terms of code review, there are a couple of things that you should definitely improve:</p>\n\n<ul>\n<li>Don't assign to <code>static</code> variables from instance methods</li>\n<li>The <code>data</code>, <code>index</code>, <code>cost</code> shouldn't be <code>static</code>, but should be <code>private</code> members of the <code>Heap</code> class.</li>\n<li>A more efficient way to fill the <code>index</code> array with -1 values is <code>Arrays.fill(index, -1)</code></li>\n<li>You don't need to fill a <code>boolean</code> array with <code>false</code> values, <code>boolean</code> arrays are like that by default</li>\n<li>You do a lot of swapping of elements in the <code>index</code> and <code>data</code> arrays. Instead of spelling out every time the <code>temp = ...[i]; ...[i] = ...[j]; ...[j] = temp</code> idiom, it would be better to create a helper <code>swap</code> method and shorten and simplify the code</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-25T21:57:40.823",
"Id": "82618",
"ParentId": "11015",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "82618",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T15:03:23.630",
"Id": "11015",
"Score": "5",
"Tags": [
"java",
"algorithm",
"memory-management",
"heap"
],
"Title": "Min Heap implementation with Dijkstra's algorithm"
}
|
11015
|
<p>I'm using VS 2008. I pass a <code>List<T> a</code> using <code>ref</code>, along with another <code>List<T> b</code>.</p>
<p>I need to cycle thru <code>List<T> b</code>, which contains around 200,000 items, and for each item in <code>b</code>, it it matches criteria in <code>a</code>, which contains 100,000 or more items, and update it.</p>
<pre><code>public static void UpdateList(ref List<ExampleT> a, List<ExampleT> b)
{
var count = 0;
for (int i = 0; i < b.Count; i++)
{
foreach (var z in a.FindAll(x => x.MatchA == b[i].MatchA && x.MatchB == b[i].MatchB))
{
z.ToUpdate = b[i].ToUpdate;
count++;
}
if(count >= 10000)
break;
}
}
</code></pre>
<p>Now, the only reason I added <code>count</code> was so that once 10000 items in <code>a</code> have been updated, the loop will stop, otherwise it will take a very long time to go thru all of the items. Even by limiting it like this, it still takes around 3 min. </p>
<p>For the sake of the example, T in this case is an object similar to the following:</p>
<pre><code>public class ExampleT
{
public string MatchA {get;set;}
public string MatchB {get;set;}
public double? ToUpdate {get;set;} //in List a this will ALWAYS be null until it gets updated in the foreach
}
</code></pre>
<p>Is there a way I can make this more efficient?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T16:01:46.193",
"Id": "17504",
"Score": "2",
"body": "You are essentially doing a join and then an update. I suspect that this can be written shorter using LINQ over objects syntax. Let me try to look it up. It should not be hard to analyze the complexity of this. Ok, this should hopefully be of some help: http://stackoverflow.com/questions/709560/linq-in-line-property-update-during-join\n\nLINQ can be slower than bare loops, but it often does a pretty good job."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T16:07:25.937",
"Id": "17505",
"Score": "3",
"body": "I would also look into PLINQ as you have a lot of data to plow through."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T17:10:59.453",
"Id": "17513",
"Score": "1",
"body": "Hm, using your example and stuffing various random data into the objects into the two lists of the sizes you specify, it executes in less than 1/100 second on my machine. I have my doubts that my box is 18,000 times faster than yours, so something else must be at work here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T19:20:58.677",
"Id": "17520",
"Score": "4",
"body": "There doesn't seem to any reason to pass `a` by reference in your code."
}
] |
[
{
"body": "<p>Not knowing the full extent of the data types behind the <code>MatchA</code>, <code>MatchB</code> and <code>ToUpdate</code> properties, it'll be difficult to give an answer which completely solves your performance issues. However, one potential optimization could be realized in your <code>foreach</code> line as such:</p>\n\n<pre><code>foreach (var z in a.FindAll(x => x.MatchA == b[i].MatchA && x.MatchB == b[i].MatchB && x.ToUpdate != b[i].ToUpdate))\n</code></pre>\n\n<p>This would limit the set brought back to only those members that actually need their <code>ToUpdate</code> set rather than just setting them whether they need to or not.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T19:53:00.930",
"Id": "17523",
"Score": "0",
"body": "I don't think this would help. You're trading one assignment for one condition, that shouldn't change much."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T20:07:15.667",
"Id": "17524",
"Score": "0",
"body": "The OP since updated the question and having it makes no more sense at all since it's true 100% of the time."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T16:07:38.970",
"Id": "11018",
"ParentId": "11017",
"Score": "2"
}
},
{
"body": "<p>Your code is O(<em>n m</em>), where <em>n</em> is the length of <code>a</code> and <em>m</em> is the length of <code>b</code>.</p>\n\n<p>You could make it O(<em>n</em> + <em>m</em>) (assuming only a small number of items from <code>a</code> match each item in <code>b</code>) by using a hash table. One possible way to do this is to use <a href=\"http://msdn.microsoft.com/en-us/library/bb549073.aspx\" rel=\"nofollow\"><code>ToLookup()</code></a>:</p>\n\n<pre><code>var aLookup = a.ToLookup(x => new { x.MatchA, x.MatchB });\n\nforeach (var bItem in b)\n{\n foreach (var aItem in aLookup[new { bItem.MatchA, bItem.MatchB }])\n aItem.ToUpdate = bItem.ToUpdate;\n}\n</code></pre>\n\n<p>Another way to do basically the same thing would be using <code>join</code>:</p>\n\n<pre><code>var pairs = from bItem in b\n join aItem in a\n on new { bItem.MatchA, bItem.MatchB } equals new { aItem.MatchA, aItem.MatchB }\n select new { bItem, aItem };\n\nforeach (var pair in pairs)\n pair.aItem.ToUpdate = pair.bItem.ToUpdate;\n</code></pre>\n\n<p>Also, you should really use better variable names.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T20:47:21.873",
"Id": "17525",
"Score": "1",
"body": "variable names where obviously renamed for the purposes of this post..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T19:46:48.597",
"Id": "11021",
"ParentId": "11017",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "11021",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T15:44:42.097",
"Id": "11017",
"Score": "2",
"Tags": [
"c#",
"performance"
],
"Title": "Updating items of one List<t> that match another List<t>"
}
|
11017
|
<p>Any improvements are welcome.</p>
<p>a.bat</p>
<pre><code>sed -r "s/private (.*) (.*);(.*)/&\npublic \1 get\u\2(){return \2;}\npublic void set\u\2(\u\2){this.\2=\u\2;}\n/" "%~1">"%~2"
</code></pre>
<p>in:</p>
<pre><code>private String firstName;// Stores firstName
private String lastName;
private String address;
</code></pre>
<p>using <code>a.bat in out</code></p>
<p>out:</p>
<pre><code>private String firstName;// Stores firstName
public String getFirstName(){return firstName;}
public void setFirstName(FirstName){this.firstName=FirstName;}
private String lastName;
public String getLastName(){return lastName;}
public void setLastName(LastName){this.lastName=LastName;}
private String address;
public String getAddress(){return address;}
public void setAddress(Address){this.address=Address;}
</code></pre>
<p>To do:
add javadoc generation to methods.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T01:36:02.687",
"Id": "17528",
"Score": "2",
"body": "Is this an exercise? Just because most IDEs do this out of the box. Otherwise I think it's an elegant solution :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T02:13:31.687",
"Id": "17529",
"Score": "0",
"body": "Thanks. I didn't really look into the IDE, since I use mostly a separate editor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T09:03:12.010",
"Id": "17549",
"Score": "0",
"body": "`private String firstName;// Stores firstName\n` You may know it, I say it anyway...do not comment what is obvious. ;)"
}
] |
[
{
"body": "<p><code>s/private (.*) (.*);(.*)</code>\nThis may be better done as <code>s/private ([^; ]+) +([^; ]+) *;(.*)$</code></p>\n\n<p>This avoids matching semicolon and space in the type and variable name.\n(Be as restrictive in your match as you can.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T02:23:01.330",
"Id": "11026",
"ParentId": "11024",
"Score": "0"
}
},
{
"body": "<p>You forgot the parameter type in the setter methods (including @blufox suggestion):</p>\n\n<pre><code>sed -r \"s/private\\s+([^; ]+)\\s+([^; ]+)\\s*;(.*)$/&\\npublic \\1 get\\u\\2(){return \\2;}\\npublic void set\\u\\2(\\1 \\2){this.\\2=\\u\\2;}\\n/\" \"%~1\">\"%~2\"\n</code></pre>\n\n<p>which produces:</p>\n\n<pre><code>private String firstName;// Stores firstName\npublic String getFirstName(){return firstName;}\npublic void setFirstName(String firstName){this.firstName=FirstName;}\n</code></pre>\n\n<p><strong>But</strong>: you better use an IDE (e.g., Eclipse) for these tasks. You are trying to parse Java code with a regex which is a bad idea.</p>\n\n<p>Just some examples:</p>\n\n<ul>\n<li><p>declarations could be on different lines</p>\n\n<pre><code>private String // some comment\n myVariableOnTheNextLine\n // some other comment\n ; // semicolon\n</code></pre></li>\n<li><p>the <code>public</code> or <code>private</code> modifier could be omitted</p>\n\n<pre><code>String myString;\n</code></pre></li>\n<li><p>fields can be initialized</p>\n\n<pre><code>String myString = \"my string\";\n</code></pre></li>\n<li><p>fields can be declared final</p>\n\n<pre><code>private final String myString;\n</code></pre></li>\n<li><p>and so on</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T07:40:56.147",
"Id": "11027",
"ParentId": "11024",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T01:11:29.050",
"Id": "11024",
"Score": "1",
"Tags": [
"java",
"regex",
"sed"
],
"Title": "Add getters and setters to a set of variables"
}
|
11024
|
<p>I've a bunch of sequential activities. These are long running. Once an activity is complete, it can't be rolled back. Now something deep down the line fails. Now I've few options</p>
<ol>
<li>Report this to end user and ask him to fix something. And then Retry same thing.</li>
<li>End user has no clue on what to do. He can choose to ignore. (Just retry won't fix things)</li>
<li>Abort/Pause? Now this is something tricky. This will stop the program. If program is rerun, it should resume from this failed point and <strong>not</strong> from the starting point.</li>
</ol>
<p>I'm thinking to implement this by defining a custom exception, Action delegate set, coming from exception object. So my question is
Do you see any issue with this pattern? Any better way to do the same?</p>
<pre><code>[Serializable]
public class SafetyNetException : Exception
{
public SafetyNetException(SafetyNet callBack) { Net = callBack; }
public SafetyNetException(SafetyNet callBack, string message) : base(message) { Net = callBack; }
public SafetyNetException(SafetyNet callBack, string message, Exception inner) : base(message, inner) { Net = callBack; }
protected SafetyNetException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
public SafetyNet Net { get; private set; }
}
public class SafetyNet
{
public Action Abort;
public Action Retry;
public Action Ignore;
}
[TestClass()]
public class SafetyNetTest
{
[TestMethod()]
public void APIUsageTest()
{
try
{
DoSomething();
}
catch (SafetyNetException targetException)
{
Debug.WriteLine(targetException.Message);
SafetyNet target = targetException.Net;
switch (AskUser())
{
case "r":
target.Retry();
break;
case "a":
target.Abort();
break;
case "i":
target.Ignore();
break;
}
}
}
private void DoSomething()
{
try
{
// try something
}
catch (Exception ex)
{
SafetyNet net = new SafetyNet();
net.Abort = () => DoSomething_Abort();
net.Retry = () => DoSomething();
net.Ignore = () => DoNextThing();
throw new SafetyNetException(net, "Ask user", ex);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T19:56:12.090",
"Id": "17563",
"Score": "2",
"body": "MS-DOS' most infamous error message. Infamous because no user could ever figure out what the proper response might be. There wasn't one :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T20:12:46.733",
"Id": "17564",
"Score": "0",
"body": "maybe look at this link to WF persistence services to see if it addresses similar concerns http://msdn.microsoft.com/en-us/library/ms734764(v=vs.90).aspx"
}
] |
[
{
"body": "<p>I would suggest that the outer routine should receive a <code>HandleError</code> delegate which is called when a problem is detected, before an exception is thrown by, or allowed to propagate beyond, anything but the lowest-level code. The code within that delegate can hopefully receive as parameters whatever information is needed to proceed sensibly from that point; the caller of the delegate can then--based upon the return value from the delegate--either retry the operation or proceed as well as possible without it; alternatively, the delegate may throw an exception to cause the outer-scope action to be aborted (possibly after recording somewhere information about how or where the action should be restarted).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T20:04:53.930",
"Id": "11033",
"ParentId": "11032",
"Score": "0"
}
},
{
"body": "<p>You really shouldn't be using exceptions to control the flow of your program's logic. What you're trying to do tends to work much better as a simple state machine that, when it fails, asks whoever is listening what it should do and responds accordingly. Here's a very rough example (which hasn't been tested, is not threadsafe, etc).</p>\n\n<pre><code>public interface ISequentialActivity\n{\n bool Run();\n}\n\npublic enum UserAction\n{\n Abort,\n Retry, \n Ignore\n}\n\npublic class FailureEventArgs\n{\n public UserAction Action = UserAction.Abort;\n}\n\npublic class SequentialActivityMachine\n{\n private Queue<ISequentialActivity> activities = new Queue<ISequentialActivity>();\n public event Action<FailureEventArgs> OnFailed; \n protected void PerformOnFailed(FailureEventArgs e)\n {\n var failed = this.OnFailed;\n if (failed != null)\n failed(e);\n }\n public void Add(ISequentialActivity activity) { this.activities.Enqueue(activity); }\n public void Run()\n {\n while (this.activities.Count > 0)\n {\n var next = activities.Peek();\n if (!next.Run())\n {\n var failureEventArgs = new FailureEventArgs();\n PerformOnFailed(failureEventArgs);\n\n if (failureEventArgs.Action == UserAction.Abort)\n return;\n if (failureEventArgs.Action == UserAction.Retry)\n continue;\n }\n\n activities.Dequeue();\n }\n }\n}\n</code></pre>\n\n<p>In this example, classes would encapsulate sections of retry-able logic by implementing <code>ISequentialActivity</code>, returning true from their <code>Run()</code> method if they succeeded and false if they failed in some way. Failure would then be pushed up to the listener through the event for decision making.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T06:44:59.540",
"Id": "17565",
"Score": "0",
"body": "Thanks! This makes sense. Few questions: The need `var failed = this.OnPerformed` is thread safety thing? And going by this way, all actions will have to go via this Machine class. Is there any other way where .NET framework can handle that. System.Transaction namespace? (or like my exception approach above)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T16:05:30.140",
"Id": "17595",
"Score": "0",
"body": "@Ankush The `var failed = this.OnPerformed` is about thread safety, in that it pushes potential race conditions to the listener. [Eric Lippert](http://blogs.msdn.com/b/ericlippert/archive/2009/04/29/events-and-races.aspx) has a good article on that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T16:11:26.670",
"Id": "17597",
"Score": "0",
"body": "@Ankush And you're correct that all actions would have to be run through this class for appropriate state transition semantics to be included. I don't know of anything inherently available in the .Net Framework that will handle this kind of thing for you, but as you saw it's not difficult to build. The System.Transactions namespace is mainly for interop with other systems that provide transactional support and I don't think it will be what you're looking for, but you're welcome to investigate and see if it would work for your specific situation."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T20:06:33.500",
"Id": "11034",
"ParentId": "11032",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "11034",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T19:46:51.100",
"Id": "11032",
"Score": "3",
"Tags": [
"c#",
".net",
"design-patterns",
"exception-handling"
],
"Title": "Is this right way to implement Abort, Retry and Ignore activity pattern?"
}
|
11032
|
<p>I basically check for required input fields and if they fail to validate, I need to go to another level of output, check for other required fields, and so on...</p>
<p>I can't get my head around this easy step-by-step validation. I already had it in a <code>while</code>-loop, but found it even more horrible than with beginner-like <code>if</code>-cases. I still think, though, that it could be written a bit simpler (and maybe improve readability).</p>
<p>It already is a quite simple thing to do, but in the course of development it will get bigger and bigger, so it needs to stay simple.</p>
<pre><code> // CHECK FOR REQUIRED PROPERTIES
if($properties['step'] == 2)
{
$req = array('cshort','cid');
foreach($req as $required)
{
if(!validate_var($req,$properties[$req]) || empty($properties[$req]))
{
$step = 1;
}
}
}
if($properties['step'] == 1)
{
$req = array('cshort');
foreach($req as $required)
{
if(!validate_var($req,$properties[$req]) || empty($properties[$req]))
{
$step = 1;
return $st
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Why do you only return a value if <code>$properties['step'] == 1</code>? If you could somehow change it so that both return, or both didn't need to, you could make it neater.</p>\n\n<pre><code>$req = array('cshort');\n$return = FALSE;\n\nif($properties['step'] == 1) {\n $req[] = 'cid';\n $return = TRUE;\n}\n\nforeach($req as $required) {\n $step = 1;\n if($return) {\n return $st;\n /*\n $step? what is this where did it come from?\n Unless you are in a function, you don't need to return.\n Just use $st/$step when you need it since you only ever\n gave it one value. Just check if it isset first.\n If you want to break from the loop, just use break,\n or continue to skip.\n */\n }\n}\n</code></pre>\n\n<p>You mentioned expanding. If this gets too much bigger you could try a switch statement instead of multiple if statements. Assuming the rest don't use the same format, otherwise just tweaking what I gave above should work.</p>\n\n<pre><code>switch($properties['step']) {\n case 1:\n foreach($req as $required) {\n }\n break;\n case 2:\n $req[] = 'cid';\n foreach($req as $required) {\n }\n break;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T16:08:58.763",
"Id": "17596",
"Score": "0",
"body": "I seem to have gotten a few upvotes since last I looked. Be sure to read Paul's post as well. He did get a few things I missed and it is still very informative."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T13:09:01.703",
"Id": "11039",
"ParentId": "11038",
"Score": "3"
}
},
{
"body": "<p>Firstly I'll review things as you have them.</p>\n\n<p><strong>Some things are backwards.</strong> You need to change it to:</p>\n\n<pre><code>$required = array('cshort');\n\nforeach ($required as $req)\n{\n if(empty($properties[$req]) || !validate_var($req,$properties[$req])) \n</code></pre>\n\n<p>The $req is now the value in the array rather than being the entire array (which would have been a mistake).</p>\n\n<p>The check for empty will come first now because logical expressions are evaluated from left to right (after any operator precedence is determined).</p>\n\n<p><strong>Missing code:</strong></p>\n\n<pre><code>$step = 1;\nreturn $st\n</code></pre>\n\n<p>I'm guessing you wanted it to be <code>return $step;</code>. I would write this as <code>return 1;</code> rather than create a variable that does not vary.</p>\n\n<h2>How to Improve</h2>\n\n<p>You are wanting to check a list of requirements. The data structure that resembles that is an array (which you have used already). The best things for processing arrays are loops because they avoid the cut and pasted code.</p>\n\n<p>Here is what I would do (there are comments in it with further explanation):</p>\n\n<pre><code>$required = array();\n\n// Build the requirements first.\nswitch ($properties['step'])\n{\n// Case statements without a break cause the processing to continue into the\n// next case. Using this case 2 will add to the start of the array 'cid' and\n// then will add 'cshort' before that. \ncase 2:\n array_unshift($required, 'cid');\ncase 1:\n array_unshift($required, 'cshort');\n break;\ndefault:\n throw new DomainException('Step is not within the correct range');\n}\n\n$step = 0;\n\n// Loop through, processing all of the requirements and counting the successful steps.\nforeach($required as $req) \n{ \n if(empty($properties[$req]) || !validate_var($req,$properties[$req])) \n {\n return $step;\n }\n\n $step++;\n}\n\nreturn $step;\n</code></pre>\n\n<p>Note: Building the list of requirements could be done many ways. The way I chose of letting the switch statement flow through the steps might be controversial. However the basic idea of looping over the array rather than having many cut and pasted loops is my main recommendation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T13:15:47.357",
"Id": "11040",
"ParentId": "11038",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "11040",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T12:43:06.213",
"Id": "11038",
"Score": "1",
"Tags": [
"php",
"validation"
],
"Title": "Validating required fields"
}
|
11038
|
<p>In Framework Design guideline book there is a chapter about Exception and they talk about return-value-based error reporting and exception based error reporting and the fact that we in a O.O language like C# we should avoid return-value-based error reporting and use exceptions. With that in mind I was looking at our code that eight years ago was written in Visual Basic and last year with a automatic tool got converted to C#!</p>
<p>So here is a method I am looking at, I was wondering if the advice from that book applies to such a method and if yes, then what would be a better approach for rewriting this method? </p>
<pre><code>public int Update(CaseStep oCaseStepIn)
{
int result = 0;
//Update the master object with the passed in object
result = UCommonIndep.gnUPDATE_FAILED;
if (Validate(oCaseStepIn) == UCommonIndep.gnVALIDATE_FAILED)
{
return result;
}
CaseStep oCaseStep = get_ItemByObjectKey(oCaseStepIn.CopyOfObjectKey);
if (oCaseStep == null)
{
return result;
}
if (oCaseStep.Update(oCaseStepIn) == UCommonIndep.gnUPDATE_SUCCESSFUL)
{
//*******************************
//FYI - Insert code here to update any Key values that might have changed.
result = UCommonIndep.gnUPDATE_SUCCESSFUL;
}
return result;
}
</code></pre>
|
[] |
[
{
"body": "<p>Yes, the refactoring \"Replace error codes with exceptions\" work perfectly here.\nAs a first step you need to create an exception type that suits your need, something like</p>\n\n<pre><code>public class UpdateException : Exception\n{\n //your custom properties, fields etc.\n}\n</code></pre>\n\n<p>and then use it in your method (an example below)</p>\n\n<pre><code>public void Update(CaseStep oCaseStepIn)\n{\n //Update the master object with the passed in object\n\n if (Validate(oCaseStepIn) == UCommonIndep.gnVALIDATE_FAILED) \n throw new UpdateException(); //pass in constructor useful messages\n\n CaseStep oCaseStep = get_ItemByObjectKey(oCaseStepIn.CopyOfObjectKey);\n if (oCaseStep == null)\n throw new UpdateException(); //pass in constructor useful messages\n\n\n if (oCaseStep.Update(oCaseStepIn) != UCommonIndep.gnUPDATE_SUCCESSFUL)\n throw new UpdateException(); //pass in constructor useful messages\n\n //*******************************\n //FYI - Insert code here to update any Key values that might have changed.\n}\n</code></pre>\n\n<p>You can create different Exception subclasses for each type of error. It's even better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T15:09:12.740",
"Id": "17589",
"Score": "1",
"body": "The code would look even better if you applied the same refactoring to the methods you're calling. I'm not sure it should be applied for all of them (e.g. it makes sense that `Validate()` returns some result and doesn't throw), but it certainly makes sense at least in some cases (like `oCaseStep.Update()`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T15:34:54.283",
"Id": "17590",
"Score": "0",
"body": "This looks like a hybrid (mix of return code enums and exceptions) to me. Obviously you do not have full access to the original code and cannot read the poster's mind, but this particular snippet is not so much better, that it is obvious that one should lean toward using exceptions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T16:26:20.177",
"Id": "17598",
"Score": "0",
"body": "@svick Yes, you are right, this is a great recommendation; the example is only on what we have in the original post :) (+1)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T14:52:20.343",
"Id": "11043",
"ParentId": "11041",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "11043",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T14:25:00.157",
"Id": "11041",
"Score": "0",
"Tags": [
"c#",
"exception",
"error-handling"
],
"Title": "uplifitng return value error reporting to Exception based error reporting"
}
|
11041
|
<p>I have an application that has multiple functions. Two in particular will query a remote computer using WMI, and return the installed printers in a datagridview. The other is a new method that will query the remote computer using WMI, and return information about the RAM.</p>
<p>I don't want to repeat the code that populates the datagrideview each time I need to display info from a WMI call. To accommodate this, I changed the way the datagrideview is populated. It is now in a separate class.</p>
<p>I'm just wanting to know if this is the best solution.</p>
<p>Here is one of the methods that implements the new class I made. This method below will get the installed printers on the target machine:</p>
<pre><code> class remote_Info
{
public Form getPrinters(string target, Form print_Form)
{
/**This will query the remote computer for the installed printers.
* It does this by using WMI and looking in Win32_Printer.
*
* */
// Check to make sure no null arguments were passed
if (target == null | print_Form == null)
throw new ArgumentNullException();
// Define the dataTable and DataColumns
// The columns will server as the header in the datagrid
DataTable dt = new DataTable();
DataColumn colName = new DataColumn("Name");
DataColumn col_Driver = new DataColumn("Driver");
DataColumn colLocation = new DataColumn("Location");
dt.Columns.Add(colName);
dt.Columns.Add(col_Driver);
dt.Columns.Add(colLocation);
ManagementScope scope = new ManagementScope("\\\\" + target + "\\root\\cimv2");
SelectQuery query = new SelectQuery("SELECT * FROM Win32_Printer");
ManagementObjectSearcher mos = new ManagementObjectSearcher(scope, query);
try
{
using (ManagementObjectCollection moc = mos.Get())
{
// Fire off a foreach loop. First creating a new data
foreach (ManagementObject mo in moc)
{
try
{
DataRow row1 = dt.NewRow();
row1[colName] = mo["Name"] ?? "N/A";
row1[col_Driver] = mo["DriverName"] ?? "N/A";
row1[colLocation] = mo["Location"] ?? "N/A";
dt.Rows.Add(row1);
}
finally
{
if (mo != null)
mo.Dispose();
}
}
}
}
catch(Exception ex)
{
writeLog(ex);
MessageBox.Show("There was an error while processing your request. View the errorlog for more information");
}
display_Forms displayInstance = new display_Forms();
return displayInstance.wmi_FillGrid("Printers", dt, print_Form);
}
}
</code></pre>
<p>Now here is the class and method I made to fill the datagrideview. My idea is to use this each time I need to fill data from WMI into a datagrideview.</p>
<pre><code> class display_Forms
{
public Form wmi_FillGrid(string title, DataTable dt, Form print_Form)
{
// Set the title of the form.
print_Form.Text = (title);
print_Form.AutoSize = true;
// Declare the datagrid view
DataGridView dataGrid = new DataGridView();
// Datagrid Properties
dataGrid.BorderStyle = BorderStyle.None;
dataGrid.BackgroundColor = SystemColors.GradientInactiveCaption;
dataGrid.AutoSize = true;
dataGrid.Width = 0;
dataGrid.Height = 0;
print_Form.Width = dataGrid.Width;
print_Form.Height = dataGrid.Height;
dataGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
// Set the datasource to the Datatable
dataGrid.DataSource = dt;
// Add the datagrid to the form
print_Form.Controls.Add(dataGrid);
return print_Form;
}
}
</code></pre>
<p>Just to show a full example, here is the calling method:</p>
<pre><code>private void getInstalledPrinterListAtTargetToolStripMenuItem_Click(object sender, EventArgs e)
{
// This will query the list of installed printers on the target machine.
// Using WMI, it will query win32_Printers and loop through the returned list.
// This is all done on a seperate thread, finally returning the form in which the data is dispalyed.
// The form is called with begininvoke and displayed on the GUI thread.
string target = null;
DialogResult results = custom_Forms.supperInputBox("Computer Name", "Enter Computer Name", ref target);
if (results == System.Windows.Forms.DialogResult.Cancel)
return;
if (validation.validate(target) == false | validation.alphaNum(target) == false)
return;
// Declare the local objects
remote_Info info = new remote_Info();
Form print_Form = new Form();
// Execute the query on a seperate thread. Wrapping in a try/catch/finally block
// The finally statement will display the returned Form from the getPrinters method.
(new System.Threading.Thread(() =>
{
try
{
print_Form = info.getPrinters(target, print_Form);
}
catch (Exception ex)
{
writeLog(ex);
return;
}
finally
{
this.BeginInvoke((Action)delegate
{
if(print_Form != null)
print_Form.Show();
});
}
})).Start();
print_Form = info.getPrinters(target, print_Form);
print_Form.Show();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T15:45:01.150",
"Id": "17592",
"Score": "2",
"body": "Please run StyleCop on this first. You are not even following the right naming conventions ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T18:27:01.507",
"Id": "17607",
"Score": "3",
"body": "Stylecop is usually a little too picky for my taste. There's a large number of rule that were developed for Microsoft internally and do not really come from the naming and layout conventions for .NET source code in general. So when using Stylecop, go through the list of rules to disable any rule which is too strict."
}
] |
[
{
"body": "<p>First, please do what <a href=\"https://codereview.stackexchange.com/users/9778/leonid\">Leonid</a> mentions in his comment. The code is woefully out of standard convention for C# and .NET. Is this a Java port perhaps? Secondly, check your spelling in your comments. Nothing makes a developer wince more than looking at someone else's code and starting off by seeing egregious spelling errors. It does not speak well for the rest of the code.</p>\n\n<p>That bit out of the way, I'm going to tackle your <code>display_Forms</code> class as an example of where to start to clean up. A big part of what I did what separate concerns into separate methods so that future changes are more easily found and dealt with. Note I made the class <code>static</code> as you're storing no state (also take note that the <code>remote_Info</code> class is the same way) and I'm using an extension method on the <code>Form</code> so it can be used a bit more fluently.</p>\n\n<p>Best of luck.</p>\n\n<pre><code>internal static class DisplayForms\n{\n public static Form WmiFillGrid(this Form printForm, string title, DataTable dt)\n {\n return printForm == null ? null : UpdatePrintForm(printForm, title, CreateDataGridView(dt));\n }\n\n private static Control CreateDataGridView(DataTable dt)\n {\n // Declare the data grid view\n return new DataGridView\n {\n // Data grid Properties\n BorderStyle = BorderStyle.None,\n BackgroundColor = SystemColors.GradientInactiveCaption,\n AutoSize = true,\n Width = 0,\n Height = 0,\n AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells,\n\n // Set the data source to the Data table\n DataSource = dt\n };\n }\n\n private static Form UpdatePrintForm(Form printForm, string title, Control dataGrid)\n {\n // Set the title of the form.\n printForm.Text = title;\n printForm.AutoSize = true;\n\n printForm.Width = dataGrid.Width;\n printForm.Height = dataGrid.Height;\n\n // Add the data grid to the form\n printForm.Controls.Add(dataGrid);\n\n return printForm;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T16:47:00.620",
"Id": "17601",
"Score": "0",
"body": "Thanks for you input. I like the idea of making displayForms static. Also, no this ilsnt a java port. I have had no formal c# training, and everything is self taught. No excuses, I need to adopt conventional standards. Also yes, I am a very bad speller. Maybe I can find a spell check add-in for VS =)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T18:24:55.173",
"Id": "17605",
"Score": "2",
"body": "Spell Check Add-on: http://visualstudiogallery.msdn.microsoft.com/7c8341f1-ebac-40c8-92c2-476db8d523ce"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T18:25:28.900",
"Id": "17606",
"Score": "3",
"body": "Naming Conventions: http://msdn.microsoft.com/en-us/library/ms229002.aspx"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T16:36:24.113",
"Id": "11046",
"ParentId": "11044",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T15:34:43.860",
"Id": "11044",
"Score": "3",
"Tags": [
"c#",
"winforms"
],
"Title": "Query a remote computer using WMI, and return the installed printers in a datagridview"
}
|
11044
|
<p>I have a class with some properties that I need to reflect over. One of the things I need, is a instance of a complex type returned for each of my properties, which means I can't just instantiate it directly in the attribute. </p>
<p>Now, I have so far two ways to do this. Either I can write method-names, in strings, in each attribute pointing to the method to call to get the instance, or I can use <em>Duck Typing</em> and add a "magic" method, that will contain information about the instance needed for each attribute.</p>
<p>Okay, let me show some code and then I need some feedback on which way is preferable or suggestions for other ways I haven't thought of.</p>
<pre><code>public class SomeClass
{
[Parameter("OnePropertyWidgetProvider")]
public string OneProperty { get; set; }
[Parameter("AnotherPropertyWidgetProvider")]
public string AnotherProperty { get; set; }
private Widget OnePropertyWidgetProvider() {}
private Widget AnotherPropertyWidgetProvider() {}
}
</code></pre>
<p>Or</p>
<pre><code>public class SomeClass
{
public string OneProperty { get; set; }
public string AnotherProperty { get; set; }
private ParameterWidgets GetWidgets()
{
return new ParameterWidgets()
{
{ () => this.OneProperty, new Widget() },
{ () => this.AnotherProperty, new Widget() },
};
}
}
</code></pre>
<p>The class itself a <em>unit-of-work</em> that can be configured through a GUI. The Widget-instance is needed to configure the editor the user should see to fill out the given property. </p>
<p>My concern with the first way is lack of type-safety, there is no way to check at compile-tile if the functions actually exists. It's always kinda verbose, and with many properties in one class, you end up with many methods returning Widgets. </p>
<p>The other way might introduce ways of coding that many programmers are not familiar with; lambdas and such. The syntax is cool, there is type safety, etc., but I'm afraid of it being "too clever".</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T16:42:14.963",
"Id": "17599",
"Score": "1",
"body": "What is the underlying goal of this class? What purpose does the class serve? Do the properties need to be simple strings? You started with \"I have a class with properties I need to reflect over\" and \"I need an instance of a complex type for each property\", but those seem like implementation details which could still be malleable, given your two code examples."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T16:45:46.987",
"Id": "17600",
"Score": "0",
"body": "The class itself a unit-of-work that can be configured through a GUI. The Widget-instance is needed to configure the editor the user should see to fill out the given property."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T17:27:43.283",
"Id": "17602",
"Score": "3",
"body": "This seems like bad separation of concerns to me. The class shouldn't decide how will its parts going to be displayed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T17:31:50.470",
"Id": "17603",
"Score": "0",
"body": "the widget can contain information like textbox, dropdownlist, checkboxlist etc. Anyway, its just the way the system is constructed and i have no way to change that, so thats not really in the scope of this question."
}
] |
[
{
"body": "<p>I've done this several times with a typeof operator in the attribute. That's how MS does their Editor attribute. The only disadvantage is that you can't pass constructor attributes that way. In other words you have an attribute on your property like this:</p>\n\n<pre><code>[Widget(typeof(TextBoxWidget))]\n</code></pre>\n\n<p>If you need parameters, you could still do it with inheritors of Widget. Suppose you need a Min/Max/Inc on your numeric widget:</p>\n\n<pre><code>[NumericWidget(-42, 42, 1)]\n</code></pre>\n\n<p>The methods to get the attributes allow you to look for inheritors of an attribute type.</p>\n\n<p>Without this parameterized attribute approach, I definitely prefer your second option. And I would put GetWidgets into its own IHasWidgets interface. That way you can fall back to some default all-text-box implementation when that interface is missing.</p>\n\n<p>Another good option is to put this information into the property registration. Are you familiar with the DependencyProperty mechanism in WPF? The CSLA framework (among others) support a property registration mechanism that is a good match for what you're doing here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-27T04:29:07.653",
"Id": "13109",
"ParentId": "11045",
"Score": "2"
}
},
{
"body": "<p>Another approach is to introduce family of types that can be mapped onto widgets to get proper representation in GUI. I.e. either interface</p>\n\n<pre><code>class OnePropertyType : IWidgetAssociatied\n{\n public string Value { get {} set {} }\n\n Widget IWidgetAssociated.CreateWidget() {}\n}\n\nclass AnotherPropertyType : IWidgetAssociated {}\n</code></pre>\n\n<p>Or through overload</p>\n\n<pre><code>Widget CreateWidgetFor(OnePropertyType one) {}\nWidget CreateWidgetFor(AnotherPropertyType another) {}\n</code></pre>\n\n<p>In first case you'll have to cast to interface in second case you'll use member resolving.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-24T12:04:50.543",
"Id": "19891",
"ParentId": "11045",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T16:06:41.310",
"Id": "11045",
"Score": "2",
"Tags": [
"c#",
".net"
],
"Title": "Best way to relate methods with properties"
}
|
11045
|
<p>I just completed <a href="https://projecteuler.net/problem=18" rel="nofollow">Project Euler</a> problem 18 which is a dynamic programming question through a graph of a triangle of numbers. The goal is to find the path from top to bottom of the triangle that has the largest sum.</p>
<p>In the example below the path is 3->7->4->9.</p>
<p>Say the numbers in the triangle are:</p>
<pre><code> 3
7 4
2 4 6
8 5 9 3
</code></pre>
<p>I built a jagged array that looks like:</p>
<pre><code>int[][] triangleNumbers = new int[4][]
{
new int[] {3},
new int[] {7, 4},
new int[] {2, 4, 6},
new int[] {8, 5, 9, 3},
};
</code></pre>
<p>Then I made a custom object <code>TriangleNode</code> and converted the numbers into <code>TriangleNodes</code>. Then I went through and connected the lower left and lower right nodes to their parent so I could graph traverse them easily.</p>
<pre><code>//build triangle graph
TriangleNode[][] triangleGraph = new TriangleNode[triangleNumbers.Length][];
for(int row = 0; row < triangleNumbers.Length; row++)
{
triangleGraph[row] = new TriangleNode[triangleNumbers[row].Length];
for(int col = 0; col < triangleNumbers[row].Length; col++)
{
//create the Node and save the value
triangleGraph[row][col] = new TriangleNode(triangleNumbers[row][col]);
}
}
//connect triangle graph
for(int row = 0; row < triangleGraph.Length; row++)
{
for(int col = 0; col < triangleGraph[row].Length; col++)
{
if(row + 1 == triangleGraph.Length)
{
//bool for easy graph traversing to check if I'm at the bottom row
triangleGraph[row][col].IsEnd = true;
}
else
{
//hook up the Left/Right pointers
triangleGraph[row][col].Left = triangleGraph[row + 1][col];
triangleGraph[row][col].Right = triangleGraph[row + 1][col + 1];
}
}
}
</code></pre>
<p>Obviously this is a ton of code just to build the graph.</p>
<p>Is there an easier way to build this graph? The requirements are that each <code>TriangleNode</code> holds its value and <code>Left</code>/<code>Right</code> pointers to the <code>Node</code>s in the row directly below. I was thinking there might be some voodoo magic via LINQ to turn the <code>triangleNumbers[][]</code> into the <code>triangleGraph[][]</code>, then some more voodoo to hook up the <code>Left</code>/<code>Right</code> pointers.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T20:45:21.663",
"Id": "17612",
"Score": "2",
"body": "You can throw out a lot of code lad :) The array of arrays is already a tree (you do not need a graph). It is not uncommon to use an array as an underlying data structure for a tree/heap, particularly when the structure is well-defined and does not change, which is the case here. JUST UPDAT THE RUNNING SUM IN PLACE working bottom to top. It is destructive, but all you want is one number. The parent-child relationship is easily defined with indexes and you already spelled it out in code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T20:51:23.873",
"Id": "17613",
"Score": "0",
"body": "@Leonid, right, I see what you're saying. To find the solution, I did exactly what you're saying, but with my custom graph. Which made it not destructive (undestructive ?), but I suppose that doesn't matter very much huh."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T20:55:05.207",
"Id": "17614",
"Score": "0",
"body": "Yes, see for instance a comment by magicdead at http://blog.functionalfun.net/2008/08/project-euler-problems-18-and-67.html"
}
] |
[
{
"body": "<p>I don't know about \"LINQ voodoo\", but you could do this in one pass if you reversed the order you're processing the rows. Something like this:</p>\n\n<pre><code> //build triangle graph \n var triangleGraph = new TriangleNode[triangleNumbers.Length][];\n\n for (int row = triangleNumbers.Length - 1; row >= 0; row--)\n {\n triangleGraph[row] = new TriangleNode[triangleNumbers[row].Length];\n for (int col = 0; col < triangleGraph[row].Length; col++)\n {\n //create the Node and save the value\n bool isEnd = row == triangleNumbers.Length - 1;\n triangleGraph[row][col] = new TriangleNode(triangleNumbers[row][col])\n {\n IsEnd = isEnd,\n Left = isEnd ? null : triangleGraph[row + 1][col],\n Right = isEnd ? null : triangleGraph[row + 1][col + 1]\n };\n }\n }\n</code></pre>\n\n<p>I'll admit, I didn't test</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T15:52:19.913",
"Id": "11226",
"ParentId": "11051",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T20:38:57.540",
"Id": "11051",
"Score": "1",
"Tags": [
"c#",
"programming-challenge"
],
"Title": "Connect graph from 2D array"
}
|
11051
|
<p>Working in C++ and I have some code which I'm refactoring. I have some code that needs to work with times of day but not dates. I do some juggling with <code>time_t</code> and <code>struct tm</code> but it's a pain and not intuitive to use. So I decided to make a basic time class with no date component. Let me know if you see any issues or have ideas for improvement:</p>
<p>TimeOnly.h</p>
<pre><code>#pragma once
class TimeOnly
{
public:
TimeOnly(int hour, int minute, int second);
virtual ~TimeOnly();
static TimeOnly GetCurrentTime();
virtual int GetHour() const;
virtual int GetMinute() const;
virtual int GetSecond() const;
private:
int hour_;
int minute_;
int second_;
};
inline bool operator==(const TimeOnly& lhs, const TimeOnly& rhs)
{
/* do actual comparison */
return (
(lhs.GetHour() == rhs.GetHour())
&& (lhs.GetMinute() == rhs.GetMinute())
&& (lhs.GetSecond() == rhs.GetSecond())
);
}
inline bool operator!=(const TimeOnly& lhs, const TimeOnly& rhs){ return !operator==(lhs, rhs); }
inline bool operator<(const TimeOnly& lhs, const TimeOnly& rhs)
{
/* do actual comparison */
if(lhs.GetHour() >= rhs.GetHour())
{
return false;
}
else if(lhs.GetMinute() >= rhs.GetMinute())
{
return false;
}
else if(lhs.GetSecond() >= rhs.GetSecond())
{
return false;
}
else
{
return true;
}
}
inline bool operator>(const TimeOnly& lhs, const TimeOnly& rhs){ return operator<(rhs, lhs); }
inline bool operator<=(const TimeOnly& lhs, const TimeOnly& rhs){ return !operator>(lhs, rhs); }
inline bool operator>=(const TimeOnly& lhs, const TimeOnly& rhs){ return !operator<(lhs, rhs); }
</code></pre>
<p>TimeOnly.cpp</p>
<pre><code>#include "TimeOnly.h"
#include <stdexcept>
#include <ctime>
TimeOnly::TimeOnly(int hour, int minute, int second):
hour_(hour),
minute_(minute),
second_(second)
{
if(
(hour_ >= 0 && hour_ <= 23)
&& (minute_ >= 0 && minute_ <= 59)
&& (second_ >= 0 && second_ <= 59)
)
{
//ok
}
else
{
throw std::invalid_argument("Time must be between 0:00:00 and 23:59:59");
}
}
TimeOnly TimeOnly::GetCurrentTime()
{
// get time now
time_t t = time(0);
struct tm * now = localtime(&t);
return TimeOnly(now->tm_hour, now->tm_min, now->tm_sec);
}
TimeOnly::~TimeOnly()
{
}
int TimeOnly::GetHour() const
{
return hour_;
}
int TimeOnly::GetMinute() const
{
return minute_;
}
int TimeOnly::GetSecond() const
{
return second_;
}
</code></pre>
<p><strong>Edit</strong></p>
<p>This is my revised class taking some suggestions from the answers:</p>
<p>Time.h</p>
<pre><code>#pragma once
class TimeOnly
{
public:
TimeOnly(int seconds);
TimeOnly(int hour, int minute, int second);
~TimeOnly();
TimeOnly AddSeconds(int seconds);
static TimeOnly Now();
int GetHour() const;
int GetMinute() const;
int GetSecond() const;
int GetTotalSeconds() const;
private:
void Init(int seconds);
int secondsInDay_;
static const int SECONDS_IN_A_DAY = 86400;
static const int SECONDS_IN_AN_HOUR = 3600;
static const int SECONDS_IN_A_MINUTE = 60;
};
inline bool operator==(const TimeOnly& lhs, const TimeOnly& rhs)
{
/* do actual comparison */
return lhs.GetTotalSeconds() == rhs.GetTotalSeconds();
}
inline bool operator!=(const TimeOnly& lhs, const TimeOnly& rhs){ return !operator==(lhs, rhs); }
inline bool operator<(const TimeOnly& lhs, const TimeOnly& rhs)
{
/* do actual comparison */
return lhs.GetTotalSeconds() < rhs.GetTotalSeconds();
}
inline bool operator>(const TimeOnly& lhs, const TimeOnly& rhs){ return operator<(rhs, lhs); }
inline bool operator<=(const TimeOnly& lhs, const TimeOnly& rhs){ return !operator>(lhs, rhs); }
inline bool operator>=(const TimeOnly& lhs, const TimeOnly& rhs){ return !operator<(lhs, rhs); }
</code></pre>
<p>TimeOnly.cpp</p>
<pre><code>#include "TimeOnly.h"
#include <stdexcept>
#include <ctime>
TimeOnly::TimeOnly(int seconds)
{
Init(seconds);
}
TimeOnly::TimeOnly(int hour, int minute, int second)
{
int seconds = (hour * SECONDS_IN_AN_HOUR) + (minute * SECONDS_IN_A_MINUTE) + seconds;
Init(seconds);
}
TimeOnly::~TimeOnly()
{
}
void TimeOnly::Init(int seconds)
{
if(seconds >= 0 && seconds < SECONDS_IN_A_DAY)
{
secondsInDay_ = seconds;
}
else
{
throw std::invalid_argument("Time must be between 0:00:00 and 23:59:59");
}
}
TimeOnly TimeOnly::AddSeconds(int seconds)
{
int newSeconds = (secondsInDay_ + seconds) % SECONDS_IN_A_DAY;
return TimeOnly(newSeconds);
}
TimeOnly TimeOnly::Now()
{
// get time now
time_t t = time(0);
struct tm * now = localtime( & t );
return TimeOnly(now->tm_hour, now->tm_min, now->tm_sec);
}
int TimeOnly::GetHour() const
{
return secondsInDay_ / SECONDS_IN_AN_HOUR;
}
int TimeOnly::GetMinute() const
{
return (secondsInDay_ % (SECONDS_IN_AN_HOUR)) / SECONDS_IN_A_MINUTE;
}
int TimeOnly::GetSecond() const
{
return secondsInDay_ % SECONDS_IN_A_MINUTE;
}
int TimeOnly::GetTotalSeconds() const
{
return secondsInDay_;
}
</code></pre>
<p>(Note renamed <code>GetCurrentTime()</code> to <code>Now()</code> because I was getting <code>error LNK2001: unresolved external symbol... GetTickCount(void)</code> even though I have no <code>GetTickCount</code> method. Turns out winbase.h has <code>#define GetCurrentTime() GetTickCount()</code>)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T21:05:07.143",
"Id": "17615",
"Score": "0",
"body": "Why not call it TimeSpan which is the time span since last midnight. This has got to be a solved problem. For instance, see this document for inspiration http://msdn.microsoft.com/en-us/library/system.timespan.aspx"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T21:21:04.597",
"Id": "17616",
"Score": "1",
"body": "To me, a TimeSpan is conceptually something different. Yes I see how you could use it the same but it also allows arbitrarily large TimeSpans whereas I'm looking for time of day in the 24 range of a day. If it is solved elsewhere I'm all ears. Good idea, however, for looking at TimeSpan for additional methods to add."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T21:39:56.633",
"Id": "17617",
"Score": "0",
"body": "I will look for the C++ implementations. Looks to me like TimeOnly can wrap (contain) a general TimeSpan and add a few restrictions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T21:46:36.627",
"Id": "17618",
"Score": "0",
"body": "I serached online using http://www.koders.com/default.aspx?s=TimeSpan+GetMinute&submit=Search&la=Cpp&li=* (the google code search alternative), and found something like this: http://www.koders.com/cpp/fid8469F6817E47596C30815ECCC492260ACA125DC5.aspx?s=TimeSpan+GetMinute#L22"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T21:51:15.217",
"Id": "17619",
"Score": "0",
"body": "Same with https://github.com/search?utf8=%E2%9C%93&q=TimeSpan&repo=&langOverride=&start_value=1&type=Code&language=C%2B%2B search: https://github.com/DrFrankenstein/amnlib/blob/397a304961e330659bc70418d88b4476d2f90013/timespan.cpp https://github.com/riviera/plex/blob/db3dd2dd7d87c16901cbdc4a964596f305e3f9b9/xbmc/DateTime.cpp"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-21T11:56:11.610",
"Id": "17629",
"Score": "0",
"body": "I agree with OP, a time span is to time as `ptrdiff_t` is to a pointer. They are conceptually different. .NET makes the same distinction, by the way (but in .NET a time always has a date associated)."
}
] |
[
{
"body": "<p>Personally I would look at boost. They probably have something.</p>\n<h3>Comments:</h3>\n<pre><code>virtual ~TimeOnly();\n</code></pre>\n<p>Are you really going to derive from this class?</p>\n<h3>Implementation</h3>\n<pre><code>private:\n int hour_;\n int minute_;\n int second_;\n</code></pre>\n<p>Holding these as separate fields makes the rest of the code more complex.<br />\nI personally would hold this a single value (seconds since start of day).</p>\n<p>Then all your comparisons become trivial.<br />\nYour get functions become slightly more complex but not not very much:</p>\n<pre><code>private:\n int secondsInDay;\n\ninline bool TimeOnly::equal(const TimeOnly& rhs)\n{\n return secondsInDay == rhs.secondsInDay;\n} \n\ninline bool TimeOnly::less(const TimeOnly& rhs)\n{ \n return secondsInDay < rhs.secondsInDay;\n} \n\nint TimeOnly::GetHour() const\n{\n return secondsInDay / (60 * 60);\n}\n\nint TimeOnly::GetMinute() const\n{\n return (secondsInDay % (60 * 60)) / 60;\n}\n\nint TimeOnly::GetSecond() const\n{\n return secondsInDay % 60;\n}\n\ninline bool operator==(const TimeOnly& lhs, const TimeOnly& rhs) {return lhs.equal(rhs);} \ninline bool operator!=(const TimeOnly& lhs, const TimeOnly& rhs) {return !lhs == rhs); } \ninline bool operator< (const TimeOnly& lhs, const TimeOnly& rhs) {return lhs.less(rhs);} \ninline bool operator> (const TimeOnly& lhs, const TimeOnly& rhs) {return (rhs < lhs); } \ninline bool operator<=(const TimeOnly& lhs, const TimeOnly& rhs) {return !(lhs > rhs); } \ninline bool operator>=(const TimeOnly& lhs, const TimeOnly& rhs) {return !(lhs < rhs); }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T22:48:33.647",
"Id": "17621",
"Score": "0",
"body": "I looked at [Boost.Date_Time](http://www.boost.org/doc/libs/1_40_0/doc/html/date_time.html) but as far as I can tell there will always be a date associated. I guess I could use boost's time_duration as the underlying implementation to my class. Probably cleaner, but I thought the class was pretty simple to begin with. Good idea with the seconds of the day."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-21T22:11:04.177",
"Id": "17642",
"Score": "0",
"body": "Good point about the virtual, you're right this will probably be a \"leaf\" class. Actually I realized I'll probably need at least an `AddSeconds()` method, and this is where your data representation really shines, then it's just adding x number of seconds (and modding by the number of seconds in a day to handle the wrap around)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-21T23:08:07.647",
"Id": "17643",
"Score": "0",
"body": "In your comparison operator definitions, can I access private members even though the operator definitions are non-member functions?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-22T18:36:04.967",
"Id": "17656",
"Score": "0",
"body": "Yes. Because they are the same class you can access private members of other instances. See: http://stackoverflow.com/a/437507/14065"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-22T23:41:32.887",
"Id": "17661",
"Score": "0",
"body": "But these are non-member operator definitions, do they need to be declared `friend` for that to work?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-22T23:57:00.450",
"Id": "17662",
"Score": "0",
"body": "@User: Whoops. OK refactored slightly."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T22:23:26.570",
"Id": "11053",
"ParentId": "11052",
"Score": "7"
}
},
{
"body": "<p>Nicer to split this into a new method (can be reused.)</p>\n\n<pre><code>bool TimeOnly::isVallid(int h, int m, int s) {\n return ((hour_ >= 0 && hour_ <= 23)\n && (minute_ >= 0 && minute_ <= 59)\n && (second_ >= 0 || second_ <= 59)\n );\n}\n</code></pre>\n\n<p>Generally nicer to check validity first in the condition rather than in else.</p>\n\n<pre><code>TimeOnly::TimeOnly(int hour, int minute, int second):\n hour_(hour),\n minute_(minute),\n second_(second)\n{\n if(!isValid(hour,minute,second))\n throw std::invalid_argument(\"Time must be between 0:00:00 and 23:59:59\");\n}\n</code></pre>\n\n<p>Think how you would like to keep the seconds minutes hours, Keeping it as seconds as in previous comment is a valid option. Another that does not require you to recompute it but will still simplify your code is to keep it as an array of 3 and index it by enum. Note that it can be extended easily for date, month year too.</p>\n\n<pre><code>enum Time_t\n{\n Sec,\n Min,\n Hour\n}\n</code></pre>\n\n<p>You can also use this for your accessors. </p>\n\n<pre><code>int TimeOnly::GetTime(Time_t t) const\n{\n return time_[t];\n}\n</code></pre>\n\n<p>This pays off in comparison operators.</p>\n\n<pre><code>inline bool operator==(const TimeOnly& lhs, const TimeOnly& rhs)\n{\n /* do actual comparison */\n for(Time_t t = Hour; t >= Sec; t = static_cast<Time_t>(t-1))\n if(lhs.GetTime(t) != rhs.GetTime(t)) return false;\n return true;\n} \n</code></pre>\n\n<p>Or you could use the STL to lexicographically compare both. (The operator becomes a friend.)</p>\n\n<pre><code>bool cmp(int i, int j) {\n return i < j;\n}\n\nbool operator<(const TimeOnly& lhs, const TimeOnly& rhs)\n{\n return lexicographical_compare(lhs.time_, lhs.time_+3, rhs.time_, rhs.time_+3, cmp);\n}\n</code></pre>\n\n<p>Correspondingly the equality is just</p>\n\n<pre><code>bool operator==(const TimeOnly& lhs, const TimeOnly& rhs)\n{\n return equal(lhs.time_, lhs.time_ +3, rhs.time_);\n}\n</code></pre>\n\n<p>This does not look right.</p>\n\n<pre><code>inline bool operator>(const TimeOnly& lhs, const TimeOnly& rhs){ return operator<(rhs, lhs); }\n</code></pre>\n\n<p>You can directly use the operator rather than use the function syntax.</p>\n\n<pre><code>inline bool operator!=(const TimeOnly& lhs, const TimeOnly& rhs){return !(lhs == rhs);} \ninline bool operator>(const TimeOnly& lhs, const TimeOnly& rhs){return !((lhs < rhs) || (lhs == rhs));} \ninline bool operator<=(const TimeOnly& lhs, const TimeOnly& rhs){return !(lhs > rhs);} \ninline bool operator>=(const TimeOnly& lhs, const TimeOnly& rhs){return !(lhs < rhs); }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-21T18:20:30.097",
"Id": "17636",
"Score": "0",
"body": "Thanks for the suggestions. I like the idea of packaging the validation check into an `IsValid` function. Realistically I don't think I'd call it anywhere else but it does improve the readability of the code. Using an array with an enum and for loops is interesting but it does not seem clearer/easier to me so I don't think I'd make that change. As for using the operator directly rather than the function syntax in the operator definitions, I'm not sure, I just cut and pasted the code from this [Operator overloading](http://stackoverflow.com/a/4421719/155268) question on stackoverflow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-21T19:15:33.877",
"Id": "17637",
"Score": "0",
"body": "Well, The problem is really that of lexicographically ordering a 3-tuple. So I felt it didn't make sense to unroll it. The bonus is that lex-compare is in STL so we can take advantage of that. See my updated version."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T23:44:40.883",
"Id": "11054",
"ParentId": "11052",
"Score": "2"
}
},
{
"body": "<p>Your (modified) solution looks decent. My only noteworthy comments would be to use <code>unsigned</code> instead of <code>int</code> (where appropriate); and, to modify it slightly to not have the '1 day only' restriction.</p>\n\n<p>However, I would recommend that you use <code>std::chrono::time_point</code> or <code>std::chrono::duration</code> from <code><chrono></code>. This is a new C++11 header supported in GCC (from 4.6 I believe) and Microsoft Visual C++ (from 11.0); and, the bulk of this proposal came from <a href=\"http://www.boost.org/doc/libs/1_47_0/doc/html/chrono.html\" rel=\"nofollow\">boost</a>.</p>\n\n<p>Some examples:</p>\n\n<pre><code>#include <chrono>\n#include <thread>\n\n// Getting the current time (there is also high_resolution_clock available)\nstd::chrono::time_point<std::chrono::system_clock> now = \n std::chrono::system_clock::now();\n\n// Do long time-consuming tasks, sleep for 10 seconds\nstd::this_thread::sleep_for(std::chrono::seconds(10));\n\n// Get time now\nauto later = std::chrono::system_clock::now();\n\n// Is now eariler than later ?\nif (now < later)\n{\n // Display difference between the two points of time\n auto x = later - now;\n\n std::cout \n << std::chrono::duration_cast<std::chrono::seconds>(x).count() \n << \" seconds\" << std::endl\n << std::chrono::duration_cast<std::chrono::milliseconds>(x).count() \n << \" milliseconds\" << std::endl;\n}\n</code></pre>\n\n<p>Hopefully it will work with what you are trying to do. If anything, look inside the <code><chrono></code> header and use it internally. It'll make you never want to look at any code using or pretending to use <code><ctime></code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T21:05:21.273",
"Id": "17724",
"Score": "0",
"body": "Unfortunately using Visual Studio 2010 so don't have full c++11 support"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T01:15:30.887",
"Id": "17728",
"Score": "0",
"body": "Then I would refer you to the second paragraph of my answer. Boost contains a drop-in replacement for your use (until such time that you decide to upgrade your compiler) [here](http://www.boost.org/doc/libs/1_47_0/doc/html/chrono.html)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T09:44:28.190",
"Id": "11108",
"ParentId": "11052",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "11053",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T20:44:15.940",
"Id": "11052",
"Score": "6",
"Tags": [
"c++",
"datetime"
],
"Title": "Time (only) class"
}
|
11052
|
<p>So I have a little XML (Sub)language,
it has 3 elements of interest: <code>para</code>, <code>point</code>, and <code>code</code></p>
<p>If a <code>code</code> occurs inside a <code>para</code>, <code>point</code> element I want to handle it for inline use,
if not, i want to set it up as it's own display section</p>
<p>Currently I'm doing it like so:</p>
<pre><code> <xsl:template match="code">
<xsl:choose>
<xsl:when test="exists(ancestor::para) or exists(ancestor::point)">
<xsl:apply-templates select="." mode="inline"/>
</xsl:when>
<xsl:otherwise>
<xsl:apply-templates select="." mode="display"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="code" mode="inline">
<code><xsl:value-of select="."/></code>
</xsl:template>
<xsl:template match="code" mode="display">
<pre><code><xsl:value-of select="."/></code></pre>
</xsl:template>
</code></pre>
<p>Instead of doing it like that i could have just two templates,
one for display and one for inline, and set up the match expressions to work out which it was.</p>
<p>Which is better?</p>
|
[] |
[
{
"body": "<p>It may not matter a lot for this case, but usually when dealing with XSLT our rule of thumb has been, always to handle different cases with different stylesheets rather than one huge complex XSLT.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-22T18:26:58.197",
"Id": "11082",
"ParentId": "11056",
"Score": "1"
}
},
{
"body": "<p>For such a simple case, I would use a single style-sheet and template without modes. You can leverage the power of predicates to produce a simpler solution like so...</p>\n\n<pre><code><xsl:template match=\"code\">\n <pre><code><xsl:value-of select=\".\"/></code></pre>\n</xsl:template>\n\n<xsl:template match=\"code[ancestor::para | ancestor::point]\">\n <code><xsl:value-of select=\".\"/></code> \n</xsl:template>\n</code></pre>\n\n<p>If you are using XSLT 2.0, as opposed to 1.0, an alternate form for the second template would be ...</p>\n\n<pre><code><xsl:template match=\"code[ancestor::(para|ancestor)]\">\n <code><xsl:value-of select=\".\"/></code> \n</xsl:template>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-15T07:20:49.987",
"Id": "14681",
"ParentId": "11056",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "14681",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-21T05:56:39.013",
"Id": "11056",
"Score": "1",
"Tags": [
"xml",
"template",
"xslt"
],
"Title": "Using Choose and Apply Templates with Mode, vs Complexless Template Matches"
}
|
11056
|
<p>Just wanted a way of attaching a jQuery search plugin to an input element (or collection) and be able to pass specific options at invoke time:</p>
<p>This is the plugin code</p>
<pre><code>(function($){
$.fn.extend({
enableSearch:function(opts,callback){
return this
.bind('focus',function(){
$(this.form.elements).val(''); // clears all search inputs
$(this).trigger('keyup'); // triggers the search on an empty input element
}) // END focus bind
.bind('keyup',function(){
var searchData = $.extend({},'source':this.form.id,'column':$(this).attr('id'),'value':$(this).val()},opts);
$.ajax({
url:opts.URL,
type:'post',
data:searchData,
dataType:'json'
})
.promise().then(function(returndata){
callback(returndata);
}); // END ajax call
return false;
}); // END bind keyup
} //END fn enableSearch
})
})(jQuery);
</code></pre>
<p>This is the call on the collection:</p>
<pre><code>$('input') // collection on which to enable searching
.enableSearch({
URL:'<server side script url>',
extra_param:extra_param_value, // extra param which gets passed in the data to the server side fn
},function(data){
//actions performed on the returned data, e.g. update a list
});
</code></pre>
<p>I couldn't get my idea to work until I came across the jQuery promise implmentation. Opens many doors.</p>
<p>Works for me - any thoughts?</p>
|
[] |
[
{
"body": "<ol>\n<li>I find <code>$.ajax().promise().then(fn)</code> to be a little more confusing when looking at the code than it would have been if you instead used <code>$.ajax().complete(fn)</code> (or success if that is what you meant).</li>\n<li>I would throttle the ajax post so that it doesn't happen on every keyup</li>\n<li>if you are using the latest syntax already for <code>$.ajax</code>, I think it makes sense to use the <code>.on</code> method instead of <code>.bind</code></li>\n<li>some of the $() calls can be cached at various levels</li>\n</ol>\n\n<p>So far the resulting code looks something like this (completely untested):</p>\n\n<pre><code>(function($, window){\n $.fn.extend({\n enableSearch:function(opts,callback){\n var timeout;\n var $t = this;\n return $t \n .on({\n focus: function(){\n $(this.form.elements).val(''); // clears all search inputs\n $t.trigger('keyup'); // triggers the search on an empty input element\n }, // END focus bind\n keyup: function(){\n var t = this;\n if (timeout) { window.clearTimeout(timeout); }\n timeout = window.setTimeout(function() {\n var searchData = $.extend({}, {\n source:t.form.id,\n column:$t.attr('id'),\n value:$t.val()\n }, opts);\n\n $.ajax({\n url:opts.URL,\n type:'post',\n data:searchData,\n dataType:'json'\n }).complete(function(returndata){\n callback(returndata);\n }); // END ajax call\n }, $.fn.enableSearch.throttle); //END setTimeout\n } //END keyup\n }); //END on\n } //END fn enableSearch\n });\n $.fn.enableSearch.throttle = 150; //$.ajax will not happen until 150 ms delay happens between keystrokes\n}(jQuery, window));\n</code></pre>\n\n<p>This code is still very specific to your particular case and isn't very reusable elsewhere. The only reasons I would even be making it into a plugin are testability and reuse. I suppose you may be able to reuse this on your application so that isn't much of a deal, but I feel like it requires too much knowledge of your specific implementation to be testable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T19:25:43.530",
"Id": "11142",
"ParentId": "11058",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-21T11:13:09.227",
"Id": "11058",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"plugin",
"promise"
],
"Title": "Simple jQuery search on input element"
}
|
11058
|
<p>I'm aware standard delegate method declaration should include the object that triggers the method, usually of the class that declared the protocol.</p>
<p>That's fine when the delegate method includes further arguments down the line, but what if it doesn't?</p>
<p>Example:</p>
<pre><code>@protocol MyObjectDelegate <NSObject>
- (void)myObject:(id)object didPerformActionWithResult:(NSObject*)resul;
- (void)myObject:(id)object didPerformActionWithoutResult;
@end
</code></pre>
<p>I know the second method isn't accepted, its missing an argument, but what do I put there? A BOOL that I know will always be true?</p>
<p>Do I change |didPerformActionWithoutResult| to performedAction:(BOOL)yesOrNo?</p>
<p>Or move the object reference to the end?</p>
|
[] |
[
{
"body": "<p>This might indeed be confusing at first. The solution is to put the calling object as the only and last argument of the method. The second delegate method would then look like the one below.</p>\n\n<pre><code>- (void)myObjectDidPerformActionWithoutResult:(id)object;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-22T12:14:56.183",
"Id": "11076",
"ParentId": "11059",
"Score": "2"
}
},
{
"body": "<p>Have a look at <a href=\"http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UITableViewDataSource_Protocol/Reference/Reference.html\" rel=\"nofollow\">TableView's datasource</a> protocol:</p>\n\n<pre><code>– tableView:cellForRowAtIndexPath:\n– numberOfSectionsInTableView:\n– tableView:numberOfRowsInSection:\n– sectionIndexTitlesForTableView:\n</code></pre>\n\n<p>I find it quite hard to come up with nice names for such sidle parameter method signature and code completion would be easier, if the form, you propose would exists, but if a method accepts parameters, it name must terminate with one of therm — if it just have one, it must be at the end.</p>\n\n<p>Your idea of adding a dead parameter is IMO very bad design. Another parameter should lead possibly to another behavior. Also it would work against objective-c strength of self explaining method name. <code>countOfSubscribersForNewsEmitter:(MyNewsEmitter *)emitter</code> make sense, while <code>newsEmitter:(MyNewsEmitter *)emitter countOfSubscribers:(BOOL) aBool</code> does not make much sense, as the bool disallows us to form a correct mental model of the purpose of this method.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T02:08:53.790",
"Id": "17854",
"Score": "0",
"body": "Seconded. Copy Apple's naming conventions like this one so your code is easier to understand and fits with the rest of the API. :) There's no great answer to this question, so What Apple Did is the best solution."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-22T16:01:29.707",
"Id": "11079",
"ParentId": "11059",
"Score": "3"
}
},
{
"body": "<pre><code>- (void)actionPerformedWithoutResultByObject:(id)object;\n</code></pre>\n\n<p>might be another alternative.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-15T21:57:49.650",
"Id": "14722",
"ParentId": "11059",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "11079",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-21T12:03:54.440",
"Id": "11059",
"Score": "2",
"Tags": [
"objective-c",
"ios"
],
"Title": "Standard delegate methods"
}
|
11059
|
<p>I have two types of session wrappers:</p>
<p><strong>Type 1</strong></p>
<pre><code>public class SessionHandler
{
public static SessionHandler CurrentSession
{
get
{
SessionHandler session =
(SessionHandler)HttpContext.Current.Session["SessionId"];
if (session == null)
{
session = new SessionHandler();
HttpContext.Current.Session["SessionId"] = session;
}
return session;
}
}
public int? UserId { get; set; }
}
</code></pre>
<p><strong>Type 2</strong></p>
<pre><code>public static class SessionHandler
{
private static void SetSession<T>(string sessionId, T value)
{
HttpContext.Current.Session[sessionId] = value;
}
private static T GetSession<T>(string sessionId)
{
return (T)HttpContext.Current.Session[sessionId];
}
public static int? UserId
{
get
{
return GetSession<int>("UserId");
}
set
{
SetSession<int>("UserId", value);
}
}
}
</code></pre>
<p>The usage is as follows:</p>
<pre><code>//Type 1
SessionHandler.CurrentSession.UserId = 10;
//Type 2
SessionHandler.UserId = 10;
</code></pre>
<p>Please suggest which one is better and why.</p>
<h3>What I think about type 1:</h3>
<p>Good for readability and maintainability. I can add more properties with less efforts, but the session will become heavy (single session for whole application). This approach may not be good, if we have more sessions to store. However, I'm not sure whether assignment/retrieving the session is just changing the reference or does some serialization/de-serialization.</p>
<h3>What I think about type 2:</h3>
<p>Usage is easy, but it needs little work while adding more sessions. This is the same as a normal session usage but, it just avoids the typos which might happen frequently while retrieving the sessions on various places.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-21T14:38:35.550",
"Id": "19169",
"Score": "0",
"body": "`Type 1` allows for inheritance, interface implementation and overall a better way to do unit testing. `static` classes should only be used when there is absolutely, positively, no way state needs to be maintained. Also, please note that the way it is written, it is not thread-safe."
}
] |
[
{
"body": "<p>Alternatively you might want to consider using enums that have string values attached to them. There is an article detailing how you can make <a href=\"http://www.codeproject.com/Articles/11130/String-Enumerations-in-C\" rel=\"nofollow\">that work with attributes</a>.</p>\n\n<p>That way you can define an enum with all the keys that you want to store values in your session with like this:</p>\n\n<pre><code>public enum SessionKey {\n\n [StringValue(\"UserId\")]\n UserId,\n\n [StringValue(\"UserName\")]\n UserName,\n\n [StringValue(\"Hcskn\")]\n HighlyComplexSessionKeyName\n\n}\n</code></pre>\n\n<p>In your session wrapper you can have methods (such as a <code>GetInt(SessionKey.UserId)</code> or <code>GetString(SessionKey.UserName)</code>) that retrieve the values for you. This way you can be completely sure that you don't use the wrong string to retrieve values from the session and it is somewhat typesafe.</p>\n\n<p>The only drawback is the amount of initial code you need to set it all up for you. The advantage is that it is easy to add new variable keys to store session values in as you only need to add that to the <code>SessionKey</code> enum.</p>\n\n<hr>\n\n<p><strong>EDIT:</strong></p>\n\n<p>As Chuck pointed out in comments: If the names on the enum values are enough then you can use ToString method on the enum to get the string representation. E.g.:</p>\n\n<pre><code>Console.Write(Session.Key.UserId.ToString()); \n// prints \"UserId\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-16T09:37:16.827",
"Id": "17632",
"Score": "0",
"body": "I was on holiday and couldn't come online(however, I watched your answer on mobile but couldn't reply). Coming to the answer, even though the approach is good to have string values on enum; I don't see any advantage to implement this approach for sessions(other than typo issue). This will be an additional burden and the performance become worse just to avoid the typos. I might be wrong, please correct me in that case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T08:32:45.283",
"Id": "17633",
"Score": "0",
"body": "I flagged the question for moderator attention. Lets see if they can move it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T08:40:00.303",
"Id": "17634",
"Score": "1",
"body": "@Knvn: Enums are type safe, which is another advantage (or disadvantage if you come from a dynamic programming background). If it's an performance issue then that claim should always be backed up with measurable test or else you'll be prematurely optimizing stuff. :-) But most likely it isn't an issue when it comes to enums as they are type safe and have (pretty much afaik) direct access and I think the performance hit is negligible when the string value has to be retrieved. But then again, it all depends on the website how much traffic it gets."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-21T17:53:44.850",
"Id": "19178",
"Score": "0",
"body": "Why go to all the trouble of the StringValue attribute when you can call \"ToString\" on the enum and get the name of the value?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-22T12:52:20.393",
"Id": "19211",
"Score": "0",
"body": "@ChuckConway That way you can have string values that does not correspond to the name of the enum value. I'll update the answer to show this."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-14T07:54:16.150",
"Id": "11061",
"ParentId": "11060",
"Score": "1"
}
},
{
"body": "<pre><code>private static T GetSession<T>(string sessionId)\n{\n return (T)HttpContext.Current.Session[sessionId];\n}\n</code></pre>\n\n<p>The above code will throw an exception if the value is not present.</p>\n\n<p>Consider something like the following:</p>\n\n<pre><code> private static T GetSession<T>(string sessionId)\n {\n T val = default(T);\n var session = HttpContext.Current.Session;\n\n if (session[sessionId] != null)\n {\n val = (T)session[sessionId];\n }\n\n return val;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-21T17:48:02.263",
"Id": "11950",
"ParentId": "11060",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-13T09:32:07.020",
"Id": "11060",
"Score": "4",
"Tags": [
"c#",
"asp.net",
"session"
],
"Title": "Session Wrapper"
}
|
11060
|
<p>This my first Python program and game. Can you please point how I can improve and what code should be changed?</p>
<pre><code>import pygame
from pygame import *
import random
import time
import os
import sys
from pygame.locals import *
black = (0,0,0)
white = (255,255,255)
pygame.init()
def game():
os.environ['SDL_VIDEO_CENTERED'] = '1'
mouse.set_visible(False)
screen = display.set_mode((800,500))
backdrop = pygame.image.load('bg.jpg').convert_alpha()
menu = pygame.image.load('green.jpg').convert_alpha()
ballpic = pygame.image.load('ball.gif').convert_alpha()
mouseball = pygame.image.load('mouseball.gif').convert_alpha()
display.set_caption('Twerk')
back = pygame.Surface(screen.get_size())
def text(text,x_pos,color,font2=28):
tfont = pygame.font.Font(None, font2)
text=tfont.render(text, True, color)
textpos = text.get_rect(centerx=back.get_width()/2)
textpos.top = x_pos
screen.blit(text, textpos)
start = False
repeat = False
while start == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
start = True
#falling = True
#finish = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
start = True
#game over screen
screen.blit(menu,[0,0])
pygame.display.set_caption("TWERK")
#Text
#"Welcome to Escape"
#needs replacing with logo
text("Twerk",60,white,300)
#"Instructions"
text("Instructions",310,white)
text("----------------------------------------------------------------------------------------",320,white)
text("Avoid the the enemies",340,white)
text("Last as long as you can!",360,white)
text("Press space to start",420,white)
pygame.display.flip()
while start == True:
positionx=[]
positiony=[]
positionxmove=[]
positionymove=[]
falling = False
finish = False
score=0
enemies=4
velocity=1
for i in range(enemies):
positionx.append(random.randint(300,400)+random.randint(-300,200))
positiony.append(random.randint(200,340)+random.randint(-200,100))
positionxmove.append(random.randint(1,velocity))
positionymove.append(random.randint(1,velocity))
font = pygame.font.Font(None, 28)
text = font.render('Starting Twerk... ', True, (100,100,100))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery
screen.blit(backdrop, (0,0))
screen.blit(text, textRect)
pygame.display.update()
game=time.localtime()
while start == True:
end=time.localtime()
score= (end[1]-game[1])*3600 + (end[4]-game[4])*60 + end[5]-game[5]
if score > 1: break
first=True
strtTime=time.localtime()
while not finish or falling:
screen.blit(backdrop, (0,0))
for i in range(enemies):
screen.blit(ballpic,(positionx[i],positiony[i]))
(mousex,mousey)=mouse.get_pos()
screen.blit(mouseball,(mousex,mousey))
display.update()
strt = time.localtime()
if first:
while True:
end=time.localtime()
score= (end[3]-strt[3])*3600 + (end[4]-strt[4])*60 + end[5]-strt[5]
if score > 3: break
first = False
if falling:
for i in range(enemies):
positionymove[i]=1000
positionxmove[i]=0
for i in range(enemies): positionx[i]=positionx[i]+positionxmove[i]
for i in range(enemies): positiony[i]=min(600,positiony[i]+positionymove[i])
if falling:
falling=False
for posy in positiony:
if posy<600: falling=True
if not falling:
for i in range(enemies):
for j in range(i+1,enemies):
if abs(positionx[i]-positionx[j])<20 and abs(positiony[i]-positiony[j])<20:
temp=positionxmove[i]
positionxmove[i]=positionxmove[j]
positionxmove[j]=temp
temp=positionymove[i]
positionymove[i]=positionymove[j]
positionymove[j]=temp
for i in range(enemies):
if positionx[i]>600: positionxmove[i]*=-1
if positionx[i]<0: positionxmove[i]*=-1
if positiony[i]>440: positionymove[i]*=-1
if positiony[i]<0: positionymove[i]*=-1
for i in range(enemies):
if abs(positionx[i]-mousex)<40 and abs(positiony[i]-mousey)<40:
falling = True
finish = True
start = False
endTime=time.localtime()
score= (endTime[3]-strtTime[3])*3600 + (endTime[4]-strtTime[4])*60 + endTime[5]-strtTime[5]
break
for event in pygame.event.get():
if event.type==KEYUP and event.key==K_ESCAPE:
finish=True
pygame.quit()
game()
</code></pre>
|
[] |
[
{
"body": "<p>At the moment your game is one long \"noodle\" of code - I would split it into several... err... entities which represent separate activities - intro screen, the main game loop, high scores screen, settings screen, whatever. At their simplest they can be separate functions, but defining some classes would be a bit nicer:</p>\n\n<pre><code>class Intro(object):\n\n def __init__(self):\n # set up stuff for the intro\n\n def run(self):\n # intro loop\n\nclass Game(object):\n ...\n\nintro = Intro()\ngame = Game()\nintro.run()\ngame.run()\n</code></pre>\n\n<p>With this approach you can add more stuff (high scores screen etc.) without complicating your game loop too much.</p>\n\n<p>I would also consider encapsulating Enemy/Player logic into separate classes.</p>\n\n<p>As a learning exercise - maybe try to rewrite the game so no function/metod is longer than 10 lines.</p>\n\n<p>And add some comments too. A lot of them. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-21T22:27:39.273",
"Id": "11066",
"ParentId": "11062",
"Score": "1"
}
},
{
"body": "<p>Here, I think you wanted to exit the for loop if start was found true right?\nAdd a break after the assignment for both. You want to do this for most of the loops.</p>\n\n<pre><code>start = False\nrepeat = False\nwhile start == False:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n start = True\n break\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n start = True\n break\n</code></pre>\n\n<p>You can combine some of these conditions, for example</p>\n\n<pre><code> for i in range(enemies): \n if positionx[i]>600 || positionx[i]<0: positionxmove[i]*=-1\n if positiony[i]>440 || positiony[i]<0: positionymove[i]*=-1\n</code></pre>\n\n<p>Note that positionx and positiony may best be stored together in some datastructure - perhaps a tuple</p>\n\n<p>Something like this</p>\n\n<pre><code> positionxmove.append(random.randint(1,velocity))\n positionymove.append(random.randint(1,velocity))\n</code></pre>\n\n<p>can be reduced to</p>\n\n<pre><code> for p in [positionxmove, positionymove]:\n p.append(random.randint(1,velocity))\n</code></pre>\n\n<p>The idea is to reduce repetition as much as you can.</p>\n\n<p>Combine the loops. for e.g</p>\n\n<pre><code> for i in range(enemies): positionx[i]=positionx[i]+positionxmove[i]\n for i in range(enemies): positiony[i]=min(600,positiony[i]+positionymove[i])\n</code></pre>\n\n<p>Should be </p>\n\n<pre><code> for i in range(enemies): \n positionx[i]=positionx[i]+positionxmove[i]\n positiony[i]=min(600,positiony[i]+positionymove[i])\n</code></pre>\n\n<p>Also remove all the magic numbers like 600. They should be named with some meaningful names, and those variables/constants should be used instead.</p>\n\n<p>You can reduce some thing such as this</p>\n\n<pre><code> temp=positionxmove[i]\n positionxmove[i]=positionxmove[j]\n positionxmove[j]=temp\n temp=positionymove[i]\n positionymove[i]=positionymove[j]\n positionymove[j]=temp\n</code></pre>\n\n<p>to</p>\n\n<pre><code> for p in [positionxmove, positionymove]:\n p[i], p[j] = p[i],p[i]\n</code></pre>\n\n<p>that is, use parallel assignment for swapping.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-21T23:11:47.000",
"Id": "11067",
"ParentId": "11062",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "11067",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-21T17:16:18.783",
"Id": "11062",
"Score": "3",
"Tags": [
"python",
"beginner",
"game",
"pygame"
],
"Title": "A game called \"Twerk\""
}
|
11062
|
<p>I recently <a href="https://stackoverflow.com/a/10263759/908879">wrote a snippet</a> to make a custom <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf" rel="nofollow noreferrer">array.indexOf</a> but with nested array support in addition to allow using a nested array as needle.</p>
<p>For example, it correctly returns the index <code>3</code> in this case:</p>
<pre><code>var arr1=[0,1,2,[3,[4,true,[],[,"x",false,,,undefined,[]]],["5"]]];
console.log(indexOfArr(arr1,[3,[4,true,[],[,"x",false,,,undefined,[]]],["5"]]));//3
</code></pre>
<hr>
<p>Here is the <em>un-commented</em> snippet (if you want to read the <em>commented</em> version, skip this one):</p>
<pre><code>function indexOfArr(arr1, fnd) {
for (var i = 0, len1 = arr1.length; i < len1; i++) {
if (!(i in arr1)) {
continue;
}
if (elementComparer(arr1[i], fnd)) {
return i;
}
}
return -1;
}
function elementComparer(fnd1, fnd2) {
var type1 = typeof fnd1;
var type2 = typeof fnd2;
if (!((type1 == "number" && type2 == "number") && (fnd1 + "" == "NaN" && fnd2 + "" == "NaN"))) {
if (type1 == "object" && fnd1 + "" != "null") {
var len1 = fnd1.length;
if (type2 == "object" && fnd2 + "" != "null") {
var len2 = fnd2.length;
if (len1 !== len2) {
return false;
}
for (var i = 0; i < len1; i++) {
if (!(i in fnd1 && i in fnd2)) {
if (i in fnd1 == i in fnd2) {
continue;
}
return false;
}
if (!elementComparer(fnd1[i], fnd2[i])) {
return false;
}
}
}
} else {
if (fnd1 !== fnd2) {
return false;
}
}
}
return true;
}
</code></pre>
<p>Here the <em>commented</em> snippet:</p>
<pre><code>function indexOfArr(arr1,fnd){
//compare every element on the array
for(var i=0,len1=arr1.length;i<len1;i++){
//index missing, leave to prevent false-positives with 'undefined'
if(!(i in arr1)){
continue;
}
//if they are exactly equal, return the index
if(elementComparer(arr1[i],fnd)){
return i;
}
}
//no match found, return false
return -1;
}
function elementComparer(fnd1,fnd2){
//store the types of fnd1 and fnd2
var type1=typeof fnd1;
var type2=typeof fnd2;
//unwanted results with '(NaN!==NaN)===true' so we exclude them
if(!((type1=="number"&&type2=="number")&&(fnd1+""=="NaN"&&fnd2+""=="NaN"))){
//unwanted results with '(typeof null==="object")===true' so we exclude them
if(type1=="object"&&fnd1+""!="null"){
var len1=fnd1.length;
//unwanted results with '(typeof null==="object")===true' so we exclude them
if(type2=="object"&&fnd2+""!="null"){
var len2=fnd2.length;
//if they aren't the same length, return false
if(len1!==len2){
return false;
}
//compare every element on the array
for(var i=0;i<len1;i++){
//if either index is missing...
if(!(i in fnd1&&i in fnd2)){
//they both are missing, leave to prevent false-positives with 'undefined'
if(i in fnd1==i in fnd2){
continue;
}
//NOT the same, return false
return false;
}
//if they are NOT the same, return false
if(!elementComparer(fnd1[i],fnd2[i])){
return false;
}
}
}
}else{
//if they are NOT the same, return false
if(fnd1!==fnd2){
return false;
}
}
}
//if it successfully avoided all 'return false', then they are equal
return true;
}
</code></pre>
<p>Things that I want to know:</p>
<ul>
<li>Do you find it readable?</li>
<li>Are there any obvious improvements (other than minifying)?</li>
<li>What practice is not recommended?</li>
</ul>
|
[] |
[
{
"body": "<p>Here are some suggestions:</p>\n\n<p><code>fnd1 + \"\" == \"NaN\"</code> would be better as <code>isNaN(fnd1)</code>. It will also speed up your code by eliminating those concatenations.</p>\n\n<p>Using the <code>in</code> operator on a array is useless as it checks if the property exists. In the case of an array (which in JavaScript is a special case of an object) you're only testing for the existence of the indexes. Also, <code>continue</code>s are almost always unnecessary. For example:</p>\n\n<pre><code>for (var i = 0, len1 = arr1.length; i < len1; i++) {\n if (!(i in arr1)) {\n continue;\n }\n if (elementComparer(arr1[i], fnd)) {\n return i;\n }\n}\n</code></pre>\n\n<p>Could be (I tested this on your fiddle):</p>\n\n<pre><code>for (var i = 0, len1 = arr1.length; i < len1; i++) {\n if (arr1[i] && elementComparer(arr1[i], fnd)) {\n return i;\n }\n}\n</code></pre>\n\n<p>I'm not sure what all that type checking is for as it looks like both parameters should be arrays. <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray\" rel=\"nofollow\">Array.isArray</a> should be used.</p>\n\n<pre><code>if (!Array.isArray(fnd1) || !Array.isArray(fnd2) {\n return false;\n}\n</code></pre>\n\n<p>It is always best to use <code>===</code> instead of <code>==</code> as <code>==</code> will do type coercion which can lead to very strange results. Also you should be consistent with the equality operator you decide to use. You occasionally use <code>!==</code> instead of <code>!=</code>.</p>\n\n<p>In terms of readability better parameter names would help as they provide little or no clue about the type they should be. Also, declaring all variable names at the top of your function is a good idea due to JavaScript's hoisting. Most importantly, nesting that deeply is very difficult to follow - especially with multiple returns. It was the hardest part of reading your code. Perhaps a few <code>if</code>s could be combined.</p>\n\n<p>Lastly, your test array leaves out <code>''</code>, <code>null</code>, and <code>{}</code>. You don't have an object in there at all i.e. <code>{'1': 'foo', bar: 'test'}</code>. Having a number as a property name is very important as it will be true when using <code>in</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-22T13:05:15.543",
"Id": "17651",
"Score": "0",
"body": "I can't use `isNaN()` because not only `NaN` return true (there are [more values](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/isNaN)). Using `in` is a security check to handle sparse arrays ([example](http://jsfiddle.net/Da5GS/2/)). `if (arr1[i] &&` will return to false in many occasions where I don't want (example `0,\"\",false,null,undefined,NaN`)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-22T13:12:02.960",
"Id": "17652",
"Score": "0",
"body": "I am worried about the compatibility of [isArray()](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray#Compatibility). I know where can be bugs and where can't on my `=== == !== ==` signs. I prefer having a `continue` break than a nested if"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-22T07:50:28.367",
"Id": "11073",
"ParentId": "11070",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-22T04:33:25.837",
"Id": "11070",
"Score": "1",
"Tags": [
"javascript",
"optimization",
"algorithm"
],
"Title": "Snippet of custom array.indexOf that supports nested arrays"
}
|
11070
|
<p>I create a simple feature tour sort of like what rdio and Facebook are doing. How can I make it better?</p>
<pre><code>$(function () {
$('a.close, a.closebtn').click(function () {
$(".tour-block").hide();
});
$('a.tour-step-01').click(function () {
$(".tour-block").hide();
$(".tour-block.tr01").fadeIn();
});
$('#tourblock-01, a.tour-step-02').click(function () {
$(".tour-block").hide();
$(".tour-block.tr02").fadeIn();
});
$('#tourblock-02, a.tour-step-03').click(function () {
$(".tour-block").hide();
$(".tour-block.tr03").fadeIn();
});
$('#tourblock-03, a.tour-step-04').click(function () {
$(".tour-block").hide();
$(".tour-block.tr04").fadeIn();
});
});
</code></pre>
<p><strong>HTML:</strong></p>
<pre><code><div class="tour-block tr01">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal">×</a>
<h3>Title Lorem Ipsum</h3>
</div>
<div class="modal-body">
<p>Content Lorem ipsum Content</p>
</div>
<div class="modal-footer">
<span class="tour-nmbrs"><a href="#" class="tour-step-01">1</a> <a href="#" class="tour-step-02">2</a> <a href="#" class="tour-step-03">3</a> <a href="#" class="tour-step-04">4</a> <a href="#" class="tour-step-05">5</a></span>
<a href="#" id="tourblock-01" class="btn btn-primary active">Next</a>
</div>
</div>
<div class="tour-block tr02">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal">×</a>
<h3>Title Lorem Ipsum</h3>
</div>
<div class="modal-body">
<p>Content Lorem ipsum Content</p>
</div>
<div class="modal-footer">
<span class="tour-nmbrs"><a href="#" class="tour-step-01">1</a> <a href="#" class="tour-step-02">2</a> <a href="#" class="tour-step-03">3</a> <a href="#" class="tour-step-04">4</a> <a href="#" class="tour-step-05">5</a></span>
<a href="#" id="tourblock-02" class="btn btn-primary active">Next</a>
</div>
</div>
<div class="tour-block tr03">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal">×</a>
<h3>Title Lorem Ipsum</h3>
</div>
<div class="modal-body">
<p>Content Lorem ipsum Content</p>
</div>
<div class="modal-footer">
<span class="tour-nmbrs"><a href="#" class="tour-step-01">1</a> <a href="#" class="tour-step-02">2</a> <a href="#" class="tour-step-03">3</a> <a href="#" class="tour-step-04">4</a> <a href="#" class="tour-step-05">5</a></span>
<a href="#" id="tourblock-03" class="btn btn-primary active">Next</a>
</div>
</div>
<div class="tour-block tr04">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal">×</a>
<h3>Title Lorem Ipsum</h3>
</div>
<div class="modal-body">
<p>Content Lorem ipsum Content</p>
</div>
<div class="modal-footer">
<span class="tour-nmbrs"><a href="#" class="tour-step-01">1</a> <a href="#" class="tour-step-02">2</a> <a href="#" class="tour-step-03">3</a> <a href="#" class="tour-step-04">4</a> <a href="#" class="tour-step-05">5</a></span>
<a href="#" id="tourblock-04" class="btn btn-primary active">Next</a>
</div>
</div>
<div class="tour-block tr05">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal">×</a>
<h3>Title Lorem Ipsum</h3>
</div>
<div class="modal-body">
<p>Content Lorem ipsum Content</p>
</div>
<div class="modal-footer">
<span class="tour-nmbrs"><a href="#" class="tour-step-01">1</a> <a href="#" class="tour-step-02">2</a> <a href="#" class="tour-step-03">3</a> <a href="#" class="tour-step-04">4</a> <a href="#" class="tour-step-05">5</a></span>
<a href="#" class="closebtn">Close</a>
</div>
</div>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T21:47:18.073",
"Id": "17653",
"Score": "0",
"body": "Can you post html too?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T21:51:17.473",
"Id": "17654",
"Score": "0",
"body": "We would need to see your HTML to see what classes are on what elements to know how to best simplify. This should actually be in Code Review, not StackOverflow."
}
] |
[
{
"body": "<p>If you could simplify your html, I would do something like this:</p>\n\n<pre><code><div class=\"tour-block\">\n <h3>Title Lorem Ipsum</h3>\n <p>Content Lorem ipsum Content</p>\n</div>\n</code></pre>\n\n<p>(repeat this for each tour block on the site)</p>\n\n<p>Then you could do something much more generic for your tour like this:</p>\n\n<pre><code>(function ($) {\n \"use strict\";\n $(function () {\n var $tour = $(\".tour-block\"),\n len = $tour.length,\n i,\n steps = '';\n\n for (i = 0; i < len; i++) {\n steps += ' <a href=\"#\" data-index=\"' + i + '\" data-type=\"skip\">' + (i + 1) + '</a>';\n }\n\n $tour.each(function (i) {\n var $t = $(this),\n title = $t.children('h3').html(),\n content = $t.children('p').html(),\n replacement = '';\n replacement += '<div class=\"modal-header\">';\n replacement += ' <a href=\"#Close\" class=\"close\" data-type=\"close\" data-dismiss=\"modal\">×</a>';\n replacement += ' <h3>' + title + '</h3>';\n replacement += '</div>';\n replacement += '<div class=\"modal-body\">';\n replacement += ' <p>' + content + '</p>';\n replacement += '</div>';\n replacement += '<div class=\"modal-footer\">';\n replacement += ' <span class=\"tour-nmbrs\">';\n replacement += steps;\n replacement += ' </span>';\n if (i + 1 === len) {\n replacement += ' <a href=\"#\" data-type=\"close\" class=\"btn btn-primary active\">Close</a>';\n } else {\n replacement += ' <a href=\"#\" data-type=\"next\" data-index=\"' + i + '\" class=\"btn btn-primary active\">Next</a>';\n }\n replacement += '</div>';\n $t.html(replacement);\n });\n\n $tour.on('click', 'a', function (e) {\n var $a = $(this),\n type = $a.data('type');\n\n e.preventDefault();\n\n if (type === 'close') {\n $tour.hide();\n } else if (type === 'skip') {\n $tour.hide().eq(+$a.data('index')).show();\n } else if (type === 'next') {\n $tour.hide().eq(+$a.data('index') + 1).show();\n }\n });\n });\n}(jQuery));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T22:44:35.097",
"Id": "18024",
"Score": "0",
"body": "playground on jsfiddle: http://jsfiddle.net/XmgpN/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T09:36:47.653",
"Id": "18050",
"Score": "0",
"body": "Hmm, on load you should show the first and hide the others."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T13:01:54.930",
"Id": "18055",
"Score": "0",
"body": "I agree; to do that, change `$t.html(replacement);` to be `$t.toggle(i === 0).html(replacement);`. I would also scroll to each stop (and why write that yourself, use http://flesler.blogspot.com/search/label/jQuery.ScrollTo instead)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T22:37:53.250",
"Id": "11237",
"ParentId": "11077",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "11237",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T21:45:34.487",
"Id": "11077",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "Script for simple feature tour"
}
|
11077
|
<p><code>Shape</code> represents an abstract class and the other two classes inherits from it. This looks insufficiently abstract to me. How could I improve it?</p>
<pre><code>import math
class Point:
def __init__(self,x,y):
self.x = x
self.y = y
def move(self,x,y):
self.x += x
self.y += y
def __str__(self):
return "<"+ str(self.x) + "," + str(self.y) + ">"
class Shape:
def __init__(self, centrePoint, colour, width, height):
self.centrePoint = centrePoint
self.colour = colour
self.width = width
self.height = height
self.type = "Square"
def __init__(self, centrePoint, radius, colour):
self.type = "Circle"
self.radius = radius
self.colour = colour
self.centrePoint = centrePoint
def move(self,x,y):
self.centrePoint.move(x,y)
def getArea(self):
if (self.type == "Square"):
return self.width * self.height
elif (self.type == "Circle"):
return math.pi*(self.radius**2)
def __str__(self):
return "Center Point: " + str(self.centrePoint) + "\nColour: "+ self.Colour + "\nType: " + self.type + "\nArea: " + self.getArea()
class Rectangle (Shape):
def scale(self, factor):
self.scaleVertically(factor)
self.scaleHorizontally(factor)
def scaleVertically(self, factor):
self.height *= factor
def scaleHorizontally(self, factor):
self.width *= factor
class Circle (Shape):
def scale(self, factor):
self.radius * factor
</code></pre>
|
[] |
[
{
"body": "<p>Your class Shape knows about what kind of shape it is (circle/square). This makes it tied to the two child classes. It should not know any thing about the composition. Rather just provide methods with empty implementations that can be overridden by child classes.</p>\n\n<p>The only thing I can see that is common across all classes is the concept of a center point and a color. So</p>\n\n<pre><code>import abc\n\nclass Shape(metaclass=abc.ABCMeta): \n def __init__(self, centrePoint, colour):\n self.centrePoint = centrePoint\n self.colour = colour\n</code></pre>\n\n<p>Since move depends only on center point, it is ok to define it in base class.</p>\n\n<pre><code> def move(self,x,y):\n self.centrePoint.move(x,y)\n</code></pre>\n\n<p>This is certainly one that should be implemented by the child classes because it requires knowledge about what kind of a shape it is.</p>\n\n<pre><code> @abc.abstractmethod\n def getArea(self):\n return\n</code></pre>\n\n<p>or if you dont want to use it</p>\n\n<pre><code> def getArea(self):\n raise NotImplementedError('Shape.getArea is not overridden')\n</code></pre>\n\n<p>see \n<a href=\"http://docs.python.org/library/abc.html\" rel=\"nofollow noreferrer\">abc</a> in \n<a href=\"https://stackoverflow.com/questions/7196376/python-abstractmethod-decorator\">so</a></p>\n\n<p>And the to string method is another that should be done in child because it holds details of what shape it is. </p>\n\n<pre><code> @abc.abstractmethod\n def __str__(self):\n return\n</code></pre>\n\n<p>However, if you are going to use the same format for all shapes, then you can provide the default implementation (as below.)</p>\n\n<pre><code> def __str__(self):\n return \"Center Point: \" + str(self.centrePoint) + \"\\nColour: \"+ self.Colour + \"\\nType: \" + self.type() + \"\\nArea: \" + self.getArea()\n</code></pre>\n\n<p>I would also recommend scale as part of the base class because all shapes can be scaled.</p>\n\n<pre><code> def scale(self, factor):\n return\n</code></pre>\n\n<p>Basically all operations that make sense on any shapes should have an abstract method on the base class.</p>\n\n<p>Now for child classes</p>\n\n<pre><code>class Rectangle (Shape):\n def __init__(self, cp, color, width, height):\n super(Rectangle, self).__init__(cp, color)\n self.width = width\n self.height = height\n\n def scale(self, factor):\n self.scaleVertically(factor)\n self.scaleHorizontally(factor)\n\n def scaleVertically(self, factor):\n self.height *= factor\n\n def scaleHorizontally(self, factor):\n self.width *= factor\n\n def getArea(self):\n return self.width * self.height\n\n def type(self):\n return \"Rectangle\"\n\nclass Circle (Shape):\n def __init__(self, cp, color, radius):\n super(Rectangle, self).__init__(cp, color)\n self.radius = radius\n\n def scale(self, factor):\n self.radius * factor\n\n def getArea(self):\n return math.pi*(self.radius**2)\n\n def type(self):\n return \"Circle\"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-22T17:34:47.620",
"Id": "11081",
"ParentId": "11080",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "11081",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-22T16:50:14.460",
"Id": "11080",
"Score": "3",
"Tags": [
"python",
"object-oriented",
"python-2.x",
"homework"
],
"Title": "Abstractness of Shape class"
}
|
11080
|
<p>I occasionally find myself bumping into code like this (either in other projects or banging out initial prototypes myself):</p>
<pre><code> if @product.save
if current_member.role == "admin"
redirect_to krowd_path(@product)
else
redirect_to new_product_offer_path(@product)
end
else
render :new
end
</code></pre>
<p>What is a good way to avoid this type of situation all together?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-22T18:50:52.250",
"Id": "17657",
"Score": "0",
"body": "Use small functions that call each other and do not be afraid of multiple return points within one function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-22T19:05:56.727",
"Id": "17658",
"Score": "2",
"body": "I am not familiar with rails, but you can avoid one level of nesting by checking the exceptional/rare condition first and returning."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-22T19:23:54.907",
"Id": "17659",
"Score": "2",
"body": "http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html"
}
] |
[
{
"body": "<p>One suggestion is to make the roles two classes, initialize them based on the role and call the save function.</p>\n\n<pre><code> class UserRole\n def save(product)\n redirect_to new_product_offer_path(product) \n end\n end\n class AdminRole < UserRole\n def save(product)\n redirect_to krowd_path(product) \n end\n end\n def create_role(r)\n case r\n when :admin\n return AdminRole.new()\n else\n return UserRole.new()\n end\n end\n\n\n ....\n role = create_role(current_member.role)\n\n if @product.save \n role.save(@product) \n else \n render :new \n end\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T00:12:32.850",
"Id": "11091",
"ParentId": "11083",
"Score": "3"
}
},
{
"body": "<p>If it matches to your requirements you could implement something like:</p>\n\n<pre><code>redirect_to_first_accessible(\n krowd_path(@product), \n new_product_offer_path(@product))\n</code></pre>\n\n<p>If you use something like CanCan gem, gererally it's defined which action is accessible to certain roles.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-30T01:49:33.020",
"Id": "18167",
"Score": "0",
"body": "I considered cancan for this case, but there are instances where it's not access based. The arrow code articlesmsup those generic cases, but cancan definitely helps separate when it comes to access."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-29T19:09:53.567",
"Id": "11311",
"ParentId": "11083",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "11091",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-22T18:47:17.553",
"Id": "11083",
"Score": "2",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Avoiding nested if statements"
}
|
11083
|
<p>This is the "Codebreaker" game in Ruby. Tell me what I can make better!</p>
<pre><code>#!/usr/bin/env ruby
class Sequence
attr_accessor :guess, :code
def initialize
puts "Type the difficulty level you would like: 1, 2, 3, 4, or 5"
begin
@level = gets; @level = @level.to_i
if @level > 6
raise "Error"
end
rescue
puts "Invalid Difficulty"
exit
end
end
def create_code
@code = "#{rand(@level*2)}#{rand(@level*2)}#{rand(@level*2)}#{rand(@level*2)}"
if @level == 5
@code += "#{rand(@level*2)}"
end
if @code.length > 5
puts "Invalid Difficulty!"
exit
end
puts @code
end
def prompt
@retstring = ""
@guess = ""
guesses = 0
while guesses < 4
print "Enter a guess: "
@guess = gets
x = 0
4.times do
if @code[x] == @guess[x]
@retstring += "+"
else
@retstring += "-"
end
puts @retstring
sleep(1)
x += 1
end
puts "Would you like a hint? Type 'hint' to get a hint"
hint = gets
match = hint =~ /(h|H)(i|I)(n|N)\w/
unless match == nil
j = rand(@level*2)
puts "#{j}: #{@code[j]}"
end
guesses += 1
if @retstring == "++++"
puts "Correct!"
break
end
@retstring = ""
end
end
def print_code
print @code
print " was the code\n"
end
end
j = Sequence.new
j.create_code
j.prompt
j.print_code
</code></pre>
|
[] |
[
{
"body": "<p>Interesting game :), and reasonable code. I only have a few suggestions.</p>\n\n<p>for</p>\n\n<pre><code> if @level > 6\n raise \"Error\"\n end\n</code></pre>\n\n<p>and</p>\n\n<pre><code> if @code.length > 5\n puts \"Invalid Difficulty!\"\n exit\n end\n</code></pre>\n\n<p>Any particular reason you handled the first one using exception and the second one using an if condition?</p>\n\n<p>Also consider returning an error code,\nIf program can be used in non-interactive way, printing any errors to stderr also helps. I would also modify it as</p>\n\n<pre><code> def sexit(code, str)\n puts str\n exit code\n end\n\n def initialize\n puts \"Type the difficulty level you would like: 1, 2, 3, 4, or 5\"\n @level = gets.to_i\n sexit 1 \"Invalid Difficulty\" if @level > 6\n end\n def create_code\n code_rows = 4\n code_rows += 1 if @level > 4\n @code = ''\n code_rows.times do\n @code += \"#{rand(@level*2)}\n end\n</code></pre>\n\n<p>Should you check this here? It is more of an assert than a problem with user input, and the user input is validated elsewhere.</p>\n\n<pre><code> # sexit 2 \"Invalid Difficulty\" if @code.length > 5\n\n puts @code\n end\n</code></pre>\n\n<p>Avoid magic numbers, replace 4 with a constant.</p>\n\n<pre><code> def askuser(var)\n print var\n return gets\n end\n</code></pre>\n\n<p>Why is retstring and guess a member variable? You dont seem to be using them any where else.</p>\n\n<pre><code> def prompt\n guess = \"\"\n</code></pre>\n\n<p>Whi is this a while loop? while you used a times loop inside?</p>\n\n<pre><code> max_guess.times |guesses|\n retstring = \"\"\n guess = askuser \"Enter a guess: \"\n</code></pre>\n\n<p>you dont need to maintain x.\nAlso, why do you have only 4 here? from the above, if the level is 5 you add a new cell.</p>\n\n<pre><code> 4.times do |x|\n</code></pre>\n\n<p>and better put as ternary</p>\n\n<pre><code> retstring += (@code[x] == guess[x] ? \"+\" : \"-\")\n puts retstring\n sleep(1)\n end\n hint = askuser \"Would you like a hint? Type 'hint' to get a hint\"\n</code></pre>\n\n<p>Why do you use a separate match? Also name j some thing descriptive.\nAnd why \\w ? Do you want to catch spellos in hint?</p>\n\n<pre><code> if hint =~ /hint/i\n j = rand(@level*2)\n puts \"#{j}: #{@code[j]}\"\n end\n</code></pre>\n\n<p>Personally I prefer a case statement to check this. Also note you can get a case insensitive match.</p>\n\n<pre><code> case askuser \"Would you like a hint? Type 'hint' to get a hint\"\n when /hint/i\n j = rand(@level*2)\n puts \"#{j}: #{@code[j]}\"\n end\n\n if retstring == \"++++\"\n puts \"Correct!\"\n break\n end\n</code></pre>\n\n<p>retstring is better reset at the beginning of the loop.</p>\n\n<pre><code> end\n end\n</code></pre>\n\n<p>Regarding the whole organization, it might be better organized as a small command interpreter with specific commands for hint, level etc</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-22T19:53:42.487",
"Id": "11086",
"ParentId": "11084",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-22T18:59:30.680",
"Id": "11084",
"Score": "3",
"Tags": [
"ruby",
"game"
],
"Title": "Codebreaker game"
}
|
11084
|
<p>So I spent a while this morning creating an xml parser in java which is part of a job interview. I would love to have some people tear it apart so I can learn from any mistakes that I made so I can grow for future job interviews.</p>
<p>XML file:</p>
<pre><code><Employees>
<Employee>
<Name> First Last</Name>
<ID> 00001 </ID>
</Employee>
<Employee>
<Name> First2 Last</Name>
<ID> 00002 </ID>
</Employee>
<Employee>
<Name> First3 Last</Name>
<ID> 00003 </ID>
</Employee>
</Employees>
</code></pre>
<p>Java File (126 LOC)- </p>
<pre><code>//@Author HunderingThooves
import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class Main {
static class openXML{
private int employeeNumber;
private String employeeName;
void getEmployee(int i){
String[] xmlStr = xmlLoader(i);
setEmployeeName(xmlStr[0]);
setEmployeeNumber(xmlStr[1]);
}
void setEmployeeNumber(String s){
employeeNumber = Integer.parseInt(s);
}
void setEmployeeName(String s){
employeeName = s;
}
String getEmployeeName(){
return employeeName;
}
int getEmployeeNumber(){
return employeeNumber;
}
};
public static final String[] xmlLoader(int i){
String xmlData[] = new String[2];
try {
int employeeCounter = i;
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("test.xml"));
// normalize text representation
doc.getDocumentElement ().normalize ();
NodeList listOfEmployee = doc.getElementsByTagName("Employee");
Node firstEmployeeNode = listOfEmployee.item(employeeCounter-1);
int totalEmployees = listOfEmployee.getLength();
//Break xml file into parts, then break those parts down int an array by passing individual elements to srtings
if(firstEmployeeNode.getNodeType() == Node.ELEMENT_NODE){
Element firstEmployeeElement = (Element)firstEmployeeNode;
//-------
NodeList nameList = firstEmployeeElement.getElementsByTagName("Name");
Element nameElement = (Element)nameList.item(0);
NodeList textNameList = nameElement.getChildNodes();
xmlData[0]= (((Node)textNameList.item(0)).getNodeValue().trim()).toString();
//-------
NodeList IDList = firstEmployeeElement.getElementsByTagName("ID");
Element IDElement = (Element)IDList.item(0);
NodeList textIDList = IDElement.getChildNodes();
xmlData[1]= (((Node)textIDList.item(0)).getNodeValue().trim()).toString();
//------
}//
}
catch(NullPointerException npe){
System.out.println("The employee number you searched for is incorrect or does not yet exist, try again. ");
String s[] = {" ", " "};
main(s);
}
catch (SAXParseException err) {
System.out.println ("** Parsing error" + ", line "
+ err.getLineNumber () + ", uri " + err.getSystemId ());
System.out.println(" " + err.getMessage ());
}
catch (SAXException e) {
Exception x = e.getException ();
((x == null) ? e : x).printStackTrace ();
}
catch (Throwable t) {
t.printStackTrace ();
}
return xmlData;
}
public static void main(String args[]){
openXML myXmlHandler = new openXML();
Scanner input = new Scanner(System.in);
int i = -1;
do{
try{
String s = "";
System.out.println("Enter the employee number that you're searching for: ");
s = input.next();
try{
i= Integer.parseInt(s);
} catch(NumberFormatException nfe){ i = -1;}
} catch(Exception e){System.out.println("Error: " +e.getMessage());}
}while(i <= 0);
myXmlHandler.getEmployee(i);
System.out.println("The employee Name is: " + myXmlHandler.getEmployeeName());
System.out.println("The employee Number is: " + myXmlHandler.getEmployeeNumber());
System.exit(0);
}
}
</code></pre>
<p>There is one known issue in the file that I will not mention unless someone finds it, I spent about an hour trying to pin it down and the best I could do is sweep it under the rug.</p>
|
[] |
[
{
"body": "<p>Why do you have two different try blocks here? Why not join them?</p>\n\n<pre><code>do{\n try{\n String s = \"\";\n System.out.println(\"Enter the employee number that you're searching for: \");\n s = input.next(); \n try{\n i= Integer.parseInt(s); \n } catch(NumberFormatException nfe){ i = -1;}\n } catch(Exception e){System.out.println(\"Error: \" +e.getMessage());}\n}while(i <= 0);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-22T20:40:22.430",
"Id": "11087",
"ParentId": "11085",
"Score": "0"
}
},
{
"body": "<p>I have done:</p>\n\n<pre><code>Employees emp = JAXB.read(Employees.class, filename);\n</code></pre>\n\n<p>where <code>read</code> was:</p>\n\n<pre><code>@SuppressWarnings(\"unchecked\") public static <T> T read(\n Class<T> t, String filename) throws Exception {\n Preconditions.checkNotNull(filename);\n Preconditions.checkNotNull(t);\n java.io.File f = checkNotNull(new java.io.File(filename));\n JAXBContext context = JAXBContext.newInstance(t);\n Unmarshaller u = context.createUnmarshaller();\n return (T) u.unmarshal(f);\n}\n</code></pre>\n\n<p>You can also read from stream, string or ... </p>\n\n<p>I still don't like what I have written. </p>\n\n<p>They are not judging if you can write code, that works. They want to see a proof that it works (tests), what has been done (jdoc documentation) and readable code. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-22T21:41:20.060",
"Id": "11088",
"ParentId": "11085",
"Score": "1"
}
},
{
"body": "<p>I just did some refactoring to your code and came up with below output.</p>\n\n<p>Few points to be mentioned,</p>\n\n<ol>\n<li>Lets try to use OOPs concept</li>\n<li>Follow naming convention (also includes meaningful names for classes and methods)</li>\n<li>Why catch NPE (do validate your input and avoid such scenario) ?</li>\n<li>Try to avoid unnecessary codes (here there is no use of \"System.exit(0);\")</li>\n<li>The parsing logic can be fine tuned but this is already good for a sample program</li>\n</ol>\n\n<p>Between good try :)\nAnd good luck with your interview.</p>\n\n<pre><code>public class XMLParserExample {\n\nstatic class Employee {\n private final int id;\n private final String name;\n\n public Employee(int id, String name) {\n this.id = id;\n this.name = name;\n }\n\n public int getId() {\n return id;\n }\n\n public String getName() {\n return name;\n }\n}\n\nstatic class EmployeeXMLParser {\n\n private final Document document;\n\n public EmployeeXMLParser(String fileName) {\n document = loadXml(fileName);\n }\n\n Employee findEmployee(int index) {\n NodeList listOfEmployee = document.getElementsByTagName(\"Employee\");\n Node employeeNode = listOfEmployee.item(index - 1);\n\n if (employeeNode != null && employeeNode.getNodeType() == Node.ELEMENT_NODE) {\n String name = getElementValue((Element) employeeNode, \"Name\");\n String id = getElementValue((Element) employeeNode, \"ID\");\n return new Employee(Integer.parseInt(id), name);\n }\n\n return null;\n }\n\n private String getElementValue(Element parentElement, String elementName) {\n NodeList nodeList = parentElement.getElementsByTagName(elementName);\n Element element = (Element) nodeList.item(0);\n NodeList childNodes = element.getChildNodes();\n return (((Node) childNodes.item(0)).getNodeValue().trim()).toString();\n }\n\n private Document loadXml(String fileName) {\n DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();\n try {\n DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();\n Document doc = docBuilder.parse(new File(fileName));\n doc.getDocumentElement().normalize();\n return doc;\n } catch (ParserConfigurationException e) {\n throw new IllegalStateException(\"Error parsing the XML\", e);\n } catch (SAXException e) {\n throw new IllegalStateException(\"Error parsing the XML\", e);\n } catch (IOException e) {\n throw new IllegalStateException(\"Error accessing the XML\", e);\n }\n }\n};\n\nvoid start() {\n EmployeeXMLParser employeeParser = new EmployeeXMLParser(\"test.xml\");\n\n Scanner input = new Scanner(System.in);\n boolean successful = false;\n do {\n System.out.println(\"Enter the employee number that you're searching for: \");\n try {\n Employee employee = employeeParser.findEmployee(Integer.parseInt(input.next()));\n if (employee == null) {\n printTryAgain();\n } else {\n System.out.println(\"The employee Number is: \" + employee.getId());\n System.out.println(\"The employee Name is: \" + employee.getName());\n successful = true;\n }\n } catch (NumberFormatException nfe) {\n printTryAgain();\n }\n } while (!successful);\n}\n\nprivate void printTryAgain() {\n System.out.println(\"The employee number you searched for is incorrect or does not yet exist, try again.\");\n}\n\npublic static void main(String args[]) {\n new XMLParserExample().start();\n} }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T16:12:52.937",
"Id": "17701",
"Score": "0",
"body": "This was a really great answer and your code is very helpful.\n\nAs for the system.exit(0); It was actually because if it was removed I would get a NumberFormatException...I was wondering if you could explain why that was happening with my code? I spent a solid 30 minutes trying to figure it out.. I could catch it but I couldn't trace it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T23:31:38.733",
"Id": "17727",
"Score": "0",
"body": "Strange that you got NFE. I couldn't figure out what went wrong. All I see is even if you don't use it in your program it is going to be terminated. Additional info: Never use System.exit in programs unless it is needed. System.exit normally used in batch programs to indicate whether the process/program was successfully completed. See [System.exit()](http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/System.html#exit(int))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T19:44:02.103",
"Id": "17766",
"Score": "0",
"body": "Try entering in a bad value (using my xml file try entering in a large number, 123451, then enter a working value when it loops.) and it will NFE without the system.exit. It's weird."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T14:04:24.783",
"Id": "11115",
"ParentId": "11085",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "11115",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-22T19:44:43.150",
"Id": "11085",
"Score": "2",
"Tags": [
"java",
"xml",
"parsing"
],
"Title": "Parse an XML file using objects / methods"
}
|
11085
|
<p>I have this Facebook class and I'm wondering if the OOP nature of it could be improved at all?</p>
<p>(GitHub project <a href="https://github.com/benhowdle89/facebookInfo" rel="nofollow">here</a>):</p>
<pre><code><?php
class Facebook {
private $baseUrl = 'https://graph.facebook.com/';
public function basicInfo($username){
if($username !== ''){
$url = $this->baseUrl . $username;
}
if($url !== ''){
$data = $this->__apiCall($url);
}
return $data;
}
public function userProfilePicture($username, $size = 'square'){
if($username !== ''){
$url = $this->baseUrl . $username . '/picture?type=' . $size;
}
return $url;
}
public function searchPublicPosts($query){
if($query !== ''){
$url = $this->baseUrl . 'search?q=' . urlencode($query) . '&type=post';
}
if($url !== ''){
$data = $this->__apiCall($url);
}
return $data;
}
public function searchPages($page){
if($page !== ''){
$url = $this->baseUrl . 'search?q=' . urlencode($page) . '&type=page';
}
if($url !== ''){
$data = $this->__apiCall($url);
}
return $data;
}
public function searchEvents($event){
if($event !== ''){
$url = $this->baseUrl . 'search?q='.urlencode($event).'&type=event';
}
if($url !== ''){
$data = $this->__apiCall($url);
}
return $data;
}
private function __apiCall($url){
$raw = file_get_contents($url);
$json = json_decode($raw, true);
return $json;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>This answer is in two sections. Firstly I am going to cover the <strong>Object Oriented</strong> nature of your solution and suggest possible architectural changes. Then I am going to look at your existing <strong>Code</strong> line by line for improvements.</p>\n\n<h2>Object Oriented</h2>\n\n<p>Your OO is good, you have nothing bad in there.</p>\n\n<p>Here are some of the features of OO that you have used:</p>\n\n<ul>\n<li>Data hiding (<code>baseUrl</code> property is private)</li>\n<li>Encapsulation (use of private <code>__apiCall</code> to minimize interface for callers)</li>\n</ul>\n\n<p>Lets have a look to see what other features you could use.</p>\n\n<p>Now, what is your class? It seems that it is a URL builder for the Facebook API. You could think about creating a class that helps you with this URL building. Let me pull one out of my hat now... (untested, only syntax checked)</p>\n\n<pre><code>class UrlBuilder {\n protected $baseUrl;\n protected $domain;\n protected $scheme;\n\n public function __construct($scheme, $domain, $baseUrl) { \n $this->baseUrl = $baseUrl;\n $this->domain = $domain;\n $this->scheme = $scheme;\n }\n\n /** Build a URL.\n * @param rel @string The relative offset from the baseUrl.\n * @param query @array Associative array of query parameters.\n * @return @string URL string.\n */\n public function buildUrl($rel, Array $query) {\n $url = $this->scheme . \"://\" . $this->domain . '/' . $this->baseUrl .\n $rel;\n\n if (!empty($query)) {\n $url .= '?' . http_build_query($query);\n }\n\n return $url;\n }\n}\n</code></pre>\n\n<p>You will see from above that I use <code>http_build_query</code> (which is covered in the Code section of the review).</p>\n\n<p>I left parameter checking out of this class to make this answer easier to read. However you should definitely check each scalar parameter <code>$scheme</code>, <code>$domain</code>, <code>$baseUrl</code>, <code>$rel</code>. Here is an example of how you would check <code>$rel</code>:</p>\n\n<pre><code>if (!is_string($rel)) {\n throw new InvalidArgumentException(__METHOD__ . 'rel must be a string');\n}\n</code></pre>\n\n<p>So, how do we go about using this? The common initial thought is the fantastic OO feature inheritance! Raise your hand if you want to use inheritance. Luckily from here I can't see any hands raised. What would happen if we used inheritance (class Facebook extends <code>UrlBuilder</code>)? We would open up the <code>buildUrl</code> method allowing any URL to be built with your Facebook object. This would be bad. Why was inheritance a bad idea? Because the Facebook object is not a <code>UrlBuilder</code>. It is something that uses URL building.</p>\n\n<p>The answer is <strong>composition</strong>. We should pass the URL builder that we want to use into our constructor (generally I would use an interface, lets call it \"UrlBuilderIface\" and have <code>class UrlBuilder implements UrlBuilderIface</code>). Using an interface allows us to keep the class loosely coupled. We can accept any object that fulfills the contract defined by our <code>UrlBuilderIface</code>. Here is the implementation with one method defined:</p>\n\n<pre><code>class Facebook {\n protected $urlBuilder;\n\n public function __construct(UrlBuilderIface $urlBuilder) {\n $this->urlBuilder = $urlBuilder;\n }\n\n public function searchPublicPosts($query) {\n if (empty($query) || !is_string($query)) {\n throw new InvalidArgumentException('query must be a non empty string.');\n }\n\n return $this->__apiCall($this->urlBuilder('search', array('q' => $query)));\n }\n\n private function __apiCall($url) {\n $raw = file_get_contents($url);\n return json_decode($raw, true);\n }\n}\n</code></pre>\n\n<p>Note how there is checking for the passed in parameter to the method. The check is simple, and it makes the rest of the code easy. It is also easy to think about it completely separately from the other code (because you know that an exception will be thrown if the guard condition is met).</p>\n\n<p>Usage becomes:</p>\n\n<pre><code>$facebookGraphUrlBuilder = new UrlBuilder('https', 'graph.facebook.com', '');\n $facebook = new Facebook($facebookGraphUrlBuilder);\n</code></pre>\n\n<h2>Code</h2>\n\n<p>Some minor comments:</p>\n\n<ul>\n<li><code>__apiCall</code> should be named <code>apiCall</code>. <code>__</code> should be reserved for magic methods.</li>\n<li><code>json_decode</code> does not produce json, so you shouldn't create a variable from it called <code>$json</code>.</li>\n<li><code>$json</code> should never have even been a variable (A variable is for varying). So you should return straight away, <code>return json_decode($raw, true);</code></li>\n</ul>\n\n<p>I am going to look at a single method because you have the same problems shared across your methods.</p>\n\n<pre><code>public function basicInfo($username){\n\n if($username !== ''){\n $url = $this->baseUrl . $username;\n }\n if($url !== ''){\n $data = $this->__apiCall($url);\n }\n return $data;\n\n }\n</code></pre>\n\n<p>Observe what would happen if $username was '':</p>\n\n<ul>\n<li>First if does not match, so <code>$url</code> is not set.</li>\n<li>Non-existent <code>$url</code> is used in second if causes E_NOTICE error.</li>\n<li>Second if matches as NULL !== '' (This is not good).</li>\n<li><code>apiCall</code> is made using NULL.</li>\n<li>Badness continues.</li>\n</ul>\n\n<p>Actually, similar or worse would happen if you used NULL an array, etc.</p>\n\n<p>The bad thing here is the combination of your conditional setting of variables and later expectation that the variables have been set. I would recommend solving this using a guard condition to ensure that the parameters to your methods are sane. Trying to continue with the processing using if statements is quite difficult. Throwing an exception may be the easiest:</p>\n\n<pre><code>if (!empty($username) || !is_string($username)) {\n throw new InvalidArgumentException('username required as a non-empty string.');\n}\n</code></pre>\n\n<p>Everything can then be assumed to work:</p>\n\n<pre><code>return $this->__apiCall($this->baseUrl . $username);\n</code></pre>\n\n<p>Finally, there is a PHP function that helps you build the query strings that you use. Here is the manual page for it: <a href=\"http://php.net/manual/en/function.http-build-query.php\" rel=\"nofollow\">http_build_query</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T18:25:35.683",
"Id": "17716",
"Score": "0",
"body": "Wow. Well this is fantastic. I'm definitely going to be using this site more often, if this is the calibre of review. This will help my coding no end!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T02:25:59.860",
"Id": "17731",
"Score": "2",
"body": "I'm glad it was helpful. I love OO, so I put some extra effort into this answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T04:52:45.013",
"Id": "11100",
"ParentId": "11092",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "11100",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T00:30:24.690",
"Id": "11092",
"Score": "2",
"Tags": [
"php",
"object-oriented"
],
"Title": "Could this PHP Facebook class be any more OOP-ified?"
}
|
11092
|
<p>What is the best way to optimize this jQuery code?</p>
<pre><code>$('#hde_test').hide();
$('#shw_test').click(function() {
$('#shw_test').hide();
$('#hde_test').show();
$('.class1').show();
});
$('#hde_test').click(function() {
$('#shw_test').show();
$('#hde_test').hide();
$('.class1').hide();
});
</code></pre>
|
[] |
[
{
"body": "<p>You can use the <a href=\"http://api.jquery.com/toggle/\" rel=\"noreferrer\">.toggle() method</a> or <a href=\"http://api.jquery.com/toggleClass/\" rel=\"noreferrer\">.toggleClass() method</a> to toggle the objects visibility. That would let you do something like:</p>\n\n<pre><code>$('#show_toggle').click(function() {\n $('.class1').toggle();\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-07T18:02:03.223",
"Id": "11095",
"ParentId": "11094",
"Score": "5"
}
},
{
"body": "<p>You can shorten it down:</p>\n\n<pre><code>$('#shw_test').click(function() {\n $('#hde_test, #shw_test').toggle();\n $('.class1').show();\n});\n$('#hde_test').click(function() { \n $('#hde_test, #shw_test').toggle();\n $('.class1').hide();\n});\n</code></pre>\n\n<p>Likely, you can shorten it to:</p>\n\n<pre><code>$('#shw_test, #hde_test').click(function() {\n $('#hde_test, #shw_test, .class1').toggle();\n});\n</code></pre>\n\n<p>Just depends how the initial state of things are.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-07T18:02:05.627",
"Id": "11096",
"ParentId": "11094",
"Score": "16"
}
},
{
"body": "<p>You could refactor that into a \"toggle\" function:</p>\n\n<pre><code>function toggle(show, hide)\n{\n $(show).show();\n $(hide).hide();\n}\n\nfunction doStuff(){\n //this will show shw_test and hide hde_test\n toggle('#shw_test', '#hde_test');\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-07T18:05:05.883",
"Id": "17665",
"Score": "0",
"body": "jQuery has this built in :) `.toggle(true/false)`"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-07T18:05:32.170",
"Id": "17666",
"Score": "0",
"body": "jQuery already has a .toggle function built in."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-07T18:02:58.633",
"Id": "11097",
"ParentId": "11094",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "11096",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2010-03-07T17:59:52.400",
"Id": "11094",
"Score": "11",
"Tags": [
"javascript",
"jquery"
],
"Title": "More elegant way to show | hide in jQuery"
}
|
11094
|
<p>I have created a queue in javascript. This queue also has blocking <code>take()</code>. As you all probably know this is not really true, because javascript does not have threads. It just wait until element has been added to queue. You can view to source-code at <a href="https://gist.github.com/2467432" rel="nofollow">https://gist.github.com/2467432</a>. I try to <a href="http://googletesting.blogspot.com/2008/08/by-miko-hevery-so-you-decided-to.html" rel="nofollow">write testable code</a>. As you can see from my code below <a href="http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/" rel="nofollow">my constructor does real work</a>?</p>
<pre><code>var EventEmitter = require('events').EventEmitter,
Queue = module.exports = function Queue() {
/* Constructor is doing work..??
*/
var _emitter = this._emitter = new EventEmitter(),
_awaiting = this._awaiting = [],
_queue = this._queue = [];
_emitter.on('offer', function (data) {
_awaiting.shift()(data);
});
};
</code></pre>
<p>My question is if this a <a href="http://en.wikipedia.org/wiki/Code_smell" rel="nofollow">code smell</a>? I think this class(object) is a <a href="http://googletesting.blogspot.com/2008/08/by-miko-hevery-so-you-decided-to.html" rel="nofollow">leaf of application graph(value-object)</a>, so maybe it is not such a big deal. This way I think I can keep my <a href="http://en.wikipedia.org/wiki/Application_programming_interface#API_in_object-oriented_languages" rel="nofollow">API</a> clean(easy to use). I think my class is still easy to test as you can hopefully see from my test class.</p>
<blockquote>
<p>Value-objects, these tend to
have lots of getters / setters and are very easy to construct are
never mocked, and probably don't need an interface. (Example:
LinkedList, Map, User, EmailAddress, Email, CreditCard, etc...). (2)
Service-objects which do the interesting work, their constructors ask
for lots of other objects for colaboration, are good candidates for
mocking, tend to have an interface and tend to have multiple
implementations (Example: MailServer, CreditCardProcessor,
UserAthenticator, AddressValidator).</p>
</blockquote>
<p>If you think it is a code smell I would like to know how you would fix this(but still keep the tests pass without any modification if possible?)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T23:07:19.267",
"Id": "460039",
"Score": "0",
"body": "PS: Your code does not actually work (`Array.prototype.shift` does not return a function). Also, starting a property name with `_` does not make it private."
}
] |
[
{
"body": "<p>Personally the only issue I see with the code in terms of your constructor doing real work or testability is the instantiation of an <code>EventEmitter</code> object. Doing this in the constructor prevents you from mocking out or injecting a different class/instance for testing. You could use <a href=\"http://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow\">Dependency Injection</a> as a simply way to resolve this:</p>\n\n<pre><code>var EventEmitter = require('events').EventEmitter,\n Queue = module.exports = function Queue( emitter ) {\n /* Constructor is doing work..?? \n */\n var _emitter = this._emitter = emitter,\n _awaiting = this._awaiting = [],\n _queue = this._queue = [];\n\n _emitter.on('offer', function (data) {\n _awaiting.shift()(data);\n });\n\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T05:26:39.727",
"Id": "17794",
"Score": "0",
"body": "I know about dependency injection. But I like to keep my API as simple as possible because I want to publish it as module for example. I think in that case a clean constructor would be best? I want to expose the class as in the test if possible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T12:19:30.760",
"Id": "17799",
"Score": "1",
"body": "In that case if you *really* care about it you could optionally pass in a emitter or just omit it altogether. Something like var _emitter = this._emitter = emitter || new EventEmitter(),"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T11:45:24.113",
"Id": "11139",
"ParentId": "11098",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "11139",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-22T23:46:45.497",
"Id": "11098",
"Score": "3",
"Tags": [
"javascript",
"unit-testing",
"node.js"
],
"Title": "my constructor is doing work. Is this a code smell in this example?"
}
|
11098
|
<p>Starting from a specific number of 1-element sets, I want to pair these sets together (forming 2-elements sets), then pair the paired sets with the original one-element sets (forming 3-elements sets), etc...</p>
<p>For example, if I start with these 1-element sets:</p>
<pre><code>{1}, {2}, {3}, {4}
</code></pre>
<p>After pairing them together I will get:</p>
<pre><code>{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}
</code></pre>
<p>Then I pair them with the original 1-element sets and I get</p>
<pre><code>{1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}
</code></pre>
<p>and finally</p>
<pre><code>{1, 2, 3, 4}
</code></pre>
<p>One important thing that I would like to add is that I will not consider all sets, the new sets need to satisfy some condition, so by the end, I might not have all possible sets.</p>
<p>To solve this problem (efficiently), someone suggested to use trees.</p>
<p>I will form one set at a time, and check if the new set already exists in the tree or not; to do that I will need to have (increasingly) ordered set.</p>
<p>Here's the tree that I will get from running my code (starting with {1}, {2}, {3}, {4}) - assuming there's no constraints on the sets I want to have.</p>
<p><img src="https://lh5.googleusercontent.com/-NNCNdyKQspM/T5TBzSqzqpI/AAAAAAAALKw/Num7asFuntU/s400/treeStructure.jpg" alt="example"></p>
<p>The only reason for this tree is to quickly for duplicates easily.</p>
<p>Is this a relatively efficient way? I will need to start with really large 1-element sets (~100s).</p>
<pre><code>import java.util.LinkedList;
public class TrieTree
{
Node treeNode = new Node();
boolean addInteger(LinkedList<Integer> IntegerToBeAdded)
{
Node startNode = new Node();
startNode = treeNode;
boolean isItNewSet = false;
for(int ix = 0; ix < IntegerToBeAdded.size(); ix++)
{
Integer currInteger = IntegerToBeAdded.get(ix);
int indexOfstartNode = -1;
for(int jx = 0; jx < startNode.children.size(); jx++)
{
if(startNode.children.get(jx).data == currInteger)
{
indexOfstartNode = jx;
break;
}
}
if(indexOfstartNode == -1)
{
Node tempNode = new Node();
tempNode.data = currInteger;
tempNode.parent = startNode;
startNode.children.add(tempNode);
startNode = startNode.children.getLast();
isItNewSet = true;
}
else
{
startNode = startNode.children.get(indexOfstartNode);
}
}
if(isItNewSet)
return true;
else
return false;
}
private class Node
{
public Integer data;
public Node parent;
public LinkedList<Node> children;
Node()
{
children = new LinkedList<Node>();
}
}
}
</code></pre>
<p>Main file:</p>
<pre><code>import java.util.LinkedList;
public class Main
{
public static void main(String[] args)
{
TrieTree myTree = new TrieTree();
LinkedList<Integer> originalSet = new LinkedList<Integer>();
originalSet.add(1);
originalSet.add(2);
originalSet.add(3);
originalSet.add(4);
LinkedList<LinkedList<Integer>> totalSet = new LinkedList<LinkedList<Integer>>();
LinkedList<LinkedList<Integer>> currentlyGeneratedSet = new LinkedList<LinkedList<Integer>>();
for(int jx = 0; jx < originalSet.size(); jx++)
{
LinkedList<Integer> temp = new LinkedList<Integer>();
temp.add(originalSet.get(jx));
// currently generated will be used later so we can add original 1-element sets to it to form more sets
currentlyGeneratedSet.add(temp);
// Add 1-element sets to the total
totalSet.add(temp);
// Add 1-element sets to the tree
myTree.addInteger(currentlyGeneratedSet.get(jx));
}
LinkedList<LinkedList<Integer>> setToBeAddedOn = new LinkedList<LinkedList<Integer>>();
Boolean continueFlag;
do
{
continueFlag = false;
setToBeAddedOn.clear();
// myLastIntegers = myNextLastIntegers; - this way will copy address
// the following way will copy values
//
for(int ix = 0; ix < currentlyGeneratedSet.size(); ix++)
{
setToBeAddedOn.add(currentlyGeneratedSet.get(ix));
}
currentlyGeneratedSet.clear();
for(int j = 0 ; j < originalSet.size(); j++)
{
for(int i = 0; i < setToBeAddedOn.size(); i++)
{
// this will be 1 first time, then 2, then 3, ...
int numberOfAtomicIntegers = setToBeAddedOn.get(i).size();
// itContains will indicate whether the element we want to add already exists or not
// for example adding {1} to {1, 2} will result in a 'true' itContains
//
boolean itContains = false;
// make sure the Integer we want ot add is not already included in the tree
//
if(setToBeAddedOn.get(i).contains(originalSet.get(j)))
itContains = true;
if(!itContains)
{
boolean continueAdding = true;
// currTemp will hold the new set for exmaple;
// when we add {1} to {2, 3}, currTemp will hold {1, 2, 3}
LinkedList<Integer> currTemp = new LinkedList<Integer>();
for(int k = 0; k < numberOfAtomicIntegers; k++)
{
// We need to do the following so that the list is still sorted
//
if(originalSet.get(j) < setToBeAddedOn.get(i).get(k))
{
currTemp.add(originalSet.get(j));
for(int kx = k; kx < numberOfAtomicIntegers; kx++)
currTemp.add(setToBeAddedOn.get(i).get(kx));
continueAdding = false;
break;
}
else
currTemp.add(setToBeAddedOn.get(i).get(k));
}
if(continueAdding)
currTemp.add(originalSet.get(j));
// Here we check if myCurrNewRule exists or not.. we use our tree
//
// addInteger will return 'true' if it's new, 'false' otherwise
boolean isNewRuleExisted = myTree.addInteger(currTemp);
if(isNewRuleExisted /*&& myConstraint here*/)
{
currentlyGeneratedSet.add(currTemp);
totalSet.add(currTemp);
continueFlag = true;
}
}
}
}
}while(continueFlag);
}
}
</code></pre>
<p>The goal that I'm trying to accomplish is to form groups of categories taken from attributes of data-sets.</p>
<p>For example, if I have this data-set:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Sex -------- Income ---------- WearsGlasses
M ---------- V. High ---------- Yes
F ---------- Low -------------- Yes
M ---------- High ------------- No
F ---------- High ------------- Yes
F ---------- V. High ---------- Yes
...
</code></pre>
</blockquote>
<p>The initial set that I will form is the following (all single categories):</p>
<p><code>{{sex(M)}, {sex(F)}, {Income(V. High)}, {Income(High)}, {Income(Low)}, {WearsGlasses(Yes)}, {WearsGlasses(no)}}</code> plus all other single categories that exist in the data-set.</p>
<p><strong>Note:</strong> to implement this as explained in the code (using a tree), I will need to give a unique number for each element in my original one-element set mentioned above.</p>
<p>My first condition is that I should have at least a specific number of instances in the data-set for each element in my set. So if I set this number to 2, and if we assume that the shown sample is all the data-set. I will need to remove <code>WearsGlasses(No)</code> and <code>Income(low)</code>, since we only have one instance of each.</p>
<p>After this condition is satisfied, I will form two-element sets (surely, only from the one-elements that satisfied my condition)</p>
<p>My second condition is that I can't form new sets that contain same attributes. What I mean is that I can't have: <code>{{Income(High), Income(V. High)}}</code>, which makes sense because we can't have both at the same time.</p>
<p>So by the end I will have all the possible sets/combinations of all the categories, that occurred more than x number of times (in my example x was 2) </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T04:40:49.303",
"Id": "17667",
"Score": "0",
"body": "You want a power set, which can't be that hard. http://www.roseindia.net/tutorial/java/core/powerset.html You can then throw out the empty set. Essentially you can loop through {true, false} 4 times and generate each set through inclusion/exclusion. If you want a generator of a set of any size, then use the linked code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T04:47:43.540",
"Id": "17668",
"Score": "0",
"body": "Here is another good approach ... bit fields: http://www.geeksforgeeks.org/archives/588"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T13:11:46.237",
"Id": "17688",
"Score": "0",
"body": "@Leonid, those are really good suggestions. In my case I will have very large 1-element sets, and I will have a constraint so I I won't be generating the actual power set per say. for example, I might start with `originalSet = {a, b, c}`, when going to 2-elements sets, I might only accept `{{a,b}, {a,c}}` and ignore `{b,c}` and so on. But I think there should be a way to still efficiently do that; by using power sets."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T16:56:29.350",
"Id": "17708",
"Score": "1",
"body": "Actually, the best way of doing this really depends on what your condition is. If you tell us more about that we can give better advice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T20:13:32.447",
"Id": "17721",
"Score": "0",
"body": "@WinstonEwert, I added all the details about my condition."
}
] |
[
{
"body": "<p>Firstly, there is a bunch of general stuff that can be cleaned up here:</p>\n\n<pre><code> boolean addInteger(LinkedList<Integer> IntegerToBeAdded)\n</code></pre>\n\n<p>You aren't add Integers here. You are adding sets. You should pick better names</p>\n\n<pre><code> { \n Node startNode = new Node(); \n\n startNode = treeNode; \n</code></pre>\n\n<p>Ok, you <code>new</code> a node object, and then throw it away on the next line.</p>\n\n<pre><code> boolean isItNewSet = false;\n</code></pre>\n\n<p>Avoid boolean logic flags, they are delayed gotos</p>\n\n<pre><code> for(int ix = 0; ix < IntegerToBeAdded.size(); ix++)\n</code></pre>\n\n<p>Use the for-each syntax</p>\n\n<pre><code> {\n Integer currInteger = IntegerToBeAdded.get(ix);\n\n int indexOfstartNode = -1; \n\n for(int jx = 0; jx < startNode.children.size(); jx++)\n {\n if(startNode.children.get(jx).data == currInteger)\n {\n indexOfstartNode = jx;\n break;\n }\n }\n</code></pre>\n\n<p>Typically a trie is implemented using an array. Then you can just lookup the proper child node instead of scanning through them.</p>\n\n<pre><code> if(indexOfstartNode == -1)\n {\n Node tempNode = new Node();\n</code></pre>\n\n<p>temp is a bad thing to put in a variabe name. All variables are temporary.</p>\n\n<pre><code> tempNode.data = currInteger;\n tempNode.parent = startNode;\n\n startNode.children.add(tempNode);\n\n startNode = startNode.children.getLast();\n\n isItNewSet = true;\n }\n else\n {\n startNode = startNode.children.get(indexOfstartNode);\n } \n }\n if(isItNewSet)\n return true;\n else\n return false;\n</code></pre>\n\n<p>use <code>return isItNewSet;</code> </p>\n\n<pre><code> }\n</code></pre>\n\n<p>Similar clean-up is possible on your other code.</p>\n\n<p>Secondly, this whole thing is necessary because you need to check whether a given set has already been generated. But the better solution is to simply not generate duplicate sets. You can use something like this:</p>\n\n<pre><code>void generateSet(Set current, List available)\n{\n // make a copy of the available list, removing one item\n available = available.clone();\n Object nextItem = available.pop();\n\n // generate all sets without that item\n generateSet(current, available); \n\n // create a new set with the item\n current = current.clone();\n current.add(nextItem);\n\n // add to the list of sets\n addSet(current);\n\n // generate all sets that contain this item\n generateSet(current, available);\n}\n</code></pre>\n\n<p>How to handle the case when the available list goes empty is left as an exercise for the reader. But this technique won't generate the same set twice, so you can avoid checking for it. </p>\n\n<p>For your exact case, you should do something like:</p>\n\n<pre><code>void generateFilter(int feature, Filter filter)\n{\n if( feature == filter.featureCount() )\n return;\n\n generateFilter(feature+1, filter);\n\n for(int index = 0; index < filter.featureOptions(feature); index++)\n {\n Filter newFilter = filter.addFilter(feature, index);\n if( newFilter.countHighEnough() )\n {\n addToListOfFilters(newFilter);\n generateFilter(feature+1,newFilter);\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T17:09:41.220",
"Id": "17812",
"Score": "0",
"body": "I think I need more help. I think I understand the idea of the function `generalSet`, but I'm not 100% positive, I tried to run the code to make sure I understand it, but I'm getting errors, mainly on `available = availabe.clone()`. Even when replacing `List` with `LinkedList<Integer>`, I'm still not able to clone. If I do it exactly like you mentioned I'll get the error `cannot convert from Object to LinkedList<Integer>`. And honestly I don't understand `generateFilter` function at all :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T17:23:59.190",
"Id": "17813",
"Score": "0",
"body": "Another question: `Typically a trie is implemented using an array. Then you can just lookup the proper child node instead of scanning through them.`. I'm interested in this; a lot. I think that's why my code is slow. But the problem is that the children don't always go from 1 to a specific number. For example the children of node 2 (on level 1) are 3 and 4. If I need to create an array for that, it will be from 0 to 4 (0, 1, and 2 will be empty). Won't this cause a problem, since I will have only a small subset of all possible sets?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T19:16:21.167",
"Id": "17821",
"Score": "0",
"body": "@RoronoaZoro, I don't do Java very much so my code was not quite correct. What you need is something like `available = (List<Integer>)available.clone()`. `generateFilter` is the same idea, but avoids picking multiple sets from the same category. As for arrays, you still avoid creating the parts of the tree that don't contain anything. It will take more space then before, but that the trade-off with tries."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T19:39:26.277",
"Id": "17824",
"Score": "0",
"body": "Ok, at least right now **I know for sure** that I shouldn't use a Trie. Since my original 1-element set might be large. From what I understand, if my original set size is 100, and by only going three levels deep, I might need 100^3 spaces (which I think is crazy). I'm currently looking into your suggested way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-24T09:54:05.043",
"Id": "21022",
"Score": "0",
"body": "@Roronora: you only allocate what you use: if some node doesn't have a child, you store `null`, and thus nothing else is allocated down that branch of the tree. Also, if the only possibilities are '3' and '4', then you don't allocate a 5-long array with 3 unused entries: you allocate a 2-long array and subtract 3 every time you do a look-up."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T21:10:08.953",
"Id": "11126",
"ParentId": "11099",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T04:06:53.837",
"Id": "11099",
"Score": "4",
"Tags": [
"java"
],
"Title": "Efficient form/pair sets from existing (1-element) sets"
}
|
11099
|
<p>This is my code that implements Dijkstra's single source shortest path algorithm, which is called multiple times to recalculate after graph changes. the graph is a road system of a city and shortest path needs to be calculated when certain roads close one at a time.</p>
<p>I am looking for advice on the following:</p>
<ul>
<li>Will this read better if it is object oriented? I guess that is a resounding yes. What kind of classes make sense? (one for adjacency list, one for list of closed roads and so on?) Is this design effort worth the time on coding competitions? </li>
<li>What are other glaring design errors in my code? (I know global vars are one. Sometimes I need multiple return values - do I make a struct for each of such type of return values? Is there a less tedious design?)</li>
</ul>
<p>I hope the question is specific enough. If not, I can add more details.</p>
<pre><code>#include <iostream>
#include <queue>
#include <list>
#include <map>
using namespace std;
#define ulong unsigned long
#define INFINITY (ulong)-1
typedef struct {
ulong nbr;
ulong cost;
} ADJ_LIST_NODE;
typedef struct {
ulong shortest_dist;
ulong predecessor;
} SP_FOUND_NODE;
typedef struct {
ulong vertex;
ulong dist;
ulong predecessor;
} SP_ESTIMATE_NODE;
typedef struct {
ulong v1;
ulong v2;
} ROAD;
class SPEstimateNodeCompare {
public:
bool operator()(const SP_ESTIMATE_NODE& a, const SP_ESTIMATE_NODE& b) {
return a.dist > b.dist;
}
};
vector< map< ulong, ulong> > city_adj_list;
ulong n_cities, m_roads;
ulong src, dest;
ulong q_broken_roads;
vector<ROAD> broken_road_list;
map< ulong, SP_FOUND_NODE > sp_found;
priority_queue< SP_ESTIMATE_NODE, vector<SP_ESTIMATE_NODE>, SPEstimateNodeCompare > sp_estimate_q;
map< ulong, ulong> estimate_distances;
void read_input() {
cin >> n_cities;
cin >> m_roads;
for (ulong i = 0; i < n_cities; i++) {
city_adj_list.push_back(*(new map<ulong, ulong>));
}
ulong v1, v2, cost;
ADJ_LIST_NODE node;
for (ulong i = 0; i < m_roads; i++) {
cin >> v1;
cin >> v2;
cin >> cost;
if (v1 >= n_cities or v2 >= n_cities) {
cout << "Invalid input!" << endl;
exit(-1);
}
node.nbr = v2;
node.cost = cost;
city_adj_list[v1][v2] = cost;
node.nbr = v1;
node.cost = cost;
city_adj_list[v2][v1] = cost;
}
cin >> src;
cin >> dest;
if (src >= n_cities or dest >= n_cities) {
cout << "Invalid input - source/destination!" << endl;
exit(-1);
}
cin >> q_broken_roads;
if (q_broken_roads > m_roads) {
cout << "Invalid input - q value!" << endl;
exit(-1);
}
for (ulong i = 0; i < q_broken_roads; i++) {
ROAD r;
cin >> r.v1;
cin >> r.v2;
if (r.v1 >= n_cities or r.v2 >= n_cities) {
cout << "Invalid input! broken roads." << endl;
exit(-1);
}
broken_road_list.push_back(r);
}
}
void print_input(vector< map <ulong, ulong> >& adj_list) {
map< ulong, ulong >::iterator next_road;
for (ulong i = 0; i < n_cities; i++) {
cout << "CITY " << i << endl;
for (next_road = adj_list[i].begin();
next_road != adj_list[i].end();
next_road++) {
cout << "Neighbour " << next_road->first << " Cost " <<
next_road->second << endl;
}
}
}
void relax_estimates(ulong vertex, ulong shortest_dist, vector< map <ulong, ulong> >& adj_list) {
if (vertex >= n_cities) {
cout << "Invalid relax vertex " << vertex << endl;
}
// cout << "Relaxing w.r.t. " << vertex << endl;
map < ulong, ulong>::iterator next_road;
// For each neighbour of relax vertex,
for(next_road = adj_list[vertex].begin();
next_road != adj_list[vertex].end();
next_road++) {
// next_road->nbr ==> first/key
// next_road->cost ==> second/value
if (sp_found.count(next_road->first) == 0 and
next_road->second + shortest_dist < estimate_distances[next_road->first]) {
estimate_distances[next_road->first] = next_road->second + shortest_dist;
// cout << "Relaxed distance to " << next_road->first << " to " << estimate_distances[next_road->first] << endl;
SP_ESTIMATE_NODE x;
x.vertex = next_road->first;
x.dist = estimate_distances[next_road->first];
x.predecessor = vertex;
sp_estimate_q.push(x);
}
}
}
ulong get_shortest_path (vector< map <ulong, ulong> >& adj_list) {
SP_ESTIMATE_NODE est_node;
SP_FOUND_NODE found_node;
// Initialize data structures
for (ulong v = 0; v < n_cities; v++) {
estimate_distances[v] = INFINITY;
sp_found.erase(v);
}
while (!sp_estimate_q.empty()) {
sp_estimate_q.pop();
}
found_node.shortest_dist = 0;
found_node.predecessor = -1;
sp_found[src] = found_node;
// list<ADJ_LIST_NODE>::iterator next_road;
map <ulong, ulong >::iterator next_road;
for (next_road = adj_list[src].begin();
next_road != adj_list[src].end();
next_road++) {
// next_road->nbr ==> first/key
// next_road->cost ==> second/value
// cout << "Adding " << next_road->first << " with dist "
// << next_road->second << " to priority q" << endl;
est_node.vertex = next_road->first;
est_node.dist = next_road->second;
est_node.predecessor = src;
sp_estimate_q.push(est_node);
estimate_distances[est_node.vertex] = est_node.dist;
}
ulong relax_vertex = src;
ulong relax_vertex_dist = 0;
while (!sp_estimate_q.empty()) {
// Get smallest dist entry from q
est_node = sp_estimate_q.top();
// Make sure est_node is not a duplicate entry in priority queue
if (sp_found.count(est_node.vertex) > 0) {
// Do nothing except delete it from map and queue.
sp_estimate_q.pop();
estimate_distances.erase(est_node.vertex);
continue;
}
// cout << "Picked vertex " << est_node.vertex << " with dist "
// << est_node.dist << " from priority q" << endl;
// Add to list of shortest path found vertices.
found_node.shortest_dist = est_node.dist;
found_node.predecessor = est_node.predecessor;
sp_found[est_node.vertex] = found_node;
// Relax all its neighbours.
relax_vertex = est_node.vertex;
relax_vertex_dist = est_node.dist;
relax_estimates(relax_vertex, relax_vertex_dist, adj_list);
// Remove the resolved vertex.
estimate_distances.erase(est_node.vertex);
sp_estimate_q.pop();
}
// Print.
cout << sp_found[dest].shortest_dist << endl;
// cout << endl;
// cout << "Shortest distance " << sp_found[dest].shortest_dist << endl;
// cout << "Path (in reverse) " << dest;
// ulong v = dest;
// while (v != src) {
// v = sp_found[v].predecessor;
// cout << " - " << v;
// }
// cout << endl;
return 0;
}
int main() {
read_input();
// cout << ">>>>> Before broken roads " << endl;
// get_shortest_path(city_adj_list);
for (ulong i = 0; i < q_broken_roads; i++) {
vector< map< ulong, ulong> > city_broken_adj_list = city_adj_list;
// ROAD broken_road_list[i];
ulong v1 = broken_road_list[i].v1;
ulong v2 = broken_road_list[i].v2;
city_broken_adj_list[v1].erase(v2);
city_broken_adj_list[v2].erase(v1);
// cout << ">>>>> Broken road " << v1 << "==" << v2 << endl;
// print_input(city_broken_adj_list);
get_shortest_path(city_broken_adj_list);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T05:40:06.777",
"Id": "17670",
"Score": "0",
"body": "Why do you use typedef struct? That looks very odd in a c++ program. c++ does not have need for that construct because user defined data types can be used exactly the same way as primitives. i.e you no longer need to prefix a struct object declaration with struct keyword."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T05:44:55.987",
"Id": "17671",
"Score": "0",
"body": "i was trying to avoid using \"struct struct_name\" for every declaration. is that a bad idea? i am wondering why?\nthanks for pointing this out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T05:46:40.747",
"Id": "17672",
"Score": "0",
"body": ":) as mentioned above, c++ does not require that any longer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T05:50:22.973",
"Id": "17673",
"Score": "0",
"body": "Also, use typedef ulong unsigned long rather than #define. Generally, avoid preprocessor when possible. Same way, you can define Infinity as a constant rather than a #define (I recommend <climits> and use ULONG_MAX instead.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T05:52:33.417",
"Id": "17674",
"Score": "0",
"body": "ah. sorry i missed the whole comment at first. great, so i can avoid more than one name for the same data type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T05:58:28.760",
"Id": "17675",
"Score": "0",
"body": "about ulong and climits -- makes sense. thanks!"
}
] |
[
{
"body": "<h3>Lets start with the explicit questions:</h3>\n\n<blockquote>\n <p>i am looking for advice on the following</p>\n \n <p>will this read better if it is object oriented?</p>\n</blockquote>\n\n<p>Most definitely. I have implemented this before; probably using less than a quarter of the lines of code shown here.</p>\n\n<blockquote>\n <p>I guess that is a resounding yes.</p>\n</blockquote>\n\n<p>Yes.</p>\n\n<blockquote>\n <p>what kind of classes make sense? (one for adjacency list, one for list of closed roads and so on?)</p>\n</blockquote>\n\n<p>Personally I think that's the wrong way to go. Just mark closed roads as having infinite cost.</p>\n\n<blockquote>\n <p>is this design effort worth the time on coding competitions?</p>\n</blockquote>\n\n<p>Depends on the goals of the competition. But I find that if you have a clear set of interacting classes then the it reduces the overall code size. This in turn will reduce the time it takes to write the code.</p>\n\n<blockquote>\n <p>what are other glaring design errors in my code?</p>\n</blockquote>\n\n<p>I will cover that below.</p>\n\n<blockquote>\n <p>i know global vars are one.</p>\n</blockquote>\n\n<p>Yes</p>\n\n<blockquote>\n <p>sometimes i need multiple return values - do i make a struct for each of such type of return values?</p>\n</blockquote>\n\n<p>No. There are a couple of utility classes that will help.</p>\n\n<blockquote>\n <p>is there a less tedious design?</p>\n</blockquote>\n\n<p>Yes. std::pair<> and std::tupple<> (boost::tupple<>) spring to mind.</p>\n\n<h3>Obvious hangovers from C</h3>\n\n<p>Stop using macros where they are not needed (and there are very few places they are needed). Macros should be used to do conditional compilation based on some factor not known at development time (OS/Compiler etc).</p>\n\n<pre><code>#define ulong unsigned long\n#define INFINITY (ulong)-1\n\n// Better to write as:\ntypedef unsigned long ulong;\nstatic ulong const INFINITY = static_cast<ulong>(-1);\n</code></pre>\n\n<p>struct's no longer need a typedef in C++</p>\n\n<pre><code>typedef struct {\n ulong nbr;\n ulong cost;\n} ADJ_LIST_NODE;\n\n// Much more readable as:\n\n// Remember all caps identifiers are traditionally reserved for macros.\n// Best not to use them just in-case there is a clash.\nstruct AdjListNode \n{\n ulong nbr;\n ulong cost;\n};\n</code></pre>\n\n<h3>Comments about class names.</h3>\n\n<p>You class names are really horrible. It is really hard to understand what they are going to be used for: <code>ADJ_LIST_NODE, SP_FOUND_NODE, SP_ESTIMATE_NODE, ROAD</code>. About the only one I can guess at is <code>ROAD</code>. I assume the <code>v1, v2</code> are the city IDs.</p>\n\n<p>Also you in your code and comments you switch between two different naming schemes. You can refer to the data as a graph sometimes (vertices) and sometimes geographically (city/roads). If you stick to one metaphor while coding it makes it easy to visualize what you are trying to achieve.</p>\n\n<h3>C++ things you should stop doing</h3>\n\n<p>Stop doing <code>using namespace std;</code> its a bad habbit. It's not as if typing std:: infront of everything is going to cost you a lot of time.</p>\n\n<p>Stop using C-Casts <code>(ulong)-1</code>. C-casts are hard to see (by reading)/ find(with the editor) and basically you are telling the compiler to shut up and accept your word that you are correct (thus you can easily miss mistakes). The C++ casts are a little more explicit in what they do and thus will catch many mistakes. Also they are easy to see and simple to search for using the editor. </p>\n\n<h3>C++ things I would change</h3>\n\n<pre><code>class SPEstimateNodeCompare {\npublic:\n bool operator()(const SP_ESTIMATE_NODE& a, const SP_ESTIMATE_NODE& b) {\n return a.dist > b.dist;\n }\n};\n</code></pre>\n\n<p>Here I would change the opeator() to be const</p>\n\n<pre><code> bool operator()(SP_ESTIMATE_NODE const& a, SP_ESTIMATE_NODE const& b) const {\n // ^^^^^^^\n</code></pre>\n\n<p>The other thing I would change is to put it into the SP_ESTIMATE_NODE class. The only time you use this is for sorting in a priority queue. So it is easier to define the priority queue if the class already intrinsicly knows how to sort itself.</p>\n\n<pre><code>struct SP_ESTIMATE_NODE\n{\n ulong vertex;\n ulong dist;\n ulong predecessor;\n bool operator<(SP_ESTIMATE_NODE const& rhs) const { return dist > rhs.dist;}\n};\n</code></pre>\n\n<p>Now your priority queue declaration becomes:</p>\n\n<pre><code>priority_queue<SP_ESTIMATE_NODE> sp_estimate_q;\n</code></pre>\n\n<p>Also I would add constructors to your classes so that you can jsut create the elements in one go:</p>\n\n<p>So if we add the constructor here:</p>\n\n<pre><code>struct SP_ESTIMATE_NODE\n{\n SP_ESTIMATE_NODE(ulong v, ulong d, ulong p) : vertex(v), dist(d), predecessor(p) {}\n ulong vertex;\n ulong dist;\n ulong predecessor;\n};\n</code></pre>\n\n<p>Then the following code:</p>\n\n<pre><code>est_node.vertex = next_road->first;\nest_node.dist = next_road->second;\nest_node.predecessor = src;\nsp_estimate_q.push(est_node);\n\n// can be simplifies to:\n\nsp_estimate_q.push(SP_ESTIMATE_NODE(next_road->first, next_road->second, src));\n</code></pre>\n\n<h3>Global variables</h3>\n\n<pre><code>vector< map< ulong, ulong> > city_adj_list;\nulong n_cities, m_roads;\nulong src, dest;\nulong q_broken_roads;\nvector<ROAD> broken_road_list;\n\nmap< ulong, SP_FOUND_NODE > sp_found;\npriority_queue< SP_ESTIMATE_NODE, vector<SP_ESTIMATE_NODE>, SPEstimateNodeCompare > sp_estimate_q;\nmap< ulong, ulong> estimate_distances;\n</code></pre>\n\n<p>Get rid of them. The side affects make it harder to remember things when modifying the code and also probably prevent the compiler optimizing the code as much as it could if you passed around things by parameter.</p>\n\n<h3>Spurious code:</h3>\n\n<p>In <code>void read_input()</code></p>\n\n<pre><code>node.nbr = v2; // This and the next line seem like a complet waste.\nnode.cost = cost; // Just remove them\ncity_adj_list[v1][v2] = cost;\n\nnode.nbr = v1; // Same comment as above.\nnode.cost = cost;\ncity_adj_list[v2][v1] = cost;\n</code></pre>\n\n<h3>Broken road list?</h3>\n\n<p>Why keep a separate list of broken roads. It would seem easier if you could just mark the roads themselves as broken.</p>\n\n<h3>I am not convinced that is dyxtra's algorithm</h3>\n\n<p>It should look like this:</p>\n\n<pre><code> void find_shortest(int start, int end, std::vector<std::map<ulong,unlong>>& graph)\n {\n std::set<unlong> searchedList;\n std::priority_queue<std::pair<ulong, ulong>> frontierList;\n\n // frontier list contains pairs of (cost, city)\n // std::pair is sorted by first then second so the frontierList\n // is automatically sorted by the cost of getting to a city.\n // Add the start city as the only city in the frontier list.\n frontierList.push(std::make_pair(0, start));\n\n while(!frontierList.empty())\n {\n std::pair<ulong, ulong> next = frontierList.top();\n frontierList.pop();\n\n if (next.second == end)\n {\n std::cout << \"Min Cost: \" << next.first << \"\\n\";\n return;\n }\n if (searchedList.find(next.second) != searchedList.end())\n {\n continue; // We already found this node. move on.\n // Note: continue starts the next loop iteration.\n }\n // We have found the lowest cost to this city.\n // So mark that information by placing it in the searched list.\n searchedList.insert(next.second);\n\n // Add all city's that can be reached from here to the frontier list.\n for(std::map<ulong,unlong>::const_iterator loop = graph[next.second].begin(); loop != graph[next.second].end(); ++loop)\n {\n // Add item for each city (cost = cost to get here + cost of road)\n frontierList.push(std::make_pair(next.first + loop->second, loop->first));\n }\n }\n }\n</code></pre>\n\n<p>As you can see my implementation is a lot simpler than yours. I am not sure what you are trying to achieve with the relax method (it actually made my less relaxed trying to read it).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T12:42:01.330",
"Id": "17686",
"Score": "0",
"body": "thanks for the detailed review!. appreciate it.\nbroken road list is to calculate s. dist. repeatedly with each of the given broken roads one at a time. but yes, it can just be a member var in graph class with a method to recalculate for ith broken road.\nterm \"relax\" was from CLRS text :) it updates the cost in queue to a lesser value via newly resolved/searched vertex if possible thus avoiding multi entries in queue for same vertex. but i couldn't find a way to alter the queue elements and made duplicate entries anyway so i might as well use your approach which is much shorter (and relaxed :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T06:45:12.737",
"Id": "11102",
"ParentId": "11101",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "11102",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T05:34:18.400",
"Id": "11101",
"Score": "5",
"Tags": [
"c++",
"beginner",
"object-oriented",
"homework"
],
"Title": "Implementation of Dijkstra's shortest path algorithm"
}
|
11101
|
<p>I have been working on a personal CMS for a site I've been running, and right now I'm working on a page that lists all entries, or posts from a database. I have given the user, with checkboxes and a drop down menu, the option to either delete or edit a post.</p>
<pre><code> //query database
$query = mysql_query("SELECT * FROM userPosts");
//turn query results into an array
while($rows = mysql_fetch_array($query)) :
//List all posts in a table (other table markup not shown).
$posts = $rows['userTexts'];
$id = $rows['ID'];
echo "<tr>\n<td>" . $id . "</td>\n<td class='posts'>" . $posts . "</td>\n<td><input type='checkbox' name='chkBox' value='chk[". $id . "]'></td>\n</tr>\n";
endwhile
</code></pre>
<p>This part is not the problem, but I figure it is necessary for the question. Is there a way to make this code cleaner, without so many <code>if</code> statements?</p>
<pre><code>$chkWhat = $_REQUEST["chkBox"];
$options = $_REQUEST["options"];
if(isset($_REQUEST["submit"])) {
if($chkWhat != "chk[" .$id . "]") {
echo "<p>Please select a post.</p>";
} else {
if( //more than one check box is checked but I still have to figure this...) {
echo "<p>For now, please just select 1 post you would like to edit.</p>";
} else {
//edit your post
echo "You will edit your post";
}
if($options == "delete") {
//delete your post(s) here
echo "You will delete your post(s)";
}
}
}
</code></pre>
<p>Sorry about the second <code>if</code> statement there, but I am still researching that.</p>
|
[] |
[
{
"body": "<p>I suppose it could be condensed a little, but overall, it's solid code. Consider using a ternary operator for your conditional echos:</p>\n\n<pre><code>echo count($_REQUEST['chkBox']) > 1 ? \"<p>For now, please just select 1 post you would like to edit.</p>\" : \"You will edit your post\";\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T04:29:30.483",
"Id": "17678",
"Score": "0",
"body": "consider to move all your echoes to *template*"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T13:02:18.010",
"Id": "17740",
"Score": "1",
"body": "Ternary operations should be short a sweet. If you were to do this, you'd be almost REQUIRED to move those strings to variables before processing them. Better to just set a default output string then if a certain condition is met change that string to the new output."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T02:24:23.917",
"Id": "11104",
"ParentId": "11103",
"Score": "0"
}
},
{
"body": "<p>I think you should look into OOP for your PHP and (optionally) ORM instead of your standard DB queries.</p>\n\n<p>It's much cleaner and easier to work with then procedures. What you have now - a huge long file (ok, bunch of files) with the wall of PHP code.</p>\n\n<p>What you will achieve using OOP: Separated <strong>blocks</strong> of code. It's much easier to get back to this. More - instead of mess in your huge file you will have neat method calls like: <code>$user->login($username, $password)</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T02:35:49.840",
"Id": "17679",
"Score": "0",
"body": "Interesting... any ideas where to start learning about \"OOP for my PHP\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T02:41:10.347",
"Id": "17680",
"Score": "0",
"body": "@St8upNewb Just google 'object oriented php tutroial' - you'll find something that will suit you. One more thing - when you'll start feeling pretty comfortable with OOP - try reading about MVC and designing your next application keeping MVC structure in mind."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T12:58:39.873",
"Id": "17739",
"Score": "0",
"body": "OOP is a good suggestion, but MVC, while popular, is still a preference. Still both good suggestions for a larger program. If there isn't much more to this code though, it will be rather redundant."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T02:27:57.140",
"Id": "11105",
"ParentId": "11103",
"Score": "1"
}
},
{
"body": "<p>Both question and answer lacks common sense.<br>\nSo here I am! :)</p>\n\n<ol>\n<li>You cannot reduce number of conditions, <em>as long as these conditions make sense.</em> </li>\n<li>Of course OOP won't reduce it either. It will just move them much deeper in the code (and dramatically increase the code amount [you will have to debug if something goes wrong]). </li>\n<li>There is no reason to make some of the conditions nested. </li>\n<li>Most wondering part. <strong>Why do you use checkboxes if only one post can be edited at once?</strong> Just for sake of using it with delete button? I am wondering if you ever been using some web interfaces. The controls to operate some posts are commonplace, there are some general ways - why not to follow them?</li>\n</ol>\n\n<p>To edit posts it is common to make <em>a hyperlink</em> on the post name. A hyperlink will lead to the edit script, not to the POST processing script. But only after hitting \"save\" button the edit process will proceed to POST processing code.</p>\n\n<p>While mass delete will go directly to the POST processing, but you will need as small code as</p>\n\n<pre><code>$err = '';\nif(!$_POST[\"chkBox\"]) {\n $err .= \"No posts selected\";\n}\nif (!$err) {\n //delete\n // Location header with redirect\n //exit\n} else {\n // fill dorm data variables\n}\n// show the form\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T16:28:22.553",
"Id": "17705",
"Score": "0",
"body": "@Your Common Sense. To link the post name to the edit script would make sense...!\n\nBut um _\"I am wondering if you ever been using some web interfaces\"_...? Explain, please?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T04:22:56.913",
"Id": "11106",
"ParentId": "11103",
"Score": "-1"
}
},
{
"body": "<p>Usually you can use switch statements to clean up abundant if statements, but only if those if statements are similar; Such as checking for different values of the same variable. Since that is not the case here, there isn't much you can change in this area. Sometimes you just need a few if statements. I would, however, suggest that you not use the global <code>$_REQUEST</code> as it is rather insecure. Even if you think you are the only one who is ever going to use it, what if someone got in, you just removed one more step of security from your site making it that much more easier for someone to destroy your hard work. Even you could make a mistake later by accidentally duplicating a POST variable as a GET variable, or vice-versa. Or someone with malicious intent does it on purpose, you could run into a lot of problems there. You should also sanitize those. Check out <a href=\"http://php.net/manual/en/function.filter-input.php\" rel=\"nofollow\"><code>filter_input</code></a> (>=PHP 5.2) to get started, or check other forums on the best way to sanitize your form variables.</p>\n\n<p>Your delima with checking for multiple checkboxes should be rather easy. You've already got your form set up to make them into an array after post. Or almost right. You need to change name to what you have for your value. That should work, but if it doesn't try making the value the <code>$id</code> and just leaving the name <code>chk[]</code>, should probably do that anyways as it won't leave empty or useless values. After that just check the count.</p>\n\n<pre><code>$checkboxes = $_POST['chk[]'];\nif(count($checkboxes) > 1) { etc... }\n</code></pre>\n\n<p>There is a minor change you should make to your if statements. Since you are checking <code>$options</code> for a \"delete\" value, you should also check it for an \"edit\" value, or move that if statement into the else block and give it an else for the edit block. Otherwise, as you can imagine, you'll end up editing and then deleting your posts and that would take up unneeded resources.</p>\n\n<pre><code>if( //more than one check box is checked but I still have to figure this...) {\n echo \"<p>For now, please just select 1 post you would like to edit.</p>\";\n} else {\n if($options == \"delete\") { /*delete your post*/ }\n else { /*edit your post*/ }\n}\n</code></pre>\n\n<p>I don't see anything else really. So good luck!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T13:30:00.490",
"Id": "11112",
"ParentId": "11103",
"Score": "4"
}
},
{
"body": "<p>Just a few comments that I can't find in the other answers.</p>\n\n<ul>\n<li>mysql_* is softly deprecated (use PDO or mysqli)</li>\n<li>while : endwhile is an uncommon choice compared to using braces { }. Consider using braces as they look nicer mixed in with if statements and other block elements that share braces IMO.</li>\n<li>Indent the contents of your while loop as you do with your if statements.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T12:55:30.267",
"Id": "17738",
"Score": "0",
"body": "yes, I actually meant to mention those first two, but the second is common enough if being used in a view file. Although the rest of the code does tend to lean more away from that. I completely missed the third +1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T02:19:45.080",
"Id": "11130",
"ParentId": "11103",
"Score": "1"
}
},
{
"body": "<p><strong>Reducing indentation.</strong> If, in a function, there are multiple levels of indentation, these can be reduced with 'guard clauses' - <a href=\"http://sourcemaking.com/refactoring/replace-nested-conditional-with-guard-clauses\" rel=\"nofollow\">http://sourcemaking.com/refactoring/replace-nested-conditional-with-guard-clauses</a></p>\n\n<p>For the top-level it could be removed by converting the first <code>if()</code> to:</p>\n\n<pre><code> if (! isset($_REQUEST[\"submit\"])) {\n return;\n }\n // rest of code here, at the same indentation level.\n</code></pre>\n\n<p>Putting that block (the outside <code>if()</code>) into a function, allows a simple exit of the block with a return out of the function.</p>\n\n<p>Equally, with a function, you could pass in the <code>$_REQUEST[\"submit\"]</code>, <code>$chkWhat</code>, and <code>$id</code> variables, to give just a small measure of potential clarification as to what they are, without using the super-global too widely.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-08T18:23:05.513",
"Id": "11602",
"ParentId": "11103",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "11112",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T01:56:54.227",
"Id": "11103",
"Score": "2",
"Tags": [
"php"
],
"Title": "CMS for allowing users to delete or edit a post"
}
|
11103
|
<p>I need to remove last text after <code>:</code> in my String and <code>:</code> too. I have tried this. Please review. If there is a better way to do, please tell me.</p>
<pre><code>String test = "temp:content:region:deposit:up";
System.out.println(test.replace(test.substring(test.lastIndexOf(":"), test.length()), ""));
</code></pre>
|
[] |
[
{
"body": "<p>Using regexp (replace) isn't the best solution. I think you should use only substring:</p>\n\n<pre><code>System.out.println(test.substring(0, test.lastIndexOf(\":\")))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T11:15:40.390",
"Id": "11111",
"ParentId": "11107",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "11111",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T09:19:44.913",
"Id": "11107",
"Score": "2",
"Tags": [
"java",
"strings"
],
"Title": "Removing text after `:`, `:` included"
}
|
11107
|
<p>I try to learn amd64 assembler. This is the first thing I tried. This piece of assembly should replicate the functionality of the following piece of C code, which turns a binary sha-256 hash into a human readable form.</p>
<h3>assembly code</h3>
<pre><code>1: .ascii "0123456789abcdef"
.global show_hash
show_hash:
.type show_hash @function
.func show_hash
mov $32,%ecx
.p2align 2
0: xor %eax,%eax
lodsb
mov %eax,%edx
shr $4,%al
and $15,%dl
mov 1b(%rax),%al
mov 1b(%rdx),%dl
mov %bl,%ah
stosw
dec %ecx
jnz 0b
mov %cl,(%rdi)
ret
.endfunc
</code></pre>
<h3>C code</h3>
<pre><code>void show_hash(char *dst, unsigned char *src) {
static const char *lookup = "0123456789abcdef";
char lo, hi, byte;
int i = 32;
do {
byte = *src++;
hi = lookup[byte >> 4];
lo = lookup[byte & 0xf];
*dst++ = hi;
*dst++ = lo;
} while (i--);
}
</code></pre>
<p>Am I doing it right? I tried to move the lookup table (label <code>1</code>) into <code>.section rodata</code>, but all references to it were changed to <code>0</code> in the linked program, so I put it into the text section for now.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-22T23:42:16.977",
"Id": "28370",
"Score": "0",
"body": "I don't think you can access data unless it's in the data segment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-23T05:02:39.727",
"Id": "28381",
"Score": "0",
"body": "@Hawken How do you come to this conclusion?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T20:43:50.693",
"Id": "28648",
"Score": "0",
"body": "all memory is referenced using the segment specified by `%ds` or if it's on the stack, `%ss`. Unless you have personally set the segment register, `mov %cs,%ds`, or your assembler is adding a custom segment offset, you can't read from outside `.data`. I don't know if modern OSs allow you to read from `.text` at all even if you did."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T20:48:00.690",
"Id": "28650",
"Score": "0",
"body": "@Hawken You see that this code is written for x86-64 linux which uses a flat memory modell? All segment registers except %fs and %gs which serve a special purpose are set to zero."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T21:43:29.640",
"Id": "28665",
"Score": "0",
"body": "Hmm, I did not know that. http://wiki.osdev.org/X86-64 contains information on this for anyone else who did not know."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T10:12:14.523",
"Id": "28676",
"Score": "0",
"body": "Okay. My bad. This code really is x86 code, but nevertless it is written for linux. Linux, in a similar way as most x86 operating systems today, does not use segmentation (except for some special threading related concepts). All segment registers are set to zero; all accesses to memory are done in the same address space."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-27T19:13:06.743",
"Id": "28691",
"Score": "0",
"body": "In 64bit it would seem that it's required, so you were right, I should have known. I'm currently writing 16bit x86 assembly without an OS where segmentation is *needed* to address your full 20bit address space. Thanks for correcting me."
}
] |
[
{
"body": "<p>I'm not sure whether it's correct:</p>\n\n<ul>\n<li><strike>If <code>show_hash</code> uses <a href=\"http://en.wikipedia.org/wiki/X86_calling_conventions#cdecl\" rel=\"nofollow\">cdecl calling conventions</a> you should preserve registers like <code>%bl</code>, and read the input parameter values from the stack into esi and edi.</strike><br>\n(see section \"3.2.3 Parameter Passing\" of <a href=\"http://www.x86-64.org/documentation/abi.pdf\" rel=\"nofollow\">the Application Binary Interface</a>: parameters are conveniently passed in the rdi and rsi registers)</li>\n<li><strike>I don't understand the syntax of <code>mov 1b(%rax),%al</code>: is it reading from the <code>lookup</code> array defined at label <code>1:</code>? On re-reading, I think it is; however that will only work if the most-significant bytes of rax and rdx are all zero; perhaps you should initialize them as you did using <code>xor %eax,%eax</code></strike><br>\n(apparently <code>xor %eax,%eax</code> will clear the whole of <code>%rax</code>)</li>\n<li>You're using <code>stosw</code> which writes two bytes (two ASCII characters) a time; but <code>%ah</code> contains a value from <code>%bl</code>, and <code>%bl</code> wasn't previously initialized? I think that statement should have been <code>mov %dl,%ah</code> not <code>mov %bl,%ah</code>; or perhaps you could have done <code>mov 1b(%rdx),%ah</code> directly.</li>\n<li>The function ends with <code>mov %cl,(%rdi)</code> to null-terminate the string; that is clever but could use a comment (it took me a bit to figure out). Most of the <a href=\"/questions/tagged/assembly\" class=\"post-tag\" title=\"show questions tagged 'assembly'\" rel=\"tag\">assembly</a> questions either have good comments, or answer which say that they should have good comments.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T20:12:31.507",
"Id": "75491",
"Score": "0",
"body": "xor %eax,%eax implicitly zeroes out the upper 32 bits of %rax as well. Second, this is x86_64 assembly on Linux. The calling convention is different; the first couple of arguments are actually passed in registers. I think I accidentially switched %dl with %bl, but I'm not very sury."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T20:15:14.283",
"Id": "75493",
"Score": "0",
"body": "I asked this question almost a year ago; I'm not really sure about most parts anymore."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T20:40:15.277",
"Id": "75497",
"Score": "0",
"body": "In that case the only error I see is the typo involving `%bl` instead of `%dl`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T16:25:59.047",
"Id": "43622",
"ParentId": "11110",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "43622",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T10:46:55.513",
"Id": "11110",
"Score": "5",
"Tags": [
"linux",
"assembly",
"lookup"
],
"Title": "First steps with amd64 assembly"
}
|
11110
|
<p>Is there a way to reduce this lengthy <code>if</code> condition:</p>
<pre><code>if(
statusCode.equals( NO_ERRORS_NO_WARNINGS ) ||
statusCode.equals( HAS_ERRORS_NO_WARNINGS ) ||
statusCode.equals( HAS_ERRORS_HAS_WARNINGS ) ||
statusCode.equals( NO_ERRORS_HAS_WARNINGS )
){
//do something
}
</code></pre>
<p>The purpose of it is to see if there is a status code set within a log file. So the <code>String statusCode</code> could be a null value, one of the 4 status codes above or an unpredicatable <code>String</code>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T13:53:46.247",
"Id": "17690",
"Score": "0",
"body": "I'm not sure you could. You might convert to an enum to use a switch statement, but that doesn't buy you much."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T13:54:24.637",
"Id": "17691",
"Score": "0",
"body": "You mention that `statusCode` may be null...have you null checked before this statement?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T14:11:18.347",
"Id": "17695",
"Score": "0",
"body": "@MichaelK, yes the null is checked. I should have said empty really."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T15:49:53.600",
"Id": "17806",
"Score": "0",
"body": "Why do you have `HAS_ERRORS_HAS_WARNINGS` in there twice?\n\nIt looks like that `statusCode` holds teh state of two boolean flag (\"errors\" and \"warning\"). It may make sense to create to boolean fields (or atleast temporary variables) to hold the two boolean flags."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T17:53:23.803",
"Id": "17815",
"Score": "0",
"body": "@RoToRa I would normally agree but the error code is a String taken from an external source. There is the potential for the String to be any array of characters - so the condition is to check whether the string we have matches any of the status codes we have. I am open to better ways of doing this if you have ideas?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T10:59:25.970",
"Id": "17873",
"Score": "0",
"body": "This is actually the neatest and quickest way to do the job. String comparison is a fast operation. And it reads pretty nicely."
}
] |
[
{
"body": "<p>First of all, if <code>statusCode</code> can be null, the code above could possibly throw a null pointer exception.</p>\n\n<p>To directly answer your question though, you could use a Set, such as a HashSet.</p>\n\n<pre><code>HashSet<String> errorOrWarning = new HashSet<String>();\nerrorOrWarning.add(HAS_ERRORS_HAS_WARNINGS);\nerrorOrWarning.add(HAS_ERRORS_NO_WARNINGS);\nerrorOrWarning.add(HAS_ERRORS_HAS_WARNINGS);\nerrorOrWarning.add(NO_ERRORS_HAS_WARNINGS);\n</code></pre>\n\n<p>Which you can then use in a single call.</p>\n\n<pre><code>if (errorOrWarning.contains(statusCode) {\n // do something\n}\n</code></pre>\n\n<p>This has the advantage that <code>statusCode</code> can be null and it would produce no exception.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T14:13:15.427",
"Id": "17696",
"Score": "0",
"body": "+1 thanks. It was a mistake to say that the status code could be null, I should have said empty. However I really like this answer as it does handle the `NULL` value nicely should it be there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T18:36:15.393",
"Id": "17719",
"Score": "0",
"body": "Very interesting solution! I'll have to add this to my bag o' tricks - I'm sure it will come in handy sometime."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:01:58.037",
"Id": "17874",
"Score": "0",
"body": "Yup, that will work. It's less readable, though, because now you've got a (probably static and probably distant in the code file) HashSet that you need to find all references to and analyze before you can know what the outcome of `if` will be. Of course, you could build the HashSet inside the method that needs it, but someone's gonna refactor it out as an invariant sooner or later."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:52:28.797",
"Id": "17977",
"Score": "0",
"body": "@RossPatterson: You shouldn't need to see the contents of the HashSet if the name describes it properly. That's the whole point of the agile naming philosophy and the corresponding rename refactoring."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T13:58:13.910",
"Id": "11114",
"ParentId": "11113",
"Score": "17"
}
},
{
"body": "<p>If you have a large number of such conditions, it may be just easier to use arrays for the same, (as in the above comment)</p>\n\n<pre><code>for(T i : new T[]{HAS_ERRORS_HAS_WARNINGS, HAS_ERRORS_NO_WARNINGS, HAS_ERRORS_HAS_WARNINGS, NO_ERRORS_HAS_WARNINGS}) \n if statusCode.equals(i) {\n // do\n break;\n }\n</code></pre>\n\n<p>Note - not as efficient as above, - O(n) </p>\n\n<p>(you could also assign that to a variable and reuse the array if the same pattern is expected elsewhere.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T18:05:38.247",
"Id": "17760",
"Score": "0",
"body": "Note that it doesn't have to be an array. Any structure that can be iterated over in a for loop will work. Not at all a bad solution though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T18:07:12.333",
"Id": "17762",
"Score": "0",
"body": "I made it an array so that it can be initialized on the fly :) (Your solution is better in terms of perf. - O(1) vs O(n))"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T20:44:42.110",
"Id": "11124",
"ParentId": "11113",
"Score": "2"
}
},
{
"body": "<p>I'm not sure about your class design, but I recommend refactoring this into some easier to use properties. I'm assuming we're within a class:</p>\n\n<pre><code>public boolean hasErrors() {\n return statusCode != null && (statusCode.equals(HAS_ERRORS_HAS_WARNINGS)\n || statusCode.equals(HAS_ERRORS_NO_WARNINGS));\n}\n\npublic boolean hasWarnings() {\n return statusCode != null && (statusCode.equals(HAS_ERRORS_HAS_WARNINGS)\n || statusCode.equals(NO_ERRORS_HAS_WARNINGS));\n}\n</code></pre>\n\n<p>That does not buy you much in withing those functions, but later on comes in handy:</p>\n\n<pre><code>if(hasErrors() || hasWarnings()) {\n // Do something\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T10:12:56.143",
"Id": "11197",
"ParentId": "11113",
"Score": "4"
}
},
{
"body": "<p>Use <a href=\"https://issues.apache.org/jira/browse/LANG-704\" rel=\"nofollow\"><code>StringUtils.equalsAny</code></a>:</p>\n\n<pre><code>if (StringUtils.equalsAny(statusCode, NO_ERRORS_NO_WARNINGS, \n HAS_ERRORS_NO_WARNINGS, HAS_ERRORS_HAS_WARNINGS, \n NO_ERRORS_HAS_WARNINGS)) {\n //do something\n}\n</code></pre>\n\n<p>Unfortunately this method is not part any official release but the code is in the JIRA, you can copy it.</p>\n\n<pre><code>/**\n * Verifies if the tested string is equal with any of the provided strings.\n * This method is null safe and case sensitive.\n * \n * @param str Tested string\n * @param any Strings to be tested against.\n * @return true if tested string is equal to any of the provided strings. false otherwise.\n */\npublic static boolean equalsWithAny(final String str, final String... any) {\n if (str == null) {\n return false;\n }\n\n if (any == null) {\n return false;\n }\n\n for (final String s: any) {\n if (str.equals(s)) {\n return true;\n }\n }\n\n return false;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-07T06:40:23.573",
"Id": "18508",
"Score": "0",
"body": "+1 nice find - thanks. I wonder if this will ever be implemented or whether it has been put on the back burner for some reason."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-06T23:07:31.560",
"Id": "11541",
"ParentId": "11113",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "11114",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T13:48:22.553",
"Id": "11113",
"Score": "9",
"Tags": [
"java"
],
"Title": "Reduce length of condition"
}
|
11113
|
<p>I'm facing an interesting issue at the moment: </p>
<p><strong>My Situation:</strong> </p>
<p>I'm having (in Java) String-Arrays like the following (more complicated, of course). Each String-Array represents one sentence (I cant change the representation): </p>
<pre><code>String[] tokens = {"This", "is", "just", "an", "example", "."};
</code></pre>
<p><strong>My Problem:</strong> </p>
<p>I want to rebuild the original sentences from this String-Arrays. This doesn't sound that hard at first, but becomes really complex since sentence structure can have many cases. Sometimes you need whitespaces and sometimes you don't. </p>
<p><strong>My Approach:</strong></p>
<p>I've implemented a method that should do most of the tasks, which means rebuilding a sentence from the original String-Array. As you can see, it's very complex and complicated already, but works "okay" for the moment - I don't know how to improve it at the moment. </p>
<pre><code>public static String detokenize(String[] tokens) {
StringBuilder sentence = new StringBuilder();
boolean sentenceInQuotation = false;
boolean firstWordInQuotationSentence = false;
boolean firstWordInParenthisis = false;
boolean date = false;
for (int i = 0; i < tokens.length; i++) {
if (tokens[i].equals(".") || tokens[i].equals(";") || tokens[i].equals(",") || tokens[i].equals("?") || tokens[i].equals("!")) {
sentence.append(tokens[i]);
}
else if(tokens[i].equals(":")){
Pattern p = Pattern.compile("\\d");
Matcher m = p.matcher(tokens[i-1]);
if(m.find() == true){
date = true;
}
sentence.append(tokens[i]);
}
else if(tokens[i].equals("(")){
sentence.append(" ");
sentence.append(tokens[i]);
firstWordInParenthisis = true;
}
else if (tokens[i].equals(")")) {
sentence.append(tokens[i]);
firstWordInParenthisis = false;
}
else if(tokens[i].equals("\"")){
if(sentenceInQuotation == false){
sentence.append(" ");
sentence.append(tokens[i]);
sentenceInQuotation = true;
firstWordInQuotationSentence = true;
}
else if(sentenceInQuotation == true){
sentence.append(tokens[i]);
sentenceInQuotation = false;
}
}
else if (tokens[i].equals("&") || tokens[i].equals("+") || tokens[i].equals("=")) {
sentence.append(" ");
sentence.append(tokens[i]);
}
//words
else {
if(sentenceInQuotation == true){
if(firstWordInQuotationSentence == true){
sentence.append(tokens[i]);
firstWordInQuotationSentence = false;
}
else if(firstWordInQuotationSentence == false){
if(firstWordInParenthisis == true){
sentence.append(tokens[i]);
firstWordInParenthisis = false;
}
else if(firstWordInParenthisis == false){
sentence.append(" ");
sentence.append(tokens[i]);
}
}
}
else if(firstWordInParenthisis == true){
sentence.append(tokens[i]);
firstWordInParenthisis = false;
}
else if(date == true){
sentence.append(tokens[i]);
date = false;
}
else if(sentenceInQuotation == false){
sentence.append(" ");
sentence.append(tokens[i]);
}
}
}
return sentence.toString().replaceFirst(" ", "");
}
</code></pre>
<p>As I said, this works quite good, but not perfect. I suggest you try my method with copy/paste and see it on your own. </p>
<p>Do you have ANY ideas or a better solution for my problem?</p>
<p><strong>Examples:</strong> </p>
<p>For example, as I just tried some texts out I noticed that I don't yet check about tokens like "[", "]", or e.g. the different types of quotations, " or “. I also heard that it can make a different if if use ... (three points) or one … unicode sign (mark it and you'll see it). So it becomes more and more complex.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T13:43:00.607",
"Id": "17694",
"Score": "0",
"body": "You could do it more declaratively, that would make it less complex. Create a Set of tokens that have no WS in front and another Set of those with no WS after. Then you just check those sets for each token."
}
] |
[
{
"body": "<p>I'm not sure if you are allowed to leverage open source projects, but perhaps you could use something like <a href=\"http://java2s.com/Open-Source/Java/Natural-Language-Processing/OpenNLP/CatalogOpenNLP.htm\" rel=\"nofollow\" title=\"OpenNLP\">OpenNLP</a>. They have an interface <code>opennlp.tools.tokenize.Detokenizer</code>. An implementation of this looks like it would do what you need (see <a href=\"http://sourceforge.net/projects/opennlp/forums/forum/9944/topic/3806859\" rel=\"nofollow\">this forum post</a>). It looks like there is at least one implementation: <code>opennlp.tools.tokenize.DictionaryDetokenizer</code>.</p>\n\n<p>You could simply create a sentence by adding a space in-between each token, and then pass this to the detokenizer. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T14:23:08.613",
"Id": "17697",
"Score": "0",
"body": "Looks great! Have a look at the `testDetokenizeToString()` method from [this test class](http://java2s.com/Open-Source/Java/Natural-Language-Processing/OpenNLP/opennlp/tools/tokenize/DictionaryDetokenizerTest.java.htm), it seems to me that it does exactly what you need."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T12:42:38.127",
"Id": "17736",
"Score": "0",
"body": "That method would also be possible, but as far as I understand it so far, you only get commands like \"MERGE_TO_LEFT\" or \"NO_OPERATION\" to your tokens. So you would need to check every token for its position-command and from this decide if you need a whitespace or not. Maybe I'll try this later as well. Thanks"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T14:15:42.733",
"Id": "11117",
"ParentId": "11116",
"Score": "3"
}
},
{
"body": "<p>I would suggest using the strategy pattern rather than code for specific tokens. Because some of the operations are state dependent, you would probably create some kind of <code>DetokenizerResult</code> object.</p>\n\n<p>For example, you default strategy would append a space, then the token, except at the beginning.</p>\n\n<pre><code>interface Detokenizer {\n void apply(String token, DetokenizerResult result);\n}\n\nclass DefaultDetokenizer implements Detokenizer {\n void String apply(String token, DetokenizerResult result) {\n if (result.atBeginning()) result.append(token);\n else result.append(\" \").append(token);\n }\n}\n</code></pre>\n\n<p>Put all of the tokens that have special strategies into a <code>HashMap<String, Detokenizer></code> and then you can reduce the loop to something like this:</p>\n\n<pre><code>DetokenizerResult result = new DetokenizerResult()\nfor (token : tokens) {\n if (map.contains(token) map.get(token).apply(token, result);\n else defaultStrategy.apply(token, result);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T14:33:15.707",
"Id": "11118",
"ParentId": "11116",
"Score": "1"
}
},
{
"body": "<p>I suspect a simpler approach would be to just join the tokens together to form a sentence as string, and then use list of regular expression patterns to substitute each case. This will reduce the complexity, and will be much more readable than your example. (I will flush it out later.)\npseudocode:</p>\n\n<pre><code>mystring = join(words,\" \")\nfor ((e,s) : regexps_andreplacements)\n mystring = mystring.replaceAll(e,s)\nreturn mystring\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T08:24:33.660",
"Id": "11136",
"ParentId": "11116",
"Score": "2"
}
},
{
"body": "<p>The <a href=\"http://opennlp.apache.org/index.html\" rel=\"nofollow\">OpenNLP</a> will provide a more robust solution, but the following approximation may be good enough.</p>\n\n<p>The general rule is to join the 'words' with a space between, there are three excpetions</p>\n\n<ol>\n<li>Special punctuation characters that should not have a space before, eg . ; :</li>\n<li>Special punctuation characters that should not have a space after, eg ( [</li>\n<li>Quoted sentences in which case the \" will start in case 2 and then switch after each occurrence</li>\n</ol>\n\n<p>The code underneath has been tested with this sentence:</p>\n\n<blockquote>\n <p>A test, (string). Hello this is a 2nd sentence. Here is a quote: \"This is the quote.\" Sentence 4.</p>\n</blockquote>\n\n<pre><code>import java.util.Arrays;\nimport java.util.List;\nimport java.util.LinkedList;\n\npublic class Detokenizer {\n public String detokenize(List<String> tokens) {\n //Define list of punctuation characters that should NOT have spaces before or after \n List<String> noSpaceBefore = new LinkedList<String>(Arrays.asList(\",\", \".\",\";\", \":\", \")\", \"}\", \"]\"));\n List<String> noSpaceAfter = new LinkedList<String>(Arrays.asList(\"(\", \"[\",\"{\", \"\\\"\",\"\"));\n\n StringBuilder sentence = new StringBuilder();\n\n tokens.add(0, \"\"); //Add an empty token at the beginning because loop checks as position-1 and \"\" is in noSpaceAfter\n for (int i = 1; i < tokens.size(); i++) {\n if (noSpaceBefore.contains(tokens.get(i))\n || noSpaceAfter.contains(tokens.get(i - 1))) {\n sentence.append(tokens.get(i));\n } else {\n sentence.append(\" \" + tokens.get(i));\n }\n\n // Assumption that opening double quotes are always followed by matching closing double quotes\n // This block switches the \" to the other set after each occurrence\n // ie The first double quotes should have no space after, then the 2nd double quotes should have no space before\n if (\"\\\"\".equals(tokens.get(i - 1))) {\n if (noSpaceAfter.contains(\"\\\"\")) {\n noSpaceAfter.remove(\"\\\"\");\n noSpaceBefore.add(\"\\\"\");\n } else {\n noSpaceAfter.add(\"\\\"\");\n noSpaceBefore.remove(\"\\\"\");\n }\n }\n }\n return sentence.toString();\n }\n}\n</code></pre>\n\n<p>And the test case...</p>\n\n<pre><code>import static org.junit.Assert.*;\nimport java.util.Arrays;\nimport java.util.List;\nimport org.junit.Test;\nimport java.util.LinkedList;\n\npublic class DetokenizerTest {\n @Test\n public void test() {\n List<String> tokens = new LinkedList<String>(Arrays.asList(\"A\", \"test\", \",\", \"(\", \"string\", \")\", \".\", \"Hello\",\"this\",\"is\",\"a\",\"2nd\",\"sentence\",\".\",\"Here\",\"is\",\"a\",\"quote\",\":\",\"\\\"\",\"This\",\"is\",\"the\",\"quote\",\".\",\"\\\"\",\"Sentence\",\"4\",\".\"));\n String expected = \"A test, (string). Hello this is a 2nd sentence. Here is a quote: \\\"This is the quote.\\\" Sentence 4.\";\n String actual = new Detokenizer().detokenize(tokens);\n assertEquals(expected, actual);\n System.out.println(actual);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T12:45:24.737",
"Id": "17737",
"Score": "1",
"body": "Thanks for this method! I've extended it by a few punctuations and it works perfect so far. A plus is that extending it is really easy, which will make the later live-maintenance of my tool hopefully much easier."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T09:21:18.257",
"Id": "11137",
"ParentId": "11116",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "11137",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T13:11:44.210",
"Id": "11116",
"Score": "5",
"Tags": [
"java",
"strings"
],
"Title": "Build a sentence from tokens / words in a String-Array"
}
|
11116
|
<p>I am implementing RSA algorithm in C++ and here's my design(code structure).</p>
<p><code>keygen.h</code></p>
<pre><code>namespace rsa{
class keygen{
public:
//Constructor
keygen(size);
//Generate keys
void generate();
//Getters
char* gete(){ return xyz; }
..
..
..
private:
//initializes bignums
void initall();
//Private Member variables goes here
}
}
</code></pre>
<p><code>prime.h</code></p>
<pre><code>namespace rsa{
//First 100 primes
unsigned int primes[]={2,3,5,7,11.....541};
//MillarRabin Primality
bool isPrime(mpz_t, unsigned short);
//Get Random Prime
void getPrime(mpz_t, mpz_t)
}
</code></pre>
<p><code>endec.h</code></p>
<pre><code>namespace rsa{
//Encryption
const char* encryption(const char* text, const char* n, const char* e);
//Decryption
const char* decryption(const char* cipher, const char* n, const char* d);
}
</code></pre>
<p><strong>Is this a good design? How can I make it better?</strong> I want to improve the structure or the overall design, that's why dint post any code. Things like naming standards, using classes wherever applicable, standard function signature and similar is what I'm looking for.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T16:31:54.333",
"Id": "17706",
"Score": "0",
"body": "I think you did not provide enough information - just a few lines of code. It's hard to say something interesting about this besides trivial things like \"it is better to use `Keygen` instead of `keygen` for a class name\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T17:10:29.277",
"Id": "17710",
"Score": "0",
"body": "I am pretty sure that is not how RSA public key encryption works. You need to do more research on it but I do not expect to see you passing a password to the `encrypt()` `decrypt()` functions. And what is with passing char* pointers around use std::string to represent a password or create a `Key` type to represent a key etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T17:32:48.073",
"Id": "17711",
"Score": "0",
"body": "@Michael- I want to improve the design, that's why dint post any code. Added more details in question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T17:39:51.167",
"Id": "17713",
"Score": "1",
"body": "@LokiAstari- Can you please tell me why you think so? Why passing passwords(keys here) as arguments is a bad idea? I can use strings, will change that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T18:29:11.720",
"Id": "17717",
"Score": "0",
"body": "Because public key encryption does not involve passwords. You have a public and private key. Encryption involves using your private key and the receivers public key. While decryption uses your public key and the recievers private key. If it is just you then you just use your key. But the key is not a password it is a cryptographically complex key object. See http://code.google.com/p/rsa/source/browse/rsa/trunk/#trunk%2Fsource"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T18:38:01.687",
"Id": "17720",
"Score": "1",
"body": "@LokiAstari- I know that and I never mentioned password anywhere. N and E are required for encryption, and N and D are required for decryption, that's what I'm passing as arguments."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T18:43:43.530",
"Id": "73059",
"Score": "0",
"body": "This question appears to be off-topic because it is primarily a design review and not a code review."
}
] |
[
{
"body": "<p>Just a couple of short comments as a starting point.</p>\n\n<p>First of all, you don't need separate encrypt and decrypt functions -- the algorithm is identical for both. You just pass different parameters for them.</p>\n\n<p>Second, I wouldn't use <code>char const *</code> for the input or output of the encrypt/decrypt function. It might be barely allowable for the plaintext (since you <em>could</em> restrict that to not contain zero bytes) but is definitely not acceptable as the encrypted data (since you can't stop it from containing zero bytes). Since, however, the same function can do either encryption or decryption, you don't want to use <code>char const *</code> for input <em>or</em> output. Personally, I'd probably have it take iterators for the input and output, so you can work with <code>string</code>, <code>vector<char></code>, <code>vector<wchar_t></code>, etc.</p>\n\n<p>Finally, I don't think I'd put implementation details like the first 100 primes directly in the <code>rsa</code> namespace -- I'd have <code>rsa</code> contain a <code>detail</code> namespace to contain details like that. I'm not sure I'd have <code>keygen</code> either -- I think I'd make <code>key</code> a class, probably with the default ctor deleted, and a static member function to create a key, and overloading <code>operator>></code> and <code>operator<<</code> to serialize keys in a standard format (e.g., X.509, PKCS #8). About all that would be visible to the outside world would be <code>key</code> and <code>crypt</code> (or whatever you decide to call the combined encrypt/decrypt funct(ion|or).</p>\n\n<p>Edit: the <code>key</code> class and signatures would be something like this:</p>\n\n<pre><code>class key { \n key() = delete; // `=delete;` is C++11 only; without that just declare private\npublic:\n static key create_key();\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T11:15:29.660",
"Id": "17734",
"Score": "0",
"body": "That was the type of answer I was looking for, thank you Sir. But why passing iterators is better than passing strings directly? and can you please give little more detail about using static member function(signature) and overloading operators?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T13:27:28.037",
"Id": "17741",
"Score": "0",
"body": "Iterators let you change outside data types more easily, and they're easier to string together with other algorithms, data structures, etc. See edited answer about function signatures."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T15:31:24.457",
"Id": "17743",
"Score": "0",
"body": "And how is the user supposed to get those keys(n,e and d)? Using operators `>>` and `<<`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T15:33:11.353",
"Id": "17744",
"Score": "0",
"body": "@vidit: Yes, you'd generate a new key with `key::generate_key()`, and use `operator<<` to write it to a stream and `operator>>` to read it from a stream. I haven't bothered to show those, but they follow pretty much the usual pattern: `std::ostream &operator<<(std::ostream &, key const &);` and `std::istream &operator>>(std::istream &, key &);`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T15:36:18.553",
"Id": "17745",
"Score": "0",
"body": "Thanks again Sir. One last question, is this the right question for CodeReview?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T15:42:23.107",
"Id": "17747",
"Score": "0",
"body": "@vidit: Yes, I'd say it's a reasonable question here. Perhaps others will weigh in with opinions on that, though any extended discussion of it should probably go to [meta](http://meta.codereview.stackexchange.com/)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T20:31:35.967",
"Id": "11123",
"ParentId": "11120",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "11123",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T15:50:08.530",
"Id": "11120",
"Score": "0",
"Tags": [
"c++"
],
"Title": "Implementing RSA in C++"
}
|
11120
|
<p>I have a method that exacts data from an XML and returns an <code>IEnumerable<Foo></code>. I am trying to create a method that will merge the results from 2 different XML's files into a single <code>IEnumerable</code> and remove any duplicate data that may be found </p>
<p>A duplicate in this case is defined as 2 <code>Foo</code> objects that have the same <code>Name</code> property even if the other data is different. If there is a duplicate, I always want to keep the <code>Foo</code> from the first <code>IEnumerable</code> and discard the 2nd.</p>
<p>Am I on the right track with this LINQ query, or is there a better way to accomplish what I am trying to do?</p>
<pre><code>public IEnumerable<Foo> MergeElements(XElement element1, XElement element2)
{
IEnumerable<Foo> firstFoos = GetXmlData(element1); // get and parse first set
IEnumerable<Foo> secondFoos = GetXmlData(element2); // get and parse second set
var result = firstFoos.Concat(secondFoos)
.GroupBy(foo => foo.Name)
.Select(grp => grp.First());
return result;
}
</code></pre>
<p>The biggest concern I have with this code is that I am not certain the duplicate filtering rules I want will be guaranteed. I know <code>Concat</code> will just append <code>secondFoos</code> to the end of <code>firstFoos</code>, but when calling <code>GroupBy()</code>, will the resulting <code>IGrouping</code> object always have elements in the same order as the source data?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T17:34:37.843",
"Id": "17712",
"Score": "0",
"body": "Can you implement `Equals()` (and preferably also `IEquatable<Foo>`) on `Foo`, to compare by `Name`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T17:40:38.130",
"Id": "17714",
"Score": "0",
"body": "@svick `Foo` already does that through overriding `Equals()` (although it does not implement `IEquatable`, but I can add it). I thought of using `Distinct()`, but I've read it is unordered, so I was concerned my filtering rules would not be guaranteed."
}
] |
[
{
"body": "<p>With things like this, it's usually best to look at the documentation.</p>\n\n<p>Is your approach with <code>GroupBy()</code> going to work? <a href=\"http://msdn.microsoft.com/en-us/library/bb534501.aspx\" rel=\"noreferrer\">Yes</a>:</p>\n\n<blockquote>\n <p>Elements in a grouping are yielded in the order they appear in source.</p>\n</blockquote>\n\n<p>Can you use <code>Distinct()</code> to do the same thing more concisely? <a href=\"http://msdn.microsoft.com/en-us/library/bb348436.aspx\" rel=\"noreferrer\">No</a> (at least you shouldn't depend on it):</p>\n\n<blockquote>\n <p>The <code>Distinct</code> method returns an <strong>unordered</strong> sequence that contains no duplicate values.</p>\n</blockquote>\n\n<p>Is there some other way? Yes, you can use <a href=\"http://msdn.microsoft.com/en-us/library/bb341731.aspx\" rel=\"noreferrer\"><code>Union()</code></a>:</p>\n\n<blockquote>\n <p>When the object returned by this method is enumerated, Union enumerates <em>first</em> and <em>second</em> in that order and yields each element that has not already been yielded.</p>\n</blockquote>\n\n<p>So, I think the best way to do it is:</p>\n\n<pre><code>var result = firstFoos.Union(secondFoos);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T18:34:50.403",
"Id": "17718",
"Score": "0",
"body": "Great answer. I was pretty sure `Distinct()` was not my solution, but somehow missed `Union()` in the documentation."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T17:56:16.570",
"Id": "11122",
"ParentId": "11121",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "11122",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T17:15:43.093",
"Id": "11121",
"Score": "7",
"Tags": [
"c#",
"linq"
],
"Title": "Merging IEnumerable and removing duplicates"
}
|
11121
|
<p>Ive written a script to loop through a couple of unparalleled arrays a loop within a loop, Now im trying to find out if using <code>break</code> is all that's needed to exit and then continue over again.</p>
<p>What eles can you see or know to improve this?</p>
<pre><code>var arr_vals = ["74","f4e3","22","r31","17","hundernds"]; // could have 500+ items
var arr_items = ["r31","22","65","100"]; // could have 50 items
var c = arr_items.length;
var arr_vals_len = arr_vals.length;
for ( var i = 0; i < c; i++ ) {
var xid = arr_items[i];
for (var j = 0; j < arr_vals_len; j++ ){
if(arr_vals[j] === xid){
// match !
break;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T21:01:08.190",
"Id": "17722",
"Score": "0",
"body": "`break` will break out of the inner loop but not the outer one, so it will continue with the next iteration of the outer loop. Is that what you're asking? Also, I think you mean `var j` rather than `var r`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T21:04:12.097",
"Id": "17723",
"Score": "0",
"body": "@seand yes that's right, and r is supposed to be j"
}
] |
[
{
"body": "<p>Instead of iterating through the inner array multiple times, it might be faster to create a map for the inner array beforehand and then test for a match within the map. (I think this will only work if they're arrays of strings, though.)</p>\n\n<pre><code>var arr_vals = [\"74\",\"f4e3\",\"22\",\"r31\",\"17\",\"hundernds\"]; // could have 500+ items\nvar arr_items = [\"r31\",\"22\",\"65\",\"100\"]; // could have 50 items\n\nvar vals_len = arr_vals.length;\nvar items_len = arr_items.length;\n\nvar map_items = {};\nfor(var j = 0; j < items_len; ++j) {\n map_items[arr_items[j]] = 1;\n}\n\nfor( var i = 0; i < vals_len; ++i) {\n if(map_items[arr_vals[i]]) {\n // match!\n }\n}\n</code></pre>\n\n<p><a href=\"http://jsperf.com/map-vs-array\" rel=\"nofollow\">Perf test</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T21:26:32.213",
"Id": "11127",
"ParentId": "11125",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "11127",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T20:55:53.073",
"Id": "11125",
"Score": "1",
"Tags": [
"javascript",
"optimization"
],
"Title": "Improving script performance for looping unparalleled arrays"
}
|
11125
|
<p>I'm working on a show/hide div with checkbox on change and on load. I've come up with this so far:</p>
<p><a href="http://jsfiddle.net/bK8EC/115/" rel="nofollow">jsFiddle</a></p>
<pre><code>$(document).ready(function() {
var $cbtextbook = $('#in-product_category-14'),
$cbimod = $('#in-product_category-15'),
$mb1 = $('#mbtextbook'),
$mb2 = $('#mbimod');
function tbmb() {
if ($cbtextbook.is(":checked")) $mb1.show();
else $mb1.hide();
}
function immb() {
if ($cbimod.is(":checked")) $mb2.show();
else $mb2.hide();
}
tbmb();
immb();
$cbtextbook.change(tbmb);
$cbimod.change(immb);
})
</code></pre>
<p>At the moment, I'm not worrying about dynamically changing elements (although I might in the future as I learn more).</p>
<p>Is there a much cleaner way to do this? I did get pretty simple toggle to work, but that didn't take into account if the box was already checked on page load, and the div I wanted to show/hide could get off cycle (i.e. show when unclicked, hide when clicked) if it was already checked, so I came up with this overly verbose solution. How can I pare this down?</p>
|
[] |
[
{
"body": "<p>It could be done with:</p>\n\n<pre><code>$(document).ready(function() {\n $(\"input\").change(function() {\n var index = $(this).closest(\"li\").index();\n $(\".metabox\").eq(index)[this.checked ? \"show\" : \"hide\"]();\n }).change();\n});\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/bK8EC/118/\" rel=\"nofollow\">http://jsfiddle.net/bK8EC/118/</a></p>\n\n<p>Remember to add proper qualifiers in your real code, for example add <code>id=\"something\"</code> to your <code>ul</code> and then do <code>$(\"#something input:checkbox\")</code> instead of just binding this event to every input on the page. The <code>.metabox</code> is also pretty fragile if a container isn't added.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T01:51:40.073",
"Id": "17729",
"Score": "0",
"body": "this is awesome..and I might use it elsewhere, but I will have to find the metaboxes by id...as they are added dynamically and wont know where...and I have stripped out a lot of the code for simplicities sake...all the ul/li/div's are id'd and class'd. If I ID'd the metaboxes like mb-product_category-14 similar to the input IDs...could the id get stripped off the selector? (now I'm just talking out my rear like I know what I'm talking about!)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T02:16:18.857",
"Id": "17730",
"Score": "0",
"body": "New attempt...with selecting ID directly...seems to work :) But....http://jsfiddle.net/fDC3B/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T13:54:54.827",
"Id": "17742",
"Score": "0",
"body": "@BrianThornton but what? http://jsfiddle.net/fDC3B/ seems to work fine. Though `.substr(-2)` is extremely fragile and works only for 2 digit numbers... You might wanna use `.match(/\\d+$/)[0]` instead`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T19:35:05.873",
"Id": "17765",
"Score": "0",
"body": "That would be the reason for \"but...\" So twice you've stated that something is \"fragile\" can you elaborate or point me to a resource to help me avoid those in the future? Question marked as answered too! Thanks again for all the help!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T20:54:47.140",
"Id": "17769",
"Score": "0",
"body": "@BrianThornton By fragile I mean naive code that only assumes a very specific situation and will break in more general one that is feasible.\nFor example, it is perfectly possible that the number might only be 1 digit or 3 digit, so `substr(-2)` won't work if that's the case. OTOH,\nthe digits couldn't be in the form of a hexadecimal (I'm assuming), so you don't need to check for that. You can avoid them in the future by thinking\nabout \"weird\" input that's still feasible and testing that against your code (mentally or physically)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T22:19:51.247",
"Id": "17772",
"Score": "0",
"body": "Awesome...thank you! It's a new way of thinking for me...I haven't coded since I took a C++ class in about 1998...but, I'm getting there! Stackexchange is helping greatly, can only read so many books before you go cross eyed...and real world examples really help. Cheers, Brian"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-31T17:42:41.163",
"Id": "19553",
"Score": "0",
"body": "You can also do: `$(\".metabox\").eq(index).toggle(this.checked);` ^_^"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T00:15:41.367",
"Id": "11129",
"ParentId": "11128",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "11129",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-23T23:57:53.773",
"Id": "11128",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Show/hide checkbox div on change and load"
}
|
11128
|
<p>Carrying on from:</p>
<ul>
<li><a href="https://codereview.stackexchange.com/q/7536/507">Yet another C++ Json Parser</a></li>
<li><a href="https://codereview.stackexchange.com/q/7567/507">Yet another C++ Json Parser (Recursive)</a></li>
</ul>
<p>All the code is available from git hub: <a href="https://github.com/Loki-Astari/ThorsSerializer" rel="noreferrer">ThorsSerializer</a> but only reviewing a small section here.</p>
<p>The idea is that using this library it should be easy to define how a class is serialized without writing any code. See example in <a href="https://github.com/Loki-Astari/ThorsSerializer/blob/master/README.md" rel="noreferrer">README</a></p>
<pre><code>#ifndef THORSANVIL_SERIALIZE_JSON_SERIALIZE_H
#define THORSANVIL_SERIALIZE_JSON_SERIALIZE_H
/* Content:
*
* Used to define how a class is imported/exported via the Json Serialized
*
* Conventions:
* T: The type of the base class
* I: The type of the member
* MP: The type of the member pointer
*
* S: Source type (std::ostream output) (ThorsAnvil::Json::ScannerSax input)
*
* Every type that is serializeable has a class JsonSerializeTraits.
* For basic types (int/float etc) no definition is required and the default template version works
* For compound types you need to define the type SerializeInfo.
* SerializeInfo: It is a mpl vector of types.
* Each type (in the vector) defines how to serialize
* a member of the compound type.
*
* Boilerplate code to create the appropriate types for SerializeInfo.
* #define THORSANVIL_SERIALIZE_JsonAttribute(className, member)
*
* Example:
* class MyClass
* {
* // STUFF
*
* // If any members are private and need to be serialized then
* // JsonSerializeTraits<MyClass> must be a friend of the class so it can generate the appropriate code
*
* friend class JsonSerializeTraits<MyClass>;
* };
*
* namespace ThorsAnvil { namespace Serialize { namespace Json {
* template<>
* class JsonSerializeTraits<MyClass>
* {
* static ThorsAnvil::Serialize::Json::JsonSerializeType const type = Map;
*
* THORSANVIL_SERIALIZE_JsonAttribute(MyClass, member1);
* THORSANVIL_SERIALIZE_JsonAttribute(MyClass, member2);
* THORSANVIL_SERIALIZE_JsonAttribute(MyClass, member3);
* typedef boost::mps::vector<member1, member2, member3> SerializeInfo;
* };
* }}}
*
* Now we can serialize/deserialize with:
* std::cout << jsonExport(myClassObj) << "\n";
* std::cin >> jsonInport(myClassObj);
*
* Same for std::vector
* std::vector<MyClass> vec; // Will serialize any fundamental type or type with JsonSerializeTraits<> specialized for it
* // If JsonSerializeTraits<> is not specialized for a compound type you get a compile time
* // error
* std::cout << jsonExport(vec) << "\n";
* std::cin >> jsonImport(vec);
*/
#include "json/ScannerSax.h"
#include "json/ParserShiftReduce.tab.hpp"
#include <boost/mpl/at.hpp>
#include <boost/mpl/pop_front.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/type_traits/is_fundamental.hpp>
#include <boost/typeof/typeof.hpp>
#include <iostream>
/*
* Helper Macros:
*
* These are macros that will build some boilerplate types needed by the serialization code.
*
* THORSANVIL_SERIALIZE_JsonAttribute: This is the main macro used.
* It identifies a class member that will be serialized
*
* THORSANVIL_SERIALIZE_JsonAttribute_1: Used internally (should probably not be used by others).
* THORSANVIL_SERIALIZE_JsonAttributeAccess: If you want to run some code to as part of the serialization processes
* this macro allows you to specify a type that will be used during serialization.
* Examples will be provided in the documentaion.
*
* THORSANVIL_SERIALIZE_JsonGenericMapAttributeAccess: A generic accessor can be used to generate multiple items.
* When de-serializing the Json can be applied to multiple elements.
* Used manly for container classes like std::map
*THORSANVIL_SERIALIZE_JsonGenericArrAttributeAccess: A generic accessor used by for arrays rather than maps (std::vector)
* But otherwise identical to THORSANVIL_SERIALIZE_JsonGenericMapAttributeAccess
*/
#define THORSANVIL_SERIALIZE_JsonAttribute(className, member) \
typedef BOOST_TYPEOF(((className*)01)->member) JsonAttribute ## member ## Type; \
THORSANVIL_SERIALIZE_JsonAttribute_1(className, member, JsonSerializeTraits<JsonAttribute ## member ## Type>)
#define THORSANVIL_SERIALIZE_JsonAttribute_1(className, member, SerTraits) \
typedef BOOST_TYPEOF(&className::member) JsonAttribute ## member ## TypePtr; \
typedef JsonSerialElementAccessor<className, JsonAttribute ## member ## TypePtr, SerTraits> JsonAttribute ## member ## Accessor; \
struct member: JsonSerializeItem<className, JsonAttribute ## member ## Accessor, std::string> \
{ \
member() \
: JsonSerializeItem<className, JsonAttribute ## member ## Accessor, std::string>(#member, &className::member) \
{} \
}
#define THORSANVIL_SERIALIZE_JsonAttributeAccess(className, member, accessor) \
struct member: JsonSerializeItem<className, accessor, std::string> \
{ \
member() \
: JsonSerializeItem<className, accessor, std::string>(#member, accessor()) \
{} \
}
#define THORSANVIL_SERIALIZE_JsonGenericMapAttributeAccess(className, accessor) \
struct genericAccessor: JsonSerializeItem<className, accessor, std::string> \
{ \
genericAccessor() \
: JsonSerializeItem<className, accessor, int>(-1 , accessor()) \
{} \
}
namespace ThorsAnvil
{
namespace Serialize
{
/* External dependencies from the generic Serialization code */
template<typename T, typename Parser>
struct Importer;
template<typename T, typename Printer>
struct Exporter;
namespace Json
{
/* Three basic element types: Invalid (this obejct is not a top level JSON object)
* Map A JSON object { [<string> : <value> [, <string> : <value>]*]? }
* Array A JSON array [ [<value> [, <value>]*]? ]
*/
enum JsonSerializeType {Invalid, Map, Array};
/*
* All objects that want to be serialized by this code must define their own specialization of this class.
* The default version will cause compilation errors. Which hopefully will bring the reader here.
*/
template<typename T>
struct JsonSerializeTraits
{
static JsonSerializeType const type = Invalid;
typedef T SerializeInfo;
};
// Forward declarations
template<typename T, typename A, typename RegisterKey>
struct JsonSerializeItem;
/* Class used by boost::mpl::for_each. Nothing special simple lamba's will replace them in the future */
/*
* T The object Type
* S The source type (parser or std::ostream)
*
* This is basically trying to templatize and remove the need for multiple action objects that
* are called from mpl::for_each
*/
template<typename T, typename S>
struct MPLForEachActivateTrait;
template<typename T>
struct MPLForEachActivateTrait<T, std::ostream>
{
typedef const T ObjectType;
static int const SerializeActionIndex = 0;
};
template<typename T>
struct MPLForEachActivateTrait<T, ThorsAnvil::Json::ScannerSax>
{
typedef T ObjectType;
static int const SerializeActionIndex = 1;
};
template<typename T, typename S>
class MPLForEachActivateItem
{
typedef MPLForEachActivateTrait<T, S> Traits;
typedef typename Traits::ObjectType ObjectType;
S& pump;
ObjectType& object;
public:
MPLForEachActivateItem(S& p, ObjectType& obj)
: pump(p)
, object(obj)
{}
// Depending on if the pump is a stream or a scanner
// Calls JsonSerialize::activate()
// or JsonDeSerialize::activate()
template<typename SerializeItem>
void operator()(SerializeItem const& item) const
{
typedef typename boost::mpl::at_c<typename SerializeItem::SerializeType, Traits::SerializeActionIndex>::type SerializeAction;
SerializeAction::activate(item, pump, object);
}
};
/*
* Objects of this type get stored in the
* JsonSerializeTraits::SerializeInfo
* This is what the user create with the macros above. The default A is JsonSerialElementAccessor
* But user can define their own action for complex objects This wrapper is merely a vehicle for
* calling the A methods in a controlled manner.
*
* Note: These classes are not designed to be used directly but via the macros:
* THORSANVIL_SERIALIZE_JsonAttribute
* THORSANVIL_SERIALIZE_JsonAttributeAccess
* See the notes by these macros for details
*/
template<typename T, typename A, typename RegisterKey, JsonSerializeType type = JsonSerializeTraits<T>::type>
struct JsonSerialize;
template<typename T, typename A, typename RegisterKey>
struct JsonSerialize<T, A, RegisterKey, Map>
{
// Generic serialization of a JSON object
static void activate(JsonSerializeItem<T, A, RegisterKey> const& item, std::ostream& stream, T const& src)
{
if (!item.first)
{ stream << ',';
}
stream << '"' << item.memberName << '"' << ":";
item.accessor.serialize(src, stream);
}
};
template<typename C, typename A, typename RegisterKey>
struct JsonSerialize<C, A, RegisterKey, Array>
{
// Generic serialization of a JSON array
static void activate(JsonSerializeItem<C, A, RegisterKey> const& item, std::ostream& stream, C const& src)
{
if (!item.first)
{ stream << ',';
}
item.accessor.serialize(src, stream);
}
};
template<typename T, typename A,typename RegisterKey, JsonSerializeType type = JsonSerializeTraits<T>::type>
struct JsonDeSerialize;
template<typename T, typename A,typename RegisterKey>
struct JsonDeSerialize<T, A, RegisterKey, Map>
{
static void activate(JsonSerializeItem<T, A, RegisterKey> const& item, ThorsAnvil::Json::ScannerSax& parser, T& dst)
{
std::auto_ptr<ThorsAnvil::Json::SaxAction> action(item.accessor.action(dst));
parser.registerAction(item.memberName, action);
}
};
template<typename T, typename A>
struct JsonDeSerialize<T, A, int, Array>
{
static void activate(JsonSerializeItem<T, A, int> const& item, ThorsAnvil::Json::ScannerSax& parser, T& dst)
{
std::auto_ptr<ThorsAnvil::Json::SaxAction> action(item.accessor.action(dst));
parser.registerActionOnAllArrItems(action);
}
};
template<typename T, typename A>
struct JsonDeSerialize<T, A, std::string, Array>
{
static void activate(JsonSerializeItem<T, A, std::string> const& item, ThorsAnvil::Json::ScannerSax& parser, T& dst)
{
std::auto_ptr<ThorsAnvil::Json::SaxAction> action(item.accessor.action(dst));
parser.registerActionNext(action);
}
};
/*
* A type holder object that picks up the correct versions of JsonSerialize and JsonDeSerialize
* Used by MPLForEachActivateItem to get the correct type
*/
template<typename T, typename A, typename RegisterKey>
struct JsonSerializeItem
{
RegisterKey memberName;
A accessor;
bool first;
JsonSerializeItem(RegisterKey const& name, A const& ac): memberName(name), accessor(ac), first(false) {}
JsonSerializeItem& makeFirst() {first = true;return *this;}
typedef JsonSerialize<T,A,RegisterKey> Serialize;
typedef JsonDeSerialize<T,A,RegisterKey> DeSerialize;
typedef boost::mpl::vector<Serialize, DeSerialize> SerializeType;
};
/*
* Importing
* ============
*
* The JsonImportAction defines a class that is registered with a Json SAX parser
* so that we can register callback actions for particular attributes.
*
* For fundamental types json is read directly into the value.
* For compound types when the attribute is reached additional callbacks are registered
* for each of the compound members that needs to be de-serialized (this is done recursively)
* So we can de-serialize arbitrary json structures.
*/
template<typename SerializeInfo, typename I, bool EnablePod = boost::is_fundamental<I>::value>
class JsonImportAction: public ThorsAnvil::Json::SaxAction
{
I& memberRef;
public:
JsonImportAction(I& mr)
: memberRef(mr)
{}
virtual void doPreAction(ThorsAnvil::Json::ScannerSax&, ThorsAnvil::Json::Key const&){}
virtual void doAction(ThorsAnvil::Json::ScannerSax&, ThorsAnvil::Json::Key const&, JsonValue const& value)
{
// Read fundamental type directly into the member
memberRef = value.getValue<I>();
}
};
template<typename SerializeInfo, typename I>
class JsonImportAction<SerializeInfo, I, false>: public ThorsAnvil::Json::SaxAction
{
I& memberRef;
public:
JsonImportAction(I& mr)
: memberRef(mr)
{}
virtual void doAction(ThorsAnvil::Json::ScannerSax&, ThorsAnvil::Json::Key const&, JsonValue const&){}
virtual void doPreAction(ThorsAnvil::Json::ScannerSax& parser, ThorsAnvil::Json::Key const&)
{
// Compound type. Register callback for each member.
// This is done when the attribute is reached in json not before
boost::mpl::for_each<SerializeInfo>(MPLForEachActivateItem<I, ThorsAnvil::Json::ScannerSax>(parser, memberRef));
}
};
/*
* Need a function template to create the correct JsonImportAction()
*/
template<typename SerializeInfo, typename T, typename I>
ThorsAnvil::Json::SaxAction* new_JsonImportAction(T& dst, I T::* memberPtr)
{
return new JsonImportAction<SerializeInfo, I>(dst.*memberPtr);
}
/* Default Serialization Traits:
* Used by all types without their own specific serialization traits.
*/
template<JsonSerializeType>
struct JsonSerializeBrace
{
static char braces[];
};
/*
* The MemberScanner is used to register callbacks that will read sub-members from the json object
*/
template<typename T, typename MemberToSerialize = typename JsonSerializeTraits<T>::SerializeInfo>
struct MemberScanner
{
void operator()(ThorsAnvil::Json::ScannerSax& scanner, T& destination)
{
boost::mpl::for_each<typename JsonSerializeTraits<T>::SerializeInfo>(MPLForEachActivateItem<T, ThorsAnvil::Json::ScannerSax>(scanner, destination));
}
};
template<typename T>
struct MemberScanner<T, T>
{
// A normal type with no SerializeInfo has no members thus no need to register callbacks.
void operator()(ThorsAnvil::Json::ScannerSax& scanner, T& destination)
{}
};
template<typename T>
struct MemberScanner<T, void>
{
// A normal type with no SerializeInfo has no members thus no need to register callbacks.
void operator()(ThorsAnvil::Json::ScannerSax& scanner, T& destination)
{}
};
/*
* The MemberPrinter prints each member of an object.
*/
template<typename T, typename MemberToSerialize = typename JsonSerializeTraits<T>::SerializeInfo>
struct MemberPrinter
{
void operator()(std::ostream& stream, T const& source)
{
typedef typename boost::mpl::at<typename JsonSerializeTraits<T>::SerializeInfo, boost::integral_constant<int,0> >::type FirstType;
typedef typename boost::mpl::pop_front<typename JsonSerializeTraits<T>::SerializeInfo>::type AllButFirstType;
MPLForEachActivateItem<T, std::ostream> itemPrinter(stream, source);
// Print the first member (Call makeFirst() means no comma is printed)
itemPrinter(FirstType().makeFirst());
// For each of the other members use a loop a proceed each object with a comma
boost::mpl::for_each<AllButFirstType>(itemPrinter);
}
};
template<typename T>
struct MemberPrinter<T, T>
{
// A normal object just prints itself.
void operator()(std::ostream& stream, T const& source)
{
stream << source;
}
};
template<typename T>
struct MemberPrinter<T, void>
{
void operator()(std::ostream& stream, T const& source)
{}
};
struct JsonSerializer
{
template<typename T, JsonSerializeType base = JsonSerializeTraits<T>::type>
struct Parser: ThorsAnvil::Json::ScannerSax
{
typedef boost::mpl::bool_<base != Invalid> Parsable;
Parser(T& dst)
: destination(dst)
{
MemberScanner<T> memberScanner;
memberScanner(*this, destination);
}
void parse(std::istream& stream)
{
ScannerSax::parse<yy::ParserShiftReduce>(stream);
}
T& destination;
};
template<typename T ,JsonSerializeType base = JsonSerializeTraits<T>::type>
struct Printer
{
typedef boost::mpl::bool_<base != Invalid> Printable;
Printer(T const& src)
: source(src)
{}
void print(std::ostream& stream)
{
stream << JsonSerializeBrace<base>::braces[0];
MemberPrinter<T> memberPrinter;
memberPrinter(stream, source);
stream << JsonSerializeBrace<base>::braces[1];
}
T const& source;
};
};
/*
* Default accessors for fundamental types std::string
* The serialize() Recursively calls jsonInternalExport() on the member to serialize the member.
*
* The action() Creates a JsonImportAction() that is registered with the SAX parser that just reads the
* Item directly into the object. If the object is a compound type it uses the SerializeInfo
* to register subsequent actions recursively so we always read directly into an object
* not a copy.
*/
template<typename T, typename MP, typename SerTraits>
class JsonSerialElementAccessor
{
MP memberPtr;
public:
JsonSerialElementAccessor(MP mp): memberPtr(mp) {}
void serialize(T const& src, std::ostream& stream) const
{
stream << jsonInternalExport(src.*memberPtr);
}
std::auto_ptr<ThorsAnvil::Json::SaxAction> action(T& dst) const
{
std::auto_ptr<ThorsAnvil::Json::SaxAction> action(new_JsonImportAction<typename SerTraits::SerializeInfo>(dst, memberPtr));
return action;
}
};
/* Helper functions */
template<typename T>
Importer<T, typename JsonSerializer::template Parser<T> > jsonInternalImport(T& object)
{
return Importer<T, typename JsonSerializer::template Parser<T> >(object);
}
template<typename T>
Exporter<T, typename JsonSerializer::template Printer<T> > jsonInternalExport(T const& object)
{
return Exporter<T, typename JsonSerializer::template Printer<T> >(object);
}
}
}
}
#endif
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T12:41:21.767",
"Id": "17735",
"Score": "8",
"body": "I strongly doubt that Loki would name something after Thor. Unless it was to ingratiate himself for some nefarious scheme."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T15:55:54.773",
"Id": "17749",
"Score": "7",
"body": "@KonradRudolph: Note: Its 'Thor's **Anvil**'. The item that Thor beats his frustration out on with his hammer(Mjölnir). Thus in my weird though patterns another pseudonym for Loki. (not the Loki was Thor's only frustration and Nemesis but he was a bit of pain)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T16:44:08.520",
"Id": "17750",
"Score": "6",
"body": "One level deeper. You win."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-17T01:17:28.613",
"Id": "362877",
"Score": "2",
"body": "Your code is no longer in-sync with your GitHub repository. Given the age of your question, I'm not sure whether you want _this_ version to be reviewed or your new one. But this could be a great opportunity for you to review your own, almost 6 year old code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-18T20:18:25.973",
"Id": "364088",
"Score": "0",
"body": "@zeta. Yes the repository was updated based on the comments it received in the reviews in other posts."
}
] |
[
{
"body": "<p>Before even trying to review this by nature incredible complex code I would comment on your {}-religion, code wrap, and vertical spacing.</p>\n\n<p>It is incredible personal what works best for you, me and others. Some of these comments might seem contradictory to each other, but some sacrifices might be made to increase code readability.</p>\n\n<p>The following is all my personal preferences </p>\n\n<p>First <a href=\"http://en.wikipedia.org/wiki/Indent_style\" rel=\"nofollow\">{}-religion</a>, '{}' should support the structure of the program and make it easy through visual inspection of the code easier.</p>\n\n<pre><code>template<JsonSerializeType>\nstruct JsonSerializeBrace\n{\n static char braces[];\n};\n</code></pre>\n\n<p>The '{' simply doesn't provide more information, the indention already tells you the next line is dependent on the previous.</p>\n\n<pre><code>template<JsonSerializeType>\nstruct JsonSerializeBrace {\n static char braces[];\n};\n</code></pre>\n\n<p>This provides exactly the same visual information namely that braces is part of the struct.<br>\nThe additional benefit of this is that it avoids some vertical scrolling. </p>\n\n<p>This block hides from a quick visual inspection that there is a control dependency</p>\n\n<pre><code>if (!item.first)\n{ stream << ',';\n}\n</code></pre>\n\n<p>If you instead write</p>\n\n<pre><code>if (!item.first) { \n stream << ',';\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>if (!item.first)\n stream << ',';\n</code></pre>\n\n<p>followed by a blank line, the control flow is more obvious.</p>\n\n<hr>\n\n<p>Next the vertical spacing, like in texts and papers the spacings are there to make it easier on the eye and improve visual search. </p>\n\n<p>This code looks like a wall of text</p>\n\n<pre><code>template<typename T>\nstruct MemberPrinter<T, T>\n{\n // A normal object just prints itself.\n void operator()(std::ostream& stream, T const& source)\n {\n stream << source;\n }\n};\ntemplate<typename T>\nstruct MemberPrinter<T, void>\n{\n void operator()(std::ostream& stream, T const& source)\n {}\n};\n</code></pre>\n\n<p>instead use a vertical spacing between the structs, functions or other distinct entities.</p>\n\n<pre><code>template<typename T>\nstruct MemberPrinter<T, T> {\n // A normal object just prints itself.\n void operator()(std::ostream& stream, T const& source) {\n stream << source;\n }\n};\n\ntemplate<typename T>\nstruct MemberPrinter<T, void> {\n void operator()(std::ostream& stream, T const& source) {\n }\n};\n</code></pre>\n\n<p>Now we can easily see that there 2 distinct structs, sacrificing 1 of the saved lines from the '{' move.</p>\n\n<pre><code> * THORSANVIL_SERIALIZE_JsonGenericMapAttributeAccess: A generic accessor can be used to generate multiple items.\n * When de-serializing the Json can be applied to multiple elements.\n * Used manly for container classes like std::map\n</code></pre>\n\n<p>This might be more readable if there is a break after the ':'</p>\n\n<pre><code> * THORSANVIL_SERIALIZE_JsonGenericMapAttributeAccess: \n * A generic accessor can be used to generate multiple items.\n * When de-serializing the Json can be applied to multiple elements.\n * Used manly for container classes like std::map\n</code></pre>\n\n<hr>\n\n<p>Code wrapping is also a problem when I try to read others code, what does this say? there is actually 2 different problems here, one is the long line length, the 2nd is what does this long line actually do.</p>\n\n<pre><code>boost::mpl::for_each<typename JsonSerializeTraits<T>::SerializeInfo>(MPLForEachActivateItem<T, ThorsAnvil::Json::ScannerSax>(scanner, destination));\n</code></pre>\n\n<p>Any horizontal scrolling takes extra time, more than vertical usually. Breaking the line at either '(),=' in order as they bind less strongly. '//' comments after the code might also have to be moved, usually by inserting a new line before and use same indention as the line from which it is moved.</p>\n\n<pre><code> boost::mpl::for_each<typename JsonSerializeTraits<T>::SerializeInfo>(\n MPLForEachActivateItem<T, ThorsAnvil::Json::ScannerSax>(\n scanner, destination\n ) // optionally combine the 2 ')'\n ); \n</code></pre>\n\n<p>Ah, it is actually 2 function calls, heavily templatized, so this code</p>\n\n<pre><code>template<typename T,\n typename MemberToSerialize =\n typename JsonSerializeTraits<T>::SerializeInfo>\nstruct MemberScanner {\n void operator()(ThorsAnvil::Json::ScannerSax& scanner, T& destination) {\n boost::mpl::for_each<typename JsonSerializeTraits<T>::SerializeInfo>(\n MPLForEachActivateItem<T, ThorsAnvil::Json::ScannerSax>(\n scanner, destination\n ));\n }\n};\n</code></pre>\n\n<p>has a break at the last ',' for the control, ie. the template arguments, before eol, then at the '=' in the template argument.<br>\nNow we can see that </p>\n\n<pre><code>typename MemberToSerialize = \n typename JsonSerializeTraits<T>::SerializeInfo>\n</code></pre>\n\n<p>might be what you meant for the template argument in the 'for_each', which I couldn't before. If this is not just for SFINAE, then 'MemberToSerialize' should be used.</p>\n\n<pre><code>template<typename T,\n typename MemberToSerialize =\n typename JsonSerializeTraits<T>::SerializeInfo>\nstruct MemberScanner {\n void operator()(ThorsAnvil::Json::ScannerSax& scanner, T& destination) {\n boost::mpl::for_each<MemberToSerialize>(\n MPLForEachActivateItem<T, ThorsAnvil::Json::ScannerSax>(\n scanner, destination\n ));\n }\n};\n</code></pre>\n\n<p>If this is what you actually meant (and not just me misunderstanding what your trying to do) making it a little easier to read. </p>\n\n<p>This leaves me with one eye-sore for this, namely the long namespace+typenames, using 'using', typedef or alias can help here.</p>\n\n<pre><code>template<typename T,\n typename MemberToSerialize =\n typename JsonSerializeTraits<T>::SerializeInfo>\nstruct MemberScanner {\n // only pollute this scope, alternatively use typedef/alias\n using ThorsAnvil::Json::ScannerSax;\n\n void operator()(ScannerSax& scanner, T& destination) {\n boost::mpl::for_each<MemberToSerialize>(\n MPLForEachActivateItem<T, ScannerSax>(scanner, destination)\n );\n }\n};\n</code></pre>\n\n<p>2 uses is really on the low side but as they are so long it might be considered.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-08T15:07:32.090",
"Id": "119338",
"Score": "8",
"body": "Unfortunately I disagree with nearly every point (apart from shortening names with using). This is more of a style review than a code review. Since my personal style preferences fall into one of the three major style groups (with a couple of tweaks for readability) this is just your opinion differs from mine review. As such not much use, especially since these things are usually covered by local style guides."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-08T15:51:58.400",
"Id": "119356",
"Score": "0",
"body": "There isn't a right style and a wrong style. I thought the page you mention, on indent styles, shows that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-08T16:07:55.937",
"Id": "119362",
"Score": "0",
"body": "@FlorianF, which is why I mentioned it was my preferences, because of the different styles, but also why I think it was relevant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-08T16:28:44.900",
"Id": "119365",
"Score": "0",
"body": "You have a point, I didn't notice that line. But the overall impression you give is still very critical of Loki's style."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-21T16:20:51.690",
"Id": "253886",
"Score": "3",
"body": "To be fair: @Loki is asking for feedback and Surt is giving it to him. \n\nLoki has the right of choice: to agree, to disagree or to learn from a Suri's point of view. \nSimple."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-09-01T22:12:21.093",
"Id": "331318",
"Score": "2",
"body": "While some comment on the style in the scope of a larger review might be helpful, just giving formatting tips which are in most cases completely subjective does not really provide any kind of substantive feedback. This basically amounts to saying \"you chose red but i prefer blue.\""
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-08T14:37:41.080",
"Id": "65091",
"ParentId": "11138",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T11:31:18.157",
"Id": "11138",
"Score": "32",
"Tags": [
"c++",
"json",
"template-meta-programming",
"serialization"
],
"Title": "JSON Serializer"
}
|
11138
|
<p>I have a basic class that I'd like to get some feedback on. I'm refactoring some old code but the new code looks more complex. Basically I'm passing a list of included and excluded cultures into a function that should return if the current culture should be allowed. Exclusions win. Any advice how to better it would be great. Thanks</p>
<pre><code>public static class CultureCheck
{
public static bool IsCurrentCultureIncluded(string includedCultures, string excludedCultures)
{
if(includedCultures == null)
{
throw new ArgumentNullException("includedCultures");
}
if (excludedCultures == null)
{
throw new ArgumentNullException("excludedCultures");
}
var isIncluded = false;
// exclusions win.
if (IsCultureInList(excludedCultures) == true)
{
isIncluded = false;
}
else if(IsCultureInList(includedCultures) == true)
{
isIncluded = true;
}
return isIncluded;
}
private static bool IsCultureInList(string cultures)
{
string currentCultureName = Thread.CurrentThread.CurrentCulture.Name;
var isFound = false;
if (cultures.IndexOf("*") != -1)
{
isFound = true;
}
else
{
List<string> cultureList = new List<string>(cultures.Split(','));
if (cultureList.Where(e => e.Equals(currentCultureName, StringComparison.InvariantCultureIgnoreCase)).Any() == true)
{
isFound = true;
}
}
return isFound;
}
}
</code></pre>
<p><strong>OLD CODE</strong></p>
<pre><code> public static bool IsCurrentCultureIncluded(string includedCultures, string excludedCultures)
{
#region Exclusion Test
// exclusions win.
if (excludedCultures.IndexOf("*") != -1)
{
return false;
}
string currentCultureName = Thread.CurrentThread.CurrentCulture.Name;
string[] excludedCulturesSplit = excludedCultures.Split(new char[] { ',' });
foreach (string excludedCulture in excludedCulturesSplit)
{
if (string.Equals(currentCultureName, excludedCulture, StringComparison.InvariantCultureIgnoreCase))
{
return false;
}
}
#endregion
#region Inclusion Test
if (includedCultures.IndexOf("*") != -1)
{
return true;
}
string[] includedCulturesSplit = includedCultures.Split(new char[] { ',' });
foreach (string includedCulture in includedCulturesSplit)
{
if (string.Equals(currentCultureName, includedCulture, StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
}
#endregion
return false;
}
</code></pre>
|
[] |
[
{
"body": "<p>I would do it like this (WARNING - not tested):</p>\n\n<pre><code>public static void SampleUsage()\n{\n IsCurrentCultureIncluded(\"*\", \"*\", Thread.CurrentThread.CurrentCulture.Name);\n}\n\npublic static bool IsCurrentCultureIncluded(string includedCultures, string excludedCultures, string currentCultureName)\n{\n return !CheckIncl(currentCultureName, excludedCultures) &&\n CheckIncl(currentCultureName, includedCultures);\n}\n\nprivate static bool CheckIncl(string currentCultureName, string includedCultures)\n{\n if (includedCultures.IndexOf(\"*\") != -1)\n return true;\n\n var includedCulturesSplit = includedCultures.Split(new[] { ',' });\n return includedCulturesSplit.Any(includedCulture => string.Equals(currentCultureName, includedCulture, StringComparison.InvariantCultureIgnoreCase));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T17:29:16.473",
"Id": "17814",
"Score": "0",
"body": "You're missing the check for null, in `CheckIncl`, so it's not the same. Otherwise, it looks perfect to me."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T14:02:27.447",
"Id": "11164",
"ParentId": "11146",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "11164",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T22:04:27.940",
"Id": "11146",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Checking for culture in comma separated list, any suggestions?"
}
|
11146
|
<p>Is this correct coding for prepared statements in php. I've done some reading but the best way to learn is criticism from peers. Any suggestions to improve this code? Anything I've done wrong? Thanks you!</p>
<pre><code>$dbh = new PDO('mysql:host=localhost;dbname=tests;charset=UTF-8', $user, $pass);
$stmt = $dbh->prepare('INSERT INTO items (item_id,itemname,itemuni, soldby,soldby2,keywords,description,sizing,price,totalquantity,lowquantity,weight,length,width,height,imagelocation,thumblocation,fblocation,cat1,cat2,cat3,size1,quantity1,size2,quantity2,size3,quantity3,size4,quantity4,size5,quantity5,size6,quantity6,size7,quantity7,size8,quantity8,size9,quantity9,size10,quantity10,size11,quantity11,size12,quantity12,size13,quantity13) VALUES (:item_id,:itemname,:itemuni,:soldby,:soldby2,:keywords,:description,:sizing,:price,:totalquantity,:lowquantity,:weight,:length,:width,:height,:imagelocation,:thumblocation,:fblocation,:cat1,:cat2,:cat3,:size1,:quantity1,:size2,:quantity2,:size3,:quantity3,:size4,:quantity4,:size5,:quantity5,:size6,:quantity6,:size7,:quantity7,:size8,:quantity8,:size9,:quantity9,:size10,:quantity10,:size11,:quantity11,:size12,:quantity12,:size13,:quantity13)');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt->bindValue(':item_id', '44', PDO::PARAM_STR);
$stmt->bindValue(':itemname', $_POST['itemname'], PDO::PARAM_STR);
$stmt->bindValue(':itemuni',$getitemuni, PDO::PARAM_STR);
$stmt->bindValue(':soldby', $soldby, PDO::PARAM_STR);
$stmt->bindValue(':solby2', $soldby2, PDO::PARAM_STR);
$stmt->bindValue(':keywords', $_POST['keywords'], PDO::PARAM_STR);
$stmt->bindValue(':description', $_POST['description'], PDO::PARAM_STR);
$stmt->bindValue(':sizing', 'yes', PDO::PARAM_STR);
$stmt->bindValue(':price', $_POST['price'], PDO::PARAM_STR);
$stmt->bindValue(':totalquantity', $_POST['quantity'], PDO::PARAM_STR);
$stmt->bindValue(':lowquantity', $_POST['lowquantity'], PDO::PARAM_STR);
$stmt->bindValue(':weight', $_POST['weight'], PDO::PARAM_STR);
$stmt->bindValue(':length', $_POST['length'], PDO::PARAM_STR);
$stmt->bindValue(':width', $_POST['width'], PDO::PARAM_STR);
$stmt->bindValue(':height', $_POST['height'], PDO::PARAM_STR);
$stmt->bindValue(':imagelocation', $_POST['imageloc'], PDO::PARAM_STR);
$stmt->bindValue(':thumblocation', $_POST['thumbloc'], PDO::PARAM_STR);
$stmt->bindValue(':fblocation', $_POST['fbloc'], PDO::PARAM_STR);
$stmt->bindValue(':cat1', $_POST['drop_1'], PDO::PARAM_STR);
$stmt->bindValue(':cat2', $_POST['drop_2'], PDO::PARAM_STR);
$stmt->bindValue(':cat3', $_POST['drop_3'], PDO::PARAM_STR);
$stmt->bindValue(':size1', $_POST['size1'], PDO::PARAM_STR);
$stmt->bindValue(':quantity1', $_POST['quant1'], PDO::PARAM_STR);
$stmt->bindValue(':size2', $_POST['size2'], PDO::PARAM_STR);
$stmt->bindValue(':quantity2', $_POST['quant2'], PDO::PARAM_STR);
$stmt->bindValue(':size3', $_POST['size3'], PDO::PARAM_STR);
$stmt->bindValue(':quantity3', $_POST['quant3'], PDO::PARAM_STR);
$stmt->bindValue(':size4', $_POST['size4'], PDO::PARAM_STR);
$stmt->bindValue(':quantity4', $_POST['quant4'], PDO::PARAM_STR);
$stmt->bindValue(':size5', $_POST['size5'], PDO::PARAM_STR);
$stmt->bindValue(':quantity5', $_POST['quant5'], PDO::PARAM_STR);
$stmt->bindValue(':size6', $_POST['size6'], PDO::PARAM_STR);
$stmt->bindValue(':quantity6', $_POST['quant6'], PDO::PARAM_STR);
$stmt->bindValue(':size7', $_POST['size7'], PDO::PARAM_STR);
$stmt->bindValue(':quantity7', $_POST['quant7'], PDO::PARAM_STR);
$stmt->bindValue(':size8', $_POST['size8'], PDO::PARAM_STR);
$stmt->bindValue(':quantity8', $_POST['quant8'], PDO::PARAM_STR);
$stmt->bindValue(':size9', $_POST['size9'], PDO::PARAM_STR);
$stmt->bindValue(':quantity9', $_POST['quant9'], PDO::PARAM_STR);
$stmt->bindValue(':size10', $_POST['size10'], PDO::PARAM_STR);
$stmt->bindValue(':quantity10', $_POST['quant10'], PDO::PARAM_STR);
$stmt->bindValue(':size11', $_POST['size11'], PDO::PARAM_STR);
$stmt->bindValue(':quantity11', $_POST['quant11'], PDO::PARAM_STR);
$stmt->bindValue(':size12', $_POST['size12'], PDO::PARAM_STR);
$stmt->bindValue(':quantity12', $_POST['quant12'], PDO::PARAM_STR);
$stmt->bindValue(':size13', $_POST['size13'], PDO::PARAM_STR);
$stmt->bindValue(':quantity13', $_POST['quant13'], PDO::PARAM_STR);
$stmt->execute()
</code></pre>
|
[] |
[
{
"body": "<p>First off, if I were about to do something this repetitive, I would set it up so that I would only have to type it all once. Best way to do this is set up an array and run it through loops. Lets start with that array.</p>\n\n<pre><code>$bindValues = array(\n 'item_id' => '44',\n 'itemuni' => $getitemuni,\n 'soldby' => $soldby,\n etc...\n);\n</code></pre>\n\n<p>\"Wait a second! You skipped some elements and those keys are missing their colons!\" Yep, DON'T add post data yet as it needs to be sanitized first. You should ALWAYS sanitize user input. Also, do not append a colon(:) to any of these array keys. You'll see why in a bit, I promise.</p>\n\n<p>Now, I'm assuming you are using the entire post array. If you are not, you should either use what you need first, or set those values to a new array/variable and then unset them from the post array. Here's what you are going to do with your post array. </p>\n\n<pre><code>$filterType = array(\n 'string' => FILTER_SANITIZE_STRING | FILTER_SANITIZE_STRIPPED,\n 'integer' => FILTER_VALIDATE_INT,\n etc...\n);\n\n$post = array();\nforeach($_POST as $key => $value) {\n $filter = $filterType[gettype($value)];\n $value = filter_var($value, $filter);\n $post[$key] => $value;\n}\n$bindValues = array_merge($bindValues, $post);\n</code></pre>\n\n<p>Here's a little explanation of what the above code does. <code>$filterType</code> sets up an array that will hold specific flags needed for PHP's <code>filter_var()</code> function. See the <a href=\"http://us2.php.net/manual/en/function.filter-var.php\">documentation</a> for an explanation of this function and its flags. <code>$post</code> sets up a new array to add our sanitized <code>$_POST</code> data to. Enter the loop. <code>$filter</code> uses PHP's <code>gettype()</code> function to return the <code>$value</code>'s type and compare it to the <code>$filterType</code> array for the necessary flags to use in the <code>filter_var()</code> function. <code>$value</code> is the sanitized value that you want to save to the new array. Using this new information we take the original key and sanitized value and append it to the new array. Exit loop. Merge both arrays.</p>\n\n<p>Now that we are done with setup, you'll want to start the code that actually does something.</p>\n\n<pre><code>$items = implode(',', array_keys($bindValues));\n$values = implode(',:', array_keys($bindValues));\n/*\nvar_dump() these variables if you want to examine them.\nBasically, this just replaces those long SQL strings you had\n*/\n\n$stmt = $dbh->prepare(\"INSERT INTO items ($items) VALUES (:$values)\");\n\nforeach($bindValues as $key => $value) {\n $stmt->bindValue(':' . $key, $value, PDO::PARAM_STR);\n}\n\n$stmt->execute();\n</code></pre>\n\n<p>Sorry if you were looking for a little more generic answer. I got a little carried away.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T04:19:33.933",
"Id": "17784",
"Score": "0",
"body": "no thank you!!! This is perfect i wanted detail i love it! I love to learn what is wrong and how to fix it! Thank you again!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T03:19:05.160",
"Id": "11157",
"ParentId": "11147",
"Score": "6"
}
},
{
"body": "<p>I agree with all of showerhead's comments.</p>\n\n<p>You should make the following three lines from your code the first ones:</p>\n\n<pre><code>$dbh = new PDO('mysql:host=localhost;dbname=tests;charset=UTF-8', $user, $pass);\n$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);\n</code></pre>\n\n<p>Then do all of the stmt lines as you had them. If you don't set the error mode attribute to <code>PDO::ERRMODE_EXCEPTION</code> before doing your <code>prepare</code> then it will not throw an exception on failure to prepare your statement. So as you have it now your prepare could produce <code>$stmt</code> as <code>false</code>.</p>\n\n<h2>Suggestions</h2>\n\n<ul>\n<li>Limit your lines to a set number of characters. I like to use 80 characters. Monitors can easily handle that without wrapping. Side-by-side diffs are also easily readable.</li>\n<li>There are too many fields in your database table!</li>\n<li>You have fields that couldn't possibly be filled for all items: quantity11, quantity12 (surely not everything has that many).</li>\n<li>Fields like <code>totalquantity</code>, <code>lowquantity</code>, <code>length</code>, <code>width</code> and many others should be stored in a numeric form within your database. This would also mean that you wouldn't bind them with PDO::PARAM_STR</li>\n<li>Your fields don't have meaningful names (quantity11?)</li>\n</ul>\n\n<p>I think the next step for you would be to learn about how to make a good database. Look for articles on Database Normalization and Database Design. This will help you break this super table into parts. It will help when you want to find information from your database later.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T04:01:02.830",
"Id": "17781",
"Score": "0",
"body": "I'm ashamed to say I have no real experience with SQL, so I was not able to provide those other suggestions, but they look in order. I know SQL is every PHP programmers bread and butter, but everything I've done thus far has been XML based. My next big project will fix that lack. Also agree with everything he has here +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T04:02:24.187",
"Id": "17782",
"Score": "0",
"body": "I'd swear, if I didn't know any better, I'd say we were following each other around ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T04:21:13.650",
"Id": "17787",
"Score": "0",
"body": "@paul thank you!!! I really appreciate your time into the answer. I don't want to bother you any further but I love new reading material. If you have any suggestions on what to read for Design and Normalization I would love to read it! Thanks again!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T04:31:21.983",
"Id": "17788",
"Score": "0",
"body": "BTW I wish I could accept both answers. They are both terrific!!!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T04:31:52.043",
"Id": "17789",
"Score": "0",
"body": "@showerhead Yes, nice to have you reviewing PHP too. I was going to miss out your good points with my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T04:32:00.673",
"Id": "17790",
"Score": "0",
"body": "@Easley It is quite difficult to understand, but read http://en.wikipedia.org/wiki/Database_normalization and the wikipedia entries for 1NF, 2NF etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T04:35:41.667",
"Id": "17793",
"Score": "0",
"body": "@Paul thank you very much! I can see this might take a bit but it's obviously something I need to learn. Once again thank you."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T03:39:03.233",
"Id": "11158",
"ParentId": "11147",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "11157",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T22:41:24.067",
"Id": "11147",
"Score": "5",
"Tags": [
"php",
"mysql"
],
"Title": "PHP prepared statements"
}
|
11147
|
<p>I am using an external library named <code>enchant</code> here. My problem is that I guess my program is not returning all possible English words and is slow as well for large string input.</p>
<p>I am using both <code>en_US</code> and <code>en_UK</code> here:</p>
<pre><code>import enchant
import itertools
uk = enchant.Dict("en_UK")
us=enchant.Dict("en_US")
a=[] # stores all possible string combinations
ent=input('enter the word: ')
ent=ent.rstrip('\r\n')
i=3 # minimum length of words
while i<=len(ent):
it=itertools.permutations(ent,i)
for y in it:
a.append("".join(y))
i+=1
a.sort(key=len,reverse=True)
possible_words=[]
for x in a:
if uk.check(x) and x not in possible_words :
possible_words.append(x)
for x in a :
if us.check(x) and x not in possible_words:
possible_words.append(x)
possible_words.sort(key=len,reverse=True)
for x in possible_words:
print(x)
</code></pre>
<p><strong>Example :</strong></p>
<pre><code>enter the word: wsadfgh
wash
wads
wags
swag
shag
dash
fads
fags
gash
gads
haws
hags
shaw
shad
was
wad
wag
saw
sad
sag
ash
ads
fwd
fas
fad
fag
gas
gad
haw
has
had
hag
</code></pre>
|
[] |
[
{
"body": "<p>As a general advice, you may want to organize your code into functions - say</p>\n\n<ul>\n<li>One function to receive user input and process it</li>\n<li>One function to generate all possible permutations for a string passed in less than a value (here 3).</li>\n<li>Another function to filter this based on whether the string passed in is in us or uk dictionaries</li>\n<li>At the end, you can combine these as a list comprehension.</li>\n</ul>\n\n<p>Regarding your problem of performance, time the program with the itertools permutation output alone (without dict checking). My guess would be that the permutations is taking the time, but it would be nice to verify. </p>\n\n<p>You may also want to check where the valid words are getting filtered. (Since you say that not all the words are being output). My guess is that permutation produces them but is not present in the enchant dictionary. But please verify.\nHere is a possible rewriting of your code. It removes the redundant sorts</p>\n\n<pre><code>import enchant\nimport itertools\n\nMIN_LEN = 3\nuk = enchant.Dict(\"en_UK\")\nus = enchant.Dict(\"en_US\")\n\ndef get_input():\n return sorted(set(input('enter the word: ').rstrip('\\r\\n')))\n\ndef gen_permutations(ent):\n tuples = map(lambda i: itertools.permutations(ent,i), range(MIN_LEN,len(ent)+1))\n arrr= [[\"\".join(j) for j in i] for i in tuples]\n return list(itertools.chain(*arrr))\n\ndef filter_dict(words):\n return [x for x in words if uk.check(x) or us.check(x)]\n\nfor i in filter_dict(gen_permutations(get_input())):\n print i\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T20:31:17.367",
"Id": "17829",
"Score": "0",
"body": "you could probably speed this implementation up by declaring `uk` and `us` outside of `filter_dict` and by not writing to the screen (see http://stackoverflow.com/questions/3857052/why-is-printing-to-stdout-so-slow-can-it-be-sped-up)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T23:51:13.860",
"Id": "11153",
"ParentId": "11151",
"Score": "3"
}
},
{
"body": "<p>I don't have enough karma (or whatever that's called) to comment on blufox's answer so...</p>\n\n<ul>\n<li><p>do what he says;</p></li>\n<li><p>but... don't use <code>input</code> use <code>raw_input</code> (you don't want to <code>eval</code> the input, right...)</p></li>\n<li><p>don't make it a <code>set</code> unless you don't mind losing letter repetitions</p></li>\n<li><p>don't build the lists, keep generators...</p></li>\n</ul>\n\n<p>the (PEP8-compatible) result:</p>\n\n<pre><code>import itertools\nimport enchant\n\nMIN_LEN = 3\nuk = enchant.Dict(\"en_UK\")\nus = enchant.Dict(\"en_US\")\n\n\ndef get_input():\n return raw_input('enter the word: ').rstrip('\\r\\n')\n\n\ndef gen_permutations(ent):\n perms = map(lambda i: itertools.permutations(ent, i),\n range(MIN_LEN, len(ent) + 1))\n return (\"\".join(tup) for perm in perms for tup in perm)\n\n\ndef filter_dict(words):\n return (x for x in words if uk.check(x) or us.check(x))\n\n\ndef test(word):\n for i in filter_dict(gen_permutations(word)):\n # print i\n pass\n\n\nif __name__ == '__main__':\n # from timeit import Timer\n word = get_input()\n test(word)\n # t = Timer(\"test(word)\", \"from __main__ import test, word\")\n # print t.timeit(number=500)\n</code></pre>\n\n<p>Timed with <code>timeit</code> without printing (replaced by <code>pass</code>) and without filtering (I don't want to install enchant) I get a few % lower time but mostly much less memory (the original version will use hundreds of Mb for a 10-letter word, whereas you don't need more than a few ones...).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T22:11:51.983",
"Id": "17837",
"Score": "0",
"body": "actually i am using python 3.2 so i've to use input() instead of raw_input().\nThanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T22:41:30.543",
"Id": "17839",
"Score": "0",
"body": "I agree with 2&3 :) for the first, I noticed she was running 3.2 after trying to run her example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T18:26:39.793",
"Id": "18008",
"Score": "0",
"body": "Ah, sorry for the 2to3 mistake ;)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T22:00:19.547",
"Id": "11178",
"ParentId": "11151",
"Score": "2"
}
},
{
"body": "<p>1) Since all the permutations produced by <code>itertools.permutations()</code> are unique, there's no need to check for list membership in possible_words. </p>\n\n<p>2) the permutations produced by itertools.permutations() in your (unnecessary) while loop are already ordered by length, so you don't need to sort the results, merely reverse them.</p>\n\n<p>3) you can combine the US and UK dictionary lookups into one if statement.</p>\n\n<p>In fact, it's possible to compress the entire lower half of your code comfortably into two lines:</p>\n\n<pre><code>word_perms = (\"\".join(j) for k in range(1, len(ent) + 1) for j in permutations(ent, k))\npossible_words = reversed([i for i in word_perms if us.check(i) or uk.check(i)])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-29T13:36:06.603",
"Id": "11308",
"ParentId": "11151",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "11308",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T23:28:46.127",
"Id": "11151",
"Score": "1",
"Tags": [
"python",
"optimization",
"algorithm",
"performance"
],
"Title": "Returning all possible English dictionary words that can be formed out of a string"
}
|
11151
|
<p>We implement a C++ class <code>Proposition</code> that represents a (possibly compound) propositional logic statement made up of named atomic variables combined with the operators AND, OR, NOT, IMPLIES and IFF.</p>
<p>We then use it to find all the truth assignments of the following proposition:</p>
<blockquote>
<p>((A and not B) implies C) and ((not A) iff (B and C))</p>
</blockquote>
<p>Once everything is defined, the snippet of C++ code that evaluates this proposition is:</p>
<pre><code>auto proposition = ("A"_var && !"B"_var).implies("C"_var) &&
(!"A"_var).iff("B"_var && "C"_var);
auto truth_assignments = proposition.evaluate_all({"A", "B", "C"});
</code></pre>
<p>Language features used include polymorphism, implicit sharing, recursive data types, operator overloading and (new in C++ 2011 and gcc 4.7) user-defined literals.</p>
<pre><code>// (C) 2012, Andrew Tomazos <andrew@tomazos.com>. Public domain.
#include <cassert>
#include <memory>
#include <set>
#include <vector>
#include <string>
#include <iostream>
using namespace std;
struct Proposition;
// The expression...
//
// "foo"_var
//
// ...creates an atomic proposition variable with the name 'foo'
Proposition operator"" _var (const char*, size_t);
// Represents a compound proposition
struct Proposition
{
// A.implies(B): means that A (antecendant) implies ==> B (consequent)
Proposition implies(const Proposition& consequent) const;
// A.iff(B): implies that A and B form an equivalence. A <==> B
Proposition iff(const Proposition& equivalent) const;
// !A: the negation of target A
Proposition operator!() const;
// A && B: the conjunction of A and B
Proposition operator&&(const Proposition& conjunct) const;
// A || B: the disjunction of A and B
Proposition operator||(const Proposition& disjunct) const;
// A.evaluate(T): Given a set T of variable names that are true (a truth assignment),
// will return the truth {true, false} of the proposition
bool evaluate(const set<string>& truth_assignment) const;
// A.evaluate_all(S): Given a set S of variables,
// will return the set of truth assignments that make this proposition true
set<set<string>> evaluate_all(const set<string>& variables) const;
private:
struct Base { virtual bool evaluate(const set<string>& truth_assignment) const = 0; };
typedef shared_ptr<Base> pointer;
pointer value;
Proposition(const pointer& value_) : value(value_) {}
struct Variable : Base
{
string name;
virtual bool evaluate(const set<string>& truth_assignment) const
{
return truth_assignment.count(name);
}
};
struct Negation : Base
{
pointer target;
bool evaluate(const set<string>& truth_assignment) const
{
return !target->evaluate(truth_assignment);
}
};
struct Conjunction : Base
{
pointer first_conjunct, second_conjunct;
bool evaluate(const set<string>& truth_assignment) const
{
return first_conjunct->evaluate(truth_assignment)
&& second_conjunct->evaluate(truth_assignment);
}
};
struct Disjunction : Base
{
pointer first_disjunct, second_disjunct;
bool evaluate(const set<string>& truth_assignment) const
{
return first_disjunct->evaluate(truth_assignment)
|| second_disjunct->evaluate(truth_assignment);
}
};
friend Proposition operator"" _var (const char* name, size_t sz);
};
Proposition operator"" _var (const char* name, size_t sz)
{
auto variable = make_shared<Proposition::Variable>();
variable->name = string(name, sz);
return { variable };
}
Proposition Proposition::implies(const Proposition& consequent) const
{
return (!*this) || consequent;
};
Proposition Proposition::iff(const Proposition& equivalent) const
{
return this->implies(equivalent) && equivalent.implies(*this);
}
Proposition Proposition::operator!() const
{
auto negation = make_shared<Negation>();
negation->target = value;
return { negation };
}
Proposition Proposition::operator&&(const Proposition& conjunct) const
{
auto conjunction = make_shared<Conjunction>();
conjunction->first_conjunct = value;
conjunction->second_conjunct = conjunct.value;
return { conjunction };
}
Proposition Proposition::operator||(const Proposition& disjunct) const
{
auto disjunction = make_shared<Disjunction>();
disjunction->first_disjunct = value;
disjunction->second_disjunct = disjunct.value;
return { disjunction };
}
bool Proposition::evaluate(const set<string>& truth_assignment) const
{
return value->evaluate(truth_assignment);
}
set<set<string>> Proposition::evaluate_all(const set<string>& variables) const
{
set<set<string>> truth_assignments;
vector<string> V(variables.begin(), variables.end());
size_t N = V.size();
for (size_t i = 0; i < (size_t(1) << N); ++i)
{
set<string> truth_assignment;
for (size_t j = 0; j < N; ++j)
if (i & (1 << j))
truth_assignment.insert(V[j]);
if (evaluate(truth_assignment))
truth_assignments.insert(truth_assignment);
}
return truth_assignments;
}
int main()
{
assert( ("foo"_var) .evaluate({"foo"})); // trivially true
assert( ("foo"_var) .evaluate_all({"foo"})
== set<set<string>> {{"foo"}} );
assert( (!"foo"_var) .evaluate({})); // basic negation
assert(! (!"foo"_var) .evaluate({"foo"})); // basic negation
assert( (!"foo"_var) .evaluate_all({"foo"})
== set<set<string>> {{}} );
assert( (!!"foo"_var) .evaluate({"foo"})); // double negation
assert( (!!"foo"_var) .evaluate_all({"foo"})
== set<set<string>> {{"foo"}} );
assert( ("foo"_var && "bar"_var) .evaluate({"foo", "bar"})); // conjunction
assert(! ("foo"_var && "bar"_var) .evaluate({"bar"})); // conjunction
assert(! ("foo"_var && "bar"_var) .evaluate({"foo"})); // conjunction
assert(! ("foo"_var && "bar"_var) .evaluate({})); // conjunction
assert( ("foo"_var && "bar"_var) .evaluate_all({"foo", "bar"})
== set<set<string>>({{"foo", "bar"}}));
assert( ("foo"_var || "bar"_var) .evaluate({"foo", "bar"})); // disjunction
assert( ("foo"_var || "bar"_var) .evaluate({"bar"})); // disjunction
assert( ("foo"_var || "bar"_var) .evaluate({"foo"})); // disjunction
assert(! ("foo"_var || "bar"_var) .evaluate({})); // disjunction
assert( ("foo"_var || "bar"_var) .evaluate_all({"foo", "bar"})
== set<set<string>>({{"foo", "bar"}, {"foo"}, {"bar"}}));
assert( ("foo"_var.implies("bar"_var)) .evaluate({"foo", "bar"})); // implication
assert( ("foo"_var.implies("bar"_var)) .evaluate({"bar"})); // implication
assert(! ("foo"_var.implies("bar"_var)) .evaluate({"foo"})); // implication
assert( ("foo"_var.implies("bar"_var)) .evaluate({})); // implication
assert( ("foo"_var.implies("bar"_var)) .evaluate_all({"foo", "bar"})
== set<set<string>>({{"foo", "bar"}, {"bar"}, {}}));
assert( ("foo"_var.iff("bar"_var)) .evaluate({"foo", "bar"})); // equivalence
assert(! ("foo"_var.iff("bar"_var)) .evaluate({"bar"})); // equivalence
assert(! ("foo"_var.iff("bar"_var)) .evaluate({"foo"})); //equivalence
assert( ("foo"_var.iff("bar"_var)) .evaluate({})); // equivalence
assert( ("foo"_var.iff("bar"_var)) .evaluate_all({"foo", "bar"})
== set<set<string>>({{"foo", "bar"}, {}}));
cout << "((A and not B) implies C) and ((not A) iff (B and C)):" << endl << endl;
auto proposition = ("A"_var && !"B"_var).implies("C"_var) && (!"A"_var).iff("B"_var && "C"_var);
auto truth_assignments = proposition.evaluate_all({"A", "B", "C"});
cout << "A B C" << endl;
cout << "-----------" << endl;
for (auto truth_assignment : truth_assignments)
{
for (auto variable : {"A", "B", "C"})
cout << (truth_assignment.count(variable) ? "1" : "0") << " ";
cout << endl;
}
}
</code></pre>
<p>The output is as follows:</p>
<pre><code>((A and not B) implies C) and ((not A) iff (B and C)):
A B C
-----------
1 1 0
1 0 1
0 1 1
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-11T13:43:31.743",
"Id": "453245",
"Score": "0",
"body": "There are no reasons for this question to have close votes without a comment, it seems to be working and the context is perfectly clear."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-04-25T01:13:01.590",
"Id": "11154",
"Score": "4",
"Tags": [
"c++",
"c++11"
],
"Title": "Propositional Logic: Proposition Evaluator"
}
|
11154
|
<p>I have written a helper method which computes the sum of values in some custom grid, given the column indexes. The method appears to work (for a decimal - as Anthony pointed out, I need to test this further), but I am not at ease with the following conversions:</p>
<pre><code>decimal valIfNull = (decimal)(object)valueIfNull;
return (T)(object)sum;
</code></pre>
<p>They seem too indirect, but <code>Convert.ChangeType</code> also returns an <code>object</code> type, so another cast is needed anyway. Also, I believe that <code>Convert.ChangeType</code> can convert a string such as "123.456" into a proper decimal value, but this is not the behavior I want in this case. I would like to see an invalid cast exception in that case. So, is what I have good enough, or is there a better way?</p>
<pre><code> private T SumColumns<T>(T valueIfNull, params short[] columnIndexes)
where T : struct, IConvertible
{
// Since we do not know what exactly T is, we will compute things as if it was a decimal.
// If this works reasonably well, then this trick should be used elsewhere.
// I am not sure if this is the best way to go about casting
decimal valIfNull = (decimal)(object)valueIfNull;
// Here this.GetCurrentRowValue<decimal> is another generic function I wrote ...
decimal sum = columnIndexes.Select(columnIndex => this.GetCurrentRowValue<decimal>(columnIndex: columnIndex, valueIfNull: valIfNull)).Sum();
return (T)(object)sum;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T01:27:43.053",
"Id": "17777",
"Score": "2",
"body": "Your method is not going to work if `T` is not `decimal`. When you box a value type, you can only unbox to the same type (or its nullable counterpart). For example, given `long L = long.MaxValue;`, you could not have `(decimal)(object)L;`"
}
] |
[
{
"body": "<p>You've already placed a constraint on the first parameter that it should be <code>IConvertible</code>, so the methods of that interface is available to you.</p>\n\n<pre><code>decimal decimalValueIfNull = valueIfNull.ToDecimal(CultureInfo.InvariantCulture);\n</code></pre>\n\n<p>Converting back to the generic type won't be as straight forward. When casting between an <code>object</code> and a value type, no conversions will be made and you are just boxing/unboxing the value. Since you have a constraint that the type be a value type, the casts won't really work here. In fact, I don't think it's even possible to do so generically. If a conversion exists from <code>decimal</code> to the type you wouldn't be able to express that here. And you won't be able to use the Convert class to do the conversion, there's no way to \"add\" conversions to existing convertible types.</p>\n\n<p>Your best (and probably only) option would be to convert it to a <code>dynamic</code> variable and let the runtime figure out whether or not that conversion exists. That way if you have a custom <code>ValueType</code> here that has an implicit or explicit conversion from a <code>decimal</code>, it will be used.</p>\n\n<pre><code>return (T)(dynamic)sum;\n</code></pre>\n\n<p>If you know for sure that the types that are used here can be converted from a <code>decimal</code>, then you could convert back using <code>IConvertible.ToType()</code>.</p>\n\n<pre><code>return ((IConvertible)sum).ToType(typeof(T), CultureInfo.InvariantCulture);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T08:08:03.523",
"Id": "17796",
"Score": "0",
"body": "Why not use `IConvertible.ToType()` for the conversion back?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T13:44:35.300",
"Id": "17802",
"Score": "0",
"body": "If `T` was a custom type (and not a builtin), the conversion would fail always since `IConvertible.ToType()` only considers the conversions defined by the object that implemented the interface. `decimal` will not have a conversion defined for your custom object and as I mentioned, it's not possible to add a conversion. This approach ensures that if the custom type provided a conversion from a `decimal`, it will be used."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T15:51:25.130",
"Id": "17807",
"Score": "0",
"body": "Jeff, thanks a bunch. I do not plan on using a custom IConvertible type here. By the way, I have to supply an `IFormatProvider` to the `ToDecimal` method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T15:58:37.273",
"Id": "17808",
"Score": "0",
"body": "@svick, did you mean `Convert.ChangeType`? I was not sure how to invoke `IConvertible.ToType()` on my `decimal sum`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T18:13:57.927",
"Id": "17818",
"Score": "0",
"body": "@Leonid: You would need to cast the `decimal` to `IConvertible` to be able to invoke that method. I'll include that detail in the answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T19:41:05.903",
"Id": "17825",
"Score": "0",
"body": "You could use `TypeDescriptor.GetConverter()`"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T05:15:58.667",
"Id": "11160",
"ParentId": "11156",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T01:20:35.810",
"Id": "11156",
"Score": "3",
"Tags": [
"c#",
"casting"
],
"Title": "Computing value sums in a custom grid"
}
|
11156
|
<p>I come from a Java background so my desire for proper unambiguous logging is strong. I prefer using the console to using some other gui widget however, in the browser I know that I can't always count on the console to exist or for it to have all the levels I might like. To remedy this I worked up the following console sanitizer and I was curious what drawbacks it might have.</p>
<pre><code>function configureConsoleLog() {
"use strict";
var logMethods = [ 'trace', 'debug', 'log', 'info', 'warn', 'error' ], i;
if (!window.console) {
window.console = {log: function (args) {}}; //noop
}
for (i = 0; i < logMethods.length; i += 1) {
if (!window.console[logMethods[i]]) {
window.console[logMethods[i]] = window.console.log;
}
}
}
</code></pre>
<p>The idea is to find out if console exists and if it does try to find out which of the supported levels I need are available. The first level of fallback is to map unsupported methods to console.log. The second level is to create my own console variable and make a noop log function since I have nowhere to send the output. This approach leaves open the possibility of coming up with a different strategy if console doesn't exist but for now I'm content to ignore logging if there is no console. </p>
<p>As a side note I looked at several JS logging packages but all of them have the fatal drawback of obscuring original line numbers, usually by delegating to a console method which only reports the line number of the delegating statement.</p>
<p>Thoughts? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T04:32:04.743",
"Id": "17791",
"Score": "0",
"body": "I think I saw a really good discussion of this exact problem. Perhaps on StackExchange - did you check there?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T04:33:52.290",
"Id": "17792",
"Score": "0",
"body": "I have searched a bit but couldn't find anything that matched my problem. However, I will take another look on SO."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T15:46:41.873",
"Id": "17805",
"Score": "0",
"body": "The post I saw was this one: http://stackoverflow.com/questions/690251/what-happened-to-console-log-in-ie8 (I meant StackOverflow in my comment)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T16:56:01.437",
"Id": "17811",
"Score": "0",
"body": "Looks like the advice is consistent with my approach, thanks for the pointer."
}
] |
[
{
"body": "<p>I don't see any problems with that. It's similar to <a href=\"https://stackoverflow.com/a/3265752/1100355\">this answer on SO</a>.</p>\n\n<p>Just a couple minor things:</p>\n\n<ul>\n<li><p>You don't need <code>args</code> in the empty <code>log</code> function</p></li>\n<li><p>You should make the entire function anonymous and execute it immediately (as it's being done in the answer I linked to); I don't think there's any usecase for calling it otherwise</p></li>\n<li><p>Don't forget <code>var</code> in front of the <code>i</code> variable, otherwise it becomes global</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T16:52:56.743",
"Id": "17809",
"Score": "0",
"body": "First, thanks for the tips! I think args was actually vestigial and definitely should be removed. This particular function is being called from inside of another framework as a part of a config/bootstrap process so it works best as a function in this case. Lastly, the i variable is declared at the top of the function (jslint enforced), it's just hanging on the end of the array initialization, probably should be moved to the front so it doesn't get lost."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T16:55:16.143",
"Id": "17810",
"Score": "0",
"body": "@adambender: ah yeah, I missed the `i` at the end :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T15:41:28.960",
"Id": "11168",
"ParentId": "11159",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "11168",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T04:28:52.563",
"Id": "11159",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Safely using console.* in browser"
}
|
11159
|
<p>I've been working some forth looking on design patterns, and I would like some help to improve the code (fixes, tips, just generally improvements, or things you consider bad practise, etcetera in my code).</p>
<p>And finally: Am I on the right track, or should just back the wheel and start over?</p>
<p>UserMapper</p>
<pre><code><?php
class UserMapper {
protected $db;
function __construct($db)
{
$this->db = $db;
}
public function save(User $user_object)
{
$data = array(
'username' => $user_object->username,
'email' => $user_object->email,
'password' => $user_object->password,
);
if (is_null($user_object->id)) {
$data['salt'] = $user_object->salt;
$data['created'] = time();
$sth = $this->db->prepare("INSERT INTO users (username, email, password, salt, created) VALUES (:username, :email, :password, :salt, :created)");
$sth->execute($data);
} else {
$data['id'] = $user_object->id;
$sth = $this->db->prepare("UPDATE `users` SET username = :username, email = :email, password = :password WHERE `id` = :id");
$sth->execute($data);
}
}
public function getUserById($id)
{
$sth = $this->db->prepare("SELECT * FROM users WHERE id = ?");
$sth->execute(array($id));
$sth->setFetchMode(PDO::FETCH_OBJ);
if ($sth->rowCount() == 0) {
throw new Exception('User not found');
}
$row = $sth->fetch();
$user_object = new User($row);
return $user_object;
}
}
?>
</code></pre>
<p>User:</p>
<pre><code><?php
class User {
private $id;
private $username;
private $email;
private $password;
private $salt;
private $created;
public function __construct($user_row = null)
{
if (!is_null($user_row)) {
$this->id = $user_row->id;
$this->username = $user_row->username;
$this->email = $user_row->email;
$this->password = $user_row->password;
$this->salt = $user_row->salt;
$this->created = $user_row->created;
}
}
public function __set($name, $value)
{
switch ($name) {
case 'password':
$value = sha1($value . $this->salt);
break;
}
$this->$name = $value;
}
public function __get($name)
{
return $this->$name;
}
}
</code></pre>
<p>Auth...</p>
<p>A empty class with logged_in, login, logout, methods.</p>
<p>function save(User $user)
{
$data = array();</p>
<pre><code>$data['username'] = $user->username;
$data['password'] = $user->password;
if (is_null($user->id)) {
$data['salt'] = $user->salt;
$columns = implode(', ', array_keys($data));
$values = implode(', :', array_keys($data));
try {
$sth = $this->db->prepare("INSERT INTO `users` ($columns) VALUES (:$values)");
$sth->execute($data);
} catch (PDOException $e) {
echo $e->getMessage();
}
} else {
$data['id'] = $user->id;
$dataSet = '';
foreach (array_keys($data) as $key) {
$dataSet .= "$key = :$key, ";
}
$sth = $this->db->prepare("UPDATE `users` SET $dataSet WHERE `id` = :id");
$sth->execute($data);
}
</code></pre>
<p>}</p>
<p>test: (all files needed included)</p>
<pre><code>$host = 'localhost';
$dbname = 'code';
$user = 'root';
$pass = '';
try {
$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch(PDOException $e) {
echo $e->getMessage();
}
$user = new User;
$user->username = 'A123123ro';
$user->password = 'h1231233';
$user->salt = 'hej';
$user->email = 'j213123e';
$user_mapper = new UserMapper($db);
$user_mapper->save($user);
</code></pre>
|
[] |
[
{
"body": "<p>There's no verification that the sql was executed correctly in your <code>UserMapper::save</code> method. It just assumes that everything went ok after <code>execute</code> (actually all your <code>execute</code> calls go un-checked). Always verify your results. You should at the very least be wrapping all your pdo executes in <code>if</code> statements as it returns <code>true</code> or <code>false</code> as stated in the <a href=\"http://php.net/manual/en/pdostatement.execute.php\" rel=\"nofollow\">php pdo docs</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T09:03:40.330",
"Id": "17865",
"Score": "0",
"body": "Can you give me some tips on verification?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T16:26:00.030",
"Id": "11169",
"ParentId": "11163",
"Score": "0"
}
},
{
"body": "<p>Not much \"wrong\" that I can see. Maybe a couple of improvements.</p>\n\n<p>I just did the following with another post and liked how it turned out. It looks cleaner to me and requires less repitition. After <code>$data</code> is completely set, do the following.</p>\n\n<pre><code>$users = implode(',', array_keys($data));\n$values = implode(',:', array_keys($data));\n\n$sth = $this->db->prepare(\"INSERT INTO users ($users) VALUES (:$values)\");\n</code></pre>\n\n<p>And, if you do the following after you initially set the <code>$data</code> array, but before you add anything else to it, it will only have the values you want to use in your SQL <code>SET</code> statement. So you can use that to set that string as well. It wont hurt anything to have this set even if it isn't used, so don't worry about putting it in an if/else statement.</p>\n\n<pre><code>$dataSet = array();\nforeach(array_keys($data) as $key) {\n $dataSet[] = \"$key = :$key\";\n}\n$dataSet = implode(',', $dataSet);\n</code></pre>\n\n<p>Finally, I would set up the user information in the User class to use an array rather than numerous variables. It will make it easier to access and more extensible if you were to ever add another field to it later. And doesn't require too much change to your current code.</p>\n\n<pre><code>public $userInfo = array();\n\npublic function __construct($user_row = null)\n{\n if (!is_null($user_row)) {\n foreach($user_row as $key => $value) {\n $this->userInfo[$key] = $value;\n }\n }\n}\n</code></pre>\n\n<p>So you'd then do the following in UserMapper to access it. Of course there are a few other minor changes you'll have to do, but I'm sure you will spot them.</p>\n\n<pre><code>$data = $user_object->userInfo;\n</code></pre>\n\n<p>And of course this last suggestion will mean that the <code>$dataSet</code> suggestion I mentioned above wont work anymore. You can either set a new array for this information, or find some way of separating it from the new array, or you could just go back to manually typing it. If I think of anything for this, I'll let you know :)</p>\n\n<p>Final thoughts: If you are going to be overloading the get and set methods for the User class, why did you bother making the variables private? Just make them public, then you won't need to overload the get method and can continue to use your set method. Of course this is just a thought, I don't know if what you are doing makes sense for your program, or if there are other benefits of doing it this way. To me though, it just seems a little pointless. Good luck!</p>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>Here's one last thing I noticed, in your <code>save()</code> function you use the <code>prepare()</code> and <code>execute()</code> functions twice, merely separated by an if/else statement. This is redundant, you could just save the SQL statement as a string and then run it once at the end of the function.</p>\n\n<pre><code>if(is_null($user->id)) {\n //rest of code\n $statement = \"INSERT INTO `users` ($columns) VALUES (:$values)\";\n //rest of code\n} else {\n //rest of code\n $statement = \"UPDATE `users` SET $dataSet WHERE `id` = :id\";\n //rest of code\n}\n\n$sth = $this->db->prepare($statement);\n$sth->execute($data);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T09:02:20.253",
"Id": "17864",
"Score": "0",
"body": "Thanks for the feedback, I will consider your points well, but do you think my script make sense, is it something I can go and continue develop on? Is it a smartway ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T12:59:20.427",
"Id": "17972",
"Score": "0",
"body": "@John: Yes, what you have is perfectly fine. I was only pointing out a few things that would make expanding it easier. You should take a look at some of my other answers on this site, yours is by far the smallest because there was little to add :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:50:20.940",
"Id": "17976",
"Score": "0",
"body": "Does it make sense to have an Auth class, with the log in, forgot password, etcetra methods, or should i rather put them in UserMapper class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T16:10:30.437",
"Id": "17984",
"Score": "0",
"body": "Also a problem with the UPDATE, would be: UPDATE `users` SET username = :username, password = :password, WHERE `id` = :id as you can see there is a comma after the last SET value.. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T16:20:18.477",
"Id": "17987",
"Score": "0",
"body": "I would add those methods to the UserMapper class as that class is already accessing the database and doing tasks that will be necessary for both. But that is just me, its really up to you. Sorry about that UPDATE bit, I have updated that to a workable solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T16:26:58.547",
"Id": "17988",
"Score": "0",
"body": "If you have a look now, smething is going crazy, the INSERT it doesnt give me any erros, nor does it insert the data, what is wrong? Updated my post"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T16:57:08.367",
"Id": "17991",
"Score": "0",
"body": "@John: Have you double checked the output of `$columns` and `$values`? I'll take another swing at it in a bit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T17:11:52.407",
"Id": "17997",
"Score": "0",
"body": "$data['username'] = 'Aventro';\n\n\n $sth = $db->prepare(\"INSERT INTO users(username) VALUES(:username)\");\n $sth->execute($data);"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T17:12:10.517",
"Id": "17998",
"Score": "0",
"body": "Unless its a error in that code, I believe something else is messing up..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T17:14:09.250",
"Id": "17999",
"Score": "0",
"body": "Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 1364 Field 'password' doesn't have a default value' in C:\\xampp\\htdocs\\code\\try.php:31 Stack trace: #0 C:\\xampp\\htdocs\\code\\try.php(31): PDOStatement->execute(Array) #1 {main} thrown in C:\\xampp\\htdocs\\code\\try.php on line 31"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T17:14:47.627",
"Id": "18000",
"Score": "0",
"body": "Is the error I get on the code above in my comments"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T18:06:00.810",
"Id": "18003",
"Score": "0",
"body": "@John: From the looks of it, your code isthrowing errors if certain fields are not passed to the `prepare()` function. Try passing all the fields you were originally to see if that works. Currently you are only passing the username."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T18:09:50.727",
"Id": "18005",
"Score": "0",
"body": "I also notice you do not have the `$data['created']` field anymore."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T18:20:47.717",
"Id": "18007",
"Score": "0",
"body": "@John: One last thing, I added an update to the bottom of my answer for another improvement for your `save()` function. Its minor, but while looking at your revisions it occurred to me to mention it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T19:04:14.183",
"Id": "18012",
"Score": "0",
"body": "But that code was just sample data: like this $data = array();\n\n$data['username'] = 'Aventro';\n\nprint_r($data);\n\n\n $sth = $db->prepare(\"INSERT INTO users(username) VALUES(:username)\");\n $sth->execute($data);"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T08:57:04.830",
"Id": "18048",
"Score": "0",
"body": "I think I have solved the problem, I think I somehow was connected to the wrong database server, :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T09:16:37.100",
"Id": "18049",
"Score": "0",
"body": "What do you think about the getUserById() method and do you think I should rethrow the error in the class, and then catch it outside when i use the method? :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T12:58:14.140",
"Id": "18054",
"Score": "0",
"body": "I'd maybe get rid of the `$user_object` variable seen as its not used and just return the `new User()` bit. Otherwise it looks fine. As for throwing/catching errors, that is a matter of preference. I know I like to separate my HTML and PHP as much as possible so I would throw the error in my model like you are currently then do the try/catch block in my controller and pass any relevant information to the view so that I could process it into the correct HTML output for such eventualities."
}
],
"meta_data": {
"CommentCount": "18",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T17:03:45.250",
"Id": "11170",
"ParentId": "11163",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T11:55:14.380",
"Id": "11163",
"Score": "0",
"Tags": [
"php",
"sql",
"pdo"
],
"Title": "User lib php v2"
}
|
11163
|
<p>The following code is part a class called <code>class db_tables</code>. All the other <code>getTbl*</code> methods other than <code>getTblHerd</code> pull information based on the ID of the animal that is passed to them.<BR></p>
<p>My question is while the following code works would it be better to move all the other <code>getTbl</code> methods into the <code>Animal</code> class and pass them the ID stored in the Animal class.
<BR>
Thanks,<BR></p>
<pre><code>public static ArrayList<Animal> getTblHerd() throws Exception {
CC_H2 db = new CC_H2();
db.Connect(Variables.getStrConn(), Variables.getStrUser(),
Variables.getStrPassword(), "Embedded");
ResultSet rs = db
.query("Select HERD_ID FROM tblHerd ORDER BY HERD_ID ASC");
ArrayList<Animal> alAnimals = new ArrayList<Animal>();
while (rs.next()) {
int i = rs.getInt("HERD_ID");
alAnimals.add(new Animal(i));
}
db.Disconnect();
return alAnimals;
}
public static ArrayList<Note> getTblNotes(int intID) throws Exception {
CC_H2 db = new CC_H2();
db.Connect(Variables.getStrConn(), Variables.getStrUser(),
Variables.getStrPassword(), "Embedded");
ResultSet rs = db
.query("Select NOTE_ID FROM tblNotes WHERE NOTE_HERD_ID = "
+ intID + " ORDER BY Note_Date DESC");
ArrayList<Note> alNotes = new ArrayList<Note>();
while (rs.next()) {
int i = rs.getInt("NOTE_ID");
alNotes.add(new Note(i));
}
db.Disconnect();
return alNotes;
}
public static ArrayList<Vaccination> getTblVaccination(int intID) throws Exception {
CC_H2 db = new CC_H2();
db.Connect(Variables.getStrConn(), Variables.getStrUser(),
Variables.getStrPassword(), "Embedded");
ResultSet rs = db
.query("Select Vac_ID FROM tblVaccination WHERE VAC_HERD_ID = "
+ intID + " ORDER BY Vac_Date DESC");
ArrayList<Vaccination> alVaccinations = new ArrayList<Vaccination>();
while (rs.next()) {
int i = rs.getInt("VAC_ID");
alVaccinations.add(new Vaccination(i));
}
db.Disconnect();
return alVaccinations;
}
public static ArrayList<Owner> getTblOwners(int intID) throws Exception {
CC_H2 db = new CC_H2();
db.Connect(Variables.getStrConn(), Variables.getStrUser(),
Variables.getStrPassword(), "Embedded");
ResultSet rs = db
.query("Select Owner_ID FROM tblOwners WHERE Owner_ID = "
+ intID + " ORDER BY Owner_Last_Name ASC");
ArrayList<Owner> alOwners = new ArrayList<Owner>();
while (rs.next()) {
int i = rs.getInt("Owner_ID");
alOwners.add(new Owner(i));
}
db.Disconnect();
return alOwners;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T10:00:58.470",
"Id": "17870",
"Score": "0",
"body": "Small note: [Classes in Java are normally in UpperCamelCase](http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141270.html#381), of course there are exceptions to that, but I just want you to know."
}
] |
[
{
"body": "<p>Well, Your code looks good, and your suspicion seems right. I would agree with you. My reasoning is that your objects should be modeled after the problem rather than the data base schema. Here I would say that the other <code>getTbl*</code> methods are actually getters on particular animals. So it makes sense to move them to Animal class and rename the <code>getTbl*</code> methods accordingly, i.e <code>getAnimalVaccinationList</code>.</p>\n\n<p>I would also recommend to refactor all these methods so that the db connect, and processing are in a different method,</p>\n\n<pre><code>public static ArrayList<Integer> runDbQuery(String query, String field) throws DbException {\n try {\n CC_H2 db = new CC_H2();\n db.Connect(Variables.getStrConn(), Variables.getStrUser(),\n Variables.getStrPassword(), \"Embedded\");\n ResultSet rs = db.query(query);\n ArrayList<Integer> lst = new ArrayList<Integer>();\n while (rs.next()) {\n lst.add(new Vaccination(rs.getInt(field)));\n }\n db.Disconnect();\n return lst;\n } catch(SpecificException e) {\n // Do not throw exception, process the exception and throw\n // some thing relevant to your program.\n throw new DbException(e);\n }\n}\n</code></pre>\n\n<p>and use this in other methods to avoid repetition. I would also recommend moving the getTblHerd to another class - say Herd because it has an independent identity other than db_tables.</p>\n\n<p>Here is an example of using the above method</p>\n\n<pre><code>public static ArrayList<Note> getTblNotes(int intID) throws DbException {\n String query = \"Select NOTE_ID FROM tblNotes WHERE NOTE_HERD_ID = \"\n + intID + \" ORDER BY Note_Date DESC\";\n\n ArrayList<Note> alNotes = new ArrayList<Note>();\n for (Integer i : runQuery(query, \"NOTE_ID\")) { \n alNotes.add(new Note(i));\n }\n return alNotes;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T14:48:12.677",
"Id": "11166",
"ParentId": "11165",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "11166",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T14:09:01.010",
"Id": "11165",
"Score": "2",
"Tags": [
"java"
],
"Title": "Should I Move Methods To A Different Class"
}
|
11165
|
<p>i do have two dimentional array of data in php. </p>
<p>I do want to add another column with constant to that array for passing tabular data to next program.</p>
<p>i am iterating and adding manually. What can be alternate code?</p>
<p>my code:</p>
<pre><code> if( is_array( $arrSource )){
foreach( $arrSource as &$dataRow){
foreach( $arrColumn as $k=>$v)
$dataRow[$k] = $v;
}
unset( $dataRow );
}
</code></pre>
|
[] |
[
{
"body": "<p>I see nothing wrong with what you already have. Assuming of course that you meant to append identical data to each <code>$arrSource</code> element. You are already doing the shorthand by using the reference operator. The only other way would be to write it all out manually, which would be pointless, unless you are looking for more novice readable code. I would hesitate to add, however, that unset should be called tithin the first foreach loop. Though I could not confirm 100% because I don't use the reference operator to know its quirks :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T18:26:24.697",
"Id": "11173",
"ParentId": "11171",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "11173",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T18:01:35.730",
"Id": "11171",
"Score": "1",
"Tags": [
"php",
"array"
],
"Title": "PHP Add Column to two dimentional array"
}
|
11171
|
<p>I wanted a pattern to manage web.config appsettings. I want to be able to have a default setting if the config setting was missing. I also wanted the check for the value in the config file to happen only once, not each time the the value is retrieved.</p>
<pre><code>Public NotInheritable Class ExternalReportRequestBL
''' <summary>
''' The default value for max number of request attempts
''' </summary>
''' <remarks></remarks>
Private Shared _ReportRequestMaxExecuteAttemptDefault As Integer
Shared Sub New()
If Not Integer.TryParse(ConfigurationManager.AppSettings("ReportRequestMaxExecuteAttempt"), ExternalReportRequestBL._ReportRequestMaxExecuteAttemptDefault) Then
_ReportRequestMaxExecuteAttemptDefault = 10
End If
End Sub
Friend Shared ReadOnly Property MaxNumberOfTries As Integer
Get
Return ExternalReportRequestBL._ReportRequestMaxExecuteAttemptDefault
End Get
End Property
End Class
</code></pre>
<p>Now, I can access the variable from anywhere in the assembly:</p>
<pre><code>ExternalReportRequestBL.MaxNumberOfTries
</code></pre>
<p>What are your thoughts?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-15T13:58:51.980",
"Id": "240117",
"Score": "0",
"body": "May I ask what lend you to wanting this? Typically, those settings are specifically for specifying defaults and configuration settings. I'm smelling an XY problem, but I don't yet understand what your real problem is."
}
] |
[
{
"body": "<p><code>Integer.TryParse</code> will overwrite the value of that shared property with 0 if the value is not there. Use something like this instead:</p>\n\n<pre><code>Shared Sub New()\n Dim parsed As Integer\n If Integer.TryParse(ConfigurationManager.AppSettings(\"ReportRequestMaxExecuteAttempt\"), parsed) Then\n _ReportRequestMaxExecuteAttemptDefault = parsed\n End If\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T23:47:21.853",
"Id": "18027",
"Score": "0",
"body": "You are correct. Changed my question accordingly."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T23:36:47.840",
"Id": "11239",
"ParentId": "11180",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T00:11:43.817",
"Id": "11180",
"Score": "1",
"Tags": [
"asp.net",
"vb.net"
],
"Title": "Managing web.config appSettings"
}
|
11180
|
<p>How can I improve this code for counting the number of bits of a positive integer n in Python?</p>
<pre><code>def bitcount(n):
a = 1
while 1<<a <= n:
a <<= 1
s = 0
while a>1:
a >>= 1
if n >= 1<<a:
n >>= a
s += a
if n>0:
s += 1
return s
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T00:53:23.950",
"Id": "17849",
"Score": "3",
"body": "My silly question :): Cant you use `math.floor(math.log(number,2)) + 1`? Or do you mean the number of bits set?"
}
] |
[
{
"body": "<p>The very first thing you should do to improve it is comment it. I'm reading it for almost half an hour and still can't understand what it does. I tested it, and it indeed work as intended, but I have no idea why. What algorithm are you using?</p>\n\n<p>I pointed below parts of the code that aren't clear to me. Since @blufox already presented a simpler way to count bits (that works for non-zero numbers), I won't bother to suggest an improvement myself.</p>\n\n<pre><code>def bitcount(n):\n a = 1\n while 1<<a <= n:\n a <<= 1\n</code></pre>\n\n<p>Why is <code>a</code> growing in powers of two, while you're comparing <code>1<<a</code> to n? The sequence you're generating in binary is <code>10 100 10000 100000000 10000000000000000 ...</code> Take n=<code>101010</code>, and notice that</p>\n\n<p><code>10000 < 100000 < 101010 < 1000000 < 10000000 < 100000000</code></p>\n\n<p>i.e. there is no relation between <code>1<<a</code> and the number of bits in <code>n</code>. Choose a=<code>1<<2</code>, and <code>1<<a</code> is too small. Choose a=<code>1<<3</code> and <code>1<<a</code> is too big. In the end, the only fact you know is that <code>1<<a</code> is a power of two smaller than <code>n</code>, but I fail to see how this fact is relevant to the task.</p>\n\n<pre><code> s = 0\n while a>1:\n a >>= 1\n if n >= 1<<a:\n n >>= a\n s += a\n</code></pre>\n\n<p>This removes <code>a</code> bits from <code>n</code>, while increasing the bit count by <code>a</code>. That is correct, but I fail to understand why the resulting <code>n</code> will still have fewer bits than the next <code>1<<a</code> in the sequence (since they vary so wildly, by <code>2**(2**n)</code>).</p>\n\n<pre><code> if n>0:\n s += 1\n\n return s\n</code></pre>\n\n<p>I see that the result is off by 1 bit, and your code correctly adjust for that. Again, no idea why it does that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T03:42:45.690",
"Id": "11192",
"ParentId": "11181",
"Score": "7"
}
},
{
"body": "<p>first of, I'm not really sure what your code does, at least not the first part. I'm also unsure if you wonder of the number of bits set, or the number of actual bits? The code under here does both:</p>\n\n<pre><code>#!/usr/bin/env python\nimport sys, math\n\ndef least_significant_bit_is_set (number):\n return (n & 1 == 1)\n\nn = int (sys.argv[1])\n\n#calculate number of set bits\nbits_set = 0\n\nwhile n > 0:\n if least_significant_bit_is_set (n):\n bits_set += 1\n n = n / 2\n\nprint bits_set\n\nn = int (sys.argv[1])\n# calculate total number of bits\nbits = 0\nif n > 0:\n bits = int (math.log (n,2)) + 1\nprint bits \n</code></pre>\n\n<p>the <code>n = n/2</code> could also be substituted by <code>n >>= 1</code> to show that we are pushing the integer to the right, thereby loosing the least significant bit</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:40:00.783",
"Id": "11200",
"ParentId": "11181",
"Score": "1"
}
},
{
"body": "<pre><code>def bitcount(n):\n count = 0\n while n > 0:\n if (n & 1 == 1): count += 1\n n >>= 1\n\n return count\n</code></pre>\n\n<p>I didn’t read your code since, as mgibsonbr said, it’s unintelligible.</p>\n\n<p>For an overview over more sophisticated ways to count bits, refer to the <a href=\"http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetNaive\" rel=\"nofollow\">Bit Twittling Hacks</a> page.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-29T08:45:12.363",
"Id": "18146",
"Score": "0",
"body": "-1 I think that denying to read the code of the OP and posting a own solution is not the intention of code review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-29T10:51:40.520",
"Id": "18147",
"Score": "1",
"body": "@miracle173 I think the intention of a review is to learn. And while I agree with you in general, I also agree with mgibsonbr in this instance, that OP’s code isn’t salvageable (I *did* try to understand the code before posting …). But if you’d write a detailed critique of the code I’d be more than happy to upvote it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T12:16:35.847",
"Id": "11211",
"ParentId": "11181",
"Score": "3"
}
},
{
"body": "<p>If you consider readibility and maintainability as improvements and \n <strong>performance does not matter</strong>, you can rely on python string formatting to bit. That is convert the integer in a bit string and measure length.</p>\n\n<pre><code>len(\"{0:b}\".format(n))\n</code></pre>\n\n<p>Step by step interpretation:</p>\n\n<pre><code>>>> \"{0:b}\".format(1234)\n'10011010010'\n>>> len(_)\n11\n</code></pre>\n\n<p>Update:</p>\n\n<p><code>\"{0:b}\".format()</code> can be replaced by <code>bin()</code> built-in functions. Note that <code>bin</code> output is prefixed with <code>\"0b\"</code>, so</p>\n\n<pre><code>len(bin(n).lstrip('0b'))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T17:23:13.757",
"Id": "18123",
"Score": "0",
"body": "Good, except the OP wants the number of bits, not the number of set bits. (At least that's what his code does)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-02T01:08:39.613",
"Id": "18261",
"Score": "1",
"body": "and `[2:]` would be (IMO) better written as `.lstrip('0b')` (self-documenting code, avoid magic numbers, etc)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T12:48:22.357",
"Id": "11243",
"ParentId": "11181",
"Score": "0"
}
},
{
"body": "<p>There's a <code>bit_length</code> method in Python's <code>int</code> object:</p>\n\n<pre><code>>>> 34809283402483 .bit_length()\n45\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-21T17:56:44.830",
"Id": "95981",
"Score": "6",
"body": "bit_length doesn't count the number of 1 bits, it returns the number of bits needed to represent the integer. For example, your 34809283402483 needs 45 bits but only 28 bits are set."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T01:39:10.460",
"Id": "45671",
"ParentId": "11181",
"Score": "6"
}
},
{
"body": "<p>You can replace your function with a much smaller function like the one shown below:</p>\n\n<pre><code>def bit_count(number, accumulator=0):\n while number:\n accumulator += 1\n number >>= 1\n return accumulator\n</code></pre>\n\n<p>Argument checking is left as an exercise for the reader. You can use the following to verify:</p>\n\n<pre><code>numbers = 1, 23, 456, 7890\ntotal_bits = 0\nfor n in numbers:\n total_bits = bit_count(n, total_bits)\nassert total_bits == sum(map(int.bit_length, numbers)), 'your code is incorrect'\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-12T09:26:25.207",
"Id": "412583",
"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-02-11T18:33:46.503",
"Id": "213261",
"ParentId": "11181",
"Score": "0"
}
},
{
"body": "<p>It seems like your code is intended to count how many times 1 needs to be doubled (<code>1 << a</code>) to reach the provided value, <code>n</code>. The code works, but the style is convoluted. Noctis Skytower provided a more straight-forward solution. Since the program expects positive integers, the end condition occurs when number is 0. For every iteration in which number is positive, accumulator is incremented by 1, and number is nearly cut in half (<code>number >> 1</code>). Notice that the number of right bit shifts required to set number to 0 is equivalent to the number of bits of the original number. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T01:04:04.643",
"Id": "238509",
"ParentId": "11181",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T00:29:57.943",
"Id": "11181",
"Score": "5",
"Tags": [
"python",
"algorithm",
"bitwise"
],
"Title": "Counting the number of bits of a positive integer"
}
|
11181
|
<p>This is an alphabetical navigation which shows only the letter that have posts in both that letter and the currently filtered "genero" taxonomy term.</p>
<p>I use multiple taxonomy queries to find "artistas" posts that, for example, are tagged as both "rock" and "funk".</p>
<p>The function works perfectly and outputs exactly what I want it to, but the multiple loops are really lagging the load time and I'm uncertain of how to optimize the function.</p>
<p><img src="https://i.stack.imgur.com/laOV6.jpg" alt="enter image description here"></p>
<pre><code><?php
function empty_alfa($current, $i, $taxonomyvar) {
$output = '<li class="'.$current.'"><a>'.strtoupper($i).'</a></li>';
return $output;
}
function is_alfa() {
$alfa = filter_input(INPUT_GET, 'alfa', FILTER_SANITIZE_STRING | FILTER_SANITIZE_STRIPPED);
$is_alfa = ( ! $alfa ? is_tax('alfa') : true );
return $is_alfa;
}
function has_artists($i, $genre) {
$has_artists = false;
if(term_exists( $i, 'alfa' )) {
$alfas[] = array(
'taxonomy' => 'alfa',
'terms' => $i,
'field' => 'slug',
);
$genres[] = array(
'taxonomy' => 'genero',
'terms' => $genre,
'field' => 'slug',
'operator' => 'AND',
);
$termquery['post_type'] = 'artistas';
if(empty($genre)) {
$termquery['tax_query'] = $alfas;
} else {
$termquery['tax_query'] = array_merge($genres, $alfas);
$termquery['tax_query']['relation'] = "AND";
}
$has_artists = get_posts($termquery);
}
return $has_artists;
}
function alfa_nav_output($home, $uri, $taxonomyvar) {
foreach(range('a', 'z') as $i) :
$current = ($i == $taxonomyvar) ? "bg1 round-res" : "";
$empty_alfa = empty_alfa($current, $i, $taxonomyvar);
if ( term_exists( $i, 'alfa' ) ){
if( has_artists($i,$genre) && $i != $taxonomyvar ) {
if(empty($genre)) {
$link = $home.'?alfa='.$i.$orden;
} else {
$genrestring = (is_array($genre) ? implode('+',$genre) : $genrestring = $genre );
$link = $home.'?alfa='.$i.'&genero='.$genrestring.$orden;
}
?>
<li class="<?php echo $current; ?>">
<?php echo sprintf('<a class="alfa-link" href="%s">%s</a>', $link, strtoupper($i) ) ?>
</li>
<?php
} else {
echo $empty_alfa;
}
} else {
echo $empty_alfa;
}
endforeach;
}
function bam_artist_alfa() {
$taxonomy = 'alfa';
$taxonomyvar = get_query_var($taxonomy);
$uri = my_url();
$home = 'http://buenosairesmusic.com/';
if(strstr($uri, '/artista/') ) {
$uri = str_replace('/artista/','/?alfa=', $uri);
$uri = substr_replace($uri ,"",-1);
}
$all_link = removeqsvar($uri, 'alfa');
$last = $all_link[strlen($all_link)-1];
if($last == '?') $all_link = substr_replace($all_link ,"",-1);
if($all_link == $home) $all_link = $home.'artistas';
$all_current = (is_alfa() ? null : ' bg1 round-res' );
?>
<ul class="bbw bo alfa-nav c2">
<li class="all-link<?php echo $all_current; ?>">
<a<?php if(is_alfa()) echo ' href="'.$all_link.'"'; ?>>A&ndash;Z</a>
</li>
<?php
$query = $_SERVER['QUERY_STRING'];
$genre = null;
$orden = (isset($_GET) && isset($_GET['orden']) ? '&orden=fecha' : null);
if( strstr($uri,'/genero/') ) {
$genre = str_replace('/genero/','/?genero=', $uri);
$genre = substr_replace($uri ,"",-1);
$genre = explode('/',$genre);
$genre = end($genre);
} elseif( isset($_GET) && isset($_GET['genero']) ) {
$genre = $_GET['genero'];
}
if(!empty($genre)) {
$spaces = strpos($genre,' ');
$genre = ($spaces === false ? $genre : explode(' ', $genre) );
}
alfa_nav_output($home, $uri, $taxonomyvar);
?>
</ul>
<?php } ?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T11:31:00.553",
"Id": "17798",
"Score": "2",
"body": "Have to agree with Cygal. There's not enough information here to provide a decent answer, and adding more would really only confuse the issue as what you already have is so large and dificult to look through. I am planning to return to give you something to look at, but I am only able to stick around for a short time this morning. In the mean time, use [`microtime`](http://us2.php.net/manual/en/function.microtime.php) to start benchmarking your code to determine where the bottleneck is. I would suggest focusing on database queries. I'll try to post something before the end of the day."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T04:18:48.427",
"Id": "17844",
"Score": "0",
"body": "Perhaps... but the amount of traffic that this site gets makes it ideal to maximize the potential for getting help."
}
] |
[
{
"body": "<p>First of all, notice that declaring <code>has_artists()</code> in <code>bam_artists_alfa</code> is confusing. It doesn't make the function \"local\", since you can call it outside of <code>has_artists()</code> too.</p>\n\n<p>It's hard to tell where the bottleneck is! You only have one <strong>visible</strong> loop, but who knows what <code>get_posts()</code>, <code>get_terms()</code>, <code>set_transient()</code> or <code>get_query_var()</code> do? Do they have loops? Do they query the database? Did you benchmark the time taken by your function? Do you know where you spent most of your time?</p>\n\n<p>Usually, the best option you have is to make sure there is no request to the database in inner loops. Do all your requests beforehand and only work on PHP data.</p>\n\n<p>You should also make sure to avoid mixing displaying and computations, since it will make the optimization easier to reason about.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T08:31:01.900",
"Id": "11162",
"ParentId": "11182",
"Score": "3"
}
},
{
"body": "<p>To find bottle necks in your code, take the following code and wrap it around the code you wish to benchmark. Take a look at the <a href=\"http://us2.php.net/manual/en/function.microtime.php\" rel=\"nofollow\">documentation</a> for more information.</p>\n\n<pre><code>$start = microtime(true);\n//code to benchmark.\n$time = microtime(true) - $start;\necho \"task took $time seconds\";\n</code></pre>\n\n<p>Now, on to your current code. I can't tell you the parts that are running slow because: One, there is just too much here; And two, there's not enough here. Kind of an Oxymoron, but it makes sense, honest! So, instead I will just look at your code and give feedback. I will limit myself to just looking for redundancies so that it focuses more on your speed issues than anything else.</p>\n\n<p>Now, ignoring what I just said, here's one fix you can do that is more design oriented rather than performance oriented. However it could have the added benefit of increasing your programs performance as well, which is why I mentioning it. The most glaring issue I have with your code is that your functions are HUGE! Functions are, first and foremost, meant to hold repetitive tasks. Secondly they are meant to make your code cleaner. I actually had to return to the top of your code while reading this to ensure that I wasn't looking at procedural code because I had forgotten I was looking at a function and thought that you had put another function in the middle of your code.</p>\n\n<p><strong>Update:</strong> Upon further observation, I still found this to be true. Your <code>has_artists()</code> function is in the middle of your <code>bam_artist_alfa()</code> function. Don't do this. Its hard to tell from your code because of how long it is, so I don't know if it was just a typo, or if you legitamately have it this way. This may even be part of your performance problem.</p>\n\n<p>So first thing to do, is break your functions up so that they are cleaner. Added benefit will be that it will be easier to debug and read and it will be easier to wrap a function in those <code>microtime</code> blocks I showed you earlier than those long lines of code you have now. And as I already mentioned, it could have the added benefit of boosting your performance. Here's an example:</p>\n\n<pre><code>function bam_artist_alfa() {\n $taxonomy = 'alfa'; \n $uri = my_url();\n $home = 'http://buenosairesmusic.com/';\n\n // save the terms that have posts in an array as a transient\n $start = microtime(true);\n check_taxonomy();//new function\n $time = microtime(true) - $start;\n echo \"It took $time seconds to save the terms\";\n //plus all other code, I won't copy it all here\n}\n\nfunction check_taxonomy() {//one of those new functions in bam_artist_alfa\n if ( false === ( $alphabet = get_transient( 'bam_archive_alphabet' ) ) ) {\n // It wasn't there, so regenerate the data and save the transient\n $terms = get_terms($taxonomy);\n\n $alphabet = array();\n if($terms){\n foreach ($terms as $term){\n $alphabet[] = $term->slug;\n }\n }\n set_transient( 'bam_archive_alphabet', $alphabet );\n } \n}\n\netc...\n</code></pre>\n\n<p>I didn't actually change any of your code here, I only moved a chunk of it to a new function <code>check_taxonomy()</code>. Break your code up into similar, logical, blocks and this will help your code drastically. Both in readability, and hopefully, performance.</p>\n\n<p>Here's the first performance issue I have spotted. Change the following:</p>\n\n<pre><code> $genre = explode('/',$genre);\n $genre = end($genre);\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code> $genre = substr($genre, - strrpos($genre, '/'));\n</code></pre>\n\n<p>If you only want the last bit of a string that you know the starting positon of, you can just use substring. Exploding it into an array just to get the last element probably takes up more resources than are necessary. I'm not 100% sure about this, but it makes sense. Use that <code>microtime</code> function on both methods to determine which is faster for you.</p>\n\n<p>Now, for the second performance issue I spotted. Your entire <code>has_artists()</code> function. I'm having a real problem getting through all these arrays, some of which are identical. If you find yourself reusing information, set it up higher in the code to be reused as the code progresses. Even if it is not used for certain parts, it will not hurt anything to have it declared. I ended up rewritting this entire function. Compare yours to mine. The size difference alone is obvious. There was a lot of redundancy here, and even reduced, it is still rather confusing and could probably be compressed more, but I don't understand it enough to try.</p>\n\n<pre><code> function has_artists($i, $genre) {\n $temp = array(\n 'taxonomy' => 'alfa',\n 'terms' => $i,\n 'field' => 'slug',\n );\n\n if( ! empty($genre)) {\n $temp['taxonomy'] = 'genero';\n $temp['terms'] = $genre;\n\n if(is_array($genre)) { $temp['operator'] = 'AND'; }\n $genres[] = $temp;\n\n $termquery['tax_query']['relation'] = \"AND\";\n }\n\n $alfaquery = array();//was not defined and should be\n $alfaquery[] = $temp;\n $termquery['tax_query'] = array_merge($genres, $alfaquery);\n $termquery['post_type'] = 'artistas';\n\n $has_artists = get_posts($termquery);\n\n return $has_artists;\n }\n</code></pre>\n\n<p>This is about as far as I got. The rest looks like it will benefit from the above changes. Try applying these methods to your other code to see if that helps.</p>\n\n<p><strong>Update for your update</strong></p>\n\n<p>I would move <code>$have_artists = false;</code> to the beginning of your <code>has_artists()</code> function, outside of the if/else statement. That way it can serve as a default value should you ever decide to extend it.</p>\n\n<p>You did move a good portion of your code from the <code>bam_artist_alfa()</code> function, but you misunderstood what I was trying to tell you. The code in <code>alfa_nav()</code> function should be broken up further into multiple other functions. As it is, it is still very hard to read, especially with that HTML thrown in there. Later, you will find that removing the HTML entirely from your classes/functions will improve your code readability immensly. However, it is not important in this case because you are still working on separating everything into its logical parts. I'm not going to rewrite this function for you, but I will point out some issues and tell you how I would break it up. Maybe that will give you and idea of where to start. First some issues I found in your new function.</p>\n\n<p><code>$uri</code> and <code>$home</code> were never defined, yet you are using them in this new function. Pass them as a function argument, or retrieve it somehow or this function will not work.</p>\n\n<p>I don't know what <code>removeqsvar()</code> does, but from the looks of it, you just reinvented PHP's <code>substr</code>.</p>\n\n<p>Don't use an if statement without those brackets <code>{}</code>. Especially if you aren't going to be consistent about it. It makes your code harder to read.</p>\n\n<p>Declare <code>$is_alfa</code> like so. The way you are currently doing it is very redundant. No need to check if get is set, just check if the element you are looking for is and whether it is empty. If you are using PHP 5.2 or better, you can use <code>filter_input</code> function to accomplish this easier. I did so in my example below. If you are not able to use this function, continue to do it the way you were, but using the suggestions I gave before I mentioned <code>filter_input</code>.</p>\n\n<pre><code>$alfa = filter_input(INPUT_GET, 'alfa', FILTER_SANITIZE_STRING | FILTER_SANITIZE_STRIPPED);\n$is_alfa = ( ! $alfa ? is_tax('alfa') : true );\n</code></pre>\n\n<p>All the above could be thrown into a new function called <code>is_alfa()</code>.</p>\n\n<p>Stop checking if a TRUE/FALSE variable is true, just do the following.</p>\n\n<pre><code>$all_current = $is_alfa ? null : ' bg1 round-res';\n</code></pre>\n\n<p>Whether the above variable ONLY has TRUE/FALSE values is irrelevant. Unless you are using the absolute equality operator('===') any value besides FALSE/NULL/''/0 will be evaluated as TRUE.</p>\n\n<p>The above could also be moved into its own function. It could be made reusable by passing a variable to it to replace those <code>'alfa'</code> strings, that way the same could be accomplished for any value you wanted to check in a similar way.</p>\n\n<p>For the purposes of this answer, I would say to move the HTML output into its own function. I would do the following, or something similar to it first though.</p>\n\n<pre><code><?php if($is_alfa) : ?><a href=\"<?php echo $all_link; ?>\"><?php endif; ?>\nA&ndash;Z\n<?php if($is_alfa) : ?></a><?php endif; ?>\n</code></pre>\n\n<p>The above if format is very common in View files(MVC), however it doesn't make a difference as it is a designer preference. But since you are already using it for a foreach loop in your main code body, I figured I would point out the more common place to use it. The foreach loop you are doing this for currently is out of place and inconsistent with the rest of your code.</p>\n\n<p>I will stop here, mostly because I have developed a headache. Not from your code, its just been a long day, I actually really enjoy doing this. With everything I've shown you here, you should be able to take the last half of your function and finish separating it into logical pieces. Once that is done, you can then use those <code>microtime</code> functions around each new function as you call it to determine how long each takes to run. That way you will be able to determine where your program bottlenecks. Don't just do it to these new functions, do it to your old ones too, such as the very first one you use <code>get_query_var()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T19:02:19.827",
"Id": "17819",
"Score": "0",
"body": "Nice answer! Upvoted. I really think speed is a matter of \"SQL queries in a loop\" here though (if he has no more than a few hundred artists)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T19:04:43.963",
"Id": "17820",
"Score": "0",
"body": "@Cygal: I agree, though this can't hurt!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T22:02:06.647",
"Id": "17836",
"Score": "0",
"body": "I've updated my code... if you see anything else let me know! In general that code takes 0,177800893784 seconds to execute."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T23:16:09.750",
"Id": "17840",
"Score": "0",
"body": "@j-man86: I've updated my answer to suit. One thing I did not mention in my update: To get an accurate reading, you will have to run it many times. The easiest way to do it would be to run it in loop a set number of times. Don't do this quite yet, finish setting up the rest of your code first and then do each separately."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T00:25:33.300",
"Id": "17842",
"Score": "0",
"body": "OK great... I added my latest code. I think I'm getting closer!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T18:16:52.260",
"Id": "11172",
"ParentId": "11182",
"Score": "5"
}
},
{
"body": "<p>One thing you can do is take out the array declarations from the <code>has_artists</code> method which gets called many times inside your loop. </p>\n\n<p>Also, when you declare <code>$genres[]</code> in two different cases, the only difference is 'operator' => 'AND'.</p>\n\n<p>Lastly, instead of printing each <code><li</code> class ... as you loop, append the results to a variable and print the contents afterwards.</p>\n\n<p>I did a test with the following code:</p>\n\n<pre><code>for($x=1, $x < 10000; $x++) {\n printf(\"%s\", $x);\n}\n</code></pre>\n\n<p>This was slow compared to the following code:</p>\n\n<pre><code>$out = ''; for($x=1, $x < 10000; $x++) { $out = sprintf(\"%s%s\", $out, $x);}; echo $out;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T11:06:50.097",
"Id": "11183",
"ParentId": "11182",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "11172",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T04:11:25.617",
"Id": "11182",
"Score": "5",
"Tags": [
"performance",
"beginner",
"php"
],
"Title": "Alphabetical navigation"
}
|
11182
|
<p>I'm wondering how I could refactor this code. It may look a little reiterative and probably there's a shorter method to accomplish the same.</p>
<pre><code>def self.location(distance=100,location)
if distance.is_a? Integer
if distance.between?(1,5000)
distance = distance
elsif distance < 1
distance = 1
elsif distance > 5000
distance = 5000
end
else
distance = 100
end
if location
within(distance, :origin => location)
else
find(:all)
end
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T22:11:11.313",
"Id": "17857",
"Score": "2",
"body": "begin by splitting in two methods: one with distance condition, other with conditionnal scope"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-29T18:57:16.513",
"Id": "18161",
"Score": "0",
"body": "I think checking if it's Integer is a smell. What if I pass 1.0 to the function? Why would it be replaced with 100?"
}
] |
[
{
"body": "<p>I've replaced the part where you take care that distance is between 1 and 5000 with <code>distance = [1, [distance, 5000].min].max</code> . </p>\n\n<pre><code>def self.location(distance=100,location)\n if distance.is_a? Integer \n distance = [1, [distance, 5000].min].max\n else \n distance = 100\n end\n if location\n within(distance, :origin => location)\n else \n find(:all) \n end \nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T23:05:22.177",
"Id": "17858",
"Score": "0",
"body": "whats exactly happening here `[1, [distance, 5000].min].max`? Is it picking the lower value from distance and 5000 then the highest value from the product of the earlier comparison and 1?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T23:08:44.103",
"Id": "17859",
"Score": "0",
"body": "we are comparing the minimum between distance and 5000 with 1, and returning the maximum there. If distance is greater than 5000, we will compare 5000 with 1, and return 5000, else if distance is less than 5000, we compare it with 1. Now if distance is less than 1, we return 1, else we return the distance wich is between 1 and 5000"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T22:12:46.250",
"Id": "11188",
"ParentId": "11187",
"Score": "4"
}
},
{
"body": "<p>Shorter, and while min/max was tricky, IMO, this is easier to understand:</p>\n\n<pre><code>def self.location(distance=100,location)\n distance = 100 unless distance.is_a?(Integer)\n distance = 1 if distance < 1\n distance = 5000 if distance > 5000\n\n if location\n within(distance, :origin => location)\n else \n find(:all) \n end \nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T22:55:11.893",
"Id": "11189",
"ParentId": "11187",
"Score": "7"
}
},
{
"body": "<p>First, I would not set the distance to 100 if it's not an integer. What if someone uses a Fixnum such as 150.0? I would check to see if it responds to to_i.</p>\n\n<p>Second, I would break the distance out into a separate method because it's easier to follow outside the context of another method.</p>\n\n<pre><code>def self.location(distance, location)\n return find(:all) unless location\n\n distance = normalize_distance(distance)\n\n within(distance, :origin => location)\nend\n\ndef self.normalize_distance(distance=100)\n return 100 unless distance.respond_to? :to_i\n return 1 if distance < 1\n return 5000 if distance > 5000\n\n distance\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T01:24:33.633",
"Id": "17860",
"Score": "0",
"body": "Just because an object responds to to_i doesn't mean it represents an integer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T02:17:41.620",
"Id": "17861",
"Score": "1",
"body": "@MarkThomas let me clarify the point I was trying to make. Checking an object's class rather than its behavior is going to make the code less flexible. If a Fixnum or Float were passed into the location method, why should it behave any different? 100.0 is equivalent to 100 but they are different classes and only one is an integer. This sort of flexibility is called duck typing: http://en.wikipedia.org/wiki/Duck_typing"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T23:38:10.750",
"Id": "11190",
"ParentId": "11187",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "11189",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T22:07:46.283",
"Id": "11187",
"Score": "4",
"Tags": [
"ruby-on-rails",
"ruby"
],
"Title": "Finding locations with a distance between 1 and 5000"
}
|
11187
|
<p>Basically trying to create a dict of all declared variables and functions along with their types of a .c source file. Does anyone think I missed anything?</p>
<pre><code>#!usr/python
import string
import re
from types import *
from pprint import pprint
varDict = {}
def find_substring(needle, haystack):
index = haystack.find(needle)
if index == -1:
return False
if index != 0 and haystack[index-1] not in string.whitespace:
return False
L = index + len(needle)
if L < len(haystack) and haystack[L] not in string.whitespace:
return False
return True
f = open('example.c')
varTypeList = []
for varType in open('typesfile.txt'):
varTypeList.append(varType[:-1])
for line in f:
for varType in varTypeList:
if find_substring(varType,line):
var = re.search('\s*[\*_a-zA-Z]+[\*_a-zA-Z0-9]?', line.split(varType)[1])
if type(var) is not NoneType:
varDict[var.group(0)] = varType
pprint(varDict)
</code></pre>
|
[] |
[
{
"body": "<p>I think this code is fundamentally broken. What about comments and the preprocessor? And just by eyeballing the code I doubt very much that it parses declarations remotely correctly.</p>\n\n<p>This is the wrong approach. <code>string.find</code> will only take you so far. You need to <em>parse</em> the code to get reliable information. The easiest way to do this is to use a library, such as <a href=\"http://eli.thegreenplace.net/2011/07/03/parsing-c-in-python-with-clang/\" rel=\"nofollow\">libclang</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T12:27:03.947",
"Id": "11213",
"ParentId": "11191",
"Score": "4"
}
},
{
"body": "<p>This library looks like a great option for solving your problem in Python: <a href=\"http://code.google.com/p/python-ctags/\" rel=\"nofollow\">http://code.google.com/p/python-ctags/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T12:54:55.963",
"Id": "11218",
"ParentId": "11191",
"Score": "1"
}
},
{
"body": "<p>The code in <code>find_substring()</code> can be accomplished in one line in regular expressions. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-29T13:15:47.923",
"Id": "11307",
"ParentId": "11191",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "11213",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T03:38:50.370",
"Id": "11191",
"Score": "2",
"Tags": [
"python",
"c"
],
"Title": "Python & C: Trying to create a dict of all declared variables and functions and their types of a .c source file"
}
|
11191
|
<p>I have a a couple of different radio buttons which return an ethnicity and a gender. The script runs inside an internal application so rather than returning "boy", "girl" or "both" I get back 7707330, 7707333, and 7707336. Similar from the ethnicity radio button. </p>
<p>I then need to validate data based on the combonation of ethnicity and gender. This was a pretty simple task but I have ended up with 15 if statements! It all works as it should, but there must be a cleaner solution? </p>
<pre><code> function test(radioResults) {
var1 = radioResults[0].toString();
var2 = radioResults[1].toString();
roll = parseFloat(parent.roll);
if (var2 == '7707330') {
gender = 'boy';
}
if (var2 == '7707333') {
gender = 'girl';
}
if (var2 == '7707336') {
gender = 'both';
}
if (var1 == '7707341') {
maori(gender);
}
if (var1 == '7707344') {
pasifika(gender);
}
if (var1 == '7707347') {
all(gender);
}
}
function maori(gender) {
//Maori
if (gender == 'boy') {
ethnicity = parseFloat(parent.getMBoys);
validation(ethnicity);
}
if (gender == 'girl') {
ethnicity = parseFloat(parent.getMGirls);
validation(ethnicity);
}
if (gender == 'both') {
ethnicity = parseFloat(parent.getTotalM);
validation(ethnicity);
}
}
function pasifika(gender) {
//Pasifika
if (gender == 'boy') {
ethnicity = parseFloat(parent.getPBoys);
validation(ethnicity);
}
if (gender == 'girl') {
ethnicity = parseFloat(parent.getPGirls);
validation(ethnicity);
}
if (gender == 'both') {
ethnicity = parseFloat(parent.getTotalP);
validation(ethnicity);
}
}
function all(gender) {
//All
if (gender == 'boy') {
ethnicity = parseFloat(parent.getBoys);
validation(ethnicity);
}
if (gender == 'girl') {
ethnicity = parseFloat(parent.getGirls);
validation(ethnicity);
}
if (gender == 'both') {
ethnicity = parseFloat(parent.getTotalRoll);
validation(ethnicity);
}
}
function validation(ethnicity) {
percent = ethnicity * 5 / 100;
if (ethnicity - percent > roll || (ethnicity + percent < roll)) {
parent.document.getElementById('CF_7784443').value = "FAIL";
} else {
parent.document.getElementById('CF_7784443').value = "PASS";
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T08:27:23.980",
"Id": "502852",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>One option is to have a map from key -> value</p>\n\n<p>for example:</p>\n\n<pre><code>var var2 = radioResults[1].toString();\nvar gender = {'7707330': 'boy',\n '7707333': 'girl',\n '7707336': 'both'}[var2];\n</code></pre>\n\n<p>You could even put functions as the values. For example:</p>\n\n<pre><code>var var1 = radioResults[0].toString()\n{'7707341': maori,\n '7707344': pasifika,\n '7707347': all}[var1](gender);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T04:21:43.363",
"Id": "11195",
"ParentId": "11194",
"Score": "7"
}
},
{
"body": "<p>As Michael Deardeuff has already pointed out, in this particular case, maps are a good answer.</p>\n\n<p>But the generic answer to \"I have a lot of <code>if (var == value)</code> statements\" is \"use <code>switch (var)</code>.\" A <code>switch</code> reads better - it lets you read a single path and ignore the rest, knowing they won't be used for this value. For example:</p>\n\n<pre><code>function test(radioResults) {\n\n roll = parseFloat(parent.roll); // This is unused\n switch (radioResults[1].toString())\n {\n case '7707330':\n gender = 'boy';\n break;\n case '7707333':\n gender = 'girl';\n break;\n case '7707336':\n gender = 'both';\n break;\n default:\n /* Your code ignores the possibility of an unexpected value */\n }\n\n switch (radioResults[0].toString())\n {\n case '7707341':\n maori(gender);\n break;\n case '7707344':\n pasifika(gender);\n break;\n case '7707347':\n all(gender);\n break;\n default:\n /* Your code ignores the possibility of an unexpected value */\n }\n}\n</code></pre>\n\n<p>Or, in this simple case, even:</p>\n\n<pre><code>function test(radioResults) {\n\n switch (radioResults[1].toString())\n {\n case '7707330': gender = 'boy'; break;\n case '7707333': gender = 'girl'; break;\n case '7707336': gender = 'both'; break;\n }\n\n switch (radioResults[0].toString())\n {\n case '7707341': maori(gender); break;\n case '7707344': pasifika(gender); break;\n case '7707347': all(gender); break;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:20:24.270",
"Id": "11199",
"ParentId": "11194",
"Score": "4"
}
},
{
"body": "<p>As the other two commenters have noted, there are simpler ways of expressing those if-statements. However, I think there is something more important that needs to be addressed in your code: organisation. You've already made some good progress at separating out logic into small, contained functions. However there are two issues I immediately notice:</p>\n\n<ol>\n<li>A function should try to follow the Single Responsibility Principle – it should only focus on one thing.</li>\n<li>Your functions rely on a the global state of several variables, this can cause many unexpected bugs and make them hard to track down – pass your functions everything they need to know.</li>\n</ol>\n\n<p>So, with those two things in mind, this is a better way to write your code using a similar style:</p>\n\n<pre><code>function validate(parent, radioResults) {\n var gen = gender(radioResults[0].toString()),\n eth = ethnicity(radioResults[1].toString()),\n mult = multiplier(parent, gen, eth),\n roll = parseFloat(parent.roll, 10),\n element = parent.document.getElementById('CF_7784443');\n\n if (isValidPercentage(mult, roll))\n element.value = 'PASS';\n else\n element.value = 'FAIL';\n}\n\nfunction gender(val) {\n switch(val) {\n case '7707330':\n return 'boy';\n\n case '7707333':\n return 'girl';\n\n case '7707336':\n return 'both';\n\n default:\n // Nadda\n }\n}\n\nfunction ethnicity(val) {\n switch(val) {\n case '7707341':\n return 'maori';\n\n case '7707344':\n return 'pasifika';\n\n case '7707347':\n return 'all';\n\n default:\n // Nadda\n }\n}\n\nfunction multiplier(parent, gender, ethnicity) {\n switch(ethnicity) {\n // All\n case 'all':\n if (gender == 'boy')\n return parseFloat(parent.getBoys, 10);\n else if (gender == 'girl')\n return parseFloat(parent.getGirls, 10);\n else\n return parseFloat(parent.getTotalRoll, 10);\n\n // Maori\n case 'maori':\n if (gender == 'boy')\n return parseFloat(parent.getMBoys, 10);\n else if (gender == 'girl')\n return parseFloat(parent.getMGirls, 10);\n else\n return parseFloat(parent.getTotalM, 10);\n\n // Pasifika\n case 'pasifika':\n if (gender == 'boy')\n return parseFloat(parent.getPBoys, 10);\n else if (gender == 'girl')\n return parseFloat(parent.getPGirls, 10);\n else\n return parseFloat(parent.getTotalP, 10);\n\n default:\n // Nadda\n }\n}\n\nfunction isValidPercentage(multiplier, roll) {\n var percent = multiplier * 5 / 100;\n\n return ! (multiplier - percent > roll || (multiplier + percent < roll));\n}\n</code></pre>\n\n<p>As you can see I have renamed some of the functions to more accurately represent their purpose, I have ensured that I pass everything I need into my functions as arguments instead of using global variables, and finally I have made each function responsible for a single task.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T22:45:28.597",
"Id": "11268",
"ParentId": "11194",
"Score": "3"
}
},
{
"body": "<p>If something will execute on every path of your <code>if</code>s, and the <code>if</code>s are arranged in a way it will execute only one of them, you can move that logic outside on the bottom:</p>\n<pre><code>if (gender == 'boy') {\n ethnicity = parseFloat(parent.getMBoys);\n //why run... validation(ethnicity);\n}\nif (gender == 'girl') {\n ethnicity = parseFloat(parent.getMGirls);\n //this line... validation(ethnicity);\n}\nif (gender == 'both') {\n ethnicity = parseFloat(parent.getTotalM);\n //on every if? validation(ethnicity);\n}\nvalidation(ethnicity); //move it outside here :)\n</code></pre>\n<p>If you are going to apply something to all of the <code>if</code>s, you don't need to apply them each time, you can apply the change later on:</p>\n<pre><code>if (...) {\n //why use... ethnicity = parseFloat(parent.getBoys);\n ethnicity = parent.getBoys;\n}\nif (...) {\n //parseFloat... ethnicity = parseFloat(parent.getGirls);\n ethnicity = parent.getGirls;\n}\nif (...) {\n //on each one? ethnicity = parseFloat(parent.getTotalRoll);\n ethnicity = parent.getTotalRoll;\n}\nethnicity = parseFloat(ethnicity); //do the change\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-04-29T00:37:58.427",
"Id": "11292",
"ParentId": "11194",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T03:48:07.260",
"Id": "11194",
"Score": "5",
"Tags": [
"javascript"
],
"Title": "Javascript - Replace lots of if statements"
}
|
11194
|
<p>I have method which checks period and return schedules:</p>
<pre><code>public IEnumerable<EventSchedule> GetSchedulesForPeriod(PeriodEvent period, string tab = "")
{
switch (period)
{
case PeriodEvent.Today:
return GetTodaySchedules(tab);
case PeriodEvent.Tomorrow:
return GetTomorrowSchedules(tab);
case PeriodEvent.Week:
return GetWeekSchedules(tab);
case PeriodEvent.FewWeek:
return GetFewWeekSchedules(tab);
case PeriodEvent.Month:
return GetMonthSchedules(tab);
case PeriodEvent.All:
return GetAllFromTodaySchedules(tab);
default:
return GetTodaySchedules(tab);
}
}
</code></pre>
<p>Consider the <code>GetTodaySchedules</code> and <code>GetTomorrowSchedules</code>:</p>
<pre><code> private IEnumerable<EventSchedule> GetTodaySchedules(string tab)
{
var today = DateTime.Now.Date;
var result = Database.EventSchedules.Where(s => s.RecurrenceStart.Value.Date <= today &&
s.RecurrenceEnd.Value.Date >= today &&
s.BaseEvent.IsApproved.Value && !s.IsRemoved.Value &&
s.BaseEvent.EventsCategories.Any(
c => c.EventCategory.Name == tab)).ToList();
return result.Where(s => Evaluator.CheckDate(s, today)).ToList();
}
private IEnumerable<EventSchedule> GetTomorrowSchedules(string tab)
{
var today = DateTime.Now.AddDays(1).Date;
var result = Database.EventSchedules.Where(s => s.RecurrenceStart.Value.Date <= today &&
s.RecurrenceEnd.Value.Date >= today &&
s.BaseEvent.IsApproved.Value && !s.IsRemoved.Value &&
s.BaseEvent.EventsCategories.Any(
c => c.EventCategory.Name == tab)).ToList();
return result.Where(s => Evaluator.CheckDate(s, today)).ToList();
}
</code></pre>
<p>The similar code have all methods above. How to rewrite it? May be, there is some pattern for this?
And, the second, now I want that <code>tab</code> checks only if it filled and introduce new var called <code>placeName</code> (also check if filled):</p>
<pre><code>private IEnumerable<EventSchedule> GetTodaySchedules(string tab, string placeName)
{
var today = DateTime.Now.Date;
var result = Database.EventSchedules.Where(s => s.RecurrenceStart.Value.Date <= today &&
s.RecurrenceEnd.Value.Date >= today &&
s.BaseEvent.IsApproved.Value && !s.IsRemoved.Value &&
s.BaseEvent.EventsCategories.Any(
c => c.EventCategory.Name == tab) && s.BasePlace.Name).ToList();
return result.Where(s => Evaluator.CheckDate(s, today)).ToList();
}
</code></pre>
<p>I don't want to create separate methods for this. What is best way to do this? </p>
<p>Thanks.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T16:58:21.290",
"Id": "504002",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>Just add another argument to the method:</p>\n\n<pre><code>private IEnumerable<EventSchedule> GetSchedules(string tab, DateTime day)\n{\n var result = Database.EventSchedules.Where(s => s.RecurrenceStart.Value.Date <= day &&\n s.RecurrenceEnd.Value.Date >= day &&\n s.BaseEvent.IsApproved.Value && !s.IsRemoved.Value &&\n s.BaseEvent.EventsCategories.Any(\n c => c.EventCategory.Name == tab)).ToList();\n\n return result.Where(s => Evaluator.CheckDate(s, day)).ToList();\n}\n</code></pre>\n\n<p>And call it with an appropriate value for <code>day</code>. Easy, no?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T14:04:41.747",
"Id": "17978",
"Score": "0",
"body": "Additionally properties can be made to get the appropriate days. `Today` returns `DateTime.Today.Date`, `Tomorrow` returns `DateTime.Tomorrow.AddDays(1).Date`, etc. Though I'd make the `day` parameter first. That way calls to the method could look like: `GetSchedules(Today, tab)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T15:49:17.990",
"Id": "17981",
"Score": "0",
"body": "There is more complex queries( RecurrenceStart and RecurrenceEnd)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T16:07:01.550",
"Id": "17983",
"Score": "0",
"body": "@user348173 Well you didn’t show them. But doesn’t matter, the same principle can be applied: just provide the parts that vary as arguments to the method."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T12:02:09.420",
"Id": "11202",
"ParentId": "11201",
"Score": "3"
}
},
{
"body": "<p>You can compose query predicates by applying several where clauses in a row.\nThe predicates must be passed as <code>Expression<Func<T, bool>></code> for composition.</p>\n<p>See <a href=\"https://docs.microsoft.com/en-us/archive/blogs/meek/linq-to-entities-combining-predicates\" rel=\"nofollow noreferrer\">LINQ to Entities: Combining Predicates</a> on Microsoft Docs.</p>\n<p>Create a general schedules query like this</p>\n<pre><code>private IEnumerable<EventSchedule> GetSchedules(\n string tab,\n Expression<Func<EventSchedule, bool>> dateCondition)\n{ \n var result = Database.EventSchedules\n .Where(s => s.BaseEvent.IsApproved.Value &&\n !s.IsRemoved.Value &&\n s.BaseEvent.EventsCategories.Any(c => c.EventCategory.Name == tab))\n .Where(dateCondition)\n .ToList();\n return result.Where(s => Evaluator.CheckDate(s, today)).ToList();\n}\n</code></pre>\n<p>And then pass it the appropriate individual date predicate like this</p>\n<pre><code>private IEnumerable<EventSchedule> GetTodaySchedules(string tab) {\n var today = DateTime.Now.Date;\n return GetSchedules(\n tab,\n s => s.RecurrenceStart.Value.Date <= today &&\n s.RecurrenceEnd.Value.Date >= today);\n}\n\nprivate IEnumerable<EventSchedule> GetTomorrowSchedules(string tab) {\n var tomorrow = DateTime.Now.AddDays(1).Date;\n return GetSchedules(\n tab,\n s => s.RecurrenceStart.Value.Date <= tomorrow &&\n s.RecurrenceEnd.Value.Date >= tomorrow);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-04-26T16:21:51.867",
"Id": "11229",
"ParentId": "11201",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "11229",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:43:27.143",
"Id": "11201",
"Score": "4",
"Tags": [
"c#"
],
"Title": "similar code in several methods"
}
|
11201
|
<p>If I want to strip a string completely of its <strong>whitespaces, punctuation and numbers</strong> (i.e. anything that is not A-Z, a-z), what is the most efficient way of doing it in C++?</p>
<p>I tried this:</p>
<pre><code>string strip(string in) {
string final;
for(int i = 0; i < in.length(); i++) {
if(isalpha(in[i])) final += in[i];
}
return final;
}
</code></pre>
<p>It works as expected, but is too slow on strings with ~2000 characters. I figured out that the code causing this slowness is the <code>isalpha()</code> call.</p>
<p>So does anyone know of a better, more efficient way of stripping a string of everything except [A-Z][a-z] in C++?</p>
<p>At most, the string will be 20000 characters long and I need to strip it in <1 second.</p>
<p>Thanks in advance.</p>
<p><strong>EDIT:</strong></p>
<p>If I remove the <code>if</code> condition, the output will display instantly. But <em>with</em> the <code>if</code> condition, it will take about 1.6 seconds to display the output.</p>
<p>For trying out the code, use this: <a href="http://pastebin.com/g3NtBFaD">http://pastebin.com/g3NtBFaD</a> and a normal 20k char string. Then try comparing.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T10:49:37.250",
"Id": "17876",
"Score": "0",
"body": "How fast/slow is your computer? Using a normal machine with about 100 mil ops per second, I think 2000 chars should be short enough."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T10:49:49.760",
"Id": "17877",
"Score": "2",
"body": "If this code doesn't run in < 1 second for 2000 character long strings you must be sitting on a c64 or something ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T10:50:12.117",
"Id": "17878",
"Score": "0",
"body": "The testing server is a Pentium III 800MHz computer.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T10:50:38.187",
"Id": "17879",
"Score": "1",
"body": "Replace isAlpha with your own comparisons perhaps, although I suspect it may be your += on the string that takes a while if you're not reserving capacity in advance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T10:50:39.947",
"Id": "17880",
"Score": "7",
"body": "Push the 'Turbo' button :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T10:50:51.410",
"Id": "17881",
"Score": "0",
"body": "@Roshnal: Do you have an equally old compiler? Because that could also be a problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T10:52:08.667",
"Id": "17882",
"Score": "0",
"body": "On my computer, I have Ubuntu 11.04 with GCC 4.6 and my processor is 2.8GHz dual core."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T10:52:45.483",
"Id": "17883",
"Score": "0",
"body": "The other posts about reserving space in advance for the output are valid but, even so, 2000 chars - shoud not remotely approach a second."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T10:54:48.463",
"Id": "17884",
"Score": "0",
"body": "@MartinJames I also thought about that, but it takes a while before showing me the output. But _if_ I remove the `isalpha()` part, the output would display instantly.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T10:56:39.180",
"Id": "17885",
"Score": "0",
"body": "@Roshnal: Show us the rest of your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:02:32.177",
"Id": "17886",
"Score": "0",
"body": "Could you try a profiler?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:04:43.420",
"Id": "17887",
"Score": "0",
"body": "Do you compile with optimizations enabled?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:04:43.467",
"Id": "17888",
"Score": "0",
"body": "OK, so what if you code the IsAlpha yourself, if((in[i]>=\"A\"&&in[i]<=\"Z\")||(in[i]>=\"a\"&&in[i]<=\"z\"))..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:08:20.700",
"Id": "17889",
"Score": "0",
"body": "I honestly cannot imagine how this task can possibly take you so long. It's a relatively simple test on a small source string."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:08:57.307",
"Id": "17890",
"Score": "0",
"body": "@FrerichRaabe Don't know, its an automatic tester in USACO"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:09:30.017",
"Id": "17891",
"Score": "0",
"body": "@MartinJames Tried that.. Still takes long"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:11:11.960",
"Id": "17892",
"Score": "0",
"body": "@DeadMG Can you please try the above code? Try inputting a 2000char string with and without the \"isalpha\" checking."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:12:49.180",
"Id": "17893",
"Score": "0",
"body": "@Martin. Ouch! multiple calls to `std::string::operator[]` in that expression. isalpha() tests by testing the bit pattern against a mask rather than numeric ranges (for ACSII encoding at least); it will be much faster. I suspect that that is not where the problem truly lies."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:17:25.443",
"Id": "17894",
"Score": "0",
"body": "@Clifford - I would have thought that it would be optimized to index the char only once. Even so, we are back to 'how can doing anything with a char take 500us?'."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:18:29.533",
"Id": "17895",
"Score": "0",
"body": "Ae we going to have to optimize this into pointer arithmetic?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:20:26.997",
"Id": "17896",
"Score": "0",
"body": "@Martin James I already did ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:21:55.653",
"Id": "17897",
"Score": "0",
"body": "@Roshnal: On my machine (i7 930 2.8GHz Windows 7 64bit), in Release mode, it takes so little time, even after increasing the timer resolution to *nanoseconds*, I still came back with 0. I had to compare the CPU cycle count to get a time- 1080 cycles."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:23:28.887",
"Id": "17898",
"Score": "0",
"body": "@DeadMG Yes I also tried with other test cases each with 2000chars. And they took 0.000 to 0.010 seconds to execute. But this: http://ace.delos.com/usacodatashow?a=AHnzwbDqkIc takes a lot of time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:24:46.577",
"Id": "17899",
"Score": "0",
"body": "@Roshnal: That page won't open for me. In addition, I used virtually your exact code from the OP- not a different test case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:25:25.843",
"Id": "17900",
"Score": "0",
"body": "@Roshnal The server at ace.delos.com is taking too long to respond :D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:26:05.863",
"Id": "17901",
"Score": "0",
"body": "@AndreasBrinck - Oh yeah... sorry! It's just that this problem is very vexing! I would have said that a character-range check operation on only 2000 characters would only take 1.6 seconds if run on an abacus, and then only if the beads are sticking."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:26:17.267",
"Id": "17902",
"Score": "0",
"body": "Sorry, try this http://pastebin.com/g3NtBFaD"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:30:22.400",
"Id": "17903",
"Score": "0",
"body": "That document has 20k chars, but still if I remove the `if` condition, it would display instantly. If not, it will take 1.6 seconds"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:30:33.457",
"Id": "17904",
"Score": "0",
"body": "@Roshnal That string is 20000 chars, not 2000. But still runs in a blink of an eye."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:31:36.347",
"Id": "17905",
"Score": "0",
"body": "@Andrey Yeah, sorry for the wrong info, but did you try enabling/disabling the `if` condition and see what happens?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:36:43.910",
"Id": "17906",
"Score": "0",
"body": "@Roshnal No difference."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:37:09.097",
"Id": "17907",
"Score": "0",
"body": "I think this is not a matter of \"the most efficient way\" as teh title asks; your way is not the most efficient, but it certainly should not take that long - something else is wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:38:09.730",
"Id": "17908",
"Score": "0",
"body": "@Roshnal if you remove the `if` condition the compiler might be smart enough to just `return in;`..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:38:22.583",
"Id": "17909",
"Score": "0",
"body": "@Andrey But it does make a difference on my computer and the testing computer. The execution time will completely change with the enabling/disabling of the `if` condition..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:38:53.723",
"Id": "17910",
"Score": "0",
"body": "@Roshnal See my previous comment"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:39:05.563",
"Id": "17911",
"Score": "0",
"body": "@AndreasBrinck I hope not.. Even with the `final += in[i]`, it executes in the blink of an eye"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:42:33.440",
"Id": "17912",
"Score": "0",
"body": "@Roshnal Did you try with a lookup table?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:43:24.047",
"Id": "17913",
"Score": "0",
"body": "@AndreasBrinck No, can you please provide a code sample?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T18:59:28.870",
"Id": "18011",
"Score": "0",
"body": "Try replacing the `isalpha` with a really trivial condition, say `i % 5` and see what happens"
}
] |
[
{
"body": "<p>Try calling reserve(2000) on your final string before using it. Also take a const ref as argument.</p>\n\n<p>Edit:</p>\n\n<p>I would suspect that on Unix, the <code>isalpha</code> function is performing a lot more work to support Unicode, and you are only interested in the ASCII range. It's still a big leap, but you might try replacing it with a custom comparison, like <code>if ((in[i] <= 'Z' && in[i] >= 'A') || (in[i] >= 'a' && in[i] <= 'z'))</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T10:55:16.840",
"Id": "17915",
"Score": "0",
"body": "Nope, no improvement.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:18:53.857",
"Id": "17916",
"Score": "0",
"body": "Still its slow (no improvement whatsoever)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T10:50:08.073",
"Id": "11204",
"ParentId": "11203",
"Score": "2"
}
},
{
"body": "<p>I would add a:</p>\n\n<pre><code>final.reserve(in.length());\n</code></pre>\n\n<p>to avoid allocations when doing the <code>+=</code>.</p>\n\n<p>You could try this code, but I doubt it will be much faster:</p>\n\n<pre><code>string strip(const string& in) {\n char final[2000];\n char* cursor = final;\n for(string::const_iterator c = in.begin(), end = in.end(); c != end; ++c) {\n char cc = *c;\n if ((cc >= 'a' && cc <= 'z') || (cc >= 'A' && cc <= 'Z'))\n {\n *cursor = cc;\n ++cursor;\n }\n }\n *cursor = 0;\n return final;\n}\n</code></pre>\n\n<p>Notice that the <code>in</code> parameter is now passed by reference. One possible, though unlikely, improvement would be to create a 256 <code>bool</code> lookup table that stores if a given char is alpha:</p>\n\n<pre><code>string strip(const string& in) {\n bool lut[256];\n for (int i = 0; i < 256; ++i)\n {\n lut[i] = (i >= 'a' && i <= 'z') || (i >= 'A' && i <= 'Z');\n }\n string final;\n final.reserve(in.length());\n for(int i = 0; i < in.length(); i++) {\n if (lut[in[i]]) final += in[i];\n }\n return final;\n}\n</code></pre>\n\n<p>Note that the LUT is populated everytime this code is called, if the string is > 20.000 this time should be insignificant though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T10:53:25.267",
"Id": "17917",
"Score": "0",
"body": "Tried that, no improvement..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:00:43.017",
"Id": "17918",
"Score": "0",
"body": "Still takes as much as long. But if I remove the `if` condition (which checks for A-Z a-z) its really fast.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:05:26.057",
"Id": "17919",
"Score": "0",
"body": "@Roshnal Try it with a lookup table, might be faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:06:48.927",
"Id": "17920",
"Score": "0",
"body": "@Clifford No, I suspect it's something else as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:10:20.163",
"Id": "17921",
"Score": "0",
"body": "If the string is indeed Unicode, it would beed either a very large lookup table or some implicit conversions to char. Even if the string is Unicode, 2000 characters is.. not that many. How could it take a human-noticeable time?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:14:04.617",
"Id": "17922",
"Score": "0",
"body": "@MartinJames: That's what I'm thinking. How on earth can the CPU fail to process such a small string in a short time?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:15:13.823",
"Id": "17923",
"Score": "0",
"body": "It seems so unnecessary to limited yourself to a 2000 characters long array when a dynamically sized vector/string would do the deed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:16:01.023",
"Id": "17924",
"Score": "0",
"body": "@DeadMG I think he's running this code on a remote testing computer, so I don't think he's getting 1 second of CPU time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:17:19.327",
"Id": "17925",
"Score": "0",
"body": "I'm doing USACO and this is a problem in section 1.3. It says for test case 8 (i.e. a string with 2000chars) it takes 1.6 seconds to complete. I tried it on my computer also, and yes, it does take 1.6 seconds..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:18:54.247",
"Id": "17926",
"Score": "0",
"body": "@Roshnal How do you measure the time? You should be able to run your code on a 1000000 character long string on your computer in < 1 second."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:20:13.640",
"Id": "17927",
"Score": "0",
"body": "I just noticed that all other test cases run fine (in 0.000 seconds to 0.010 seconds) **except** this: http://ace.delos.com/usacodatashow?a=AHnzwbDqkIc"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:21:57.663",
"Id": "17928",
"Score": "0",
"body": "Given that `isalpha()` probably tests by bitmask rather than numeruc range, I suggest that it will be faster than this expression. The fact that the change makes no difference, suggests that the execution time for both is insignificant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:22:12.240",
"Id": "17929",
"Score": "0",
"body": "@Roshnal I can't access that. Can you add the offending string to your question?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:24:13.147",
"Id": "17930",
"Score": "0",
"body": "@AndreasBrinck Its really large. I'll use pastebin to post it here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:25:50.403",
"Id": "17931",
"Score": "0",
"body": "@AndreasBrinck http://pastebin.com/g3NtBFaD"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:28:28.280",
"Id": "17932",
"Score": "0",
"body": "Sorry, that document has 20,000 chars.. But still?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:51:33.857",
"Id": "17933",
"Score": "0",
"body": "Sorry, but why the 256 and what's the cc?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:52:58.410",
"Id": "17934",
"Score": "0",
"body": "The `cc` was just a typo when I copied the code, and 256 is the number of different values for a `char`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:55:11.623",
"Id": "17935",
"Score": "0",
"body": "@AndreasBrinck No I meant from where is cc coming? You have directly used cc >=... and it gives me an error."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:56:14.650",
"Id": "17936",
"Score": "0",
"body": "@Roshnal Reload my answer, in the second version of the code there's no reference to `cc`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:59:58.890",
"Id": "17937",
"Score": "0",
"body": "@AndreasBrinck OK, but for some reason, it gives an error in the `lut[in[i]]` code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T12:07:48.660",
"Id": "17963",
"Score": "0",
"body": "@Roshnal: You would have to say *what the error is*."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T12:32:16.000",
"Id": "17966",
"Score": "0",
"body": "@DeadMG No, no error. But still it takes as much time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T12:37:46.303",
"Id": "17969",
"Score": "0",
"body": "If I remove the lut-assigning part, it executes really fast. So I think the problem is with checking for alpha-characters (with or without `isalpha` method."
}
],
"meta_data": {
"CommentCount": "24",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T10:50:23.160",
"Id": "11205",
"ParentId": "11203",
"Score": "10"
}
},
{
"body": "<p>I suggest that it is not the <code>isalpha()</code> call that is taking the time but rather the two <code>std::string::operator[]</code> calls and/or the <code>std::string::operator+=</code> call.</p>\n\n<p>You could probably speed this loop up by using an iterator to reference <code>in</code>, thus avoiding <code>std::string::operator[]</code>, and appending the character will be faster using <code>std::string::push_back</code> and if you initially expanding <code>final</code> to have the same initial capacity as <code>in</code>.</p>\n\n<p>Passing the unmodified input string as a const reference may also help but will only be significant if you are calling the function itself iteratively.</p>\n\n<pre><code>string strip( const string& in) \n{\n final.reserve( in.length() ) ;\n string::iterator it;\n for ( it=str.begin() ; it < str.end(); it++ )\n {\n if( isalpha( *it ) )\n {\n final.push_back( *it ) ;\n }\n }\n\n return final ;\n}\n</code></pre>\n\n<p>All that said, I strongly suggest that your use the profiler or add timing instrumentation to the code to reveal the true performance hog. The timings you suggest do not seem likely - something else is happening here I think.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T10:58:12.220",
"Id": "17938",
"Score": "0",
"body": "No, when I only remove the `if` condition in the shown code, the output is instantly shown, _even if_ the `final += in[i]` part is still there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:26:02.643",
"Id": "17939",
"Score": "0",
"body": "@Roshnal: Possibly because the compiler can optimise it out to a string copy. If the call assigns the string to itself, it might even optimise out the call altogether (if it were very smart). Something is wrong here; isalpha() is a very simple function (in fact it is a macro, so you can see what it does in the ctype.h file)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T10:56:58.330",
"Id": "11206",
"ParentId": "11203",
"Score": "1"
}
},
{
"body": "<p>You may try following C++11 code which allocates memory and changes the final string size only once</p>\n\n<pre><code>std::string strip(std::string in) \n {\n in.erase(std::remove_if(in.begin(), in.end(), [] (std::string::value_type ch)\n { return !isalpha(ch); }\n ), in.end());\n return in;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:02:21.100",
"Id": "17940",
"Score": "0",
"body": "You mean except in the unnecessary copy in the argument?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:03:59.373",
"Id": "17941",
"Score": "1",
"body": "@DeadMG I can eliminate that copy, taking into account that `in` is passed by value"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:04:37.290",
"Id": "17942",
"Score": "0",
"body": "If the argument is an lvalue, you just unnecessarily copied it. There is no reason to take by vaue here because you do not need to own the argument string."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:08:03.340",
"Id": "17944",
"Score": "0",
"body": "Gives me an error in the `, in.end()` part.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:11:06.637",
"Id": "17945",
"Score": "0",
"body": "@Roshnal Tested in VC2010. If your compiler doesn't support C++11, you have to replace the lambda with a predicate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:11:35.870",
"Id": "17946",
"Score": "0",
"body": "@Andrey How was it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:13:18.240",
"Id": "17947",
"Score": "0",
"body": "@Roshnal: does your compiler support lambdas ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:14:14.133",
"Id": "17948",
"Score": "0",
"body": "@Roshnal yes, it supports lambdas, and the result is instant even in debug. You really should profile your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:14:17.607",
"Id": "17949",
"Score": "0",
"body": "calfflac.cpp: In function ‘std::string strip(std::string)’:\ncalfflac.cpp:37:94: warning: lambda expressions only available with -std=c++0x or -std=gnu++0x\ncalfflac.cpp:37:95: error: no matching function for call to ‘remove_if(std::basic_string<char>::iterator, std::basic_string<char>::iterator, strip(std::string)::<lambda(std::basic_string<char, std::char_traits<char>, std::allocator<char> >::value_type)>)’"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:15:06.367",
"Id": "17950",
"Score": "0",
"body": "@Andrey Sorry I don't know what's lambda.. I'm a complete beginner to C++"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:15:17.427",
"Id": "17951",
"Score": "0",
"body": "@Roshnal Perhaps, you have to use `-std=c++0x` compiler switch to enable lambdas?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:16:38.210",
"Id": "17952",
"Score": "0",
"body": "@Roshnal Look http://en.wikipedia.org/wiki/Anonymous_function#C.2B.2B"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:36:06.453",
"Id": "17953",
"Score": "0",
"body": "The only issue with this version is the initial copy. If the string is only sparsely populated with alphabetic characters, then a big memory allocation and large copy are done... for nothing."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:01:23.973",
"Id": "11207",
"ParentId": "11203",
"Score": "7"
}
},
{
"body": "<p>A few thoughts which come to my mind, without having actually profiled your code:</p>\n\n<ol>\n<li>Try passing <code>std::string</code> as reference-to-const to avoid a copy (in case your <code>std::string</code> implementation is not Copy-On-Write).</li>\n<li>Reserve space in the <code>std::string</code> by calling <code>reserve</code>.</li>\n<li>Avoid calling <code>std::string::length</code> repeatedly, memorize the value.</li>\n<li>Avoid indexing the string repeatedly, use an iterator instead.</li>\n</ol>\n\n<p>For what it's worth, you could try a different (more functional) way to implement this function. Some may consider this idiomatic, other will find it harder to read. Your call -maybe just for the fun of it, to see how it performs (remember to enable optimizations!):</p>\n\n<pre><code>#include <algorithm>\n#include <functional>\n#include <locale>\n#include <string>\n\nstd::string strip( const std::string &s ) {\n std::string result;\n result.reserve( s.length() );\n\n std::remove_copy_if( s.begin(),\n s.end(),\n std::back_inserter( result ),\n std::not1( std::ptr_fun( isalpha ) ) );\n\n return result;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:16:01.043",
"Id": "17954",
"Score": "1",
"body": "\"in case your std::string implementation is not Copy-On-Write\" -- none that I know of is. \"Avoid calling std::string::length repeatedly, memorize the value.\" -- this is a non-issue, the lookup is constant. \"Avoid indexing the string repeatedly, use an iterator instead.\" -- non-issue aswell, it's a simple read. Iterators and indexing are both equally fast. And if you're going for the functional-y route, please don't use function pointers. They slow down the code considerably as opposed to function objects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:30:48.530",
"Id": "17955",
"Score": "0",
"body": "@Xeo: According to http://gcc.gnu.org/onlinedocs/libstdc++/manual/strings.html libstdc++'s string is Copy-On-Write. No idea to which version(s) it applies. Regarding O(1) complexity of `std::string::length` - that's only what's *specified* but maybe the OP's implementation is flawed (there seems to be something fishy given how slow it is). Same is true for your other comments, just because *most* implementations comply to the specifications, this is not true for all of them (and I'm saying this as somebody who hsa to use MSVC6 a lot...)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:34:05.830",
"Id": "17956",
"Score": "0",
"body": "@Xeo: In general, any sufficiently old compiler will trigger every bug in the standard (template) libraries you can think of. So be careful when taking things for granted. ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:49:59.363",
"Id": "17957",
"Score": "0",
"body": "@FrerichRaabe: personally, I care little for outdated compilers. Still, your solution is the fastest that I tested (redefining `isalpha` and using an inline predicate). Which is comforting me that theory does help, since it's perhaps the most conservative with regard to memory allocation and copies."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:51:57.117",
"Id": "17958",
"Score": "0",
"body": "@MatthieuM.: Glad to hear that increasing the level of abstraction actually improves the runtime efficiency of the code for a change. ;-)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:12:59.017",
"Id": "11208",
"ParentId": "11203",
"Score": "17"
}
},
{
"body": "<p>Use the C locale. On some locales, <code>isalpha</code> and friends might be very slow.</p>\n\n<p>E.g. on UNIX</p>\n\n<pre><code>LANG=C\nexport LANG\n</code></pre>\n\n<p>or use std::locale to activate the C locale from code</p>\n\n<pre><code>std::locale::global(std::locale::classic); // untested draft\n</code></pre>\n\n<p><strong>Background</strong></p>\n\n<p>For an example of how locales can slowdown performance of e.g. UNIX <code>sort(1)</code> by a factor of 20x, see this old answer:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/7124489/unix-sort-command-takes-much-longer-depending-on-where-it-is-executed-fastest/7150015#7150015\">https://stackoverflow.com/questions/7124489/unix-sort-command-takes-much-longer-depending-on-where-it-is-executed-fastest/7150015#7150015</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T08:45:44.577",
"Id": "18047",
"Score": "0",
"body": "@Roshnal can you provide any feedback on this? In all fairness I think this was unjustly moved to codereview, and, though interesting, all micro-optimization beyond `final.reserve(in.size())` smells like premature optimization."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:27:34.330",
"Id": "11209",
"ParentId": "11203",
"Score": "3"
}
},
{
"body": "<p>Sometimes, one needs to use benchmarks.</p>\n\n<p>An idiomatic C++ solution is likely to be better optimized, so Andrey's and Frerich's solutions are both strong contenders.</p>\n\n<p>The code exposed below gives the following results with gcc 4.3.2 and -O2:</p>\n\n<ul>\n<li><p>Input1: <code>\"afoiahge m8hfw fewu8 n hv ghwvoiwbegh2390ty3t80ytgh8ghng8hg24u8b vh2vn289vh2gh28g9jfhfuweghwu2hbvgfw22ghb84ty2bgv2nfbukbvsdbvwuivbnbvbnn hf wgwg gwev wgbv23t4 1sv4gbwer14hh414ernhe 01e4g 1e 1h4ghwerh14re e4hj 14yv y344yjd1vh h 1e6\"</code></p></li>\n<li><p>Input2: the string you proposed</p></li>\n<li><p>Original: 1: 3268, 2: 138894</p></li>\n<li><p>From Andrey's: 1: 1243, 2: 65469</p></li>\n<li><p>From Frerich's: 1: 1965, 2: 140818</p></li>\n</ul>\n\n<p>Therefore, Andrey's solution offers a solid 2x speed up over your proposed solution. Much better.</p>\n\n<p>Their strategy differ though, because Andrey copies the whole string in one swoop and then removes the parts that do not fit, while Frerich only copy the right parts to begin with.</p>\n\n<p>I would select Frerich's approach (despite it being stlightly slower here), just to avoid large unused copies if memory is a concern. Note that if you have an inkling about the distribution, then you can adjust the amount of memory reserved.</p>\n\n<p>Code:</p>\n\n<pre><code>#include <sys/time.h>\n\n#include <algorithm>\n#include <iostream>\n\nnamespace bench {\n\n template <typename Func>\n double benchmark(Func f, size_t iterations)\n {\n f();\n\n timeval a, b;\n gettimeofday(&a, 0);\n for (; iterations --> 0;)\n {\n f();\n }\n gettimeofday(&b, 0);\n return (b.tv_sec * (unsigned int)1e6 + b.tv_usec) -\n (a.tv_sec * (unsigned int)1e6 + a.tv_usec);\n }\n\n}\n\nnamespace test {\n\n bool isalpha(char c) { return (c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z'); }\n bool notalpha(char c) { return not isalpha(c); }\n\n struct NotAlpha {\n bool operator()(char c) { return notalpha(c); }\n };\n\n // Roshal\n std::string strip1(std::string const& in) {\n std::string final;\n for(size_t i = 0; i < in.length(); i++) {\n if(isalpha(in[i])) final += in[i];\n }\n return final;\n }\n\n // Andrey\n std::string strip2(std::string const& s) {\n std::string in = s;\n in.erase(std::remove_if(in.begin(), in.end(), NotAlpha()), in.end());\n return in;\n }\n\n // Frerich Raabe\n std::string strip3( const std::string &s ) {\n std::string result;\n result.reserve( s.length() );\n\n std::remove_copy_if( s.begin(),\n s.end(),\n std::back_inserter( result ),\n NotAlpha() );\n\n return result;\n }\n\n} // namespace test\n\nnamespace bench {\n struct Stripper {\n typedef std::string (*Func)(std::string const&);\n\n Stripper(Func f, std::string const& s): _func(f), _s(s) {}\n\n void operator()() { _func(_s); }\n\n Func const _func;\n std::string const _s;\n };\n}\n\nint main(int argc, char* argv[]) {\n\n std::string const ref = argc == 1 ? \"Let's make an example\" : argv[1];\n\n bench::Stripper s1(test::strip1, ref);\n bench::Stripper s2(test::strip2, ref);\n bench::Stripper s3(test::strip3, ref);\n\n double const r1 = benchmark(s1, 1000);\n double const r2 = benchmark(s2, 1000);\n double const r3 = benchmark(s3, 1000);\n\n std::cout << \"1: \" << r1 << \"\\n\";\n std::cout << \"2: \" << r2 << \"\\n\";\n std::cout << \"3: \" << r3 << \"\\n\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:55:18.957",
"Id": "17959",
"Score": "0",
"body": "Can you post the test result using the worst case string included in the OP?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:55:43.760",
"Id": "17960",
"Score": "0",
"body": "I guess that, just for the record, you should verify that the solutions you benchmark actually produce the same results."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T12:05:22.430",
"Id": "17961",
"Score": "0",
"body": "Furthermore, in `benachmark`, you call `f()` up front - why is that? Finally, your program doesn't run my solution at all. Both `s2` and `s3` use `test::strip2`. If you actually run my version, you will see that it's much slower. So I'd actually go for Andrey's version."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T12:06:23.287",
"Id": "17962",
"Score": "0",
"body": "Andrey’s original code was better than your adaptation because it passes the argument by value to take advantage of move construction from temporaries. Oh, and +1 for ISO 646 keywords."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T12:35:44.230",
"Id": "17967",
"Score": "0",
"body": "@AndreasBrinck: done. It's a alpha string so unsurprisingly Andrey's solution performs very well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T12:37:06.897",
"Id": "17968",
"Score": "0",
"body": "@FrerichRaabe: Sorry for the slip, I edited the code. I call the function up front before benchmarking as a cache warm-up."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T12:38:11.157",
"Id": "17970",
"Score": "0",
"body": "@KonradRudolph: using gcc 4.3.2 for this benchmark, move operations are not a concern. Therefore I edited the signature so that it would match that of the two other functions."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T11:48:20.020",
"Id": "11210",
"ParentId": "11203",
"Score": "3"
}
},
{
"body": "<p>This is a quick method. Maybe a bit naughty writing directly into the string contents, but the new c++ standard guarantees that the string will be contiguous (according to another stackoverflow post).</p>\n\n<pre><code>inline bool isAZaz(char ch) {\n return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z');\n}\n\nvoid strip(std::string const& s, std::string* result)\n{\n result->clear();\n if (s.empty()) {\n return;\n }\n result->resize(s.size());\n\n char ch;\n char const* p = s.c_str();\n char const* e = p + s.size();\n char* o = &(*result)[0];\n char const* r = o;\n for (; p < e; ++p) {\n ch = *p;\n if (isAZaz(ch)) {\n *o++ = (ch);\n }\n }\n result->resize(o - r);\n}\n</code></pre>\n\n<p>Executes in 0.000037 seconds on my PC, compared to 0.000759 for your original method, so roughly 20 times faster. using ::isalpha instead of a handwritten check takes 0.000096 seconds (3x slower my version).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T18:30:00.297",
"Id": "18009",
"Score": "0",
"body": "What are you doing here?! Just use iterators instead of pointers. Why do you pass the argument as a pointer? Unorthodox, error-prone and unnecessary. Why do you declare `ch` outside of the loop? And while I agree that using iterators is nice, it won’t change the the performance – at least not nearly as drastic as observed by you. That’s probably due to the removal of an unnecessary copy and avoiding `isalpha`. Oh, and the code is UB if the string is empty."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T06:10:45.240",
"Id": "18034",
"Score": "0",
"body": "You can thank Microsoft for the poor iterator performance on visual studio compiler. the fact of the matter is that the correct way of doing things often isn't optimal. Yes perhaps a check for empty strings is an idea to prevent an exception accessing element zero. I think your point that using iterators won't change performance as much as I have observed by actually profiling the code is a little naive."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T06:13:23.490",
"Id": "18035",
"Score": "0",
"body": "Oh, and passing the output parameter as a pointer makes it more obvious that it is an output parameter in calling code. See the Qt coding guidelines."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T06:59:27.520",
"Id": "18036",
"Score": "0",
"body": "Iterators on strings *are* just `char*` when you compile with optimisations enabled. Going to Qt for coding guidelines is like going to the pope for the pill. Don’t use `out` parameters at all, use return values. VS (and every other modern compiler) optimises this. As for pointer-versus-index, there is virtually no difference. Again, this is optimised anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T07:59:58.690",
"Id": "18039",
"Score": "0",
"body": "On the Visual Studio compiler a string iterator IS NOT a char*. Perhaps it is on GCC, which the OP is using (have you checked?). If it is, then he might as well use iterators, but the fact you've pointed out that it is the same leads me to wonder why it matters? On VS, incrementing and dereferencing an iterator is a function call in RELEASE mode. You only need to look at the ASM output to see this. As for coding guidelines, this is not really applicable to the OP's question, which is asking how to optimize the function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T08:01:54.397",
"Id": "18040",
"Score": "0",
"body": "Added check for empty string, as this is a valid point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T08:04:03.037",
"Id": "18041",
"Score": "0",
"body": "On VS, you can turn off _SECURE_SCL, but this leads to a whole host of other problems if STL is used in libraries that don't do the same."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T08:04:23.207",
"Id": "18042",
"Score": "0",
"body": "And he is on GCC anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T08:05:31.583",
"Id": "18043",
"Score": "0",
"body": "OP should profile the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T08:09:20.037",
"Id": "18044",
"Score": "0",
"body": "Also, as for the return value, if you have a local string that is returned, it often will be a copy, not all compilers apply the RVO to this, only if the string is constructed as part of the return statement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T08:34:34.813",
"Id": "18045",
"Score": "0",
"body": "*All* modern compilers implement NRVO. As for using `_SECURE_SCL ≠ 0` … well, people who have to care about this have my deepest sympathy (I’m serious). Microsoft did developers a huge disservice with this feature."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T08:41:32.163",
"Id": "18046",
"Score": "1",
"body": "I'd have to agree with you there. Sometimes you have to be pragmatic, especially when optimizing. If you were to manually vectorize this loop, then you would have to use pointers..."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:06:37.337",
"Id": "11219",
"ParentId": "11203",
"Score": "1"
}
},
{
"body": "<p>Here's another benchmark, showing yet another possibility that may be worth considering, if you can:</p>\n\n<pre><code>#include <algorithm>\n#include <string>\n#include <iterator>\n#include <iostream>\n#include <vector>\n#include <functional>\n#include <ctype.h>\n#include <time.h>\n#include <limits.h>\n\nclass not_isalpha {\n bool table[UCHAR_MAX];\npublic:\n not_isalpha() {\n for (int i=0; i<UCHAR_MAX; i++)\n table[i] = !isalpha(i);\n }\n\n bool operator()(char input){\n return table[(unsigned char)input];\n }\n};\n\ntemplate <class T>\nT gen_random(size_t len) {\n T x;\n x.reserve(len);\n\n std::generate_n(std::back_inserter(x), len, rand);\n return x;\n}\n\ntemplate <class Container, class stripper>\nclock_t test(Container const &input, Container &result, stripper strip) { \n result.reserve(input.size());\n clock_t start = clock();\n std::remove_copy_if(input.begin(), input.end(), std::back_inserter(result), strip);\n return clock() - start;\n}\n\nvoid show(std::string const &label, clock_t ticks) {\n std::cout << label << \": \" << ticks/(double)CLOCKS_PER_SEC << \" Seconds\\n\";\n}\n\nint main(){\n typedef std::vector<char> T;\n static const size_t size = 50000000; \n\n T x(gen_random<T>(size));\n T result;\n\n show(\"not_isalpha, vector\", test(x, result, not_isalpha()));\n show(\"::isalpha, vector\", test(x, result, std::not1(std::ptr_fun(isalpha))));\n\n std::string input2(x.begin(), x.end());\n std::string result2;\n\n show(\"not_isalpha, string\", test(input2, result2, not_isalpha()));\n show(\"::isalpha, string\", test(input2, result2, std::not1(std::ptr_fun(isalpha))));\n\n return 0;\n}\n</code></pre>\n\n<p>At least in my testing, with both VC++ (10), and g++ (4.7.0), <code>std::vector</code> comes out faster than string. </p>\n\n<p>VC++ 10:</p>\n\n<pre><code>not_isalpha, vector: 0.246 Seconds\n::isalpha, vector: 0.401 Seconds\nnot_isalpha, string: 0.473 Seconds\n::isalpha, string: 0.631 Seconds\n</code></pre>\n\n<p>g++ 4.7.0:</p>\n\n<pre><code>not_isalpha, vector: 0.212 Seconds\n::isalpha, vector: 0.382 Seconds\nnot_isalpha, string: 0.285 Seconds\n::isalpha, string: 0.413 Seconds\n</code></pre>\n\n<p>Using our own table-driven version of <code>isalpha</code> helps speed quite a bit compared to using <code>::isalpha</code>, but using <code>std::vector</code> improves speed even more, especially with VC++ (though the difference is <em>fairly</em> substantial with g++ as well).</p>\n\n<p>For those who like to compare compilers, it's worth noting that g++ is not only faster overall, but also more consistently fast. With g++, the worst case is only about two times slower than the fastest. With VC++, the worst case is about three times slower.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T17:10:32.040",
"Id": "11252",
"ParentId": "11203",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "39",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T10:47:37.983",
"Id": "11203",
"Score": "25",
"Tags": [
"c++",
"strings",
"algorithm",
"homework"
],
"Title": "Most efficient way in C++ to strip strings"
}
|
11203
|
<p>I took a little heat on a method I had to resize an image and I'm hoping I can get a little help on the best way to do it. This is intended for a simple <a href="https://github.com/kentcdodds/Java-Helper" rel="nofollow">Java Helper Library</a> I'm developing. I have a few ways to do it.</p>
<p>New Method:</p>
<pre><code>/**
* This method resizes the given image
*
* @param image
* @param width
* @param height
* @param max if true, sets the width and height as maximum heights and widths, if false, they are minimums
* @return
*/
public static BufferedImage resizeImage(BufferedImage image, int width, int height, boolean max) {
int type = (image.getTransparency() == Transparency.OPAQUE)
? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
BufferedImage bi = new BufferedImage(width, height, type);
Graphics2D graphics = bi.createGraphics();
graphics.drawImage(image, 0, 0, width, height, null);
graphics.dispose();
return bi;
}
</code></pre>
<p>Original Method:</p>
<pre><code>/**
* This method resizes the given image
*
* @param width
* @param height
* @param max if true, sets the width and height as maximum heights and widths, if false, they are minimums
* @return
*/
public static ImageIcon resizeImage(ImageIcon imageIcon, int width, int height, boolean max) {
Image image = imageIcon.getImage();
Image newimg = image.getScaledInstance(-1, height, java.awt.Image.SCALE_SMOOTH);
int width1 = newimg.getWidth(null);
if ((max && width1 > width) || (!max && width1 < width)) {
newimg = image.getScaledInstance(width, -1, java.awt.Image.SCALE_SMOOTH);
}
return new ImageIcon(newimg);
}
</code></pre>
<p>Are these kinds of convenience methods ok?</p>
<pre><code>/**
* Convenience method. Creates ImageIcon from the given file location and calls resizeImage with it
*
* @param location
* @param width
* @param height
* @param max
* @return
*/
public static ImageIcon resizeImageFromFile(String location, int width, int height, boolean max) {
ImageIcon imageIcon = new ImageIcon(location);
return resizeImage(imageIcon, width, height, max);
}
/**
* Convenience method. Creates ImageIcon from the given resource location and calls resizeImage with it
*
* @param location
* @param width
* @param height
* @param max
* @return
*/
public static ImageIcon resizeImageFromResource(String location, int width, int height, boolean max) {
ImageIcon imageIcon = new ImageIcon(SwingHelper.class.getResource(location));
return resizeImage(imageIcon, width, height, max);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-29T21:55:44.650",
"Id": "18164",
"Score": "0",
"body": "Doing this correctly (working around some bugs in the Java2D pipeline, incompatible image types or poorly chosen image types, etc.) is actually not as straight forward as it seems -- you might give imgscalr a try, this is exactly what it does (and all it does -- just some static methods) http://www.thebuzzmedia.com/software/imgscalr-java-image-scaling-library/"
}
] |
[
{
"body": "<p>Edit: about the new method, I'd say Graphics2D is a bit overkill (look at Konrad Rudolph's comment for another opinion). And you don't use the max parameter anymore. Does it stretch the image?</p>\n\n<p>The original method is better, but you should have a real <code>if else</code>: resizing the image twice is a hack. It would look like this: you just have to fill in the <code>if</code>.</p>\n\n<pre><code>public static ImageIcon resizeImage(ImageIcon imageIcon, int width, int height, boolean max) {\n Image image = imageIcon.getImage();\n Image newimg;\n if(/* think what condition would work here */) {\n newimg = image.getScaledInstance(-1, height, java.awt.Image.SCALE_SMOOTH);\n } else {\n newimg = image.getScaledInstance(width, -1, java.awt.Image.SCALE_SMOOTH);\n }\n return new ImageIcon(newimg);\n}\n</code></pre>\n\n<p>I think the helper methods are useless since there is no abstraction: it just does two separate things. This does not help that much, and it's better if opening the file is explicit: the code is easier to read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T16:11:50.890",
"Id": "17985",
"Score": "1",
"body": "That’s wrong. `Graphics2D` is about painting on an image. It is *not* in any way about “displaying” images. It just so happens that most UI widgets manage their own drawing object rather than just the underlying buffered image (For performance reasons I imagine). That said, the new code doesn’t have any advantage over the old code *in this particular instance*. But as soon as you need to actually *draw*, use a `Graphics2D` object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T19:05:05.180",
"Id": "18013",
"Score": "0",
"body": "Reworded my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T19:06:43.853",
"Id": "18014",
"Score": "0",
"body": "Now I agree: for this case, it’s overkill."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:20:29.880",
"Id": "11221",
"ParentId": "11214",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "11221",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T12:34:32.167",
"Id": "11214",
"Score": "2",
"Tags": [
"java",
"optimization",
"image",
"comparative-review"
],
"Title": "Image-resizing methods"
}
|
11214
|
<p>I have a class with approximately 140 menu buttons in a nested ribbon-style menu over a canvas type area within a WinForms application.</p>
<p>As a result of this, a large swathe of my codebehind file consists of 140 event handlers for click events.</p>
<p>Many of them however, are remarkable similar, for example:</p>
<pre><code> private void btnFinancialStatusReport(object sender, EventArgs e)
{
SwitchCurrentControl(new FinancialStatusReport());
}
private void btnMonthlySalesReport(object sender, EventArgs e)
{
SwitchCurrentControl(new MonthlySalesReport());
}
private void btnDailySalesReport(object sender, EventArgs e)
{
SwitchCurrentControl(new DailySalesReport());
}
</code></pre>
<p>SwitchCurrentControl is a private method with the responsibility of essentially taking the newly constructed UserControl and docking it correctly into the active canvas. This is irrelevant to the question but I thought somebody might ask...</p>
<p><strong>The Question</strong></p>
<p>For this many buttons, (140+) a good 50% of them are practically the same, the only difference being in which Control they create.</p>
<p>Is this acceptable, or is there a way I can refactor this to reduce the amount of handlers?</p>
<p><strong>Note</strong></p>
<p>Before anybody suggests I switch to WPF btw, that is not an option...unless that same person wants to come and redo all 140 associated controls for me ;-)</p>
|
[] |
[
{
"body": "<p>You can create a Dictionary, where key is a MenuItem, a value us function/delegate that has to be called on click. All 140+ menu items subscribe to the <em>same</em> event hadler and in that event \nhandler write something like </p>\n\n<pre><code>myMenuItemsDictionary[((MenuItem)sender)]()\n</code></pre>\n\n<p>this is good, in case when you <em>have no</em> parameters to pass to a delegate, in case when you need to pass them, you can go farther:</p>\n\n<p>define a class </p>\n\n<pre><code>public class MenuItemHandler\n{\n delegate MethoddToInvokeOnClick()\n List<object> parametersToPassToDelegate = ..\n}\n</code></pre>\n\n<p>and the instances of this class have in a <code>Value</code> of the dictionary</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T10:16:55.063",
"Id": "40612",
"Score": "1",
"body": "How would you use the Class MenuItemHandler?\nWould you parse the dictionary entry and try to extract the MethodToInvoke from the value-string in the dictionary?\nCould you give a brief example?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T12:27:59.053",
"Id": "11216",
"ParentId": "11215",
"Score": "4"
}
},
{
"body": "<p>Something like this?</p>\n\n<pre><code>btnFinancialStatusReport.Click += delegate(object sender, EventArgs args) { btnGenericClick<FinancialStatusReport> (sender, args); }; \nbtnMonthlySalesReport.Click += delegate(object sender, EventArgs args) { btnGenericClick<btnMonthlySalesReport> (sender, args); }; \n\nprivate void btnGenericClick<T>(object sender, EventArgs e) where T: new()\n{\n SwitchCurrentControl(new T());\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T15:39:55.523",
"Id": "17980",
"Score": "0",
"body": "Good idea; however, you need to a the constraint `where T : new()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T17:03:51.573",
"Id": "17993",
"Score": "0",
"body": "It's also impossible to detach an anonymous delegate from an event unless you keep a named reference to it elsewhere; this may or may not be a concern to the OP."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T15:54:41.030",
"Id": "18121",
"Score": "0",
"body": "Can't say I'm a fan of creating a generic method where none of the inputs or outputs use the generic parameter(s). That makes the use confusing."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T12:29:29.987",
"Id": "11217",
"ParentId": "11215",
"Score": "3"
}
},
{
"body": "<p>You could use a \"curried\" anonymous delegate...</p>\n\n<pre><code>public static Func<object, EventArgs> CurryWith<T>(this Func<Func<T>, object, EventArgs> input, Func<T> func)\n{\n return (s,e) => input(func(), s, e);\n}\n\n...\n\nFunc<Func<Control>, object, EventArgs> switchHandler = (f, s, e)=> SwitchCurrentControl(f());\n\n...\n\nbtnFinancialStatusReport.Click += switchHandler.CurryWith(()=>new FinancialStatusReport());\nbtnMonthlySalesReport.Click += switchHandler.CurryWith(()=>new MonthlySalesReport());\nbtnDailySalesReport.Click += switchHandler.CurryWith(()=>new DailySalesReport());\n</code></pre>\n\n<p>Personally if I were doing this myself I would set up a factory that could produce various reports based on input identifying the type of report to produce. Tigran's idea of a Dictionary of delegates is an excellent one.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T17:22:00.927",
"Id": "11230",
"ParentId": "11215",
"Score": "2"
}
},
{
"body": "<p>The handlers are very simple and can hardly be simplified; However, by assigning the handlers programmatically as lambda expressions, you can turn them into one-liners</p>\n\n<pre><code>btnFinancialStatusReport.Click += (sender, e) => SwitchTo(new FinancialStatusReport());\nbtnMonthlySalesReport.Click += (sender, e) => SwitchTo(new MonthlySalesReport());\nbtnDailySalesReport.Click += (sender, e) => SwitchTo(new DailySalesReport()); \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T13:22:07.953",
"Id": "11244",
"ParentId": "11215",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "11216",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T12:19:13.803",
"Id": "11215",
"Score": "3",
"Tags": [
"c#",
"winforms"
],
"Title": "Refactoring Event Handlers - How to go about this for growing WinForms application"
}
|
11215
|
<p>Looking at a code review at work for a Win32 C# code I am seeing some lines like this:</p>
<pre><code>int MinutesPerDay = 1440;
int MinutesPerWeek = 10080;
int MinutesPerMonth = 43200;
</code></pre>
<p>and so on ...</p>
<p>I am not sure what is wrong with it but still I feel this is not a good code and design? What do you guys think? Could he do it in a better way?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T17:08:10.053",
"Id": "17995",
"Score": "1",
"body": "It should be noted that these values are only valid in timezones which do not participate in Daylight Savings Time. `MinutesPerMonth` is of course approxiamate, which may not be quite what you want."
}
] |
[
{
"body": "<p>There is a class called \"TimeSpan\", you can use that</p>\n\n<pre><code>TimeSpan interval = TimeSpan.FromDays(1);\ndouble seconds = interval.TotalSeconds;\n</code></pre>\n\n<p>I don't consider that better from a coding stand point. You should probably look at your code and figure out why you are storing those values, and find a better way. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T15:17:01.110",
"Id": "11223",
"ParentId": "11222",
"Score": "6"
}
},
{
"body": "<p>Since these are constants, I would declare them as such. Also, making the calculation explicit would be more informative.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>private const int MinutesPerDay = 24 * 60;\nprivate const int MinutesPerWeek = 7 * MinutesPerDay;\nprivate const int MinutesPerMonth = 30 * MinutesPerDay;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T17:00:13.497",
"Id": "17992",
"Score": "0",
"body": "Because these values are constant by definition, I accept the use of constants here. However, it should be noted that .NET constants are tricky, because the value is copied to the manifest of any other assembly that uses it, requiring a recompile of those assemblies should the value ever change (such as to increase precision of a decimal \"constant\" like pi, e, Planck's constant, etc). These values, however, are so extremely unlikely to ever change that this isn't a problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T17:08:43.837",
"Id": "17996",
"Score": "0",
"body": "@KeithS: Yes. In scenarios where this could be a problem, you could declare them as `static readonly` fields. By the way, they are not declared as public here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T20:29:45.950",
"Id": "18018",
"Score": "2",
"body": "I would spell out the `private` in front of `const int`. StyleCop would ask you to."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T15:21:12.320",
"Id": "18119",
"Score": "1",
"body": "@Leonid: Yes, you are probably right; however, the context is not clear here, this code could be local to a method."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T15:33:50.520",
"Id": "11224",
"ParentId": "11222",
"Score": "10"
}
},
{
"body": "<p>The closest thing .NET has is <code>TimeSpan.TicksPerDay</code></p>\n\n<p>Honestly, using ticks for your time constants is generally a good way to go, because ticks are the root value of DateTime and TimeSpan, and it makes it a little more efficient to compare Time values without having to create new instances of anything by simply comparing the Ticks of either your DateTime or TimeSpan to whatever Ticks constant you need to (be it .NET's or yours).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T15:56:46.010",
"Id": "11227",
"ParentId": "11222",
"Score": "3"
}
},
{
"body": "<p>I have ran into this just last week. I wish <code>TimeSpan</code> had a few more <code>From</code> methods for bigger time periods like weeks months and years, but I made due with these:</p>\n\n<pre><code> /// <summary>\n /// Number of minutes in an hour.\n /// </summary>\n private static readonly double minutesInHour = TimeSpan.FromHours(1).TotalMinutes;\n\n /// <summary>\n /// Number of hours in a day.\n /// </summary>\n private static readonly double hoursInDay = TimeSpan.FromDays(1).TotalHours;\n\n /// <summary>\n /// Number of hours in a week (7 days).\n /// </summary>\n private static readonly double hoursInWeek = 7.0D * hoursInDay;\n\n /// <summary>\n /// Number of hours in a month (30 days).\n /// </summary>\n private static readonly double hoursInMonth = 30.0D * hoursInDay;\n</code></pre>\n\n<p>The reason they're <code>double</code>s are to do multiplication and division calculations later on with user input that could be in a different \"base\" unit.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T15:58:54.437",
"Id": "11228",
"ParentId": "11222",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "11223",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T15:04:19.240",
"Id": "11222",
"Score": "2",
"Tags": [
"c#"
],
"Title": "MinutesPerDay - Does .NET have anything for it?"
}
|
11222
|
<p>Here is a utility that supports ETL/merging in Entity Framework. </p>
<p>If it's not appealing as a general purpose tool, why?</p>
<p>If it is appealing as a general purpose tool, how might the design be made better?</p>
<p>Also, I'm not the world's most experienced programmer when it comes to writing re-usable code with paramaterized types - any feedback on that aspect would be appreciated.</p>
<pre><code>public static class MergeUtility
{
/// <summary>
/// TODO: documentation
/// </summary>
/// <typeparam name="TItem">The type of the source items.</typeparam>
/// <typeparam name="TContainer">The type of the destination container.</typeparam>
/// <typeparam name="TTarget">The type of the destination items.</typeparam>
/// <param name="items">A function returning an enumerable set of source items.</param>
/// <param name="container">A function returning a destination container.</param>
/// <param name="sourceKey">The name of the property on each source item who's value uniquely identifies it in the whole set.</param>
/// <param name="targetSet">The name of the property on the target container who's value is the ObjectSet containing the target items.</param>
/// <param name="targetKey">The name of the property on each target item who's value uniquely identifies it in the whole set.</param>
/// <param name="save">A function called when the merge is completed to save the changes in the target container.</param>
public static void Merge<TItem, TContainer, TTarget>(
Func<IEnumerable<TItem>> items,
Func<TContainer> container,
string sourceKey,
string targetSet,
string targetKey,
Action<TContainer> save)
where TItem : class
where TContainer : IDisposable
where TTarget : class, new()
{
Log<TItem, TContainer, TTarget>();
var source = items();
using (var destination = container())
{
var target = destination.MemberValue<ObjectSet<TTarget>>(targetSet);
var existing = target.ToDictionary(c => c.MemberValue<object>(targetKey));
var mapper = new Mapper<TItem, TTarget>();
foreach (var item in source)
{
var id = item.MemberValue<object>(sourceKey);
TTarget entity;
if (existing.ContainsKey(id))
{
entity = existing[id];
}
else
{
entity = new TTarget();
target.AddObject(entity);
}
mapper.MapProperties(item, entity, false);
}
save(destination);
}
}
public static void Merge<TSource, TSourceContainer, TTarget, TTargetContainer>(
EntitySource<TSource, TSourceContainer> source,
EntityTarget<TTarget, TTargetContainer> target)
where TSource : class
where TSourceContainer : IDisposable
where TTarget : class, new()
where TTargetContainer : IDisposable
{
using (var container = source.Container())
{
Merge<TSource, TTargetContainer, TTarget>(
() => container.MemberValue<ObjectSet<TSource>>(source.Set),
target.Container,
source.Key,
target.Set,
target.Key,
target.Save);
}
}
public static void Merge<TSource, TContainer, TTarget>(
Source<TSource> source,
EntityTarget<TTarget, TContainer> target)
where TSource : class
where TContainer : IDisposable
where TTarget : class, new()
{
Merge<TSource, TContainer, TTarget>(
source.Items,
target.Container,
source.Key,
target.Set,
target.Key,
target.Save);
}
public static void Merge<T1, T2, T3>()
where T1 : class
where T2 : class, new()
where T3 : IDisposable
{
Merge(
ServiceLocator.GetInstance<Source<T1>>(),
ServiceLocator.GetInstance<EntityTarget<T2, T3>>());
}
private static void Log<TSource, TContainer, TTarget>()
where TSource : class
where TContainer : IDisposable
where TTarget : class, new()
{
Console.WriteLine("MERGE");
Console.WriteLine(" Source: " + typeof(TSource).FullName);
Console.WriteLine(" Container: " + typeof(TContainer).FullName);
Console.WriteLine(" Target: " + typeof(TTarget).FullName);
}
}
</code></pre>
<p>This is how I'm using it in my code:</p>
<pre><code>class Program
{
static void Main(string[] args)
{
Configuration.Initialize();
new Program().ExtractAndStageCakeAffiliates();
}
public Program()
{
MapperItem.AddConversion<Int32, Decimal>(c => Convert.ToDecimal(c));
MapperItem.AddConversion<Int32, String>(c => c.ToString());
MapperItem.AddConversion<Boolean, String>(c => c.ToString());
MapperItem.AddConversion<Int16, String>(c => c.ToString());
MapperItem.AddConversion<DateTime, String>(c => c.ToString());
MapperItem.AddConversion<Decimal, String>(c => c.ToString());
}
public void ExtractAndStageCakeAffiliates()
{
MergeUtility.Merge(
ServiceLocator.GetInstance<Source<Cake.Data.Wsdl.ExportService.Affiliate>>(),
ServiceLocator.GetInstance<EntityTarget<Cake.Model.Staging.CakeAffiliate, Cake.Model.Staging.CakeStagingEntities>>());
}
public void LoadCakeAffiliates()
{
MergeUtility.Merge(
ServiceLocator.GetInstance<EntitySource<Cake.Model.Staging.CakeAffiliate, Cake.Model.Staging.CakeStagingEntities>>(),
ServiceLocator.GetInstance<EntityTarget<Cake.Model.CakeAffiliate, Cake.Model.CakeContainer>>());
}
public void RefreshCakeAffiliates()
{
this.ExtractAndStageCakeAffiliates();
this.LoadCakeAffiliates();
}
}
</code></pre>
<p>And here's the DI setup:</p>
<pre><code>internal class Configuration
{
internal static void Initialize()
{
IUnityContainer container = new UnityContainer()
// Extract from web service
.RegisterInstance<Source<Cake.Data.Wsdl.ExportService.Affiliate>>(
new Source<Cake.Data.Wsdl.ExportService.Affiliate>(
() => ServiceLocator.GetInstance<Cake.Data.Wsdl.ICakeWebService>().ExportAffiliates(),
"affiliate_id"))
// Load to staging
.RegisterInstance<EntityTarget<Cake.Model.Staging.CakeAffiliate, Cake.Model.Staging.CakeStagingEntities>>(
new EntityTarget<Cake.Model.Staging.CakeAffiliate, Cake.Model.Staging.CakeStagingEntities>(
() => new Cake.Model.Staging.CakeStagingEntities(),
"CakeAffiliates",
"Affiliate_Id",
c => c.SaveChanges()))
// Extract from staging
.RegisterInstance<EntitySource<Cake.Model.Staging.CakeAffiliate, Cake.Model.Staging.CakeStagingEntities>>(
new EntitySource<Cake.Model.Staging.CakeAffiliate, Cake.Model.Staging.CakeStagingEntities>(
() => new Cake.Model.Staging.CakeStagingEntities(),
"CakeAffiliates",
"Affiliate_Id"))
// Load to production
.RegisterInstance<EntityTarget<Cake.Model.CakeAffiliate, Cake.Model.CakeContainer>>(
new EntityTarget<Cake.Model.CakeAffiliate, Cake.Model.CakeContainer>(() =>
new Cake.Model.CakeContainer(),
"CakeAffiliates",
"Affiliate_Id",
c => c.SaveChanges()))
;
</code></pre>
<p>And the object mapper:</p>
<pre><code> /// <summary>
/// This Mapper can transfer the values bwtween two existing objects, the source and the destination.
///
/// Property names are matched after being normalized:
/// 1. Underscores are removed (foo_bar_id becomes foobarid).
/// 2. Converted to uppercase (foobarid becomes FOOBARID)
/// </summary>
/// <typeparam name="S"></typeparam>
/// <typeparam name="T"></typeparam>
public class Mapper<S, T>
{
List<MemberInfo> targetMembers = new List<MemberInfo>();
private List<string> ignoreList = new List<string>();
public List<string> IgnoreList
{
get { return ignoreList; }
set { ignoreList = value; }
}
public Mapper()
{
this.targetMembers.AddRange(typeof(T).GetProperties());
this.targetMembers.AddRange(typeof(T).GetFields());
}
/// <summary>
/// Transfer the values bwtween two existing objects, the source and the destination.
/// </summary>
/// <param name="source">The object from which property values will be obtained.</param>
/// <param name="target">The object who's properties recieve the value of their matching property in the <paramref name="source"/></param>
/// <param name="failIfNotMatched">When a property in the <paramref name="source"/> does not match to a property in the <paramref name="target"/>
/// and <paramref name="failIfNotMatched"/> is TRUE, a <c>TargetNotMatchedException</c> will be thrown. Otherwise the unmatched property is ignored.< </param>
/// <param name="mapInheritedMembers">When <paramref name="mapInheritedMembers"/> is TRUE the set of source properties will include properties which
/// are inherited. Otherwise only the properties of the most derived type are mapped.</param>
public void MapProperties(S source, T target, bool failIfNotMatched = true, bool mapInheritedMembers = false)
{
BindingFlags bindingFlags = mapInheritedMembers
? BindingFlags.Public | BindingFlags.Instance
: BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance;
foreach (PropertyInfo property in source.GetType()
.GetProperties(bindingFlags)
.Where(c => !IgnoreList.Contains(c.Name)))
{
try
{
var sourceField = Factory.Get<MapperItem>(property, source);
var targetField = Factory.Get<MapperItem>(MatchToTarget(property), target);
targetField.Assign(sourceField);
}
catch (TargetNotMatchedException noMatch)
{
if (failIfNotMatched)
{
throw noMatch;
}
}
}
}
private MemberInfo MatchToTarget(MemberInfo member)
{
var exactMatch = this.targetMembers.Where(c => c.Name == member.Name);
if (exactMatch.FirstOrDefault() != null)
{
return exactMatch.First();
}
var sameAlphaChars = this.targetMembers.Where(c => Normalize(c.Name) == Normalize(member.Name));
if (sameAlphaChars.FirstOrDefault() != null)
{
return sameAlphaChars.First();
}
throw new TargetNotMatchedException(member, typeof(T));
}
private static string Normalize(string input)
{
string normalized = input.Replace("_", "").ToUpper();
return normalized;
}
}
</code></pre>
<p>MapperItem:</p>
<pre><code> /// <summary>
/// Encapsulates an item to be mapped and supports conversion from the souce type to the destination type.
/// </summary>
public class MapperItem
{
private MemberInfo memberInfo;
private object target;
private Type type;
private static Dictionary<Tuple<Type, Type>, Func<object, object>> Conversions = new Dictionary<Tuple<Type, Type>, Func<object, object>>();
/// <summary>
/// Constructor. TODO: improve comment
/// </summary>
/// <param name="member"></param>
/// <param name="target"></param>
public MapperItem(MemberInfo member, object target)
{
this.memberInfo = member;
this.target = target;
this.type = this.memberInfo.UnderlyingType();
}
/// <summary>
/// Transfers the value from one mapper item to the other while applying type conversion.
/// </summary>
/// <param name="source"></param>
public void Assign(MapperItem source)
{
this.memberInfo.Assign(this.target, source.Convert(this.type));
}
/// <summary>
/// Allows arbitrary conversions.
/// </summary>
/// <typeparam name="S"></typeparam>
/// <typeparam name="T"></typeparam>
/// <param name="converter"></param>
public static void AddConversion<S, T>(Func<object, object> converter)
{
Conversions.Add(Tuple.Create(typeof(S), typeof(T)), converter);
}
private object Value
{
get
{
return this.memberInfo.Value(this.target);
}
}
private object Convert(Type convertToType)
{
object converted = null;
if (this.Value == null)
{
return converted;
}
else if (convertToType.IsAssignableFrom(this.type))
{
converted = this.Value;
}
else
{
var conversionKey = Tuple.Create(this.type, convertToType);
if (Conversions.ContainsKey(conversionKey))
{
converted = Conversions[conversionKey](this.Value);
}
else
{
throw new Exception(convertToType.Name + " is not assignable from " + this.type.Name);
}
}
return converted;
}
}
</code></pre>
<p>Reflection extensions:</p>
<pre><code>public static class ReflectionExtensions
{
public static Type UnderlyingType(this MemberInfo member)
{
Type type;
switch (member.MemberType)
{
case MemberTypes.Field:
type = ((FieldInfo)member).FieldType;
break;
case MemberTypes.Property:
type = ((PropertyInfo)member).PropertyType;
break;
case MemberTypes.Event:
type = ((EventInfo)member).EventHandlerType;
break;
default:
throw new ArgumentException("member must be if type FieldInfo, PropertyInfo or EventInfo", "member");
}
return Nullable.GetUnderlyingType(type) ?? type;
}
public static object Value(this MemberInfo member, object target)
{
if (member is PropertyInfo)
{
return (member as PropertyInfo).GetValue(target, null);
}
else if (member is FieldInfo)
{
return (member as FieldInfo).GetValue(target);
}
else
{
throw new Exception("member must be either PropertyInfo or FieldInfo");
}
}
public static void Assign(this MemberInfo member, object target, object value)
{
if (member is PropertyInfo)
{
(member as PropertyInfo).SetValue(target, value, null);
}
else if (member is FieldInfo)
{
(member as FieldInfo).SetValue(target, value);
}
else
{
throw new Exception("destinationMember must be either PropertyInfo or FieldInfo");
}
}
public static T MemberValue<T>(this object source, string memberName)
{
return (T)source.GetType().GetMember(memberName)[0].Value(source);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T21:06:06.530",
"Id": "18020",
"Score": "0",
"body": "Is there a suitable *Contrib project?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-27T21:52:12.957",
"Id": "153451",
"Score": "1",
"body": "I would remove the DI library dependency, if it exists. Generally, reusable code has as few dependencies as possible."
}
] |
[
{
"body": "<p>In this object method I would change a couple of things</p>\n\n<blockquote>\n<pre><code> private object Convert(Type convertToType)\n {\n object converted = null;\n\n if (this.Value == null)\n {\n return converted;\n }\n else if (convertToType.IsAssignableFrom(this.type))\n {\n converted = this.Value;\n }\n else\n {\n var conversionKey = Tuple.Create(this.type, convertToType);\n\n if (Conversions.ContainsKey(conversionKey))\n {\n converted = Conversions[conversionKey](this.Value);\n }\n else\n {\n throw new Exception(convertToType.Name + \" is not assignable from \" + this.type.Name);\n }\n }\n\n return converted;\n }\n</code></pre>\n</blockquote>\n\n<p>I would return directly and get rid of the Object variable.</p>\n\n<pre><code>private object Convert(Type convertToType)\n{\n if (this.Value == null)\n {\n return null;\n }\n else if (convertToType.IsAssignableFrom(this.type))\n {\n return this.Value;\n }\n else\n {\n var conversionKey = Tuple.Create(this.type, convertToType);\n\n if (Conversions.ContainsKey(conversionKey))\n {\n return Conversions[conversionKey](this.Value);\n }\n else\n {\n throw new Exception(convertToType.Name + \" is not assignable from \" + this.type.Name);\n }\n }\n return null;\n}\n</code></pre>\n\n<p>we were discussing this question in <a href=\"http://chat.stackexchange.com/rooms/8595/the-2nd-monitor\">The Second Monitor</a> and thought that it would be a good idea to turn this method into a Generic Method like so</p>\n\n<pre><code>private T Convert<T>(objectToConvert)\n{\n if (this.Value == null)\n {\n return null;\n }\n else if (convertToType.IsAssignableFrom(this.type))\n {\n return this.Value;\n }\n else\n {\n var conversionKey = Tuple.Create(this.type, convertToType);\n\n if (Conversions.ContainsKey(conversionKey))\n {\n return Conversions[conversionKey](this.Value);\n }\n else\n {\n throw new Exception(convertToType.Name + \" is not assignable from \" + this.type.Name);\n }\n }\n return null;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-27T18:15:32.280",
"Id": "91968",
"ParentId": "11231",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T17:25:39.493",
"Id": "11231",
"Score": "5",
"Tags": [
"c#",
"entity-framework",
"etl"
],
"Title": "MergeUtility for Entity Framework"
}
|
11231
|
<p>This is a fairly popular interview question that I conceptually understand but have never really attempted to implement. In other similar implementations of this in Java I have seen they typically operate on an array of boolean values which kind of irks me. It turns out that the way the JVM works however is that it will allocate 8 bits for a single <code>boolean</code> primitive. Granted I believe that an array of booleans actually does allocate a single bit for each value but just as a personal challenge I decided to use an array of <code>byte</code> and through bitwise operations utilizing each bit for a boolean value of N.</p>
<p>This means that the byte array will really be <code>N / 8</code> or a single bit representing each possible random number that COULD occur in a list of numbers that just happens to be of N length as well.</p>
<p>The strategy is to construct my bytes by scanning each randomly generated number, determining which byte and bit that number correlates to in my byte array, and flipping the appropriate bit when that number is encountered. When the scan is finished I simply inspect each bit and the first 0 bit I encounter means that bit location in my array represents the smallest integer that is not in the list of randomly generated numbers.</p>
<p>It should consume roughly 1/8th of memory from if I were to use a List and is 1/4 faster than sorting the list of random numbers.</p>
<pre><code>import junit.framework.TestCase;
public class TestSmallestNumberNotInList extends TestCase {
static final int N = 30000000;
static int[] numbers = null;
static {
numbers = new int[N];
for (int i = 0; i < numbers.length; i++)
numbers[i] = Math.abs((int)(Math.round(Math.random() * N)));
}
public void testFindSmallestNumberNotInList() throws Exception {
long startTime = System.currentTimeMillis();
int byteArrayLength = (int) Math.ceil(N / 8);
byte[] bitset = new byte[byteArrayLength];
for (int number : numbers) {
int byteIndex = (int)Math.floor(number / 8);
byte b = bitset[byteIndex];
int bitMod = (int)(number % 8);
// The bit value will be 1 if we encountered this number before
int bitVal = b>>>(32-bitMod) & 0x00000001;
if (bitVal == 1)
continue;
//Get a byte mask to OR against the existing byte, flipping just the one bit
//we are concerned with.
byte byteMask = (byte)(1<<bitMod);
b = (byte)(b | byteMask);
//assign the new byte value for the byte array
bitset[byteIndex] = b;
}
//Scan the byte array for the first 0 bit, this ((index * 8) + bitmodulus) is the smallest
//integer not in the list.
int location = 0;
for (int i = 0; i < bitset.length; i++) {
byte b = bitset[i];
if (b == 0xFF) {
location += 8;
continue;
} else {
for (int j=8; j>=1; j--) {
if ((b>>>(j) & 0x00000001) == 1)
location++;
}
break;
}
}
long duration = System.currentTimeMillis() - startTime;
System.out.println("Total Memory: " + Runtime.getRuntime().totalMemory());
System.out.println("Free Memory: " + Runtime.getRuntime().freeMemory());
System.out.println("Smallest number not in the list is " + location);
System.out.println("Time to execute in milliseconds: " + duration);
}
private static String getBitString(int x) {
StringBuffer buf = new StringBuffer();
for (int i=1; i<=32; i++) buf.append(x>>>(32-i) & 0x00000001);
return buf.toString();
}
}
</code></pre>
<p>I believe the output is correct although I really haven't unit tested the results. It certainly <em>seems</em> correct. I was wondering if I am making any glaring mistakes in my arithmetic or code or if you have any other possibilities or suggestions for improvement?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T20:43:17.020",
"Id": "18019",
"Score": "1",
"body": "http://docs.oracle.com/javase/6/docs/api/java/util/BitSet.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T09:37:00.660",
"Id": "18051",
"Score": "1",
"body": "Maybe I missed something here, but why not sort the array and walk through it until `numbers[idx] != counter++` with `counter = numbers[0];`? Maybe even utilize a binary search..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T11:59:30.283",
"Id": "18052",
"Score": "0",
"body": "@palacsint Wow... was never aware of that class! Like I said though this is more of a skills exercise. If I were going to deploy such code into a production environment it would be unit tested and I would likely use the BitSet class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T12:00:52.900",
"Id": "18053",
"Score": "0",
"body": "@Bobby The metrics I ran performed the sort operation on the list in almost 5 seconds. This method sorts this list in a little under a second so it is over 4 times faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-03T22:49:11.783",
"Id": "18377",
"Score": "1",
"body": "However, the implementation using sort is simpler. Performance doesn't matter until it matters; until then, maintainability is king."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-29T18:45:15.937",
"Id": "24629",
"Score": "0",
"body": "Looks like the data structure you need is [BitSet](http://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-28T01:24:20.223",
"Id": "124290",
"Score": "0",
"body": "This sometimes throws an ArrayIndexOutOfBounds on the statement `byte b = bitset[byteIndex];`"
}
] |
[
{
"body": "<p>So just a few things that I am seeing here. You are using Math.floor, ceil on integers which is totally unnecessary, integers by definition don't have a decimal portion. You also don't need to cast an int as an int. </p>\n\n<p>To make this run faster and take up less stack space, in the for loop where you set the bits you don't need to check anything, just do the bit twiddling you want.</p>\n\n<pre><code>int bitMod = 0x1 << (number % 8);\nbyte b = number / 8;\nbitset[b] |= bitMod;\n</code></pre>\n\n<p>Getting the position of the bit you want to change and then just or ing it won't change any other bits.</p>\n\n<p>Finally, I don't know why you did it the way you did, but your final for loop doesn't work correctly. It starts with the Most Significant Bit and moves down, instead of the least moving up. Here is a version that I have tested and found to work.</p>\n\n<pre><code>for (int j=0; j<8; j--) {\n if ((b & (1 << j)) != 0){\n location++;\n } else {\n break;\n }\n}\n</code></pre>\n\n<p>Finally, just to see what kind of memory this might be using, I called the free memory before and after to compare the difference. It looks like this program uses 56 MB, and takes under 100 ms after my few changes.</p>\n\n<pre><code>actual lowest is 1\n(Initial Implementation)\nFree Memory: 563760\nSmallest number not in the list is 2\nTime to execute in milliseconds: 156\n2 is in the list true\n\n(Optimized and cleaned up)\nFree Memory: 563760\nSmallest number not in the list is 1\nTime to execute in milliseconds: 93\n1 is in the list false\n</code></pre>\n\n<p>Here is the class I used to test.</p>\n\n<pre><code>public class TestSmallestNumberNotInList {\n\nstatic final int N = 3000000;\nstatic int[] numbers = null;\nstatic {\n numbers = new int[N];\n for (int i = 0; i < numbers.length; i++) {\n numbers[i] = Math.abs((int)(Math.round(Math.random() * N)));\n }\n}\n\npublic void testFindSmallestNumberNotInList() {\n\n Runtime.getRuntime().gc();\n Runtime.getRuntime().gc();\n Runtime.getRuntime().gc();\n long total = Runtime.getRuntime().totalMemory();\n long free = Runtime.getRuntime().freeMemory();\n long startTime = System.currentTimeMillis();\n\n int byteArrayLength = (int) Math.ceil(N / 8);\n byte[] bitset = new byte[byteArrayLength];\n\n for (int number : numbers) {\n int byteIndex = (int)Math.floor(number / 8);\n byte b = bitset[byteIndex];\n int bitMod = (int)(number % 8);\n\n // The bit value will be 1 if we encountered this number before\n int bitVal = b>>>(32-bitMod) & 0x00000001;\n if (bitVal == 1)\n continue;\n\n //Get a byte mask to OR against the existing byte, flipping just the one bit\n //we are concerned with.\n byte byteMask = (byte)(1<<bitMod);\n b = (byte)(b | byteMask);\n\n //assign the new byte value for the byte array\n bitset[byteIndex] = b;\n }\n\n //Scan the byte array for the first 0 bit, this ((index * 8) + bitmodulus) is the smallest\n //integer not in the list.\n int location = 0;\n for (int i = 0; i < bitset.length; i++) {\n byte b = bitset[i];\n if (b == 0xFF) {\n location += 8;\n continue;\n } else {\n for (int j=8; j>=1; j--) {\n if ((b>>>(j) & 0x00000001) == 1)\n location++;\n }\n break;\n }\n }\n\n long duration = System.currentTimeMillis() - startTime;\n\n System.out.println(\"Total Memory: \" + (total - Runtime.getRuntime().totalMemory()));\n System.out.println(\"Free Memory: \" + (free - Runtime.getRuntime().freeMemory()));\n System.out.println(\"Smallest number not in the list is \" + location);\n System.out.println(\"Time to execute in milliseconds: \" + duration);\n boolean isInList = false;\n for (int next : numbers){\n if (location == next){\n isInList = true;\n break;\n }\n }\n System.out.println(location + \" is in the list \" + isInList);\n}\n\npublic void testMine() {\n Runtime.getRuntime().gc();\n Runtime.getRuntime().gc();\n Runtime.getRuntime().gc();\n long total = Runtime.getRuntime().totalMemory();\n long free = Runtime.getRuntime().freeMemory();\n long startTime = System.currentTimeMillis();\n\n int byteArrayLength = numbers.length / 8;\n byte[] bitset = new byte[byteArrayLength];\n\n for (int number : numbers) {\n int byteIndex = number / 8;\n int bitMod = (1 << (number % 8)) & 0xFF;\n bitset[byteIndex] |= bitMod;\n }\n\n //Scan the byte array for the first 0 bit, this ((index * 8) + bitmodulus) is the smallest\n //integer not in the list.\n int location = 0;\n for (int i = 0; i < bitset.length; i++) {\n byte b = bitset[i];\n if (b == 0xFF) {\n location += 8;\n continue;\n } else {\n for (int j=0; j<8; j++) {\n if ((b & (1 << j)) != 0){\n location++;\n } else {\n break;\n }\n }\n break;\n }\n }\n\n long duration = System.currentTimeMillis() - startTime;\n\n System.out.println(\"Total Memory: \" + (total - Runtime.getRuntime().totalMemory()));\n System.out.println(\"Free Memory: \" + (free - Runtime.getRuntime().freeMemory()));\n System.out.println(\"Smallest number not in the list is \" + location);\n System.out.println(\"Time to execute in milliseconds: \" + duration);\n\n boolean isInList = false;\n for (int next : numbers){\n if (location == next){\n isInList = true;\n break;\n }\n }\n System.out.println(location + \" is in the list \" + isInList);\n}\n\n\npublic void getSmallestNotInList() {\n int lowest = 0;\n boolean notLowest = true;\n while (notLowest){\n int last = lowest;\n for (int i=0; i<numbers.length; i++){\n if (numbers[i] == lowest){\n lowest++;\n break;\n }\n }\n if (last == lowest){\n break;\n }\n }\n System.out.println(\"actual lowest is \" + lowest);\n}\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T19:40:34.973",
"Id": "15335",
"ParentId": "11232",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T17:44:57.980",
"Id": "11232",
"Score": "3",
"Tags": [
"java",
"optimization",
"memory-management",
"interview-questions"
],
"Title": "Java: Find the smallest integer not in the list - Memory Efficiency"
}
|
11232
|
<p>I have all these functions that work together to create functionality on a page. Is the structure of these functions OK? Can I do anything to speed this up or make my code better? I'm not exactly sure what namespaces are, but might they help me here?</p>
<p>This code is for a responsive/adaptive calendar website. On the homepage, there is a calendar with events listed by day. These functions filter the events using the ISOTOPE plugin, open and close dropdowns, etc.</p>
<p>If anyone is really interested. I can send you a link + login to the PW protected site.</p>
<pre><code>var $eventwrap = $j('.tw-lists'),
$daywrap = $j('.tw-day'),
$dayfilter = $j('#tw-filter-days li a');
$daywraphide = $j('tw-day.hide'),
$catwrap = $j('.tw-list-filter'),
$viewctrls = $j('.tw-view a'),
$selectdays = $j('.select-days option'),
$selectbarrio = $j('.select-barrio option'),
$selectcats = $j('.select-cats option');
filters = {};
var opday = [],
opcategory = [],
opbarrio = [];
function optionArray(select,options) {
$j(select).find('option').each(function() {
options.push($j(this).attr('data-filter'));
});
return options;
}
// CHECK IF A GIVEN DAY HAS EVENTS
function filterToggle(element,x,y) {
element.each(function(){
var $me = $j(this),
isli = $me.is('li');
if(isli) {
var myvalue = $me.find('a').attr('data-filter');
} else {
var myparent = $me.parent().attr('data-filter-group'),
myvalue = $me.attr('data-filter');
}
if(!x) {x = ''}
if(!y) {y = ''}
var eventcount = $j('.tw-list'+ myvalue + x + y).length;
if(eventcount == 0) {
if(isli) {
$me.addClass('empty tdn');
} else {
$me.attr('disabled','disabled');
}
} else {
if(isli) {
$me.removeClass('empty tdn');
} else {
$me.removeAttr('disabled');
}
}
});
}
function filterAll() {
var currentbarrio = $j('#tw-filter-barrio .current a').attr('data-filter'),
currentcats = $j('#tw-filter-cats .current a').attr('data-filter'),
currentday = $j('#tw-filter-days .current a').attr('data-filter'),
selectbarrio = $j('.select-barrio :selected').attr('data-filter'),
selectcats = $j('.select-cats :selected').attr('data-filter'),
selectday = $j('.select-days :selected').attr('data-filter');
filterToggle($j('#tw-filter-days li'),currentbarrio,currentcats);
filterToggle($j('#tw-filter-barrio li'),currentcats,currentday);
filterToggle($j('#tw-filter-cats li'),currentday,currentbarrio);
filterToggle($selectdays,selectbarrio,selectcats);
filterToggle($selectbarrio,selectcats,selectday);
filterToggle($selectcats,selectday,selectbarrio);
$j('#tw-filter-days .current a').click();
return false;
}
// SELECT FILTER ON CLICK
function filterDrop(dropdown) {
dropdown.find('.tw-filter-drop-options a').on('click',function(){
var $me = $j(this);
if($me.parent().hasClass('empty')){
//No events for that option
return false;
} else {
var $toggle = dropdown.find('.tw-filter-drop-toggle'),
toggleText = $toggle.find('span').html(),
myDropText = $me.html();
dropdown.removeClass('open');
if (myDropText == toggleText) {
return false;
} else {
var $parent = $me.parents('.tw-filter-dropdown'),
parentId = $parent.attr('id');
dropdown.find('.tw-filter-drop-options li').removeClass('current');
$me.parent().addClass('current');
dropdown.find('.tw-filter-drop-label').html(myDropText);
filterAll();
}
}
});
}
// FILTER CLICK
function filterClick($element) {
$element.on('click',function(){
var $me = $j(this),
$parent = $me.parent(),
myvalue = $me.attr('data-filter'),
$mytwin = $j(".tw-filter-select").find("[data-filter='"+myvalue+"']");
if($parent.hasClass('empty') || $parent.hasClass('current')) {
return false;
}
if($me.parents('#tw-filter-days').length !== 0) {
$j('#tw-filter-days li').removeClass('current');
$parent.addClass('current');
}
var $optionSet = $me.parents('ul'),
group = $optionSet.attr('data-filter-group');
filters[ group ] = myvalue;
var isoFilters = [];
for ( var prop in filters ) {
isoFilters.push( filters[ prop ] )
}
var selector = isoFilters.join(''),
currentday = $j('#tw-filter-days .current a').attr('data-filter'),
$dayheader = $j('.tw-day-header');
$dayheader.hide();
$dayheader.filter(currentday).show();
$j('.tw-list-filter').isotope({ filter: selector, animationEngine : 'css' });
$mytwin.attr('selected','selected');
filterAll();
return false;
});
}
// SWITCH VIEWS
function switchViews($element, $events) {
$element.on('click',function(){
var $me = $j(this),
$parent = $me.parent();
myclass = $me.attr('class').split('-');
myview = myclass[0];
if($me.hasClass('selected')) {
return false;
}
var selector = $j('#tw-filter-days .current a').attr('data-filter');
if(myview == 'list') {
$events.removeClass('grid-wrap');
$j('.tw-list-filter').isotope({ animationEngine : 'css' });
} else {
$events.addClass('grid-wrap');
$j('.tw-list-filter').isotope({ animationEngine : 'css' });
}
$parent.removeClass('list grid').addClass(myview);
$element.removeClass('selected');
$me.addClass('selected');
});
}
// SETUP SCROLLABLE
function scrollableSetup($textslide, $imgslide, $homeslide) {
$textslide.scrollable({easing: 'swing', keyboard: true, speed: 500}).navigator();
$imgslide.scrollable({keyboard: false, speed: 950}).navigator();
if($textslide.length) {
var textscroll = $textslide.data("scrollable");
textscroll.onSeek(function() {
if(!$imgslide.is(':visible')) {
var myindex = this.getIndex(),
$myslide = $textslide.find('.item:eq('+myindex+')'),
myheight = $myslide.find('.text-inner').height(),
homeslideHeight = $homeslide.css('height'),
homeslideHeight = homeslideHeight.replace('px','')
if(homeslideHeight != myheight){
$homeslide.removeAttr('style').css('height',myheight);
}
}
return false;
});
}
$j(document).keydown(function(e){
if (e.keyCode == 37) {
$textslide.scrollable().prev();
$imgslide.scrollable().prev();
return false;
}
if (e.keyCode == 39) {
$textslide.scrollable().next();
$imgslide.scrollable().next();
return false;
}
});
}
// OPEN AND CLOSE DROPDOWN
function openDropDowns($droptoggle, $dropdown) {
$droptoggle.on('click',function() {
$j('.tw-filter-dropdown.open').removeClass('open');
var $me = $j(this)
var toggletext = $me.find('span').html();
$me.parent().addClass('open');
});
//Hide drop downs on click off
$j(document).bind('click', function (e) {
$j('.tw-filter-dropdown').removeClass('open');
});
$dropdown.bind('click', function(e) {
e.stopPropagation();
});
}
// FOCUS FUNCTION FOR MOBILE SELECTS
function mobileFocus($select) {
$select.focus(function(){
var $me = $j(this),
previousval = $me.value,
$previous = $me.find(':selected');
}).change(function(){
var $me = $j(this),
myvalue = $me.find(':selected').attr('data-filter'),
$myoption = $me.find("[data-filter='"+myvalue+"']");
mygroup = $me.attr('data-filter-group'),
$mytwin = $j('.tw-filter a[data-filter="'+myvalue+'"]');
if($myoption.attr('disabled') == 'disabled') {
alert('No hay eventos en este barrio y día');
return false;
}
filters[ mygroup ] = myvalue;
var isoFilters = [];
for ( var prop in filters ) {
isoFilters.push( filters[ prop ] )
}
var selector = isoFilters.join(''),
currentday = $j('.select-days :selected').attr('data-filter'),
$dayheader = $j('.tw-day-header .white-bub, .tw-day-header');
$dayheader.hide();
$dayheader.filter(currentday).show();
$j('.tw-list-filter').isotope({ filter: selector, animationEngine : 'css' });
$mytwin.click();
filterAll();
});
}
$j(window).smartresize(function(){
$j('.tw-list-filter').isotope({animationEngine : 'css'});
$j('#tw-filter-barrio .current a').click();
if($j(this).height() > 500) {
$j('.navi .active').click();
$j('.home-slide').removeAttr('style')
}
});
</code></pre>
<p>Then in my HTML:</p>
<pre><code><script>
$j(document).ready(function($){
var $textslide = $('.text-slide'),
$imgslide = $('.img-slide'),
$homeslide = $('.home-slide'),
$filters = $('.tw-filter ul a'),
$views = $('.tw-view a'),
$droptoggle = $('.tw-filter-drop-toggle'),
$dropdown = $('.tw-filter-dropdown'),
$select = $('.tw-filter-select'),
$filterdays = $('#tw-filter-days'),
$filtercats = $('#tw-filter-cats'),
$filterbarrio = $('#tw-filter-barrio'),
$events = $('.tw-lists');
scrollableSetup($textslide, $imgslide, $homeslide);
filterClick($filters);
switchViews($views, $events);
mobileFocus($select)
filterDrop($filterbarrio);
filterDrop($filtercats);
openDropDowns($droptoggle, $dropdown);
$('.list-view').click();
$dayfilter.not('.empty > a').first().click();
});
</code></pre>
<p></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T18:07:28.210",
"Id": "18004",
"Score": "0",
"body": "Look into object oriented programming, DRY, modules, separation of concerns. As it is now, anyone trying to understand this code needs to be intimately familiar with the whole thing in its entirety instead of nice digestible chunks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T18:11:23.977",
"Id": "18006",
"Score": "1",
"body": "I agree with Esailija. Please, explain the functionality at least."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-29T01:55:12.327",
"Id": "18140",
"Score": "0",
"body": "I don't have the rep to re-tag, but `functional-programming` seems to not apply here."
}
] |
[
{
"body": "<p>Here are the first steps I would take (not necessarily in order):</p>\n\n<ol>\n<li><p><strong>Surround everything with an anonymous self calling function</strong></p>\n\n<pre><code>(function () {\n ...\n}());\n</code></pre>\n\n<p>This both helps ensure you don't accidentally add/overwrite global variables and aids in the future minification of your script.</p></li>\n<li><p><strong>Define all variables at the start of their respective functions</strong></p>\n\n<pre><code>if(isli) {\n var myvalue = $me.find('a').attr('data-filter');\n} else {\n var myparent = $me.parent().attr('data-filter-group'),\n myvalue = $me.attr('data-filter');\n}\n</code></pre>\n\n<p>This kind of code is error-prone and makes future refactorings harder (and you will change it later).</p></li>\n<li><p><strong>Explicitly export any globals you wish to define at the very end of your script</strong></p>\n\n<pre><code>$.extend(window, {\n 'scrollableSetup': scrollableSetup,\n 'filterClick': filterClick,\n 'switchViews': switchViews,\n 'mobileFocus': mobileFocus,\n 'filterDrop': filterDrop,\n 'openDropDowns': openDropDowns\n});\n</code></pre>\n\n<p>This also helps the minification process (internally the function names can be munged). As a general rule it is better to be explicit where you can be. The quotes are important to certain minifiers.</p></li>\n<li><p><strong>Explicitly declare/pass in any global objects to the anonymous function</strong></p>\n\n<pre><code>(function (window, document, $, ...) {\n ...\n}(window, document, jQuery, ...));\n</code></pre>\n\n<p>Again this helps minification (now globals can be munged). Also, still better to be explicit.</p></li>\n<li><p><strong>Run JSLint on your code</strong></p>\n\n<p><a href=\"http://www.jslint.com/\">http://www.jslint.com/</a></p>\n\n<p>The only errors I tolerate in JSLint are:</p>\n\n<ul>\n<li>messy whitespace (sometimes) </li>\n<li>++ usage (only in counter part of for loops)</li>\n<li>\"'variable' was used before it was defined.\" (only in the parameter list to the anonymous method)</li>\n</ul></li>\n<li><p><strong>Remove unused variables</strong></p>\n\n<pre><code>$select.focus(function(){\n var $me = $j(this),\n previousval = $me.value,\n $previous = $me.find(':selected');\n}).change(function(){\n</code></pre>\n\n<p>Unused variables are dead weight. Every line of code you don't need to write is a line of code that the person looking at this 6 months from now doesn't need to look at and figure out what you were thinking. Unused variables come in several forms:</p>\n\n<ol>\n<li>variables in the beginning of your functions (see step 2) that don't get used within the function</li>\n<li>variables that get exported to an outer scope but do not serve a purpose</li>\n<li>functions that do not get used</li>\n<li>event handlers that don't do anything</li>\n</ol></li>\n<li><p><strong>Code that does the same thing should look the same</strong></p>\n\n<p>JQuery has a half dozen ways to bind events (<code>.bind</code>, <code>.on</code>, <code>.click</code>, <code>.live</code>, <code>.delegate</code>, <code>.one</code>). The only one you need is <code>.on</code>. Replace:</p>\n\n<pre><code>.bind('click', function () {\n</code></pre>\n\n<p>with</p>\n\n<pre><code>.on('click', function () {\n</code></pre>\n\n<p>and so on. </p>\n\n<p>Similarly within a method, avoid switching between <code>if</code> statements and <code>switch</code> statements and back:</p>\n\n<pre><code>if (x === y) {\n return 'x';\n}\nswitch (x) {\ncase z:\n ...\n}\nif (x ...\n</code></pre>\n\n<p>This is better written with pure if statements.</p>\n\n<p>Continuing this thought process, don't switch between method short circuiting and \"The One Return\" (with one exception: arg checks):</p>\n\n<pre><code>if (x) { return a; }\nif (y) { return b; }\nif (z) { r = ... }\nif (!r && t) { r = ... }\n...\nreturn r || ...;\n}\n</code></pre>\n\n<p>In general, logic that changes in style is much harder to read than logic that remains stylistically constant.</p></li>\n<li><p><strong>Pull constants out</strong></p>\n\n<p>If a variable doesn't change within a function or between runs of a function, then it is not a variable with respect to that function. Thus it doesn't belong there (except at the root level). </p></li>\n<li><p><strong>Use the right method for the job</strong></p>\n\n<pre><code>Instead of Use \n.attr('data-x') .data('x')\nif (x) { $a.show() } else { $a.hide() } $a.toggle(x) \nx ? $a.addClass('a') : $a.removeClass('a') $a.toggleClass('a', x)\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T21:59:21.533",
"Id": "18023",
"Score": "0",
"body": "Great! Thanks for the pointers. The one thing I'm having trouble with is wrapping everything with the anonymous function and exporting the variables-- after doing so the script doesn't seem to load. Is there anything I need to change in my document.ready function in my footer where I call those functions?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T22:56:32.040",
"Id": "18025",
"Score": "0",
"body": "I'd try using firebug (or equivalent for other browsers, but fb is the best imo). I'd need the error in the console to help farther."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T23:22:06.033",
"Id": "18026",
"Score": "0",
"body": "that's the frustrating part... it doesn't throw an error"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T00:22:29.623",
"Id": "18028",
"Score": "0",
"body": "ok try this: start with the empty anonymous function over at JSLint, and add code to it one function at a time until you get everything over there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T00:29:46.417",
"Id": "18029",
"Score": "0",
"body": "While I think it would be best if you went through that process yourself, here is a link with all of this done: http://jsfiddle.net/qcbng/ (there is still a lot more that can be done to make this code better, but your code should look in jslint just like that and I may have fixed some variables you were expecting to be broken due to misplaced semicolons)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T02:53:00.820",
"Id": "18032",
"Score": "0",
"body": "Bill thanks so much for your time! I put my latest code here and everything is working great. http://jsfiddle.net/msfh3/1/\n\nAny more comments and feedback are much appreciated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T02:16:20.617",
"Id": "20163",
"Score": "0",
"body": "Item 9, toggle examples, must x be transformed into a boolean? How do I do that in JS?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-13T13:21:13.887",
"Id": "20181",
"Score": "0",
"body": "`false`, `undefined`, `null`, `0`, `''`, `NaN` are all false; every other value is true."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-23T06:41:17.033",
"Id": "37432",
"Score": "0",
"body": "consider adding a `;` before the IIFE to protect your code."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T19:09:52.400",
"Id": "11235",
"ParentId": "11233",
"Score": "24"
}
}
] |
{
"AcceptedAnswerId": "11235",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T17:57:44.017",
"Id": "11233",
"Score": "12",
"Tags": [
"javascript",
"jquery",
"beginner",
"functional-programming",
"datetime"
],
"Title": "Responsive/adaptive website code"
}
|
11233
|
<p>I'm attempting to create a comparison table to compare products depending on the add-ons they have. To grab the data and filter it I'm using LINQ To SQL.</p>
<p>Table's Layout (cut short):</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Products Table
ID
Name
CategoryID
ProductAddons
Category Table
ID
Name
ProductAddon Table
ID
Amount
AddonID
ProductID
Addon Table
ID
Name
</code></pre>
</blockquote>
<p>Example Data:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Products
ID Name CategoryID
1 Product1 1
2 Product2 1
3 Product3 1
Categories
ID Name
1 Category1
ProductAddons
ID Amount AddonID ProductID
1 1 1 1
2 2 2 1
3 1 3 1
4 2 1 2
5 3 2 2
6 1 2 3
7 1 3 3
Addons
ID Name
1 Addon1
2 Addon2
3 Addon3
</code></pre>
</blockquote>
<p>Currently I have this:</p>
<pre class="lang-cs prettyprint-override"><code>var addons = (from s in Products
where s.Category.Name == "Category1"
orderby s.ProductAddons.Count descending
let adds = from a in s.ProductAddons
orderby a.Addon.Name
select new { Name = a.Addon.Name, Amount = a.Amount }
select adds).ToList();
var compare = from c in addons
let has = from z in addons.First().Union(addons.First().Except(c))
let add = (from a in c
where a.Name == z.Name
select a.Amount).FirstOrDefault()
select new { Name = z.Name, Amount = add }
select has;
var compileResults = from c in addons.First()
let adds = from s in compare
let y = (from a in s
where a.Name.Contains(c.Name)
select a.Amount).First()
select y
select new { Addon = c.Name, Amounts = adds };
</code></pre>
<p>This would return (3 products, 3 Add-ons):</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Addon Amounts
Addon1 1
2
0
Addon2 2
3
1
Addon3 1
0
1
</code></pre>
</blockquote>
<p>I can then loop through the results to build my compare table, which works fine. But to me the LINQ looks somewhat messy. Would there be a cleaner way to do this? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T04:32:10.483",
"Id": "18033",
"Score": "2",
"body": "Do you have some sample data that would produce those results that you could share with us? Your query is _very_ complicated, much more complicated than it probably has to be and it's hard to make sense of it. \"somewhat messy\" is a _huge_ understatement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T13:20:42.550",
"Id": "18059",
"Score": "0",
"body": "Hi Jeff. I've added the table layouts and sample data. The table layouts are set in stone and cannot be changed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-29T02:36:04.647",
"Id": "18142",
"Score": "0",
"body": "You say you're using LINQ to SQL, but there's an Entity Framework tag on the question. They're really two different technologies any may (or may not) matter in getting a proper answer."
}
] |
[
{
"body": "<p>So it looks like what you want is some sort of outer join. I think this should work for you:</p>\n\n<pre><code>var categoryFilter = \"Category1\";\nvar query =\n from addon in dc.Addons\n select new\n {\n Addon = addon.Name,\n Amounts =\n from product in dc.Products\n where product.Category.Name == categoryFilter\n join productAddon in dc.ProductAddons\n on new { AddonId = addon.Id, ProductId = product.Id }\n equals new { productAddon.AddonId, productAddon.ProductId }\n into pas\n from productAddon in productAddons.DefaultIfEmpty()\n select (int?)productAddon.Amount ?? 0,\n };\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-29T02:37:40.883",
"Id": "18143",
"Score": "0",
"body": "Where does this order by the add-on count in a descending fashion? I've been wrestling with it myself to no end and can't get it to work properly in a single query."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-04T14:09:15.647",
"Id": "18394",
"Score": "0",
"body": "This assumes the order provided by the context. No additional ordering was made on the addons. Though that could easily be added by including `orderby addon.Id`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T18:20:11.423",
"Id": "11253",
"ParentId": "11236",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T19:56:14.097",
"Id": "11236",
"Score": "7",
"Tags": [
"c#",
"linq",
"entity-framework",
"linq-to-sql"
],
"Title": "Comparison table for comparing products"
}
|
11236
|
<p>Firstly, apologies if this is not the correct type of question for here, I had it on the stackoverflow but it was closed with a suggestion I post here. </p>
<p>I’m in the process of converting from Latin 15 to Unicode/UTF-8 and researched several tutorials, and am looking here for a critique of what I have implemented based on them (or, IOW, did I understand it!) :</p>
<p>I want to parse form data in PHP to ensure it is safe from SQL injection and email header attacks, and any other security holes I've not considered.</p>
<p>Although I’m using UTF-8, I just want to cater for English plus some of the extra acute, tilde etc. characters that would normally encounter, plus the Euro symbol. Everything else is disallowed and throws an error, as opposed to silently being replaced/removed.</p>
<p>This is my code so far:</p>
<pre><code>// ensure it's valid unicode / get rid of invalid UTF8 chars
$text = iconv("UTF-8","UTF-8//IGNORE",$text);
// and just allow a basic english...ish.. chars through - no controls, chinese etc
$match_list = "\x{09}\x{0a}\x{0d}\x{20}-\x{7e}"; // basic ascii chars plus CR,LF and TAB
$match_list .= "\x{a1}-\x{ff}"; // extended latin 1 chars excluding control chars
$match_list .= "\x{20ac}"; // euro symbol
if (preg_match("/[^$match_list]/u", $text) )
$error_text_array[] = "<b>INVALID UNICODE characters</b>";
</code></pre>
<p>This code should only allow the characters shown in yellow here <a href="http://solomon.ie/unicode/" rel="nofollow">http://solomon.ie/unicode/</a></p>
<p>My main question is does this do as I want (it seems to work) or have I missed anything? My understanding of this is that the <code>iconv</code> function will remove any invalid sequences (i.e. hack attempts at the bit level) and leave just valid UTF-8, then my regexp checks for the characters I want allowed.</p>
<p>Although it seems to work I’m still confused by the regexp and the hex notation. Am I matching the Unicode code points, or, the actual binary UTF-8 representation of those code points? * It appears to be the former.</p>
<p>*<em>my understanding is that a codepoint is basically the virtual location of a specific character in the Unicode “world” or characters, i.e. Euro symbol is the 20ACth character from the start, but it’s actual binary code, and number of bytes, is depended on if you use UTF-8, or 16 or 2 etc. So the codepoint never changes but the bit sequence can.</em></p>
<p>And, I have seen both, say, <code>\x{20}-\x{7e}</code> and <code>\x20-\x7e</code> used – what is the difference with and without the braces?</p>
<p>I intend to use the above few lines on all form fields, then follow it by further checks depending on the nature of the input.</p>
<p>For example if expecting an integer of the <code>0-9</code> kind, can I just use <code>preg_match("/[^0-9]/", $text)</code> without the <code>/u</code> modifier and specify literal characters (from <code>x00</code> to <code>x7e</code>)? And suppose I want to allow <code>0-9</code> and the Euro in, is this the correct way <code>preg_match("/[^0-9\x{20ac}]/u", $text)</code>? And if I’m expecting a hidden field with ”ADD” or “EDIT” is <code>if (!preg_match("/^(ADD|EDIT)$/", $text))</code> is still valid to test that?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T13:05:24.147",
"Id": "18057",
"Score": "1",
"body": "I don't see why they closed it and told you to move it here. This is a legitimate question and not so much a code review. At least if I am understanding your issue correctly, you are just looking for clarification. Someone here might be able to help, but all I know about regex is that some alien wrote it, so good luck!"
}
] |
[
{
"body": "<p>Your code seems legit to me, so I'll try to answer some of your questions.\n<code>preg_match()</code> uses UTF-8 input based on code points, so you don't have to worry about that.\nThe difference between <code>\\xYY</code> and <code>\\x{YYYY}</code> is that the first one accepts either one or two characters after control <code>\\x</code> (so, up to 256-th code point), and the latter one is universal and accepts range which covers all Unicode table.\nThe <code>u</code> flag for RegExp pattern indicates that engine should treat the pattern as Unicode, it doesn't do anything with the text under test. So you can omit this flag in simple patterns like <code>/[0-9]/</code>. The last two code snippets also correct.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-12T03:23:17.063",
"Id": "19516",
"ParentId": "11242",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T12:24:32.123",
"Id": "11242",
"Score": "3",
"Tags": [
"php",
"parsing",
"regex",
"unicode"
],
"Title": "Unicode parsing in PHP"
}
|
11242
|
<p>I have some code that loops over a number and populates a list using other lists. I think I can refactor it somehow to make it look nicer but not sure the best way to do it.</p>
<p>Here is the code:</p>
<pre><code>for (int i = 0; i < loopCount; i++)
{
switch (NoOfRows)
{
case 1:
if (InputList1.Count > i)
ExpectedValues.Add(InputList1[i]);
break;
case 2:
if (InputList1.Count > i)
ExpectedValues.Add(InputList1[i]);
if (InputList2.Count > i)
ExpectedValues.Add(InputList2[i]);
break;
case 3:
if (InputList1.Count > i)
ExpectedValues.Add(InputList1[i]);
if (InputList2.Count > i)
ExpectedValues.Add(InputList2[i]);
if (InputList3.Count > i)
ExpectedValues.Add(InputList3[i]);
break;
case 4:
if (InputList1.Count > i)
ExpectedValues.Add(InputList1[i]);
if (InputList2.Count > i)
ExpectedValues.Add(InputList2[i]);
if (InputList3.Count > i)
ExpectedValues.Add(InputList3[i]);
if (InputList4.Count > i)
ExpectedValues.Add(InputList4[i]);
break;
case 5:
if (InputList1.Count > i)
ExpectedValues.Add(InputList1[i]);
if (InputList2.Count > i)
ExpectedValues.Add(InputList2[i]);
if (InputList3.Count > i)
ExpectedValues.Add(InputList3[i]);
if (InputList4.Count > i)
ExpectedValues.Add(InputList4[i]);
if (InputList5.Count > i)
ExpectedValues.Add(InputList5[i]);
break;
case 6:
if (InputList1.Count > i)
ExpectedValues.Add(InputList1[i]);
if (InputList2.Count > i)
ExpectedValues.Add(InputList2[i]);
if (InputList3.Count > i)
ExpectedValues.Add(InputList3[i]);
if (InputList4.Count > i)
ExpectedValues.Add(InputList4[i]);
if (InputList5.Count > i)
ExpectedValues.Add(InputList5[i]);
if (InputList6.Count > i)
ExpectedValues.Add(InputList6[i]);
break;
case 7:
if (InputList1.Count > i)
ExpectedValues.Add(InputList1[i]);
if (InputList2.Count > i)
ExpectedValues.Add(InputList2[i]);
if (InputList3.Count > i)
ExpectedValues.Add(InputList3[i]);
if (InputList4.Count > i)
ExpectedValues.Add(InputList4[i]);
if (InputList5.Count > i)
ExpectedValues.Add(InputList5[i]);
if (InputList6.Count > i)
ExpectedValues.Add(InputList6[i]);
if (InputList7.Count > i)
ExpectedValues.Add(InputList7[i]);
break;
case 8:
if (InputList1.Count > i)
ExpectedValues.Add(InputList1[i]);
if (InputList2.Count > i)
ExpectedValues.Add(InputList2[i]);
if (InputList3.Count > i)
ExpectedValues.Add(InputList3[i]);
if (InputList4.Count > i)
ExpectedValues.Add(InputList4[i]);
if (InputList5.Count > i)
ExpectedValues.Add(InputList5[i]);
if (InputList6.Count > i)
ExpectedValues.Add(InputList6[i]);
if (InputList7.Count > i)
ExpectedValues.Add(InputList7[i]);
if (InputList8.Count > i)
ExpectedValues.Add(InputList8[i]);
break;
case 9:
if (InputList1.Count > i)
ExpectedValues.Add(InputList1[i]);
if (InputList2.Count > i)
ExpectedValues.Add(InputList2[i]);
if (InputList3.Count > i)
ExpectedValues.Add(InputList3[i]);
if (InputList4.Count > i)
ExpectedValues.Add(InputList4[i]);
if (InputList5.Count > i)
ExpectedValues.Add(InputList5[i]);
if (InputList6.Count > i)
ExpectedValues.Add(InputList6[i]);
if (InputList7.Count > i)
ExpectedValues.Add(InputList7[i]);
if (InputList8.Count > i)
ExpectedValues.Add(InputList8[i]);
if (InputList9.Count > i)
ExpectedValues.Add(InputList9[i]);
break;
case 10:
if (InputList1.Count > i)
ExpectedValues.Add(InputList1[i]);
if (InputList2.Count > i)
ExpectedValues.Add(InputList2[i]);
if (InputList3.Count > i)
ExpectedValues.Add(InputList3[i]);
if (InputList4.Count > i)
ExpectedValues.Add(InputList4[i]);
if (InputList5.Count > i)
ExpectedValues.Add(InputList5[i]);
if (InputList6.Count > i)
ExpectedValues.Add(InputList6[i]);
if (InputList7.Count > i)
ExpectedValues.Add(InputList7[i]);
if (InputList8.Count > i)
ExpectedValues.Add(InputList8[i]);
if (InputList9.Count > i)
ExpectedValues.Add(InputList9[i]);
if (InputList10.Count > i)
ExpectedValues.Add(InputList10[i]);
break;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:20:41.257",
"Id": "18060",
"Score": "0",
"body": "And how/where are `InputList1..10` defined?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:21:11.883",
"Id": "18061",
"Score": "0",
"body": "@Jamiec Not sure how to move it, copy & paste?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:21:56.610",
"Id": "18062",
"Score": "0",
"body": "@sinelaw they are class properties"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:22:40.183",
"Id": "18063",
"Score": "0",
"body": "@Jon, ok but why do you define them like that? Why not make a list of lists?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:24:19.810",
"Id": "18064",
"Score": "0",
"body": "I think it started off with just 2 or 3 lists but over time they've been added and its a bit unsightly now"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:20:46.170",
"Id": "18065",
"Score": "0",
"body": "You can put all InputLists into array of inputLists and use a simple for"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-16T14:17:20.317",
"Id": "294397",
"Score": "0",
"body": "Like said above, put them in a list, then you can do this in a few lines with a simple method that utilizes a loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-16T14:27:45.863",
"Id": "294399",
"Score": "0",
"body": "I see everyone has it's code ready haha... my 2 cents: http://pastebin.com/a5SNKTJx"
}
] |
[
{
"body": "<p>Yes, a very simple way to do this is to have a number of methods and store delegates to them in a dictionary, keyed on NumberOfRows. </p>\n\n<p>It'll look prettier but doesn't add any functional benefit. For instance: </p>\n\n<pre><code> switch (NoOfRows)\n {\n case 1:\n if (InputList1.Count > i)\n ExpectedValues.Add(InputList1[i]); \n break;\n case 2:\n if (InputList1.Count > i) \n ExpectedValues.Add(InputList1[i]); \n if (InputList2.Count > i)\n ExpectedValues.Add(InputList2[i]);\n break;\n</code></pre>\n\n<p>Becomes</p>\n\n<pre><code>Dictionary<int, Action<int>> _operations;\n\npublic void Foo()\n{\n // Create methods and store in a dictionary once\n if (_operations == null)\n {\n _operations = new Dictionary<int, Action>();\n _operations.Add(1, ProcessOneRow); \n _operations.Add(2, ProcessTwoRows); \n // ... \n }\n\n for (int i = 0; i < loopCount; i++)\n {\n // Invoke the delegate to the correct method\n var operation = _operations[NoOfRows];\n operation(i);\n }\n}\n\npublic void ProcessOneRow(int i)\n{\n if (InputList1.Count > i) ExpectedValues.Add(InputList1[i]);\n}\n\npublic void ProcessTwoRows(int i)\n{ \n ProcessOneRow(i);\n if (InputList2.Count > i)\n ExpectedValues.Add(InputList2[i]);\n}\n</code></pre>\n\n<p>To be honest looking at the above you ought to move your delegate lookup outside of the loop if NoOfRows does not change inside the loop. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:28:16.927",
"Id": "18066",
"Score": "1",
"body": "I was about to post something similar; Instead of an `Action` as the value in the `Dictionary`, use the `InputListx`. Then based on the number of rows, perform the same action on each list for i to n. The patter in the OP is each list is doing the same thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:30:03.313",
"Id": "18067",
"Score": "1",
"body": "Aha yes, flip-side of the coin. I didn't notice the InputLists were just incrementing each time. I suppose the correct answer to this question is going to be \"Do what is readable and simple for developers to understand\". If it's too funky then it detracts from code readability and might not be that valuable!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:38:20.327",
"Id": "18068",
"Score": "1",
"body": "@MetroSmurf Post your answer!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:39:32.690",
"Id": "18069",
"Score": "0",
"body": "@Jon - posted and done."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:25:16.183",
"Id": "11246",
"ParentId": "11245",
"Score": "1"
}
},
{
"body": "<p>What about some Linq?</p>\n\n<pre><code>var allInputLists = new List<List<T>>\n{\n InputList1, InputList2, \n InputList3, InputList4, \n InputList5, InputList6, \n InputList7, InputList8, \n InputList9, InputList10\n};\n\nvar expectedValues = from i in Enumerable.Range(0, loopCount)\n from list in allInputLists.Take(NoOfRows - 1)\n where list.Count > i\n select list[i];\n</code></pre>\n\n<p>Or, in fluent syntax:</p>\n\n<pre><code>var expectedValues = Enumerable.Range(0, loopCount)\n .SelectMany(i => allInputLists.Take(NoOfRows - 1)\n .Where(list => list.Count > i)\n .Select(list => list[i])\n );\n</code></pre>\n\n<p>Although the query syntax in this case is a bit nicer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:33:03.070",
"Id": "18078",
"Score": "1",
"body": "can't quite see whats going on here, could you explain it more or use fluent linq?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:36:44.867",
"Id": "18079",
"Score": "0",
"body": "`Enumerable.Range` is like your `for` loop, and for each of the values that are generated, that walks through all the lists (so a nested `for` loop) up to the `NoOfRows`, checks that they have more elements than the current `i`, and \"joins\" together all those elements to build your `ExpectedValues` from scratch."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:27:12.553",
"Id": "11248",
"ParentId": "11245",
"Score": "1"
}
},
{
"body": "<p>The alternate method of <a href=\"https://stackoverflow.com/a/10334399/9664\">Dr. Andrew Burnett-Thom</a> would be to use a <code>Dictionary<int, InputList></code>:</p>\n\n<pre><code> var dic = new Dictionary<int, InputList>();\n // add InputLists\n dic.Add(0, InputList1);\n dic.Add(1, InputLIst2);\n //etc...\n\n for( int i = 0; i < loopCount; i++ )\n {\n for( int j = 0; j < NoOfRows; j++ )\n {\n if( dic[j].Count > i )\n {\n ExpectedValues.Add( dic[j][i] );\n }\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:44:37.147",
"Id": "18080",
"Score": "0",
"body": "Except you need to index into `dic[j]` to get the value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:47:42.527",
"Id": "18081",
"Score": "0",
"body": "@Khanzor I'm not following... what do you mean?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:48:33.387",
"Id": "18082",
"Score": "0",
"body": "The result of `dic[j]` will be an `InputList`, you want the `i`th value of that list, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:53:15.673",
"Id": "18083",
"Score": "0",
"body": "@Khanzor good catch!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:55:11.523",
"Id": "18084",
"Score": "0",
"body": "Not sure why the downvote... oh well."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:39:06.340",
"Id": "11249",
"ParentId": "11245",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:17:38.667",
"Id": "11245",
"Score": "5",
"Tags": [
"c#",
".net"
],
"Title": "Refactoring code into a simpler method"
}
|
11245
|
<p>Assume that we have a <code>.txt</code> file that has one word per line.
Find out the word that occurs the most.</p>
<p>Here's what I was able to write (I used array of strings instead of a file in this example):</p>
<pre><code>string[] source = { "test1", "test2", "test3", "test4", "test1", "test1", "test3" };
Dictionary<string, int> dic = source.Distinct().ToDictionary(p => p, p => 0);
var keys = new List<string>(dic.Keys);
foreach (string key in keys)
{
dic[key]=source.Count(f => f == key);
}
int max = dic.Values.Max();
foreach (KeyValuePair<string, int> kvp in dic)
{
if (kvp.Value == max)
{
Console.WriteLine(kvp.Key + " " + max);
break;
}
}
</code></pre>
<p>Questions:</p>
<ol>
<li>Can this be done better and more efficient way (speed/ memory)?</li>
<li>What if file size is 10GB. How would you do it differently from my approach?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T15:49:54.397",
"Id": "18120",
"Score": "0",
"body": "In addition to other answers listed here, if you have a 10GB file, then you should consider parallel computations. The trick is to keep reading the file sequentially, but hand off the work in reasonable sized chunks to several threads. http://stackoverflow.com/questions/9314042/quicker-file-reading-using-multi-threading If a single-threaded approach works fast enough for you, then do not bother with the extra complexity, of course."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-01T14:56:47.843",
"Id": "18246",
"Score": "3",
"body": "`cat file.txt | sort | uniq -c | sort -rn | head -n1`"
}
] |
[
{
"body": "<p>You are trying to count each key separately. This means you need to iterate through the entire list to count each key. Instead you can keep a running total of your key's and only have to iterate through your list once:</p>\n\n<pre><code>string[] source = { \"test1\", \"test2\", \"test3\", \"test4\", \"test1\", \"test1\", \"test3\" };\nDictionary<string, int> dic = new Dictionary<string, int>();\n\nforeach(string s in source){\n if(dic.Keys.Contains(s))\n dic[s] = dic[s]++;\n else\n dic.Add(s, 1);\n}\n</code></pre>\n\n<p>EDIT: I did not include getting the max value as what you have works for that and has already been re-written by thantos</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T19:06:05.517",
"Id": "18092",
"Score": "0",
"body": "+1 for efficiency and simplicity in your code. `Contains` is a much more efficient method than operations on the values collection of a Dictionary. Plus it doesn't have those notoriously overused lambda expressions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T19:23:31.377",
"Id": "18093",
"Score": "3",
"body": "You can avoid reading the dictionary twice by using `TryGetValue()`, but the gain is probably going to be minuscule when compared with reading the file."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T19:27:15.037",
"Id": "18094",
"Score": "0",
"body": "True I hadnt thought of that with the short time I threw it together. I was more focused on not iterating the entire list to get each count(which would result in terrible performance)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T06:37:44.013",
"Id": "18111",
"Score": "2",
"body": "You also should consider casting all words to lower case, because it won't work if the case of the words are different. Moreover, the initial input requires a preprocessing via stemming, if you want words like \"cat\" and cats to be counted as the same word - http://en.wikipedia.org/wiki/Stemming"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T18:59:22.403",
"Id": "11261",
"ParentId": "11254",
"Score": "6"
}
},
{
"body": "<p>You could use a collection type which is called <code>Bag</code>. A bag counts the items added to it. Here is a suggestion of how a bag can be implemented. (It is not necessarily feature-complete; however you get the idea.)</p>\n\n<pre><code>public class Bag<T>\n{\n private Dictionary<T, int> _dict = new Dictionary<T, int>();\n\n public void Add(T item)\n {\n int count;\n if (_dict.TryGetValue(item, out count)) {\n _dict[item] = count + 1;\n } else {\n _dict.Add(item, 1);\n }\n }\n\n public bool Remove(T item)\n {\n int count;\n if (_dict.TryGetValue(item, out count)) {\n if (count == 1) {\n _dict.Remove(item);\n } else {\n _dict[item] = count - 1;\n }\n return true;\n }\n return false;\n }\n\n public IEnumerator<KeyValuePair<T, int>> GetEnumerator()\n {\n return _dict.GetEnumerator();\n }\n\n public int CountOf(T item)\n {\n int count;\n _dict.TryGetValue(item, out count);\n return count;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T16:21:27.923",
"Id": "11279",
"ParentId": "11254",
"Score": "2"
}
},
{
"body": "<p>I wrote this little business back in 2009. It counts unique words in a file (separated by certain delimiters) and spits them out in frequency order, highest to lowest.</p>\n\n<pre><code> private static readonly char[] delimiters = { ' ', '.', ',', ';', '\\'', '-', ':', '!', '?', '(', ')', '<', '>', '=', '*', '/', '[', ']', '{', '}', '\\\\', '\"', '\\r', '\\n' };\n\n private static readonly Func<string, string> theWord = Word;\n\n private static readonly Func<IGrouping<string, string>, KeyValuePair<string, int>> theNewWordCount =\n NewWordCount;\n\n private static readonly Func<KeyValuePair<string, int>, int> theCount = Count;\n\n private static void Main(string[] args)\n {\n foreach (var wordCount in File.ReadAllText(args.Length > 0 ? args[0] : @\"C:\\Test\\WarAndPeace.txt\")\n .Split(delimiters, StringSplitOptions.RemoveEmptyEntries)\n .AsParallel()\n .GroupBy(theWord, StringComparer.OrdinalIgnoreCase)\n .Select(theNewWordCount)\n .OrderByDescending(theCount))\n {\n Console.WriteLine(\n \"Word: \\\"\"\n + wordCount.Key\n + \"\\\" Count: \"\n + wordCount.Value);\n }\n\n Console.ReadLine();\n }\n\n private static string Word(string word)\n {\n return word;\n }\n\n private static KeyValuePair<string, int> NewWordCount(IGrouping<string, string> wordCount)\n {\n return new KeyValuePair<string, int>(wordCount.Key, wordCount.Count());\n }\n\n private static int Count(KeyValuePair<string, int> wordCount)\n {\n return wordCount.Value;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T23:44:52.363",
"Id": "11288",
"ParentId": "11254",
"Score": "4"
}
},
{
"body": "<p>I think it is worth mentioning that for large data a different approach could be used, since keeping exact frequency counts of words is too time consuming.</p>\n\n<p>Streaming Algorithms like \"Count Sketch\" makes a single pass over the data, uses low amount of space, and based on the amount of space you allocate to it, can guarantee to get the Maximum Frequency Word with say 99% probability. </p>\n\n<p>Algorithms like these are used every day in routers to approximate which IP addresses are requested the most frequently, given that routers do not have enough memory to store everything it sees and only sees each IP address once. </p>\n\n<p>For large data, I would recommend this approach.</p>\n\n<p>Not sure if 10 GB of text counts as big data for this problem though, however if every word in the file was unique (except one word which occurs twice), you probably don't want to try storing them all in a Dictionary :p. </p>\n\n<p>As an aside,</p>\n\n<p>Multi-threading may be able to help give a speed-up, although pulling data from a single .txt file seems intrinsically IO bound. It seems possible to pre-partition the .txt file into parts for each thread to process independently, using \"unsafe\" code with pointers directly at the partition locations in memory, and writing the line parsing yourself from the bit representations of chars. </p>\n\n<p>I doubt the above would be worth doing in C#, since you might as well manage memory as well using C or another low-level language for that extra gain in speed-up.</p>\n\n<p>Multiple threads would exhibit higher speed-ups on certain processors like the intel i7 which has 3 channels to memory, and this is a highly IO dependent task.</p>\n\n<p>If it happened to be hundreds of thousands of 10 GB .txt files across a cluster of computers, I would consider using an approach utilizing MapReduce on a distributed file system. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-23T07:00:45.630",
"Id": "12965",
"ParentId": "11254",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>Can this be done better and more efficient way (speed/ memory)?</p>\n</blockquote>\n\n<p>Your code iterates once over the input, <code>Distinct</code> internally creates a set, of which you then create a dictionary (redundant work).</p>\n\n<p>You then copy the keys of the dictionary to a list to iterate over them (redundant work).</p>\n\n<p>You then iterate over all keys, and for each, iterate over the input <em>again</em> (redundant work).</p>\n\n<p>Then you iterate over the dictionary <em>again</em> (redundant work).</p>\n\n<p><strong>This code has almost more redundant operations than lines.</strong></p>\n\n<p>This can be vastly simplified, both conceptually and concerning runtime. Unfortunately, the resulting code will be slightly <em>longer</em> and still contain one redundancy since C#’s dictionary implementation has a fatal error in its interface: it doesn’t allow querying and updating a value at the same time.</p>\n\n<pre><code>string[] source = { \"test1\", \"test2\", \"test3\", \"test4\", \"test1\", \"test1\", \"test3\" };\n\nvar frequencies = new Dictionary<string, int>();\nstring highestWord = null;\nint highestFreq = 0;\n\nforeach (string word in source) {\n int freq;\n frequencies.TryGetValue(word, out freq);\n freq += 1;\n\n if (freq > highestFreq) {\n highestFreq = freq;\n highestWord = word;\n }\n frequencies[word] = freq;\n}\n\nConsole.WriteLine(highestWord);\n</code></pre>\n\n<blockquote>\n <p>What if file size is 10GB. How would you do it differently from my approach?</p>\n</blockquote>\n\n<p>If you expect comparably few different word (say, less than 100.000), use the same approach as above, just don’t load the whole input at once, instead, do it in chunks. You can also process chunks in parallel, with each thread working on its own dictionary, and afterwards you merge those dictionaries in one final step.</p>\n\n<p>If you expect that almost every word in the input is distinct (not realistic with natural language words, but if your “words” are generated strings, this could happen) then the frequency dictionary could become quite large in size and might require special treatment. But this is an extreme scenario.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-23T10:44:43.293",
"Id": "12969",
"ParentId": "11254",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "11261",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T18:36:29.733",
"Id": "11254",
"Score": "6",
"Tags": [
"c#",
"algorithm",
".net"
],
"Title": "Find most occurring word in a txt file"
}
|
11254
|
<p>Ok, I am in a JavaScript class, and I have no desire for anyone to do my schoolwork, I have already done what I think is correct, I am just hoping someone can take a look and tell me if I am close, or right, or whatever. Any feedback appreciated. Also, the instructor was very specific in saying that if it asks for a line of code, then just do a line of code- so if it appears things are missing that would be why.</p>
<p>1.Write a line of code using the Location object to return the uniform resource locator (URL) of a Web page to a variable called myWebPage.</p>
<pre><code>function getLocation(){
alert(document.location);}
</code></pre>
<p>2.Write a line of code using the Navigator object to return the Web browser name to a variable called myBrowserName.</p>
<pre><code>function getLocation(){
alert(navigator.appName);}
</code></pre>
<p>3.Write a line of code using the Screen object to return the height of the display screen, not including operating system features such as the Windows Taskbar, to a variable called myScreenHeight</p>
<pre><code>function getLocation(){
alert("Total height is : "+screen.height);}
</code></pre>
<p>4.Write a line of JavaScript code using the Window object and other properties to open a new Web browser window with www.google.com displaying and no menu bar</p>
<pre><code>function getWindow(){
window.open('http://www.google.com','mywindow','width=400,height=200');}
</code></pre>
<p>That's it! Let me know if I did anything wrong, thank you!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T18:37:39.650",
"Id": "18088",
"Score": "0",
"body": "@CorbinHolbert This may be better for our Code Review site. I'll migrate it for you, and then you can watch there as people help evaluate your code."
}
] |
[
{
"body": "<p>It looks like you're not following the instructions strictly. For example, here:</p>\n\n<blockquote>\n <p>1.Write a line of code using the Location object to return the uniform resource locator (URL) of a Web page to a variable called myWebPage.</p>\n</blockquote>\n\n<p>You didn't write a line of code, you wrote two, and you alerted the value instead of assigning to the variable. You also used a function, where the requirements do not include a function. I think the instructor is expecting something like this:</p>\n\n<pre><code>var myWebPage = window.location.href;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T18:44:25.300",
"Id": "11256",
"ParentId": "11255",
"Score": "5"
}
},
{
"body": "<p>Three small changes for numbers 1, 2, and 3 as it says they should be assigned to variables.</p>\n\n<blockquote>\n <p>1.Write a line of code using the Location object to return the uniform resource locator (URL) of a Web page to a variable called myWebPage.</p>\n</blockquote>\n\n<p><code>var myWebPage = document.location.href;</code></p>\n\n<blockquote>\n <p>2.Write a line of code using the Navigator object to return the Web browser name to a variable called myBrowserName.</p>\n</blockquote>\n\n<p><code>var myBriowserName = navigator.appName;</code></p>\n\n<blockquote>\n <p>3.Write a line of code using the Screen object to return the height of the display screen, not including operating system features such as\n the Windows Taskbar, to a variable called myScreenHeight</p>\n</blockquote>\n\n<p><code>var myScreenHeight = screen.height;</code></p>\n\n<p>Otherwise it looks good at first glance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T22:40:04.157",
"Id": "18106",
"Score": "0",
"body": "So I did number four right though? I guess I was overcomplicating things. At first I had exactly what you just typed up and I looked at it and thought \"no way, that's too simple\" :/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T22:51:34.983",
"Id": "18107",
"Score": "0",
"body": "You could remove it from the function, the inner line is all you really need."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T18:46:24.087",
"Id": "11257",
"ParentId": "11255",
"Score": "2"
}
},
{
"body": "<p>Give up on putting everything in functions, especially when the question does not ask for a function but for a line of code (it probably means \"a single statement\").</p>\n\n<p>Pay attention when the question requests that the value be put in a variable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T18:46:55.547",
"Id": "11258",
"ParentId": "11255",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "11257",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T18:35:15.960",
"Id": "11255",
"Score": "3",
"Tags": [
"javascript",
"homework"
],
"Title": "JavaScript Objects- Can you confirm?"
}
|
11255
|
<p>I have Django unit tests that are pretty much the following format:</p>
<pre><code>class Tests(unittest.TestCase):
def check(self, i, j):
self.assertNotEquals(0, i-j)
for i in xrange(1, 4):
for j in xrange(2, 6):
def ch(i, j):
return lambda self: self.check(i, j)
setattr(Tests, "test_%r_%r" % (i, j), ch(i, j))
</code></pre>
<p>A function that returns a lambda that is bound as a method via <code>setattr</code>, which is an eyesore and as unreadable as you can get in Python without really trying to obfuscate.</p>
<p>How can I achieve the same functionality in a more readable way, preferably without <code>lambda</code>?</p>
<p>For reference, see <a href="https://stackoverflow.com/q/10346239/180174">the original SO question</a> about the subject.</p>
|
[] |
[
{
"body": "<p>Don't bother with generating tests:</p>\n\n<pre><code>class Tests(unittest.TestCase):\n def check(self, i, j):\n self.assertNotEquals(0, i-j)\n\n def test_thingies(self):\n for i in xrange(1, 4):\n for j in xrange(2, 6):\n self.check(i,j)\n</code></pre>\n\n<p>It would be nicer to generate individual tests, but do you really get that much benefit out of it?</p>\n\n<p>Or write a reusable function:</p>\n\n<pre><code>data = [(i,j) for i in xrange(1,4) for j in xrange(2,6)]\nadd_data_tests(TestClass, data, 'check')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T20:08:25.457",
"Id": "18095",
"Score": "0",
"body": "Generating tests is pretty much a must - as there will be a few things that will be checked for hundreds of items so a single \"ok\" / \"failed\" for the 1k+ individual asserts does not give enough resolution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T20:11:15.750",
"Id": "18096",
"Score": "0",
"body": "So even though I'm using unittest I'm actually doing this to do regression testing :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T20:55:03.163",
"Id": "18097",
"Score": "2",
"body": "@Kimvais, you don't need separate tests to get that resolution. (Albeit, that's the nicest way. Some unit testing frameworks like nose make it easy.) Just catch the exception when it fails, and add some information on the parameters being tested."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T20:02:25.147",
"Id": "11264",
"ParentId": "11259",
"Score": "2"
}
},
{
"body": "<p>Both <a href=\"https://nose.readthedocs.org/en/latest/writing_tests.html#test-generators\" rel=\"nofollow\">nose</a> and <a href=\"https://pytest.org/latest/parametrize.html#parametrize-basics\" rel=\"nofollow\">py.test</a> support mechanisms to run parameterized tests. Either of these options will likely produce a better result than trying to spin your own implementation.</p>\n\n<p>The issue with the big nested loop to call check method, is that it stops on the first failure. That single failure might tell you want is broken. But knowing the 5 of the 20 input sets cause the failure will give you a much better idea of what the core issue is.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T22:20:31.367",
"Id": "48827",
"ParentId": "11259",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T18:54:37.923",
"Id": "11259",
"Score": "4",
"Tags": [
"python",
"unit-testing",
"functional-programming"
],
"Title": "How do I dynamically create Python unit tests in a readable way?"
}
|
11259
|
<p>I have made the following classes and objects.
It was made to create forms programattically easily. It should produce highly readable, valid, and clean HTML.</p>
<p>Care to give me some feedback? :)</p>
<p><a href="https://gist.github.com/2510553">https://gist.github.com/2510553</a></p>
<p>Full code:</p>
<pre><code><?php
namespace Forms;
/**
* This file is supposed to give a good way of generating forms programmatically with PHP.
*/
/*
* WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING!
* -----------------------------------------------------------------------------------------------------------
* None of the strings you see in the following classes are escaped/secured against any kind of
* SQL Injections, XSS attacks, or any other sort of attack for that matter! For your own safety
* Implement the necessary protections on any strings you use in these classes before entering them!
* -----------------------------------------------------------------------------------------------------------
* WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING!
* @package Classes
*/
/**
* All containing nodes should implement this.
*/
interface Contains_Nodes {
/**
* @abstract
*
* @param Node $node
*
* This method will add a node to the node list of the implementing object.
*/
public function add(Node $node);
}
</code></pre>
<h2>Node</h2>
<pre><code>/**
* Base object for all Nodes.
*/
class Node {
/**
* @var string $element Will hold the element name (or tag name)
*/
public $element;
/**
* @var array $attribute_list Will hold all of the rest of the form's attributes such as ID, class and whatnot.
*/
public $attribute_list = array();
/**
* @var bool $self_contained Signifies whether the Node is self contained. Self contained nodes do not get a closing tag.
*/
public $text;
public $self_contained = false;
const SELF_CONTAINED = true;
const NOT_SELF_CONTAINED = false;
const TAB = " ";
/**
* @param string $element
* @param string $text
* @param bool $self_contained
* @param array $attribute_list
*
* General constructor for nodes. Should be overridden regularly.
*/
public function __construct($element, $text = "", $self_contained = false, array $attribute_list = array()) {
$this->element = $element;
$this->self_contained = $self_contained;
$this->text = $text;
$this->attribute_list = $attribute_list;
}
/**
* @return string
*
* General string generator for nodes. Should be overridden regularly.
*/
public function __toString() {
//Open element
$result = "<{$this->element}";
//Node list
$result .= $this->string_attribute_list();
//Close element
$result .= ">";
if (!$this->self_contained && !empty($this->text)) {
$result .= $this->text;
}
if (!$this->self_contained) {
$result .= "</{$this->element}>";
}
return $result;
}
/**
* @return string
*/
public function string_attribute_list() {
$result = "";
if (!empty($this->attribute_list)) {
foreach ($this->attribute_list as $attr => $value) {
$result .= " {$attr}=\"{$value}\"";
}
}
return $result;
}
}
</code></pre>
<h2>Form</h2>
<pre><code>/**
* The Form object, will describe a single form.
* After constructing it is done, it should format into a cool, simple, valid, readable, HTML code.
*/
class Form extends Node implements Contains_Nodes {
public $element = "form";
public $self_contained = false;
/**
* @var Node[] $node_list This will hold all of the nodes in the form. Including fields and inputs.
*/
public $node_list;
/**
* @var string $action Will hold the action for the form. This is a required field.
*/
public $action;
/**
* @var string $method Will hold the form submission method for the form. Defaults to POST.
*/
public $method = Form::METHOD_POST;
const METHOD_POST = 'POST';
const METHOD_GET = 'GET';
/**
* @param string $action Page to which the form submits.
* @param string $method POST or GET, will throw an exception otherwise.
* @param array $attribute_list Miscellaneous attributes for the form element.
*/
public function __construct($action, $method = self::METHOD_POST, array $attribute_list = array()) {
$this->action = $action;
$this->method = $method;
$this->attribute_list = $attribute_list;
if (($method != self::METHOD_GET) && ($method != self::METHOD_POST)) {
throw new \Exception("Form method must be either POST or GET");
}
}
/**
* @param Node $node Node to add.
*
* @return Form to not break the chain
*/
public function add(Node $node) {
$this->node_list[] = $node;
return $this;
}
/**
* @return string Format and stringify the form.
*/
public function __toString() {
//Open tag, usually <form ...>
$result = "<{$this->element} action=\"{$this->action}\" method=\"{$this->method}\"";
//Attribute list
$result .= $this->string_attribute_list();
//Close opening tag
$result .= ">";
//Loop through the nodes
foreach ($this->node_list as $node) {
$result .= "\n" . self::TAB . str_replace("\n", "\n" . self::TAB, $node->__toString());
//The replace is to keep the code indented and formatted properly.
}
//Close form element
$result .= "\n</{$this->element}>";
return $result;
}
}
</code></pre>
<h2>Input</h2>
<pre><code>/**
* Class to describe a single input node.
*/
class Input extends Node {
public $element = "input";
public $self_contained = true;
public $type;
public $label;
public $name;
public $default_value;
public $label_before_input = true;
/**
* @param string $type
* @param string $name
* @param Label $label
* @param string $default_value
* @param array $attribute_list
*
* Constructor for input node.
*/
public function __construct($type, $name, Label $label, $default_value = "", array $attribute_list = array()) {
$this->type = $type;
$this->name = $name;
$this->label = $label;
$this->default_value = $default_value;
$this->attribute_list = $attribute_list;
}
/**
* @return string Formatted input HTML.
*/
public function __toString() {
//Label element open (usually "<label"
$result = "<{$this->label->element}";
//Begin attribute list
$result .= $this->label->string_attribute_list();
//Close opening tag
$result .= ">";
//If we want label before the input...
if ($this->label_before_input) {
$result .= "\n" . self::TAB . $this->label->text;
}
//Begin input element usually "<input ..."
$result .= "\n" . self::TAB . "<{$this->element} type=\"{$this->type}\" name=\"{$this->name}\"";
//Default value
if (!empty($this->default_value)) {
$result .= " value=\"{$this->default_value}\"";
}
//Attribute list
$result .= $this->string_attribute_list();
//Close input element
$result .= ">";
//If we want label after input
if (!$this->label_before_input) {
$result .= "\n" . self::TAB . $this->label->text;
}
//Close label element (usually "</label>"
$result .= "\n</{$this->label->element}>";
/*
* FINAL RESULT should look like:
* <label [label-attributes]>
* [text-if-before]
* <input type=[type] name=[name] value=[value] [input-attributes]
* [text-if-after]
* </label>
*/
return $result;
}
}
</code></pre>
<h2>Label</h2>
<pre><code>/**
* Class to describe a single label node.
* Labels should be contained inside of inputs on a 1:1 relationship.
*/
class Label extends Node {
public $element = "label";
/**
* @param string $text
* @param array $attribute_list
*/
public function __construct($text, array $attribute_list = array()) {
$this->text = $text;
$this->attribute_list = $attribute_list;
}
/**
* @return string Returns label text only. Labels can only be part of inputs.
*/
public function __toString() {
return $this->text;
}
}
</code></pre>
<h2>Fieldset</h2>
<pre><code>/**
* Class to describe a single fieldset node.
*
* @implements Contains_Nodes
*/
class Fieldset extends Node implements Contains_Nodes {
public $element = "fieldset";
/**
* @var Node[]
*/
public $node_list;
public $legend;
/**
* @param $legend
*
* Construct a fieldset element
*/
public function __construct($legend) {
$this->legend = $legend;
}
/**
* @param Node $node
*
* @return Fieldset to not break the chain
*
* Add a node to the fieldset.
*/
public function add(Node $node) {
$this->node_list[] = $node;
return $this;
}
/**
* @return string Generate a formatted node list of the fieldset.
*/
public function __toString() {
//Open element (usually <fieldset)
$result = "<{$this->element}";
//Attribute list
$this->string_attribute_list();
//Close opening tag
$result .= ">";
//Legend text
$result .= "\n" . self::TAB . "<legend>{$this->legend}</legend>";
//Loop through node list
foreach ($this->node_list as $node) {
$result .= "\n" . self::TAB . str_replace("\n", "\n" . self::TAB, $node->__toString());
//The replace is to keep the code indented and formatted properly.
}
//Close fieldset tag
$result .= "\n</{$this->element}>";
return $result;
}
}
</code></pre>
<h1>Button</h1>
<pre><code>class Button extends Node {
public $element = "button";
public function __construct($text, array $attribute_list = array()) {
parent::__construct($this->element,$text, Node::NOT_SELF_CONTAINED, $attribute_list);
}
}
</code></pre>
<h1>Submit</h1>
<pre><code>class Submit extends Button {
public $type = "submit";
public function __construct($text = "Submit", array $attribute_list = array()) {
$attribute_list["type"] = $this->type;
parent::__construct($text, $attribute_list);
}
}
</code></pre>
<h1>Testing</h1>
<pre><code>/*
* Testing begins!
*/
$form = new Form("index.php", Form::METHOD_GET);
$field = new Fieldset("Fieldset");
$field->add(new Input("text", "name", new Label("Input inside of Fieldset")));
$form
->add(
new Input(
"text", //Type
"test", //Name
new Label("Testing Input", array("class" => "label")), //Label
"Woot", //Default value
array("id" => "test") //Attribute List
)
)
->add(new Node("hr", "", Node::SELF_CONTAINED))
->add(new Submit("Go"));
echo $form . "\n\n";
echo "<pre>";
echo print_r($form);
echo "</pre>";
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T21:49:11.397",
"Id": "18102",
"Score": "0",
"body": "I only got about halfway through this, so here are a few questions for you while I finish, get home, and write a better reply. What do you do for self terminating tags (`<input />`)? This looks like it could be used for any HTML, why do you say it is only for forms? Would you mind terribly separating this code by class so that we don't have to continuously scroll the same text box while reading your code? It makes it quite difficult. I will finish reading your code in a bit and have an answer ready shortly after."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T21:52:23.223",
"Id": "18103",
"Score": "0",
"body": "It could be used for different kinds of HTML, however it is designed for forms. I could indeed pass in multiple nodes. As for the self closing nodes, there is the `$self_contained` field for it in the `Node` class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T21:54:41.670",
"Id": "18104",
"Score": "0",
"body": "Final comment. While this looks promising, and we've all attempted something similar, I'm sure, the whole point of a class like this would be to make writing HTML in PHP automated, cleaner/clearer, and faster/shorter. You may have accomplished the first, but the second two are lacking. Looking at your test, I'm not quite sure what is going on, so cleaner/clearer is not met. As for faster/shorter, is this any faster/shorter than manually typing the code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T21:58:25.680",
"Id": "18105",
"Score": "0",
"body": "@showerhead: The point is to provide a structured layout to generate forms, so that it's easily generated programmatically. Nothing beats writing HTML code manually, but it is definitely better structured. What I really wanted to make here is that no matter if you know how to write forms markup, you can do it easily from the server side (especially if you need to generate it from a database of some sort)."
}
] |
[
{
"body": "<p>If you cannot write form mockup, you leave it to the designer. Or if you are the only one working on the project you use online tools or similar libraries. I'm not saying what you have here is bad, far from it, I'm just saying solutions for this already exist and more well known solutions will be used before one by an unknown author. Just a simple fact of life, people are trendy and suspicious. If you want to use it for your own purposes, that is fine, just don't expect to create the new goto for form creation :) <- (the smile is there to let you know I don't mean this harshly).</p>\n\n<p>I will review your code, though there is little for me to go over, it is already quite clear. Your code is well formed, well documented, and self documenting, so mostly I will be giving observations and suggestions. I will also provide you with input on what I think of your program, as I think that is more what you were looking for. My first input has already been given, so I'll continue with the code review then give my final thoughts towards the end.</p>\n\n<p>There is no need to perform a check on the <code>$self_contained</code> variable twice, it is redundant.</p>\n\n\n\n<pre class=\"lang-php prettyprint-override\"><code> if ( ! $this->self_contained) {\n if( ! empty($this->text)) { $result .= $this->text; }\n $result .= \"</{$this->element}>\";\n }\n</code></pre>\n\n<p>Correct me if I'm wrong, but from what I can tell, your <code>$self_contained</code> check doesn't actually terminate the tag. Simply closing a tag, adding the greater-than bracket \">\", does not terminate an element, you must either use the matched closing tag or a self terminator \"/>\". Most browsers (I believe all) will still process this, but it is still improper and could result in errors in the future. To do this proper add the following else statement to the end of the if statement I gave above.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code> else { substr_replace($result, '/>', -1); }\n</code></pre>\n\n<p>Why are you not checking for empty strings and such? What if I were to create an input with no type? Not saying someone would do so purposefully, but what if they were using a variable to set the type and it somehow got emptied? Adding an error check here could save a lot of debugging time.</p>\n\n<p>You've thrown all these errors but not caught any :(</p>\n\n<p>Well, thats it for the code review, told you there wasn't much. Here's some thoughts I had in the form of suggestions.</p>\n\n<p>I would think about passing associative arrays to your construction methods. This will make it more clear what you are doing. For example.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$form = new Form(array(\n 'action' => 'index.php',\n 'method' => Form::METHOD_GET,\n);\n//Compared to:\n$form = new Form(\"index.php\", Form::METHOD_GET);\n</code></pre>\n\n<p>Yes, because of your self documenting code, it is a little more obvious, but assume someone just passes \"get\" as the second parameter. Two things will happen, the first is that it will throw an error, the second will be that people reading this won't know what it means. Adding <code>strtoupper</code> to your code will prevent that from throwing any errors and will allow people to continue to be lazy. People like being lazy. I'm people, I like being lazy, therefore my statement stands :) Making it use associative arrays will make it more apparent what you are doing.</p>\n\n<p>Have you thought about adding a depth check? Something to determine the initial tabs to add to each new element? Not all forms will be added to the body tag. Some will be deeper.</p>\n\n<p>No class for textareas?</p>\n\n<p>I do believe your code could use some clarity on implementation. As I said in one of my comments, I'm not sure what is going on in your test. Well that's a lie. I read your program, I know whats going on. But someone who has never used your program before will look at that code and not be sure. They could infer much, but not everything. I for one, have not found where <code>$field</code> is used after it is declared, and I HAVE read your code. Maybe I am missing something? My suggestion about associative arrays will clear up your clarity issue somewhat.</p>\n\n<p>Finally, I would change the TAB constant to <code>\\t</code> rather than the escaped equivalent to keep consistent with all those <code>\\n</code>'s, and then I would make the <code>\\n</code> a constant as well, but that is just me. Actually I wouldn't, I would just remove the TAB constant and start using <code>\\t</code>. There's nothing wrong with repeatedly using escaped characters. There is no need to use variables or constants to define them, unless of course they are system specific, such as directory separators, but that is not the case here, at least not if all you are using is <code>\\n</code>, <code>\\r</code> would have to be added as well.</p>\n\n<p>Good luck!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T00:01:36.423",
"Id": "11269",
"ParentId": "11262",
"Score": "2"
}
},
{
"body": "<p>raw html is much cleaner and I suspect much faster than waiting for php to render markup. Let them then input any data they like once validation is passed. Its only when you get to the output stage should you stand up and take notice. So rather than a form or input class consider building a logical(common suituation) output class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T04:20:48.427",
"Id": "11274",
"ParentId": "11262",
"Score": "1"
}
},
{
"body": "<p>I'm not particularly fond of the style of coding, not everything needs to be a class. But there is only one point that I feel warrants <em>significant</em> attention:</p>\n<h2>Huge Point: Not escaping means not useful</h2>\n<blockquote>\n<p>WARNING! WARNING! WARNING! ...<br />\n-------------------------------------------- ...<br />\nNone of the strings you see in the following classes are escaped/secured against any kind ofSQL Injections, XSS attacks, or any other sort of attack for that matter!</p>\n</blockquote>\n<p>There would be little point using the code as presented if it didn't make life easy, and not escaping any of the properties would make it cumbersome and error-prone to use.</p>\n<p>E.g. you've got this in the Testing section</p>\n<pre><code>new Label($label ...\n</code></pre>\n<p>What is going to happen if $label is <code>"Categories > Food"</code> or any other innocent string that will cause malformed html as a result? <em>Why</em> is the class not taking care of that automatically? Note that there will be use cases where you <em>want</em> to put html in some tags - such as using an image for a label, or where tags are nested - attributes should always be escaped though.</p>\n<p>And that's just talking about how innocent users could break your code, not those with malicious intent who submit <code>"<script>document.location = 'http://mysite';"</code> as their name.</p>\n<h2>Big Point: Write real tests</h2>\n<p>If you write a real test (by which I mean using <a href=\"http://www.phpunit.de/manual/current/en/\" rel=\"nofollow noreferrer\">phpunit</a>) you can quickly test normal and edge case scenarios (What if the <code>$x</code> property looks like this?), which will highlight any difficulties in using the code. It'll also permit you the confidence - if you choose to rewrite any of the code in the future - of knowing that it still works in the same way as it did originally.</p>\n<h2>Mid Point: Inconsistent constructors</h2>\n<p>You have all these different constructors:</p>\n<pre><code>public function __construct($element, $text = "", $self_contained = false, array $attribute_list = array()) {\npublic function __construct($action, $method = self::METHOD_POST, array $attribute_list = array()) {\npublic function __construct($type, $name, Label $label, $default_value = "", array $attribute_list = array()) {\npublic function __construct($text, array $attribute_list = array()) {\npublic function __construct($legend) {\npublic function __construct($text, array $attribute_list = array()) {\npublic function __construct($text = "Submit", array $attribute_list = array()) {\n</code></pre>\n<p>Yet all classes extend Node. Why not just have one:</p>\n<pre><code>public function __construct($args = array()) {\n</code></pre>\n<p>A consistent constructor makes it easy to know how to use a class without having to continually refer to the docs or class definition. If that's something you do with none-constructor functions (not applicable here) your code would not be <code>E_STRICT</code> compliant. Having different constructors isn't particularly intuitive, and means you can't have simple override logic like so:</p>\n<pre><code>public function __construct($args = array()) {\n .. anything ..\n parent::__construct($args);\n}\n</code></pre>\n<p>You can enforce any mandatory args just the same, but given that everything is a class you should be able to set all of the currently-mandatory properties after instanciation anyway.</p>\n<h2>Mid Point: Needless interface</h2>\n<p>The interface only defines one method, and where used has exactly the same code. You could just as easily add it to your Node class and override or configure it to be disabled in the cases where it's not applicable.</p>\n<h2>Mid Point: Needless constants</h2>\n<p>What's the real benefit of these:</p>\n<pre><code>const METHOD_POST = 'POST';\nconst METHOD_GET = 'GET';\n</code></pre>\n<p>It's more to type and doesn't add any clarity.</p>\n<p>There's also this:</p>\n<pre><code>const TAB = " ";\n</code></pre>\n<p>Which is in fact set to four spaces. "\\t" is easier and shorter to type.</p>\n<h2>Minor Point: Whitespace</h2>\n<p>Whitespace in html is insignificant, so doing this:</p>\n<pre><code> $result .= "\\n" . self::TAB . "<{$this->e...\n</code></pre>\n<p>doesn't do anything for end users.</p>\n<p>It also doesn't do what you want, as it leads to ugly html. Look at the source of this page and look for "<form>" - if it were left aligned it would break out of the indentation level where it is. If you used similar code to that in the question to build all your html the indentation would be so wayward you wouldn't be able to read the raw html output without re-indenting it.</p>\n<p>It's something that is of no real value, because anyone who wants to see the html structure can just use firebug/devtools/their-tool-of-choice and it'll indent the code for them. If you really want to have indented html anyway, there are tools for that like <a href=\"http://php.net/manual/en/book.tidy.php\" rel=\"nofollow noreferrer\">htmltidy</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-30T21:09:25.783",
"Id": "19505",
"Score": "0",
"body": "There are some good points here +1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-29T07:49:24.333",
"Id": "12135",
"ParentId": "11262",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "12135",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T19:23:55.720",
"Id": "11262",
"Score": "5",
"Tags": [
"php",
"object-oriented",
"form"
],
"Title": "PHP Form generator class"
}
|
11262
|
<p>I am trying to improve my C skills, and I hope someone might be able to provide me with some feedback on the following code.</p>
<p>It is just basic string splitting, it should behave the similar to <a href="http://www.ruby-doc.org/core-1.9.3/String.html#method-i-split" rel="nofollow">Ruby's String#split</a> or Clojure's clojure.string.split. I couldn't think of a simple/efficient way to create an array of variable-size strings so I went the callback route.</p>
<p>Anyway, any and all feedback is greatly appreciated, thank you! Check out the code: </p>
<pre><code>void strsplit(char *str, char *delim, int limit, void (*cb)(char *s, int idx))
{
char *search = strdup(str);
if (limit == 1) {
cb(search, 0);
}
else {
int i = 0, count = 0, len = strlen(str), len_delim = strlen(delim);
char *segment = NULL, *leftover = NULL;
limit = limit > 0 ? limit - 1 : len;
segment = strtok(search, delim);
for (i = 0; segment != NULL && i < limit; i++) {
count += strlen(segment) + len_delim;
cb(segment, i);
segment = strtok(NULL, delim);
}
if (len != limit && count < len) {
leftover = (char*) malloc(len - count + 1);
memcpy(leftover, str + count, len - count);
leftover[len - count] = '\0';
cb(leftover, i);
free(leftover);
}
}
}
</code></pre>
<p>Also see the <a href="http://ideone.com/5dXY1" rel="nofollow">code with a test framework</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T21:26:04.110",
"Id": "18098",
"Score": "0",
"body": "Hmm...at least for me, `strdup` doesn't lead to warm fuzzy feelings, and `strtok` makes me feel...less than happy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T21:31:09.440",
"Id": "18100",
"Score": "0",
"body": "@JerryCoffin Can you point me to some literature as to why I should avoid these guys?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T21:35:10.090",
"Id": "18101",
"Score": "0",
"body": "`strdup` should be avoided because it's non-standard (though, in fairness, it is pretty widely available). `strtok` should be avoided because it's ugly to use, requires heroic efforts to be thread safe, and can't be used on string literals. Duplicating the input avoids the last problem, but not the other two."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-03T21:13:51.123",
"Id": "18350",
"Score": "0",
"body": "I might be missing the call here, but you need to be sure to call `free` on your `search` string since you called `strdup` to allocate it."
}
] |
[
{
"body": "<p>I'd suggest not rolling your own implementation; just use <code>strtok_r</code> properly and save yourself some time. For memory allocation, you can either use the offsets into the string in-place, or use <code>strndup</code> to get copies of each token as you find it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T21:30:12.497",
"Id": "18099",
"Score": "1",
"body": "This is purely for learning experience. It isn't actually being used anywhere."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T21:25:46.933",
"Id": "11266",
"ParentId": "11265",
"Score": "5"
}
},
{
"body": "<p>Here's a few comments. You need a comment giving a better definition of what the function should do. Otherwise we have to guess what your approximation to the Ruby function might be. An alternative interface might be to pass in a pointer array and its length instead of the callback.</p>\n\n<ul>\n<li><p>I prefer to use <code>strspn</code> and <code>strcspn</code> or <code>strsep</code> if available to locate the tokens (just my preference).</p></li>\n<li><p><code>str</code> and <code>delim</code> should be const char *</p></li>\n<li><p>I'd prefer to see the <code>limit == 1</code> case handled in the main clause. Is there\na good reason to treat it separately?</p></li>\n<li><p>Each variable on its own line</p></li>\n<li><p>I think you can modify the algorithm to avoid having to count the length of\nthe string (<code>strlen(str)</code>). I don't think either <code>len</code> or <code>count</code> is necessary. </p></li>\n<li><p>efficiency: you traverse the string with <code>strlen</code> at the start, then <code>strtok</code> traverses each word and then you do it again with <code>strlen</code> on the word.</p></li>\n<li><p>why limit - 1 ??</p></li>\n<li><p>not sure <code>count</code> will be computed correctly (<code>len_delim</code> added but\nthe actual sequence of separators present may not be of that length)</p></li>\n<li><p>prefer <code>len < limit</code> to <code>len != limit</code> (more robust to future changes)</p></li>\n<li><p>is the condition for the final <code>if</code> clause correct? When do you want it to be\nexecuted?</p></li>\n<li><p>prefer brackets round multiple conditions <code>((len != limit) && (count < len))</code></p></li>\n<li><p>why use both <code>strdup</code> and <code>malloc</code> ?</p></li>\n<li><p>malloc return should not be cast (C not C++)</p></li>\n<li><p>why malloc the remaining string from <code>str</code> instead of just modifying <code>search</code> - it is\nalready writeable because you strdup-ed it</p></li>\n<li><p>the duped string should be freed on return, else it is a leak. Depends\nwhat the callback does with the bits of course.</p></li>\n</ul>\n\n<p>Possibly missed other things - but there are enough things above to be going on with I guess :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-05T20:03:15.493",
"Id": "18460",
"Score": "0",
"body": "Awesome, thank you, this is exactly the critical feedback I was hoping for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-05T20:05:29.580",
"Id": "18462",
"Score": "0",
"body": "The reason for `limit == 1` is to handle the case that no splitting is required, this mimics the behaviour of the Ruby and Clojure behaviour."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-05T20:06:06.800",
"Id": "18463",
"Score": "0",
"body": "I then use `limit - 1` to match zero-based iteration with the limit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-05T20:08:03.837",
"Id": "18464",
"Score": "0",
"body": "I believe I require `len` and `count` to track the offset of the last match, so I can then return the rest of the unsplit string in case of a limit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-05T20:09:22.493",
"Id": "18465",
"Score": "0",
"body": "I incorrectly assumed that `strdup` allocated on the stack, so I did not free it. How embarrassing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-06T02:09:22.190",
"Id": "18474",
"Score": "0",
"body": "I'm not sure about your comments here - without an exact definition of what the code should do it is impossible to determine. Note that the code in your test framework fails if you change the `delim` strings from `;` to something like `;:`. I think this would be a valid delimiter string according to your definition of the problem but maybe I misunderstood. It is good to do examples, but for my money, to be worth doing, a full definition of the requirement should precede the design (and review) of the code :-)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-30T04:42:54.033",
"Id": "11321",
"ParentId": "11265",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "11321",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T21:17:20.237",
"Id": "11265",
"Score": "5",
"Tags": [
"c"
],
"Title": "String splitting in C"
}
|
11265
|
<p>I sometimes find myself wanting custom events on a global object with JQuery.</p>
<p>For example:</p>
<pre><code>$(window).trigger('blah', {x: 'y'});
</code></pre>
<p>This plugin is designed to provide exactly that, except faster:</p>
<pre><code>$.multicast('blah')({x: 'y'});
</code></pre>
<p>Full plugin code (minus test pages, really gotta get some qunit going on):</p>
<pre><code>(function ($) {
"use strict";
var namedDelegates = {},
guid = 0,
multicastDelegate = function () {
var targets = {},
proxy = function () {
var args = arguments,
useargs = args.length > 0,
results = [],
site;
for (site in targets) {
if (targets.hasOwnProperty(site)) {
if (useargs) {
results.push(targets[site].apply(this, args));
} else {
results.push(targets[site].call(this));
}
}
}
if (proxy.aggregate) {
return proxy.aggregate.call(this, results);
}
return results;
};
$.extend(proxy, {
exists: function () {
var site;
for (site in targets) {
if (targets.hasOwnProperty(site)) {
return true;
}
}
return false;
},
add: function (func, key) {
if (typeof (func) === 'string') {
var temp = func;
func = key;
key = temp;
}
guid += 1;
if (!key) {
key = guid;
}
targets[key] = func;
},
remove: function (key) {
if (targets.hasOwnProperty(key)) {
delete targets[key];
}
},
callsites: function () {
return $.extend({}, targets);
},
aggregate: null
});
return proxy;
};
$.multicast = function (name) {
if (!namedDelegates[name]) {
namedDelegates[name] = multicastDelegate();
}
return namedDelegates[name];
};
$.extend($.multicast, {
aggregates: {
any_or_empty: function (args) {
var r = args.length === 0,
i,
l = args.length;
for (i = 0; i < l && !r; ++i) {
r = r || args[i];
}
return r;
},
all_or_empty: function (args) {
var r = args.length === 0,
i,
l = args.length;
for (i = 0; i < l && r; ++i) {
r = r && args[i];
}
return r;
},
atLeastN: function (n) {
return function (args) {
var r = 0,
i,
l = args.length;
if (l < n) { return false; }
for (i = 0; i < l && r < n; ++i) {
r += !!args[i] ? 1 : 0;
}
return r === n;
};
},
all: function (args) {
var r = args.length !== 0,
i,
l = args.length;
for (i = 0; i < l && r; ++i) {
r = r && args[i];
}
return r;
}
}
});
}(jQuery));
</code></pre>
<p><a href="http://jsperf.com/multicast" rel="nofollow">jsPerf</a></p>
<p>Eventually I'll get around to uploading this to github (I am waiting on the new plugin site). Feel free to use this. </p>
<p>License header is and has been since I started using this:</p>
<pre><code>/**
* jQuery.multicast
* Copyright (c) 2008 Bill Barry - after.fallout(at)gmail(dot)com | http://16randombytes.blogspot.com
* Dual licensed under MIT and GPL.
* Date: 13 Dec 2009
*/
</code></pre>
<p>I'd prefer if you kept it if you use this code, perhaps with a link here (when I do get this on JQuery plugins, I'll link there from here and update the header).</p>
<p>How can I make this code better? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T15:25:36.457",
"Id": "35875",
"Score": "0",
"body": "How come you don't use $.fn if it's a jQuery plugin?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T20:12:15.100",
"Id": "35958",
"Score": "0",
"body": "It doesn't extend the jQuery object. It extends jQuery itself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-24T11:43:06.827",
"Id": "219092",
"Score": "0",
"body": "Wouyld be interested to see how this works wqiuth the aggregates any demos?"
}
] |
[
{
"body": "<h3>Namespacing</h3>\n<p>There's no reason why this needs to be a jQuery plugin other than that you're using the jQuery $ as the namespace, and that you're using $.extend. You could easily make this an independent library, and use a UMD-style header to load it into whatever namespace is available.</p>\n<h3>Duplication</h3>\n<p>There's a lot of duplicate control flow code, especially in the aggregate functions. This is javascript: Use higher order functions! Look at using <code>ES5</code>'s <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some\" rel=\"nofollow noreferrer\"><code>Array.some</code></a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every\" rel=\"nofollow noreferrer\"><code>Array.every</code></a>, and don't be afraid to make your own. Just make sure that you use <a href=\"https://leanpub.com/javascript-allonge/read\" rel=\"nofollow noreferrer\">common idioms</a>.</p>\n<h3>Documentation and testing</h3>\n<p>This should go hand in hand with uploading it to github. Nobody's going to use your code unless you document it, and nobody at a serious business company is going to trust it unless you have tests. There's plenty of javascript <a href=\"https://github.com/Wolfy87/EventEmitter\" rel=\"nofollow noreferrer\">event</a>/<a href=\"https://github.com/daniellmb/MinPubSub/blob/master/minpubsub.src.js\" rel=\"nofollow noreferrer\">pubsub</a> <a href=\"http://microjs.com/#pub\" rel=\"nofollow noreferrer\">libraries</a> <a href=\"http://microjs.com/#event\" rel=\"nofollow noreferrer\">to</a> <a href=\"https://npmjs.org/search?q=event\" rel=\"nofollow noreferrer\">go</a> <a href=\"https://npmjs.org/search?q=pub+sub\" rel=\"nofollow noreferrer\">around</a>.</p>\n<h3>Minor details</h3>\n<p>Something like this</p>\n<pre><code>var r = args.length === 0,\n i,\n l = args.length;\n</code></pre>\n<p>Should be more like this</p>\n<pre><code>var i,\n l = args.length,\n r = l === 0;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-07T00:12:40.470",
"Id": "32351",
"ParentId": "11267",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "32351",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T22:21:42.527",
"Id": "11267",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "JQuery plugin for lightweight global events"
}
|
11267
|
<p>I'm using C# for a project and thought I would get a feel for the language by making some simple programs. My current program is a simple file recurser that prints the names of files and directories. Any suggestions would be greatly appreciated.</p>
<pre><code>using System;
using System.IO;
namespace FileRecurser
{
class Program
{
private static int indent = -2; // Start off at -2 so first indent
// starts at 0.
static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("Usage: recurser <directory>");
return;
}
// Check if directory exists.
string directory = args[0];
if (!Directory.Exists(directory))
{
Console.WriteLine("Error: {0} doesn't exist!", directory);
return;
}
Console.WriteLine("Printing files for {0}\n", directory);
PrintDirectoryFiles(directory);
}
private static void PrintDirectoryFiles(string directory)
{
indent += 2;
// If any subdirectories.
string[] subdirectories = Directory.GetDirectories(directory);
if (subdirectories.Length != 0)
{
foreach (var subdirectory in subdirectories)
{
// Change color to reflect directory.
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(
"{0}{1}:",
new String(' ', indent),
Path.GetFileName(subdirectory)
);
Console.ResetColor();
PrintDirectoryFiles(subdirectory);
Console.WriteLine();
}
}
// Print file names.
string[] files = Directory.GetFiles(directory);
if (files.Length != 0)
{
foreach (var file in files)
{
Console.WriteLine(
"{0}{1}",
new String(' ', indent),
Path.GetFileName(file)
);
}
}
indent -= 2;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I don't like how you use static field to indicate level of indentation, I think it would be better if you passed it down the recursion in parameters of the methods.</p>\n\n<p>And while you're at it, you should probably separate your concerns: don't have everything in your <code>Program</code> class, but have one class that recurses directories, and one that writes them out. That way, you can reuse them if you want to write the output in a different way (say in a GUI app) or if you want to recurse through something else than files (say, registry entries).</p>\n\n<p>Also, there is no need to check whether a collection is empty before iterating it, it just unnecessarily clutters the code.</p>\n\n<p>And you should think about handling exceptions: there might be directories you don't have access to. And there's also a chance that a directory was deleted while you were iterating its siblings, so you should handle that too.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T01:09:39.837",
"Id": "11271",
"ParentId": "11270",
"Score": "2"
}
},
{
"body": "<p>I would avoid using <code>return</code> to terminate when you are in <code>Main</code>, and use <a href=\"http://msdn.microsoft.com/en-us/library/system.environment.exit.aspx\" rel=\"nofollow\">Environment.Exit()</a> instead. </p>\n\n<p>It allows you to specify an error code (which is usually useless, but anyway), and also it makes your code easier to move to another method.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-30T17:31:01.020",
"Id": "18206",
"Score": "1",
"body": "I think it makes your code *harder* to move to another method. If I call a method, I don't expect it to exist the whole application on failure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-30T23:26:16.093",
"Id": "18233",
"Score": "0",
"body": "well, it depends who you are coding for, but one of my motto for coding is \"fail fast, fail hard\", and I like to have my app crash when something goes really wrong.\nOn second thought, I guess a better option would be to throw exceptions and leave them uncatched if you still want to crash the app."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-29T02:08:04.617",
"Id": "11296",
"ParentId": "11270",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "11271",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T00:47:10.410",
"Id": "11270",
"Score": "3",
"Tags": [
"c#",
"recursion",
"file"
],
"Title": "Simple file recurser"
}
|
11270
|
<p>I've implementing the <a href="http://www.csie.ntu.edu.tw/~cjlin/papers/online_ranking/" rel="nofollow">this algorithm</a> in Java, Scala, and Clojure to show my teammates. I know the code works as expected. What I'm looking for is tips on good Clojure style.</p>
<pre><code>(ns gaming.online.ranking
"Synopsis:
(bradley-terry-full 5
(list (create-team 1 45 (list (create-player 101 (create-ability-with-stddev 25 8))))
(create-team 2 32 (list (create-player 102 (create-ability-with-stddev 25 8))))))
Updates players' ability compared with how they were expected to perform")
; defn- means a private function
(defn- sum [f xs]
(apply + (map f xs)))
(defn- plus-pair [[a1 a2] [b1 b2]]
[(+ a1 b1) (+ a2 b2)])
(defn split-with-similar
"Where split-with is like [(take-while pred xs) (drop-while pred xs)], this method is like
recursive calls to split-with on the drop-while'd portion
The predicate takes two arguments: the head of the current list, and the element to compare it
against"
[pred xs]
(when xs
; loop/recur is how to do tail recursion in clojure
; 'let', 'do', 'for', 'loop' and function params can destructure collections like this next line
(loop [[head & tail] xs
acc (vector)]
(let [[like-head not-like-head] (split-with #(pred head %) tail)
updated-acc (conj acc (cons head like-head))] ; conj is like cons, but works with vectors too
(if (empty? not-like-head)
acc
(recur not-like-head updated-acc))))))
; defining a class called Ability with these fields. It acts much like a clojure map
(defrecord Ability [mean stddev variance])
; keywords are also functions accepting a map
; maps are also functions accepting a key
; vectors are also functions accepting an index
(defn mean [ability] (:mean ability))
(defn stddev [ability] (:stddev ability))
(defn variance [ability] (:variance ability))
(defn create-ability-with-stddev [mean stddev]
"Create ability from stddev"
(Ability. mean stddev (* stddev stddev))) ; how to call a java constructor
(defn create-ability-with-variance [mean variance]
"Create ability from variance"
(Ability. mean (Math/sqrt variance) variance)) ; call java static function
(defprotocol HasAbility
"Both Player and Team have these methods. A protocol
actually compiles down to a Java interface
Another approach would be to use multi-methods."
(id [this])
(ability [this]))
(defn skill
"A single number representative of the player(s)'s true ability.
For ranking purposes, this is chosen as a lower bound (with 95% confidence)
on the player's true ability: it only goes up from here!
With 95% confidence, the number is below the players true ability"
[has-ability]
(let [ability (ability has-ability)]
(- (mean ability) (* 3 (stddev ability)))))
; shows how to implement a protocol/interface
(defrecord Player [id ability]
HasAbility
(id [this] (:id this))
(ability [this] (:ability this)))
(defn create-player [id ability]
(Player. id ability))
(defn copy-player [player ability]
(create-player (:id player) ability))
(defrecord Team [id score ability players]
HasAbility
(id [this] (:id this))
(ability [this] (:ability this)))
(defn create-team [id score players]
(let [abilities (map ability players)
mean (sum mean abilities)
variance (sum variance abilities)]
(Team. id score (create-ability-with-variance mean variance) players)))
(defn team-players [team] (:players team))
(defn team-size [team] (count (team-players team)))
(defn score [team] (:score team))
(def by-score-and-skill
(reify java.util.Comparator ; implement a java comparator in place
(compare [this a b]
(or
(first (drop-while zero?
[(compare (score b) (score a))
(compare (team-size b) (team-size a))
(compare (skill b) (skill a))
(compare (id a) (id b))]))
0))))
(defn- score-within-allowance? [allowance]
(fn [a b] ; defining a lambda is done via 'fn'
(<= (- (score a) allowance) (score b))))
(defn- calculate-ranks [rank-allowance teams]
(loop [current-rank 0
ranks {}
[similar-head & similar-rest] (split-with-similar (score-within-allowance? rank-allowance) teams)]
(let [updated-ranks (apply assoc ranks (flatten (map #(vector % current-rank) similar-head)))]
(if (empty? similar-rest)
updated-ranks
(recur (+ current-rank (count similar-head))
updated-ranks
similar-rest)))))
(defn- update-player-abilities [player team-ability Omega Delta]
(let [ability (ability player)
variance-to-team-variance (/ (variance ability) (variance team-ability))]
(copy-player player
(create-ability-with-stddev
(+ (mean ability) (* Omega variance-to-team-variance))
(* (stddev ability)
(Math/sqrt (max (- 1 (* Delta variance-to-team-variance)) 0.0001)))))))
(defn- full-update
"calc is a function expecting 2 params: team and opponent"
[teams calc]
(concat
(for [team teams ; map,for,reduce are "chunked lazy" so don't do side effects!
:let [scores (for [opponent teams :when (not= opponent team)] (calc team opponent))
[omega delta] (reduce plus-pair [0.0 0.0] scores)
team-ability (ability team)]
player (team-players team)]
(update-player-abilities player team-ability omega delta))))
(defn bradley-terry-full [rank-allowance _teams]
(when _teams ; nil is an empty list
(let [mu 25.0
sigma (/ mu 3.0)
beta (* sigma 0.5)
beta**2 (* beta beta)
teams (sort by-score-and-skill _teams)
ranks (calculate-ranks rank-allowance teams)
gamma (/ 1.0 (count teams))]
(full-update teams
(fn [team opponent-team]
(let [team-ability (ability team)
rank (ranks team)
opponent (ability opponent-team)
c (Math/sqrt (+ (variance team-ability) (variance opponent) (* 2 beta**2)))
p (/ 1.0 (+ 1 (Math/exp (/ (- (mean opponent) (mean team-ability)) c))))
variance-to-c (/ (variance team-ability) c)
cmp-opponent-rank (compare rank (ranks opponent-team))
s (cond (pos? cmp-opponent-rank) 1.0
(neg? cmp-opponent-rank) 0.0
:default 0.5)]
[(* variance-to-c (- s p))
(* gamma (/ variance-to-c c) p (- 1 p))]))))))
(defn- join [sep coll]
(if (empty? coll)
""
(loop [[head & tail] coll
acc ""]
(let [pretty-head (pr-str head)]
(if (empty? tail)
(str acc pretty-head)
(recur tail (str acc pretty-head sep)))))))
(let [team1 (create-team 1 500
(list (create-player 1 (create-ability-with-stddev 25 8))
(create-player 2 (create-ability-with-stddev 27 5))
(create-player 3 (create-ability-with-stddev 22 3))))
team2 (create-team 2 400
(list (create-player 4 (create-ability-with-stddev 25 8))
(create-player 5 (create-ability-with-stddev 27 5))
(create-player 6 (create-ability-with-stddev 22 3))))
team3 (create-team 3 395
(list (create-player 7 (create-ability-with-stddev 25 8))
(create-player 8 (create-ability-with-stddev 27 5))
(create-player 9 (create-ability-with-stddev 22 3))))
updated-players (bradley-terry-full 10 (list team1 team2 team3))]
(println (join "\n" updated-players)))
</code></pre>
|
[] |
[
{
"body": "<p>This is a huge file to comment on, so maybe just some general tips:</p>\n\n<ul>\n<li><p><code>map</code> and <code>mapv</code> (a variant of map returning a vector) can take any number of sequences as argument, each element of the nth sequence being used as the nth argument of the function given to map. So plus-pair could be written:</p>\n\n<pre><code>(defn plus-vectors [v1 v2]\n (mapv + v1 v2)\n</code></pre></li>\n<li><p><code>loop</code> can be replaced by <code>iterate</code> and <code>take-while</code>, but that is mostly a matter of taste</p></li>\n<li><p>You can use <code>map->Ability</code> to instantiate an Ability record</p></li>\n<li><p>You can use the threading macros <code>-></code> and <code>->></code> more often for clarity:</p>\n\n<pre><code>(for [opponent teams :when (not= opponent team)] (calc team opponent))\n</code></pre>\n\n<p>can be written more cleanly as:</p>\n\n<pre><code>(->> teams \n (remove #{team})\n (map calc team))\n</code></pre></li>\n<li><p>I would avoid the use of <code>:let</code> inside a <code>for</code> definition, I would instead use a proper <code>(let [])</code> inside its body whenever possible</p></li>\n<li><p>By convention, argument that start with an underscore mean they are ignored, so <code>_team</code> might not be the best choice in this example</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T16:39:49.380",
"Id": "18018",
"ParentId": "11275",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "18018",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T06:30:37.550",
"Id": "11275",
"Score": "8",
"Tags": [
"clojure"
],
"Title": "Bayesian approximation method for online ranking"
}
|
11275
|
<p>In the code below, I want to remove the "white space character" from 2 places only, from the end of 1st line and from the end of last line. How can I optimize it ?</p>
<p>Platform : Linux , gcc compiler </p>
<pre><code>int remove_special_chars(char *file_path, char *dest_file, int flag)
{
PRINT_FUN_NAME
struct stat st;
unsigned char *fileData=NULL;
FILE *fp = NULL, *dest_file_fp = NULL, *intermidiate_fp = NULL;
char tmp_str[256] = {0}, str_buffer[100] = {0};
int file_size = 0, count = 0, read_len = 0;
/* I have taken 3 files here "file_path" is
the source file from which i am reading
data and intermidiate_path is the 2nd file
in which iam storing data after removing
the space from 1st line. Then iam reding
the intermidiate file and removing the space
from last line and finally storing it into
3rd file i.e is "dest_file". */
if ((fp = fopen(file_path, "r")) == NULL) {
DPRINTF("File Opening Failed!\n");
return -1;
}
if((intermidiate_fp = fopen(INTERMEDIATE_FILE_PATH, "wb+")) == NULL) {
DPRINTF("File Opening Failed!\n");
return -1;
}
if((dest_file_fp = fopen(dest_file, "wb")) == NULL) {
DPRINTF("File Opening Failed!\n");
return -1;
}
while(fgets(tmp_str, sizeof(tmp_str), fp) != NULL) {
DPRINTF("tmp_str : %s\n", tmp_str);
fputs(tmp_str, intermidiate_fp);
if(count == 0) {
rewind(intermidiate_fp);
strncpy(str_buffer, tmp_strstrlen(tmp_str));
str_buffer[strlen(str_buffer) - 1] = '\0';
DPRINTF("str_buffer : %s\n", str_buffer);
fputs(str_buffer, intermidiate_fp);
count ++;
}
}
rewind(intermidiate_fp);
stat(INTERMEDIATE_FILE_PATH, &st);
if (st.st_size == 0) {
return (-2);
}
file_size = st.st_size;
DPRINTF("File size : %d\n", file_size);
fileData = (unsigned char *)malloc(sizeof(char)*file_size);
if(fileData == NULL) {
DPRINTF("Unable to allocate size for fileData!\n");
return -1;
}
if ((read_len=fread(fileData, 1, file_size, intermidiate_fp)) == 0) {
DPRINTF("Reading Failed!\n");
free(fileData); fileData=NULL;
return (-3);
}
fileData[(file_size-1)] = '\0';
DPRINTF("File Data : %s\n", fileData);
fputs((char*)fileData, dest_file_fp);
fclose(dest_file_fp); fclose(fp);
fclose(intermidiate_fp);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T18:52:49.043",
"Id": "18124",
"Score": "0",
"body": "Minor nitpick: could you please correct the spelling of \"intermediate\" ?"
}
] |
[
{
"body": "<p>A couple lines that bother me:</p>\n\n<pre><code>strncpy(str_buffer, tmp_strstrlen(tmp_str));\n</code></pre>\n\n<p>First, bear in mind that <code>strncpy</code> does not place a <code>\\0</code> terminator at the end of the string if the buffer size limit is reached (but it does in every other case!). Thus, you have to be extremely careful when using <code>strncpy</code>.</p>\n\n<p>Second, you're copying a large (256-byte) buffer into a smaller (100-byte) buffer, and you're (presumably) passing the length of the larger buffer to <code>strncpy</code>. If <code>tmp_str</code> holds a string that's too long, you'll get a buffer overflow.</p>\n\n<pre><code>str_buffer[strlen(str_buffer) - 1] = '\\0';\n</code></pre>\n\n<p>When the string has length zero (e.g. the file is empty or did not have a trailing newline), the array access will be out of range. Otherwise, it will blindly delete the last character, even if it wasn't whitespace.</p>\n\n<p>The lines that I highlighted will work... if you make a couple assumptions:</p>\n\n<ul>\n<li><p>Every line of input has < 100 characters</p></li>\n<li><p>The \"whitespace characters\" we want to delete always exist.</p></li>\n</ul>\n\n<p>However, it looks like you're deleting the trailing newline returned by <code>fgets</code>. I'm not even sure your code works.</p>\n\n<hr>\n\n<p>If I were you, the first step I'd take is to come up with a concise specification of what you're trying to do. Correct me if I'm wrong, but it sounds like you want to do this:</p>\n\n<pre><code>first line: s/[\\t ]$//\nlast line: s/[\\t ]$//\nLines are terminated by '\\n', except the last line might not have a terminator.\n</code></pre>\n\n<p>The <code>s/[\\t ]$//</code> syntax is borrowed from <a href=\"http://en.wikipedia.org/wiki/Sed\" rel=\"nofollow\">sed</a>, and means: if there's a <code>'\\t'</code> or <code>' '</code> character at the end of the string, remove it (i.e. replace it with an empty string).</p>\n\n<p>Then, observe that this operation can be done with a trivial amount of buffering. When a newline is detected, hang on to the last character in the line, and only emit it when you're not on the first line and you know that more lines follow. Thus, you don't need an intermediate file.</p>\n\n<p>I recommend implementing a helper function with this signature:</p>\n\n<pre><code>int remove_trailing_spaces(FILE *in, FILE *out);\n</code></pre>\n\n<p>You should only need to <code>fread</code> and <code>fwrite</code> in large chunks. The <code>int</code> lets you return an error code if one of these functions fails.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T19:33:04.127",
"Id": "11284",
"ParentId": "11276",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T08:24:39.603",
"Id": "11276",
"Score": "3",
"Tags": [
"optimization",
"c",
"linux"
],
"Title": "Trimming whitespace from the beginning and ending of a file"
}
|
11276
|
<p>This is my first attempt with MVC and I almost get it, but a small thing bothers me.</p>
<p>I have this controller in CodeIgniter:</p>
<pre><code><?php
class Page extends CI_Controller {
public function index($page = "home")
{
$data['page'] = $page;
list($data['title']) = array_keys($this->_menu(), $page);
$data['menuItems'] = $this->_menu();
$this->load->view('templates/header', $data);
$this->load->view('templates/menu', $data);
$this->load->view('pages/'.$page, $data);
$this->load->view('templates/footer', $data);
}
private function _menu()
{
static $menuItems = array(
"Home page" => "home",
"Our history" => "history",
"About us" => "about",
"Contact page" => "contact"
);
return $menuItems;
}
}
</code></pre>
<p>And here is the menu view:</p>
<pre><code><?php
$menu = "";
foreach ($menuItems as $menuName => $view) {
$menu .= '<li';
if ( $page == $view ) {
$menu .= ' class="selected">';
$menu .= '<a href="#">';
} else {
$menu .= '><a href="' . $view . '">';
}
$menu .= $menuName . '</a></li>' .PHP_EOL ;
}
echo $menu;
</code></pre>
<p>Where do the menu items belong in MVC logic? Is it ok to store things like the menu in the <code>Controller</code> or do I have to make a new <code>Model</code> for it like this?</p>
<pre><code>class Menu extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function get_menu_items()
{
static $menuItems = array(
"Home page" => "home",
"Our history" => "history",
"About us" => "about",
"Contact page" => "contact"
);
return $menuItems;
}
}
</code></pre>
<p>Then load it from <code>Controller</code>:</p>
<pre><code>public function index($page = "home")
{
...
$this->load->model('Menu');
$data['menuItems'] = $this->Menu->get_menu_items();
$this->load->view(...);
$this->load->view(...);
$this->load->view(...);
}
</code></pre>
|
[] |
[
{
"body": "<p>This a nice example: it shows how the MVC is just a pattern which should be ajusted to your needs.</p>\n\n<ul>\n<li>The menu items you're showing seem <em>very unlikely</em> to change over time. This means you can simply put them in your \"templates/menu\" <strong>view</strong>.</li>\n<li>If they're shared among multiple views, then the <strong>controller</strong> is OK.</li>\n<li>If the menu items can change dynamically, then your model can provide a meaningful abstraction over your data, and then it would go into a <strong>model</strong>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T13:40:40.633",
"Id": "18113",
"Score": "0",
"body": "So if I get the menu elements from database, it should go to model, right ?\nHow can I set page title if I put the array into the view ?\n`list($data['title']) = array_keys($this->_menu(), $page);`\nI cannot acces the menu items from the controller then. Or can I ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T13:47:33.253",
"Id": "18114",
"Score": "0",
"body": "`$data['menuItems']` becomes `$menuItems` in the view. So if you want to use `array_keys`, simply use `array_keys($menuItems, \"about\")` to get \"About us\". By the way, it would make more sense for \"about\" to be the key, and \"About us\" to be the value. You could then write `$menuItems[\"about\"]`. Why don't you simply use a foreach over `$menuItems`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T14:13:54.243",
"Id": "18115",
"Score": "0",
"body": "I want the active page menu item to look different, so I mark the active menu with `selected` class.\nIn my question I meant that If I put the menu elements array in the view, not the controller, I can't determine what is the actual page title, so it have to reachable from the controller to assign `$data['title']` based on which page is active."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T14:19:46.020",
"Id": "18116",
"Score": "0",
"body": "Ah! Simply set `$data['page'] = $page;`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T14:40:14.100",
"Id": "18117",
"Score": "0",
"body": "I want \"About us\" to be the page title in the browser tab, not \"about\". And I cannot if I put the array in the view."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T14:56:03.497",
"Id": "18118",
"Score": "0",
"body": "Since `templates/header` does not know about `$menuItems`, but `templates/menu` does? That's the second bullet point of my answer."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T13:33:00.353",
"Id": "11278",
"ParentId": "11277",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "11278",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T13:16:23.910",
"Id": "11277",
"Score": "3",
"Tags": [
"php",
"mvc",
"codeigniter"
],
"Title": "Where should I put menu items in MVC with PHP - Model or Controller?"
}
|
11277
|
<p>So I have convert the <code>getDisplayPosition</code> from the beta version of the Kinect SDK to the full version. Here's what I have right now<br/><h3>The Original</h3></p>
<pre><code> private Point getDisplayPosition(Joint joint)
{
float depthX, depthY;
nui.SkeletonEngine.SkeletonToDepthImage(joint.Position, out depthX, out depthY);
depthX = Math.Max(0, Math.Min(depthX * 320, 320)); //convert to 320, 240 space
depthY = Math.Max(0, Math.Min(depthY * 240, 240)); //convert to 320, 240 space
int colorX, colorY;
ImageViewArea iv = new ImageViewArea();
// only ImageResolution.Resolution640x480 is supported at this point
nui.NuiCamera.GetColorPixelCoordinatesFromDepthPixel(ImageResolution.Resolution640x480, iv, (int)depthX, (int)depthY, (short)0, out colorX, out colorY);
// map back to skeleton.Width & skeleton.Height
return new Point((int)(skeleton.Width * colorX / 640.0), (int)(skeleton.Height * colorY / 480));
}
</code></pre>
<p><br/></p>
<h3>My Version</h3>
<pre><code>private Point getDisplayPosition(Joint joint)
{
float depthX, depthY;
KinectSensor sensor = kinectSensorChooser1.Kinect;
DepthImageFormat depth = DepthImageFormat.Resolution320x240Fps30;
depthX = 320;
depthY = 240;
sensor.MapSkeletonPointToDepth(joint.Position, depth);
depthX = Math.Max(0, Math.Min(depthX * 320, 320));
depthY = Math.Max(0, Math.Min(depthY * 240, 240));
int colorX, colorY;
colorX = 320;
colorY = 240;
return new Point((int)(skeleton.Width * colorX / 640.0), (int)(skeleton.Height * colorY / 480));
}
</code></pre>
<p>Basically I want to know if my version will do the same thing as the origin</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T19:21:59.787",
"Id": "18126",
"Score": "7",
"body": "Hmm, I think to would be better received at [SO]. This isn't really a \"please review my working code\" question but more of a \"help me get this updated to the current version\" question which doesn't really fit here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T20:32:54.490",
"Id": "18131",
"Score": "0",
"body": "@Mercado Oh I was gonna ask it there but didnt know if it would fit. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-29T23:56:36.173",
"Id": "18166",
"Score": "0",
"body": "@Mercado can you add a `kinect` tag, I have insufficient rep to do so, and is kinda necassary"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-18T17:26:35.230",
"Id": "31577",
"Score": "0",
"body": "I found some information here\nhttp://everythingyoumightneed.blogspot.com/2012/11/complete-guide-converting-code-from.html\n\nfor other similar subjects aswell"
}
] |
[
{
"body": "<p>Since I have this same question on Stack Overflow now, the answer can be found <a href=\"https://stackoverflow.com/questions/10367582/converting-kinect-methods-from-beta-2-to-version-1/10448663#10448663\">here</a>. The updated version is:</p>\n\n<pre><code>private Point getDisplayPosition(DepthImageFrame depthFrame, Joint joint)\n{ \n float depthX, depthY; \n DepthImagePoint depthPoint = kineticSensor.MapSkeletonPointToDepth(joint.Position, depthImageFormat);\n\n depthX = depthPoint.X;\n depthY = depthPoint.Y;\n\n depthX = Math.Max(0, Math.Min(depthX * 320, 320));\n depthY = Math.Max(0, Math.Min(depthY * 240, 240));\n\n int colorX, colorY;\n ColorImagePoint colorPoint = depthFrame.MapToColorImagePoint(depthPoint.X, depthPoint.Y, sensor.ColorStream.Format);\n colorX = colorPoint.X;\n colorY = colorPoint.Y;\n\n return new Point((int)(skeleton.Width * colorX / 640.0), (int)(skeleton.Height * colorY / 480));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-21T02:01:01.733",
"Id": "14880",
"ParentId": "11280",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "14880",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T18:06:32.350",
"Id": "11280",
"Score": "4",
"Tags": [
"c#"
],
"Title": "Converting Kinect Methods from Beta 2, to Version 1"
}
|
11280
|
<p>Any suggestions to make this better? </p>
<pre><code> import math
# BSD License:
"""Copyright (c) 2012, Solomon Wise
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software
must display the following acknowledgement:
This product includes software developed by Solomon Wise.
4. Neither the name of CRange nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY SOLOMON WISE "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL SOLOMON WISE BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
class CRange:
"""CRange is short for Changeable Range. With this type of range object, one
can edit the start, stop, and step for the range, as well as easily
retrieving the values in the range"""
def __init__(self, maximum, start=0, step=1):
"""Sets the maximumimum"""
self.maximum = math.ceil(maximum)
self.start = math.floor(start)
self.step = math.ceil(step)
def __iter__(self):
"""Iterates over the range"""
for x in range(self.start, self.maximum, self.step):
yield x
def __str__(self):
"""Returns a string representation of the CRange"""
return "CRange object with Max: {0}, Min: {1}, and Step: {2}".format(self.maximum, self.start, self.step)
def __int__(self):
"""Returns a integer representation of the maximum"""
return self.maximum
def __len__(self):
"""Returns the number of values in the range"""
x = 0
for i in self:
x += 1
return x
def tuple(self):
"""Returns a tuple representation of the maximum, minimum, and step"""
return (self.maximum, self.start, self.step)
def dict(self):
"""Returns a dictionary representation of the maximum, minimum, and step"""
return {"Max": self.maximum, "Min": self.start, "Step": self.step}
def getmaximum(self):
"""Gets the length of the range"""
return self.maximum
def getstart(self):
"""Gets the starting point of the range"""
return self.start
def getstep(self):
"""Gets the step of the range"""
return self.step
def getall(self):
"""Returns all range attributes"""
print("Start:", self.start)
print("Step:", self.step)
print("Stop:", self.maximum)
return 0
def change_range(self, attr, option, x):
"""Provides options to change attributes of the range"""
if option == "add" and attr == "maximum":
try:
self.maximum += x
except:
print("Error")
elif option == "sub" and attr == "maximum":
try:
self.maximum -=x
except:
print("Error")
elif option == "mult" and attr == "maximum":
try:
if self.maximum <= 0:
raise SyntaxError
self.maximum *= x
except:
print("Error")
elif option == "div" and attr == "maximum":
try:
self.maximum /= x
if self.maximum <= 0:
raise SyntaxError
except:
print("Error")
elif option == "add" and attr == "start":
try:
self.start += x
except:
print("Error")
elif option == "sub" and attr == "start":
try:
self.start -=x
except:
print("Error")
elif option == "mult" and attr == "start":
try:
if self.start <= 0:
raise SyntaxError
self.start *= x
except:
print("Error")
elif option == "div" and attr == "start":
try:
self.start /= x
if self.start <= 0:
raise SyntaxErros
except:
print("Error")
elif option == "add" and attr == "step":
try:
self.step += x
except:
print("Error")
elif option == "sub" and attr == "step":
try:
self.step -= x
except:
print("Error")
elif option == "mult" and attr == "step":
try:
if self.step <= 0:
raise SyntaxError
self.step *= x
except:
print("Error")
elif option == "div" and attr == "step":
try:
self.step /= x
if self.step <= 0:
raise SyntaxError
except:
print("Error")
self.start = math.ceil(self.start)
self.step = math.ceil(self.step)
self.maximum = math.ceil(self.maximum)
def shift(self, x):
"""Shifts both the maximum and the start in one function call"""
try:
if self.maximum + x < 0 or self.start + x < 0:
raise SyntaxError
self.maximum += x
self.start += x
self.maximum, self.start = math.ceil(self.maximum), math.ceil(self.start)
except:
print("Error")
def stretch(self, x):
"""Changes both the maximum and the step in one function call"""
try:
if self.maximum + x < 0 or self.step + x < 0:
raise SyntaxError
self.maximum += x
self.step += x
self.maximum, self.step = math.ceil(self.maximum), math.ceil(self.step)
except:
print("Error")
def docs():
"""Documentation for the module"""
print("This module was written for Python 3.2")
print("Text Editors Used: Emacs, Komodo Edit")
print("OS Used: Mac OS X")
</code></pre>
<p>A follow-up to this question can be found <a href="https://codereview.stackexchange.com/questions/11295/what-can-i-improve">here</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T19:19:04.033",
"Id": "18125",
"Score": "0",
"body": "Better in what way? Be specific."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T19:33:13.783",
"Id": "18127",
"Score": "2",
"body": "@JeffMercado, without any specific requests, the assumption of Code REview is that they want general feedback on the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T19:35:48.227",
"Id": "18129",
"Score": "0",
"body": "@Winston: I don't know about that, we could give a better review if we were given some direction on where he wants to go. \"I want this to be faster,\" \"Is my implementation efficient,\" \"I want to use the X design pattern\" is a lot better than \"How can I make this better?\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T20:11:03.880",
"Id": "18130",
"Score": "2",
"body": "Drop the copyright would you? NASA will not use this code and neither will Goldman Sachs. Python code is not meant to take up pages and pages ..."
}
] |
[
{
"body": "<pre><code>import math\n# BSD License:\n\"\"\"Copyright (c) 2012, Solomon Wise\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n3. All advertising materials mentioning features or use of this software\n must display the following acknowledgement:\n This product includes software developed by Solomon Wise.\n4. Neither the name of CRange nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY SOLOMON WISE \"AS IS\" AND ANY\nEXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL SOLOMON WISE BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\nclass CRange:\n</code></pre>\n\n<p>Is abbreviating really helpful? Maybe the name should be ChangeableRange or MutableRange. CRange is kinda problematic because C gets used to mean class in prefixe a lot</p>\n\n<pre><code> \"\"\"CRange is short for Changeable Range. With this type of range object, one\n can edit the start, stop, and step for the range, as well as easily\n retrieving the values in the range\"\"\"\n def __init__(self, maximum, start=0, step=1):\n \"\"\"Sets the maximumimum\"\"\"\n</code></pre>\n\n<p>That's not a very good description</p>\n\n<pre><code> self.maximum = math.ceil(maximum)\n self.start = math.floor(start)\n self.step = math.ceil(step)\n</code></pre>\n\n<p>Thats a seriously unexpected transformation. Using this will be confusing</p>\n\n<pre><code> def __iter__(self):\n \"\"\"Iterates over the range\"\"\"\n for x in range(self.start, self.maximum, self.step):\n yield x\n</code></pre>\n\n<p>Just <code>return iter(range(self.start, self.maximum, self.step))</code>, don't needlessly iterate over the range yourself.</p>\n\n<pre><code> def __str__(self):\n \"\"\"Returns a string representation of the CRange\"\"\"\n return \"CRange object with Max: {0}, Min: {1}, and Step: {2}\".format(self.maximum, self.start, self.step)\n def __int__(self):\n \"\"\"Returns a integer representation of the maximum\"\"\"\n return self.maximum\n</code></pre>\n\n<p>Does converting a range into an int actually make any sense?</p>\n\n<pre><code> def __len__(self):\n \"\"\"Returns the number of values in the range\"\"\"\n x = 0\n for i in self:\n x += 1\n return x\n</code></pre>\n\n<p>That's a seriously inefficient way to calculate the length</p>\n\n<pre><code> def tuple(self):\n \"\"\"Returns a tuple representation of the maximum, minimum, and step\"\"\"\n return (self.maximum, self.start, self.step)\n def dict(self):\n \"\"\"Returns a dictionary representation of the maximum, minimum, and step\"\"\"\n return {\"Max\": self.maximum, \"Min\": self.start, \"Step\": self.step}\n</code></pre>\n\n<p>Why? Why would you want either of these functions</p>\n\n<pre><code> def getmaximum(self):\n \"\"\"Gets the length of the range\"\"\"\n return self.maximum\n def getstart(self):\n \"\"\"Gets the starting point of the range\"\"\"\n return self.start\n def getstep(self):\n \"\"\"Gets the step of the range\"\"\"\n return self.step\n</code></pre>\n\n<p>Python doesn't need getter functions. Just access attribute directly or via properties.</p>\n\n<pre><code> def getall(self):\n \"\"\"Returns all range attributes\"\"\"\n</code></pre>\n\n<p>No, it does not.</p>\n\n<pre><code> print(\"Start:\", self.start)\n print(\"Step:\", self.step)\n print(\"Stop:\", self.maximum)\n return 0\n</code></pre>\n\n<p>What possible purpose would this function serve?</p>\n\n<pre><code> def change_range(self, attr, option, x):\n \"\"\"Provides options to change attributes of the range\"\"\"\n</code></pre>\n\n<p>What the fried turkey are you trying to do here? The whole function is a complete and total disaster. Do you seriously want this function? Whatever you are trying to do with it, you are doing it wrong.</p>\n\n<pre><code> def shift(self, x):\n \"\"\"Shifts both the maximum and the start in one function call\"\"\"\n try:\n if self.maximum + x < 0 or self.start + x < 0:\n raise SyntaxError\n</code></pre>\n\n<p>Raise appropriate errors. Whatever the problem is, its not a SyntaxError.</p>\n\n<pre><code> self.maximum += x\n self.start += x\n self.maximum, self.start = math.ceil(self.maximum), math.ceil(self.start)\n except:\n print(\"Error\")\n</code></pre>\n\n<p>NEVER NEVER NEVER NEVER catch errors and just print \"Error.\" Always catch only the specific errors you want to handle, and always provide all the information available about the problem.</p>\n\n<pre><code> def stretch(self, x):\n \"\"\"Changes both the maximum and the step in one function call\"\"\"\n try:\n if self.maximum + x < 0 or self.step + x < 0:\n raise SyntaxError\n self.maximum += x\n self.step += x\n self.maximum, self.step = math.ceil(self.maximum), math.ceil(self.step)\n except:\n print(\"Error\")\n</code></pre>\n\n<p>Again, don't do that.</p>\n\n<pre><code>def docs():\n \"\"\"Documentation for the module\"\"\"\n print(\"This module was written for Python 3.2\")\n print(\"Text Editors Used: Emacs, Komodo Edit\")\n print(\"OS Used: Mac OS X\")\n</code></pre>\n\n<p>Documentation should go into the docstring for the file. Not in a docs function. </p>\n\n<p>This class seems very odd. I suspect that there is probably a much better way of doing whatever you are trying to do. But since you don't tell us what you are trying to do, I can't say for certain.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-29T01:46:46.687",
"Id": "18139",
"Score": "0",
"body": "+1 I really need to post some of my python code sometime to get one of your great in-depth reviews."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T19:32:30.383",
"Id": "11283",
"ParentId": "11282",
"Score": "5"
}
},
{
"body": "<p>I mostly agree with Winston Ewert that there's likely a better way. In case there's not, here's something to cut your SLOC way down:</p>\n\n<pre><code>def change_range(self, attr, option, x):\n val = getattr(self, attr)\n op = { \"add\" : lambda v: v += x,\n \"sub\" : lambda v: v -= x,\n \"div\" : lambda v: v /= x,\n \"mult\" : lambda v: v *= x }[option]\n try:\n val = op(val)\n except Error as e:\n print(\"Error in change_range %s %s %d: %s\" % (attr, option, x, e))\n if val <= 0:\n raise SyntaxError\n setattr(self, attr, math.ceil(val))\n</code></pre>\n\n<p>It's not an exact workalike (your odd error-checking for values of val is in a slightly different place in some cases) but it's pretty close. Tweak it as needed, of course.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-16T06:45:31.463",
"Id": "11796",
"ParentId": "11282",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T19:05:45.600",
"Id": "11282",
"Score": "1",
"Tags": [
"python"
],
"Title": "Suggestions for changeable range object?"
}
|
11282
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.