body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>i came across <a href="http://www.logicmazes.com/n2mz.html">this fun puzzle</a> while being on vacation. </p>
<p>It was designed by Robert Abbott and painted into the grass of a Wisconsin farm. Robert succeeded into making it seem really easy to solve. Well, it is not. I spent hours with my friends wandering the puzzle and left frustrated. </p>
<p>I decided to solve it using computers. chose javascript because it made it easy to visualize the process and solution. </p>
<p>Initially i started with a brute force algorithm, which run for hours and got me nowhere. Than i shifted to this final one (below). I just kinda came up with this recursive solution that explores all paths, and terminates any path that comes across a previously visited node, so the one that makes it to the end should be the shortest one in (my) theory. I am wondering if this is a known algorithm (and how i botched it), and if there is a better way to achieve this. Also this algo appears to find the answer in 28 steps (including entry step).. A friend of mine solved this using an algo that works its way back from the end which supposedly solved it in 20 steps.</p>
<p>anyways, <a href="http://pics.nicecomeback.com/puzzle.html">the working solution can be seen here</a>. </p>
<p>here is the recursive function: </p>
<pre><code>_delay = 50;
_successfulSteps = null;
function findRecursive(params){
var cell = params[0];
var steps = params[1];
var history = params[2];
var x = getX(cell);
var y = getY(cell);
var steps = getCellSteps(cell);
markCellActive(x,y);
var h = [];
for (var i = 0; i<history.length; i++) {
h.push(history[i]);
};
h.push([getX(cell),getY(cell)]);
if (steps == 0) {
var sp = $('#solutionSpan')[0];
sp.innerHTML = 'solved in ' + h.length + ' steps';
return;
}
for (var i = history.length - 1; i >= 0; i--) {
if (x == history[i][0] && y == history[i][1]) {
// this cell already processed
console.log('terminating recursion for: ' + y + ':' + x);
return;
}
};
var rightCell = getRightCell(x,y, steps);
var leftCell = getLeftCell(x,y, steps);
var upCell = getUpCell(x,y, steps);
var downCell = getDownCell(x,y, steps);
// add delay to visualize the process
if (rightCell){
setTimeout(findRecursive, _delay, [rightCell, steps, h]);
}
if (leftCell){
setTimeout(findRecursive, _delay, [leftCell, steps, h]);
}
if (upCell){
setTimeout(findRecursive, _delay, [upCell, steps, h]);
}
if (downCell){
setTimeout(findRecursive, _delay, [downCell, steps, h]);
}
}
</code></pre>
<p>(i should note that this is not the prettiest code and i'm not looking for a way to reduce # of lines or anything, just to find a better algorithm)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T20:56:37.117",
"Id": "30327",
"Score": "2",
"body": "The [shortest path problem](http://en.wikipedia.org/wiki/Shortest_path_problem) can be solved using [Dijkstra's algorithm](http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T23:06:23.400",
"Id": "30332",
"Score": "0",
"body": "since each node is forcing a # of subsequent steps, i believe it's not as simple as finding the least # of steps between 2 points. Those steps are already routed and the problem is finding that route. is that still the same as shortest path problem ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T16:03:29.360",
"Id": "30356",
"Score": "1",
"body": "@SonicSoul: Yes. This puzzle can be represented as a directed graph. Each node has a directed edge to each node that is N spaces away."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T03:29:04.757",
"Id": "30406",
"Score": "0",
"body": "Thanks for the cool puzzle. I am learning Scala and just completed an exhaustive, breadth-first search algorithm. I'm pretty sure it's ten times as long as it needs to be. :)"
}
] |
[
{
"body": "<p>You're finding all solutions, but because the code overwrites the <code><span></code> for every solution found you only see the last one. Try this:</p>\n\n<pre><code>sp.innerHTML += 'solved in ' + h.length + ' steps<br/>';\n</code></pre>\n\n<p>You're performing a breadth-first search of all possible paths through the maze which is what I ended up going with. By scheduling timer events you're essentially queueing up cells. I did the same but with an actual queue of cells to visit.</p>\n\n<p>This is the core of my Scala version.</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>// pathTo tracks the best path to each point\n// moves(Point) returns the number in that cell\n\nval queue = new Queue[Point]\nqueue enqueue new Point(0, 0) // start from top-left\nwhile (!queue.isEmpty) {\n val start = queue dequeue\n val path = pathTo(start)\n (UP, DOWN, LEFT, RIGHT) foreach { direction =>\n val end = start.move(direction, moves(start))\n if (end != None && !pathTo.contains(end)) {\n pathTo(end) = path + end\n queue enqueue end\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T03:16:14.207",
"Id": "30404",
"Score": "0",
"body": "actually i don't stop after first solution. if any others were found, it should print it again.. although that has not happened, but technically the code is not stopping after first success"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T03:32:00.840",
"Id": "30407",
"Score": "0",
"body": "ok good point!.. heheh.. i do see it solved like 10 times now.. and the least steps was 19 :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T03:57:58.357",
"Id": "30408",
"Score": "0",
"body": "i kind of assumed i'd see the span rewrite, since i had that delay.. but the delay was not big enough to notice the rewrites."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T07:33:47.343",
"Id": "30415",
"Score": "0",
"body": "If you're counting the starting square as the first step, I got the same answer as you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T17:36:09.080",
"Id": "30454",
"Score": "0",
"body": "well my question was more about figuring out if this is the best algorithm.. if if there is a better way to find the answer.. but i'll accept if there arent any other suggestions"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T20:08:59.877",
"Id": "30565",
"Score": "0",
"body": "very nice thanks! what platform do you use scala on? what do you find most useful about this language ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T02:16:19.760",
"Id": "30579",
"Score": "0",
"body": "I'm running it on a Windows 7 machine for now inside Eclipse since I'm learning the language at home. I just got started last week so haven't gotten beyond the small stuff. The syntax is quite expressive. :)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T00:43:26.477",
"Id": "19045",
"ParentId": "19000",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "19045",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T17:59:12.467",
"Id": "19000",
"Score": "10",
"Tags": [
"javascript",
"algorithm"
],
"Title": "Solving a 7x7 maze puzzle"
}
|
19000
|
<p>I am writing a package that will provide a light weight wrapper for PyMongo insert (and eventually other methods), in order to perform basic validation, logging, etc.</p>
<p>I'm looking for design and code correctness feedback.</p>
<p><strong>pymongobean/collection.py</strong></p>
<pre><code>import pymongo
import inspect
class MongoBeanWriteWrapper:
def __init__(self, before=None, after=None):
self.before = before
self.after = after
def __call__(self, fn):
def wrapped(*args, **kwargs):
if self.before:
self.before(*args, **kwargs)
result = fn(*args, **kwargs)
if self.after:
self.after(result)
return result
return wrapped
class MongoBeanCollection(pymongo.collection.Collection):
def __init__(self, database, name, create=False, **kwargs):
self._before_insert = None
self._after_insert = None
super(MongoBeanCollection, self).__init__(database, name)
def __getattr__(self, name):
return MongoBeanCollection(self.__database, u"%s.%s" % (self.__name, name))
def before_insert(self, fn):
argspec = inspect.getargspec(fn)
if fn and argspec[0]: # insert must at least have one required arg
self._before_insert = fn
else:
raise InvalidMongoBeanBeforeInsert('before_insert expects a function argument')
def after_insert(self, fn):
argspec = inspect.getargspec(fn)
if fn and argspec[0]:
self._after_insert = fn
else:
raise InvalidMongoBeanAfterInsert('after_insert expects a function argument')
def insert(self, doc_or_docs, manipulate=True,
safe=None, check_keys=True, continue_on_error=False, **kwargs):
@MongoBeanWriteWrapper(self._before_insert, self._after_insert)
def call(doc_or_docs, manipulate, safe, check_keys,
continue_on_error, **kwargs):
return self.base_insert(doc_or_docs, manipulate, safe, check_keys,
continue_on_error, **kwargs)
return call(doc_or_docs, manipulate, safe, check_keys,
continue_on_error, **kwargs)
def base_insert(self, doc_or_docs, manipulate, safe, check_keys,
continue_on_error, **kwargs):
return super(MongoBeanCollection, self).insert(doc_or_docs, manipulate,
safe, check_keys,
continue_on_error,
**kwargs)
class InvalidMongoBeanBeforeInsert(ValueError):
pass
class InvalidMongoBeanAfterInsert(ValueError):
pass
</code></pre>
<p><strong>Tests</strong></p>
<pre><code>import unittest
import pymongo
import time
import mock
#assumes local install off mongodb is running
#will create a test db if it does not exist
class PyMongoBeanDBTests(unittest.TestCase):
def _get_db(self):
from pymongobean.database import MongoBeanDB
pymongo_conn = pymongo.connection.Connection('mongodb://localhost')
db = pymongo_conn.test
return MongoBeanDB(db)
def test_should_be_instance_of_pymongo_db(self):
mongobean_db = self._get_db()
self.assertTrue(isinstance(mongobean_db, pymongo.database.Database),
str(mongobean_db.__class__))
def test_should_call_validate_function_before_insert_into_user_collection(self):
db = self._get_db()
validate_mock = mock.Mock()
def validate(data, *args, **kwargs):
validate_mock(data) # we just want to make sure before_insert is called with data
user_col = db.user
user_col.before_insert(validate)
data = {'username': timestamp()}
user_col.base_insert = mock.Mock(return_value='testid')
oid = user_col.insert(data)
validate_mock.assert_called_once_with(data)
user_col.base_insert.assert_called_once_with(data,
True, None, True, False)
self.assertTrue(oid, oid)
def test_should_raise_invalid_mongobean_before_insert_error(self):
db = self._get_db()
user_col = db.user
def missing_arg_func():
pass
from pymongobean.collection import InvalidMongoBeanBeforeInsert
with self.assertRaises(InvalidMongoBeanBeforeInsert):
user_col.before_insert(missing_arg_func)
def test_should_raise_invalid_mongobean_after_insert_error(self):
db = self._get_db()
user_col = db.user
def missing_arg_func():
pass
from pymongobean.collection import InvalidMongoBeanAfterInsert
with self.assertRaises(InvalidMongoBeanAfterInsert):
user_col.after_insert(missing_arg_func)
def test_should_call_log_function_after_insert(self):
db = self._get_db()
log_mock = mock.Mock()
def log(data, *args, **kwargs):
log_mock(data)
user_col = db.user
user_col.after_insert(log)
data = {'username': timestamp()}
user_col.base_insert = mock.Mock(return_value='testid')
oid = user_col.insert(data)
log_mock.assert_called_once_with(oid)
user_col.base_insert.assert_called_once_with(data,
True, None, True, False)
self.assertTrue(oid, oid)
def timestamp():
return time.strftime('%Y%m%d%H%M%S')
if __name__ == '__main__':
unittest.main()
</code></pre>
<p><a href="https://github.com/mongodb/mongo-python-driver/blob/master/pymongo/collection.py" rel="nofollow">PyMongo driver for your reference</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T03:39:08.733",
"Id": "19008",
"Score": "1",
"Tags": [
"python",
"pymongo"
],
"Title": "PyMongo collection wrapper"
}
|
19008
|
<p>I would like to make the search faster as it takes a long time to retrieve the data that I require. Is there a faster method to do this? I have written the code below to allow me to search through a data table and retrieve data, which currently is fully functional. It's the nested for loops which I am using and wondering if there is another method of completing the tasks that the for loops get?</p>
<pre><code> DataTable sqlData = GetConfiguration();
// var q = sqlData.AsEnumerable().Where(data=> data.Field<String>("slideNo")=="5");
var w = sqlData.AsEnumerable().Where(data => data.Field<String>("slideNo") == "5")
.Select(data => data.Field<String>("QuestionStartText")).Distinct();
List<String> queryResult = new List<String>();
foreach (var item in w.ToArray<string>())
{
if (item != null)
{
String queryString = item;
//queryResult.Clear();
for (int i = 0; i < excelDataTable.Columns.Count; i++)
{
for (int k = 2; k < excelDataTable.Rows.Count; k++)
{
String row = "";
bool check = excelDataTable.Rows[k][0].ToString().StartsWith(queryString);
if (check)
{
for (int j = 0; j < excelDataTable.Columns.Count; j++)
{
string value = excelDataTable.Rows[k][j].ToString()+":";
row += value;
}
if (!queryResult.Contains(row))
{
queryResult.Add(row);
}
}
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T11:10:43.887",
"Id": "30345",
"Score": "4",
"body": "You should really run this through a profiler and tell us what exactly takes so long as this totally depends on the data."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T16:51:36.430",
"Id": "30361",
"Score": "0",
"body": "Arrow code is bad, you should work on reducing that nesting. Also, do you really want the last \":\" in `row`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T13:05:36.440",
"Id": "30430",
"Score": "2",
"body": "why iterate the columns than the rows and again the columns? Couldn't you just remove the 'for (int i'?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-26T15:58:29.183",
"Id": "31880",
"Score": "1",
"body": "If performance is an issue, then I would start with direct SQL queries first and see how long that takes. You have too much stuff \"complected\", e.g. braided together in one method, plus ORM can be painfully slow - depending on how optimized and how flexible it is. It is hard to reason about you method as a whole, so I would recommend breaking it down to smaller chunks and timing each one. Remember that lazy functions do not execute till later. Every little piece should have some space and time complexity. Try to do as much as you can in SQL first, for it is (usually) optimal."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T06:00:57.213",
"Id": "39556",
"Score": "1",
"body": "How many records for `w` and how many cells in `excelDataTable`?"
}
] |
[
{
"body": "<p>The most obvious problem is when there are large number of strings, string concatenation is inherently slow. Try using a StringBuilder instead, like this:</p>\n\n<pre><code> DataTable sqlData = GetConfiguration();\n\n // var q = sqlData.AsEnumerable().Where(data=> data.Field<String>(\"slideNo\")==\"5\");\n\n var w = sqlData.AsEnumerable().Where(data => data.Field<String>(\"slideNo\") == \"5\")\n .Select(data => data.Field<String>(\"QuestionStartText\")).Distinct();\n\n List<String> queryResult = new List<String>();\n StringBuilder sb = new StringBuilder();\n foreach (var item in w.ToArray<string>())\n {\n if (item != null)\n {\n String queryString = item;\n //queryResult.Clear();\n for (int i = 0; i < excelDataTable.Columns.Count; i++)\n { \n for (int k = 2; k < excelDataTable.Rows.Count; k++)\n {\n sb.Clear();\n bool check = excelDataTable.Rows[k][0].ToString().StartsWith(queryString);\n if (check)\n {\n for (int j = 0; j < excelDataTable.Columns.Count; j++)\n {\n sb.Append(excelDataTable.Rows[k][j].ToString());\n sb.Append(':');\n }\n string row = sb.ToString();\n if (!queryResult.Contains(row))\n {\n queryResult.Add(row);\n }\n }\n }\n }\n } \n } \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T16:53:19.707",
"Id": "30362",
"Score": "0",
"body": "-1: while your premiss is not wrong, your conclusion is. You should fix that particular problem by using `string.Join` instead of a `for` and a `StringBuilder`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T10:30:41.473",
"Id": "30424",
"Score": "0",
"body": "I didn't know there was this method. Anyways, we don't have an `IEnumerable` with the appropriate elements"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T13:00:50.923",
"Id": "30429",
"Score": "0",
"body": "@ANeves: I am not sure that String.Join is better in this case, because: their performance is very close (with the Append method of stringbuilder atleast) and he is reusing the allocated memory (by using sb.Clear()) which string.Join can't. At least regarding memory allocation StringBuilder is the winner. How this translates to performance? I wouldn't know without measuring."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T14:07:18.597",
"Id": "30435",
"Score": "0",
"body": "@Cohen I don't believe that performance of string concatenation is the culprit on issue in question. But you make good points."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T10:49:24.707",
"Id": "19016",
"ParentId": "19014",
"Score": "1"
}
},
{
"body": "<p>Guessing at intent a little bit here, but this should simplify and be more performant (I don't see the point in the outer loop over the columns). That being said, where is your bottleneck? I'd almost guess it's in the database operation <code>GetConfiguration()</code> more than any of this code.</p>\n\n<pre><code> var sqlData = GetConfiguration();\n\n ////var q = sqlData.AsEnumerable().Where(data => data.Field<string>(\"slideNo\") == \"5\");\n var w = sqlData\n .AsEnumerable()\n .Where(data => data.Field<string>(\"slideNo\") == \"5\")\n .Select(data => data.Field<string>(\"QuestionStartText\")).Distinct();\n var queryResult = new List<string>();\n\n foreach (var queryString in w.Where(item => item != null))\n {\n ////queryResult.Clear();\n for (var k = 2; k < excelDataTable.Rows.Count; k++)\n {\n if (!excelDataTable.Rows[k][0].ToString().StartsWith(queryString))\n {\n continue;\n }\n\n var rowSb = new StringBuilder();\n\n for (var j = 0; j < excelDataTable.Columns.Count; j++)\n {\n rowSb.Append(excelDataTable.Rows[k][j] + \":\");\n }\n\n var row = rowSb.ToString();\n\n if (!queryResult.Contains(row))\n {\n queryResult.Add(row);\n }\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-26T17:10:29.150",
"Id": "19946",
"ParentId": "19014",
"Score": "0"
}
},
{
"body": "<p>Well, you can certainly make it easier to read by cleaning it up a little bit and getting rid of the extra (<code>for i</code>) loop, and substituting a <code>string.Join</code> and <code>Select</code> for the inner (<code>for j</code>) loop's concatenation:</p>\n\n<pre><code>List<String> queryResult = new List<String>();\nforeach (var queryString in w.ToArray<string>())\n{\n if (string.IsNullOrEmpty(queryString)) continue;\n for (int rowIndex = 2; rowIndex < excelDataTable.Rows.Count; rowIndex++) {\n var excelRow = excelDataTable.Rows[rowIndex];\n if (!excelRow[0].ToString().StartsWith(queryString)) continue;\n var row = string.Join(\":\", excelRow.Select(c => c.ToString()).ToArray());\n if (!queryResult.Contains(row)) queryResult.Add(row);\n }\n}\n</code></pre>\n\n<p>Now that we can see that we're looping over all the rows for each <code>queryString</code>, we can change to traversing <code>rows</code> once and pick up any <code>queryStrings</code> along the way. \nThis effectively flips the order of iteration (I'm assuming there's more rows than\nquery strings). To get rid of the nested loops altogether, we'll switch to using <code>Any</code> to find any matches. We'll also drop the <code>queryResult.Contains</code> check on each iteration for a single <code>Distinct</code> call at the end. That should keep us from iterating <code>queryResult</code> multiple times.</p>\n\n<pre><code>var queryStrings = w.ToArray<string>();\nList<String> queryResult = new List<String>();\nfor (int rowIndex = 2; rowIndex < excelDataTable.Rows.Count; rowIndex++) {\n var row = excelDataTable.Rows[rowIndex];\n var rowStart = row[0].ToString();\n if (!queryStrings.Any(q => rowStart.StartsWith(q)) continue;\n var s = string.Join(\":\", row.Select(c => c.ToString()).ToArray());\n queryResult.Add(s);\n}\nqueryResult = queryResult.Distinct().ToList();\n</code></pre>\n\n<p>That's not going to do a whole lot for performance (basically get rid of a rows iteration), but everything else I see is really context specific that may end up with worse performance assuming your data looks like I expect it does (< 10 <code>queryStrings</code>, < 50 <code>queryResults</code> and thousands of rows).</p>\n\n<p>A couple of additional thoughts you can try, though, depending on your data:</p>\n\n<ul>\n<li>If <code>queryStrings</code> and/or <code>queryResults</code> are large, using a <code>HashSet<string></code> may be a better choice. You'll take a hit on insert, but lookups (<code>Any</code> and <code>Contains</code>) will be faster.</li>\n<li>the <code>queryResult.Contains</code> call can effectively invalidate all of our work in looking through <code>queryStrings</code> and concatenating <code>row</code>. Depending on how many duplicate results you expect vs how many <code>queryString</code> matches, swapping that and the <code>queryStrings.Any</code> could help.</li>\n<li>You could partition the <code>rows</code> and then parallel process them. This may help depending on the number of rows and CPUs available.</li>\n</ul>\n\n<p>From there, any further optimizations would be <em>heavily</em> dependent on your data and would need some example data of the correct relative sizes to profile and test.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T17:07:34.653",
"Id": "27771",
"ParentId": "19014",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T09:52:09.110",
"Id": "19014",
"Score": "4",
"Tags": [
"c#",
".net-datatable"
],
"Title": "Search datatable faster"
}
|
19014
|
<p><strong>Background</strong></p>
<p>I retrieve data from a 3rd party API, over HTTP. It's often slow, and sometimes just fails.
I needed a class that would keep getting data from that source, and keep it in memory. </p>
<p>So, this "TaskKeeper" class's purpose is:</p>
<ul>
<li>Have a timer (interval lengths are parameters of the class)</li>
<li>Every timer-tick, perform a "getter" function, on a separate thread, as a "task" (don't hang the current thread).</li>
<li>save the data as a property. If the data was received, the old data is discarded, if not, keep the old data.</li>
</ul>
<p><strong>The Question</strong></p>
<p>I'm asking, more specifically, if I can improve the code which handles the "Task" object, but I would appreciate any helpful comments, about any of the code!</p>
<p><strong>The Code</strong></p>
<pre><code>public class TaskKeeper<TParam, TResult> : IDisposable
where TParam : class
{
// ReSharper disable StaticFieldInGenericType
//By design: Different Locker object, per type of task keeper.
private static readonly object Locker = new object();
private static readonly object Locker2 = new object();
// ReSharper restore StaticFieldInGenericType
private readonly Func<ITaskKeeperFuncParam<TParam>, ITaskKeeperFuncResult<TResult>> _dataGetter;
private readonly TParam _parameter;
private CancellationTokenSource _cancellationTokenSource;
private Task<ITaskKeeperFuncResult<TResult>> _task;
private Timer _timer;
public TaskKeeper(Func<ITaskKeeperFuncResult<TResult>> dataGetter, int timerInterval, int dueTime,
TParam parameter)
{
_parameter = parameter;
Func<ITaskKeeperFuncParam<TParam>, ITaskKeeperFuncResult<TResult>> noParamFunc = arg => dataGetter();
_dataGetter = noParamFunc;
SetTimer(timerInterval, dueTime);
}
public TaskKeeper(Func<ITaskKeeperFuncParam<TParam>, ITaskKeeperFuncResult<TResult>> dataGetter,
int timerInterval, int dueTime, TParam parameter)
{
_dataGetter = dataGetter;
_parameter = parameter;
SetTimer(timerInterval, dueTime);
}
public TResult Data { get; private set; }
public DateTime LastSuccess { get; private set; }
#region IDisposable Members
public void Dispose()
{
//stop timer
_timer.Change(Timeout.Infinite, Timeout.Infinite);
_timer.Dispose();
//cancel task
_cancellationTokenSource.Cancel();
}
#endregion
public event EventHandler<EventArgs<TResult>> DataChangedHandler;
public void OnDataChangedHandler(EventArgs<TResult> e)
{
//from C# 4.0 in a nutshell:
////In multithreaded scenarios (Chapter 21), you need to assign the
////delegate to a temporary variable before testing and invoking it
////in order to be thread-safe:
////var temp = PriceChanged;
////if (temp != null) temp (this, e);
EventHandler<EventArgs<TResult>> handler = DataChangedHandler;
if (handler != null) handler(this, e);
}
private void SetTimer(int timerInterval, int dueTime)
{
_timer = new Timer(CheckForNewData, _parameter, dueTime, timerInterval);
}
/// <summary>
/// If the previous task has finished, executes it anew.
/// </summary>
public void CheckForNewData(object param)
{
lock (Locker)
{
if (_task != null && !_task.IsCompleted && !_task.IsCanceled) return;
var closure = new Func<ITaskKeeperFuncResult<TResult>>(() => Wrapper(param));
_cancellationTokenSource = new CancellationTokenSource();
_task = Task<ITaskKeeperFuncResult<TResult>>.Factory.StartNew(closure, _cancellationTokenSource.Token);
_task.ContinueWith(RunWhenFuncFinished);
}
}
private ITaskKeeperFuncResult<TResult> Wrapper(object paramObject)
{
var taskKeeperFuncParam = new TaskKeeperFuncParam<TParam>(LastSuccess, (TParam)paramObject);
return _dataGetter(taskKeeperFuncParam);
}
private void RunWhenFuncFinished(Task<ITaskKeeperFuncResult<TResult>> task)
{
if (!task.IsFaulted)
{
ITaskKeeperFuncResult<TResult> result = task.Result;
if (!result.Success) return;
lock (Locker2)
{
Data = result.Result;
LastSuccess = DateTime.Now;
}
EventArgs<TResult> args = DataChangedHandler.CreateArgs(Data);
OnDataChangedHandler(args);
}
else
{
Logger.Current.LogError(task.Exception);
}
}
}
</code></pre>
<p><strong>EDIT:</strong>
@almaz asked "Why do you submit last success date to the method that is supposed just to query the data via HTTP?" - The answer is, that it's one of the parameters needed for the HTTP request. It tells the 3rd party repository to return all data "since" the last time we succeeded in retrieving the information.</p>
|
[] |
[
{
"body": "<p>In the dispose why don't you dispose the timer <code>_timer.Dispose();</code>?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T11:39:45.180",
"Id": "30346",
"Score": "0",
"body": "Thanks, idiotretard (it's your nick, but I feel as if i'm being rude, calling you that).\nThe reason is here: http://stackoverflow.com/a/4563834/532517\n\nI added the disposing, anyway, after that line."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T11:54:04.657",
"Id": "30349",
"Score": "0",
"body": "@AngelEyes don't feel anything i dont mind well its my name :) Really, if you're disposing the timer, I see no reason not to simply dispose it. You're not even trying to stop it (you won't restart it), hence my answer. I still insist on recommending you to do away with the `_timer.Change(Timeout.Infinite, Timeout.Infinite);`. I might have posted a more comprehensive review and answer had I more time too but alas..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T11:00:01.043",
"Id": "19018",
"ParentId": "19015",
"Score": "0"
}
},
{
"body": "<p>Assign a empty delegate to the event to avoid race condition , much better version </p>\n\n<pre><code>public event EventHandler<EventArgs<TResult>> DataChangedHandler= delegate { };\n</code></pre>\n\n<p>Rest code looks okay.\njust wondering why you just not cache the data for a predefined interval rather that doing this.I am not sure which kind of application you are working on.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-26T12:08:01.437",
"Id": "19939",
"ParentId": "19015",
"Score": "0"
}
},
{
"body": "<p>The main issue here is that you don't expose the actual slow part as a <code>Task</code>. What you currently do is you create a new thread each time you need to send HTTP request instead of just using asynchronous execution that doesn't require new threads (except the one your code runs on). </p>\n\n<p>Other issues worth noting:</p>\n\n<ul>\n<li><p>The presence of first .ctor that doesn't actually use <code>TParam</code> means that you need to create a class hierarchy here, with one class having a single <code>TResult</code> generic parameter and derived one with both parameters.</p></li>\n<li><p>Interval is better represented with <code>TimeSpan</code> struct, or at least rename <code>timerInterval</code> to <code>timerIntervalInMilliseconds</code> or something like that.</p></li>\n<li><code>CancellationTokenSource</code> is usually created just once, but you create it for every call.</li>\n<li>Locking is done quite strange, why do you use <strong>static</strong> <code>Locker</code> objects? Why do you want to block different instances of the same class from querying (potentially) different data at the same time?</li>\n<li>I don't think you need <code>Locker2</code> since users of your class won't be able to lock on it, and you don't use values of <code>Data</code> and <code>LastSuccess</code> so that assignment may cause a racing condition</li>\n<li>If you want to check for \"good\" task status then it's better to look at <code>task.IsCompleted</code> rather than <code>!task.IsFaulted</code>.</li>\n<li>And finally I don't see the reason for those <code>ITaskKeeperFuncParam<T></code> and <code>ITaskKeeperFuncResult<T></code>, what is the purpose of those? Why do you submit last success date to the method that is supposed just to query the data via HTTP? If HTTP request is not successful I assume there would be exception, in which case task will be faulted and there is no need in <code>ITaskKeeperFuncResult<T>.Success</code> property.</li>\n</ul>\n\n<p>Full implementation after these changes will look like:</p>\n\n<pre><code> public class DataChangedEventArgs<TResult> : EventArgs\n {\n public TResult Data { get; set; }\n public DateTime LastSuccess { get; set; }\n }\n\n public class TaskKeeper<TResult> : IDisposable\n {\n private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();\n private readonly Func<CancellationToken, Task<TResult>> _dataGetter;\n private readonly Timer _timer;\n private Task _dataLoadingTask;\n\n public TaskKeeper(Func<CancellationToken, Task<TResult>> dataGetter, TimeSpan whenToStart, TimeSpan interval)\n {\n _dataGetter = dataGetter;\n _timer = new Timer(CheckForNewData, null, whenToStart, interval);\n }\n\n public TResult Data { get; private set; }\n public DateTime LastSuccess { get; private set; }\n\n public event EventHandler<DataChangedEventArgs<TResult>> DataChangedHandler;\n\n #region IDisposable Members\n\n public void Dispose()\n {\n _cancellationTokenSource.Cancel();\n _timer.Dispose();\n }\n\n #endregion\n\n protected void OnDataChangedHandler(DataChangedEventArgs<TResult> eventArgs)\n {\n var eventHandler = DataChangedHandler;\n\n if (eventHandler != null)\n eventHandler(this, eventArgs);\n }\n\n /// <summary>\n /// If the previous task has finished, executes it as new.\n /// </summary> \n private void CheckForNewData(object _)\n {\n var existingTask = _dataLoadingTask;\n if (existingTask != null)\n existingTask.Wait(); //TODO: or maybe just quit?\n\n //TODO: Here you may want to introduce double-check locking to make sure that there won't be 2 tasks running at the same time.\n _dataLoadingTask = _dataGetter(_cancellationTokenSource.Token).ContinueWith(RunWhenFuncFinished);\n }\n\n private void RunWhenFuncFinished(Task<TResult> task)\n {\n if (task.IsCompleted) //if not - then either there was an exception or task was cancelled\n {\n Data = task.Result;\n LastSuccess = DateTime.Now;\n OnDataChangedHandler(new DataChangedEventArgs<TResult> { Data = Data, LastSuccess = LastSuccess });\n }\n else if (task.IsFaulted)\n Logger.Current.LogError(task.Exception);\n\n _dataLoadingTask = null;\n }\n }\n\n //TODO: Not sure if you actually need it :)\n public class TaskKeeper<TParam, TResult> : TaskKeeper<TResult>\n {\n public TaskKeeper(Func<TParam, CancellationToken, Task<TResult>> dataGetter, TimeSpan whenToStart, TimeSpan interval, TParam param)\n : base(ct => dataGetter(param, ct), whenToStart, interval) { }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-26T14:16:29.113",
"Id": "19941",
"ParentId": "19015",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T10:17:54.093",
"Id": "19015",
"Score": "3",
"Tags": [
"c#",
"asynchronous"
],
"Title": "(async) Task \"Keeper\" for keeping the \"fresh\" data - How do I improve this?"
}
|
19015
|
<p>I am writing a program in C running on UNIX which counts the number of each letters in a input text file. For a file like this:</p>
<p>The cat sat on the green mat</p>
<p>The output would be like this:</p>
<pre><code> The letter ’a’ occurs 3 times.
The letter ’c’ occurs 1 times.
The letter ’e’ occurs 4 times.
The letter ’g’ occurs 1 times.
The letter ’h’ occurs 2 times.
The letter ’m’ occurs 1 times.
The letter ’n’ occurs 2 times.
The letter ’o’ occurs 1 times.
The letter ’r’ occurs 1 times.
The letter ’s’ occurs 1 times.
The letter ’t’ occurs 5 times.
5 *
4 * *
4 * *
3 * * *
3 * * *
2 * * * * *
2 * * * * *
1 * * * ** *** ***
1 * * * ** *** ***
0 **************************
0 **************************
... abcdefghijklmnopqrstuvwxyz
</code></pre>
<p>Where the graph represents the amount of times a letter appears. (If it is more than 10, i simply put a '+' after the 10th row). The code I've currently written to achieve this is as follows: (Haven't found a good way to test for capital letters as well as lowercase yet).</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void drawGraph(int letters[26], char alpha[26]);
void printLetters(int letters[26], char alpha[26]);
void getLetters(FILE *fp, int letters[26], char alpha[26]);
int main(int argc, char *argv[]) {
FILE *fp;
int letters[26] = { 0 };
char alpha[26] = { 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' };
int indexedAlpha[256] = { 0 };
int j = 1;
for (i = 97; i <= 127; i++)
{
indexedAlpha[i] = j;
j++;
}
//open file
if ((fp = fopen(argv[1], "r")) == NULL)
{
perror("Cannot open file");
exit(EXIT_FAILURE);
}
getLetters(fp, letters, alpha);
printLetters(letters, alpha);
printf("\n");
drawGraph(letters, alpha);
printf("\n");
return EXIT_SUCCESS;
}
void getLetters(FILE *fp, int letters[26], char alpha[26]) {
int c;
for (int i = 0; (c = fgetc(fp)) != EOF; i++)
{
c = fgetc(fp);
if ( isalpha(c) )
{
for ( int j = 0; j < 26; j++ ) //find which letter it is
{
if( c == alpha[j] )
{
letters[j]++;
break;
}
}
}
}
}
void printLetters(int letters[26], char alpha[26]) {
for( int i = 0; i < 26; i++ )
{
if(letters[i] != 0){
printf("The letter '%c' occurs %d times.\n", alpha[i], letters[i]);
}
}
}
void drawGraph(int letters[26], char alpha[26]) {
int x = 11;
int y;
while(x >= 0)
{
y = 0;
while (y < 2)
{
if (x == 10)
{
printf(" %d ", x);
}
else if (x == 11)
{
printf(" ");
}
else
{
printf(" %d ", x);
}
for( int i = 0; i < 26; i++ )
{
if(letters[i] > 10)
{
printf("+");
letters[i] = 10;
y++; // Break out of while loop
}
else if(letters[i] == x)
{
printf("*");
}
else
{
printf(" ");
}
if (letters[i] == x && y == 1)
{
letters[i] = letters[i] - 1;
}
}
printf("\n");
y++;
}
x--;
}
printf("... ");
for( int i = 0; i < 26; i++ )
{
printf("%c", alpha[i]);
}
}
</code></pre>
<p>What I'm looking for is advice and tips on notation, efficiency(In amount of code written and memory usage) and any other good tips/Best practices or better methods i could use to complete this task.</p>
<p>Thanks!</p>
|
[] |
[
{
"body": "<p>Let just say when I first read the question I was very impressed by the graph.<br>\nWell done.</p>\n\n<p>Small mistake in reading the file:</p>\n\n<pre><code>char c;\nfor (int i = 0; !feof(fp); i++)\n{\n c = fgetc(fp);\n</code></pre>\n\n<p>This is wrong in all languages. The eof is never set until you read past the eof. The last successful read reads up-to (but not past) the eof. So even if there are no more characters in the file the eof flag is not set (until you try and read the character after eof).</p>\n\n<p>As a result you are suffering a one off error. The loop is executed one time to many. The value of 'c' on the last iteration is EOF truncated to fit into a char.</p>\n\n<p>So the standard patter is to read from the file and see if it works. If it works then you enter the loop:</p>\n\n<pre><code>int c;\nfor (int i = 0; (c = fgetc(fp)) != EOF; i++)\n{\n</code></pre>\n\n<p>Note we need to change the <code>c</code> from a <code>char</code> into an <code>int</code> to make sure that EOF is not truncated out of the value.</p>\n\n<p>Not an error: But you are implementing an O(1) operation is O(n). </p>\n\n<pre><code> for ( int j = 0; j < 26; j++ ) //find which letter it is\n {\n if( c == alpha[j] ) \n {\n letters[j]++;\n break;\n }\n</code></pre>\n\n<p>With a little though you can invert the array. So you use the letter to look up its ID.</p>\n\n<pre><code>char alpha[256] = \n{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0->15 ignore\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16->31 ignore \n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 32->47 ignore \n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 48->63 ignore \n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 64->79 ignore \n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 80->95 ignore \n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, // 96->111 a - \n 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 0, 0, 0, 0, 0, // 112->127 -z \n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 128->143 ignore \n\n .. etc\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // 240->255 ignore \n\n // Now the lookup becomes:\n if (alpha[c] != 0) \n {\n letters[alpha[c] - 1]++;\n }\n</code></pre>\n\n<p>But do you really care if you count all the characters. I would not (unless there are some serious space constraints). You can just count all the characters. When you print them out you just print the ones you want.</p>\n\n<pre><code> int letters[256];\n\n ....\n letters[c]++; // or maybe letters[tolower(c)]++;\n .....\n\n // Now we just need to de reference the count of the letters we are interested in.\n for( int i = 0; i < 26; i++ )\n {\n int count = letters[alpha[i]];\n if(count != 0){\n printf(\"The letter '%c' occurs %d times.\\n\", alpha[i], count);\n }\n }\n</code></pre>\n\n<p>Some small tidy up (you seem to have embeded tabs that mess up spacing on this site).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T15:00:59.313",
"Id": "30444",
"Score": "0",
"body": "Your second solution `letter[c-'a']` comments on an assumption of consecutively numbers letters. It is worth noting that your first solution makes an even stronger assumption, one which I do not believe is actually guaranteed by the standard."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T19:58:33.263",
"Id": "30468",
"Score": "0",
"body": "Brian... I don't see the problem with the first solution, whereas your point about the second solution might be valid if we're talking about alternate charsets, etc. The first solution (if chars are treated numerically as unsigned bytes, I forget) should work with any set of bytes imaginable, as long as you map any byte either to zero or their \"appropriate\" location (plus one) in the count array. The programmer determines the appropriate-ness of the location, and a proper alpha array even allows for the numbering of \"classes\" of bytes, if desired."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T20:15:14.427",
"Id": "30473",
"Score": "0",
"body": "@Brian: Yes I coded up the hand built array assuming ascii. But the point is not the encoding it is the fact that you can use a look up to do it in O(1). With only a tiny bit of work you can build the array dynamically at run time (so it works for your current encoding)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T20:26:38.243",
"Id": "30476",
"Score": "0",
"body": "@JayC: Fixed concerns with second alternative."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T22:46:36.250",
"Id": "30489",
"Score": "0",
"body": "If i use the inverted array, will this help to catch Uppercase and lower case characters? as aren't their ASCII values different? Also is there any ideas on how i could only print the Y-axis up to the value needed? E.g for the example shown the Y-axis would go only up to 5. Thanks for the great answer already!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T19:19:10.800",
"Id": "30562",
"Score": "0",
"body": "Is it also possible to explain the O(1) operation and O(n) change benefits please? thankyou"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T20:33:15.290",
"Id": "30569",
"Score": "0",
"body": "@Brad: O(X) is big O complexity. O(1) means it is constant time. While O(n) means the time it takes is relative to the data set size. Luckily your data set size is small 26. But if there is an O(1) solution it is usually preferable (unless the cost in space is huge)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T01:07:55.737",
"Id": "30575",
"Score": "0",
"body": "the upper/lowercase issue is addressed (by combining the two) in the comment in the code snippet above: `// or maybe letters[tolower(c)]++;`"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T16:26:50.573",
"Id": "19025",
"ParentId": "19019",
"Score": "7"
}
},
{
"body": "<p>Brad</p>\n\n<p>I have a few comments:</p>\n\n<p>General points:</p>\n\n<ul>\n<li><p>Many people, including me, put functions in the opposite order to their\nuse. This avoids having to use prototypes. In your code this would mean\nputting <code>main</code> at the end.</p></li>\n<li><p>make all local functions 'static'. This is not important in\nsingle-file programs but is preferable for bigger programs.</p></li>\n<li><p>starting functions with the '{' in column 0 is preferable.</p></li>\n<li><p>leave a space after keywords consistently (or if you must, don't leave a\nspace, but be consistent).</p></li>\n<li><p>you have several points where the level of indenting is excessive to my\ntaste. Nested loops are best avoided in my opinion.</p></li>\n<li><p>use of 26 everywhere might be best replaced by a #define constant (upper\ncase)</p></li>\n<li><p>note that in a function that takes a 1-D array such as <code>void f(char array[26]);</code> the\narray size (26) is ignored. The function is the same as <code>void f(char *array);</code></p></li>\n</ul>\n\n<p>Detailed remarks:</p>\n\n<ul>\n<li><p>note that <code>alpha</code> should be const</p></li>\n<li><p>I would define it as <code>const char alpha[] = \"abcdefghijklmnopqrstuvwxyz\";</code>.\nThis is one byte longer but is briefer and makes printing the alphabet\neasier too. </p></li>\n<li><p><code>indexedAlpha</code> is not used beyond the initialization loop.</p></li>\n<li><p>the error message printed by the call to <code>perror</code> would be better if the\nfailed file name is passed: <code>perror(argv[1]);</code></p></li>\n</ul>\n\n<p>in getLetters:</p>\n\n<ul>\n<li><p><code>alpha</code> should be <code>const</code></p></li>\n<li><p>the <code>for</code> loop would be better as a <code>while</code>, since you dont use the loop\nvariable <code>i</code> : <code>while((c = fgetc(fp)) != EOF)</code></p></li>\n<li><p>and delete the call to fgetc in the body of the loop</p></li>\n<li><p>the nested <code>for</code> loop in <code>getLetters</code> can be replaced, as discussed by\n@LokiAstari. That solution is best, but <strong>if</strong> you were to keep your way\nof finding a match, this nested loop would belong as a separate simple\nfunction.</p></li>\n</ul>\n\n<p>in printLetters:</p>\n\n<ul>\n<li><code>alpha</code> and <code>letters</code> should both be <code>const</code></li>\n</ul>\n\n<p>in drawGraph:</p>\n\n<ul>\n<li><p><code>printGraph</code> might be more a accurate name</p></li>\n<li><p><code>alpha</code> should be <code>const</code></p></li>\n<li><p>I don't find the function easy to read. Too many loops and nesting levels\nand variables numbers.</p></li>\n<li><p>I dont understand why you want to double the vertical scale. It makes the\ngraph less readable (to me). I'm going to address the function on the\nbasis of one line per count vertically.</p></li>\n<li><p>note that the printf format \"%2d\" prints a number in a field width of 2 -\nwhich is what your conditionals at the beginning of the 2nd while loop do.</p></li>\n<li><p>the <code>printf(\" \");</code> can be extracted outside the loop.</p></li>\n<li><p>printing the <code>+</code> line can also be extracted from the loop;</p></li>\n<li><p>you can print the graph without modifying the <code>letters</code> array with a little\nreorganisation.</p></li>\n</ul>\n\n<p>Here is my version of <code>drawGraph</code>:</p>\n\n<pre><code>static void printGraphLine(const int *letters, char ch, int limit)\n{\n for (int i = 0; i < 26; i++) {\n putchar(letters[i] >= limit ? ch : ' ');\n }\n printf(\"\\n\");\n}\n\nstatic void printGraph(const int *letters, const char *alpha)\n{\n printf(\" \");\n printGraphLine(letters, '+', 11);\n\n for (int x = 10; x >= 0; --x) {\n printf(\" %2d \", x);\n printGraphLine(letters, '*', x);\n }\n printf(\"... %s\\n\", alpha);\n}\n\nint main(int argc, char *argv[]) \n{\n const char alpha[] = \"abcdefghijklmnopqrstuvwxyz\";\n ...\n</code></pre>\n\n<p>So did I cheat? My code is much simpler but prints only one line per count\ninstead of the two yours prints; it breaks the original \"contract\". You could double-up the <code>printGraphLine</code> calls if you wanted the original behaviour. </p>\n\n<p>Simplicity is king in my book (and I recommend it to be so in yours too) and if I can do almost the same job for half the code, I will, unless there is a <strong>strong</strong> reason not to. Even if it doesn't do exactly what I started out wanting to do. This is perhaps a philosophical point and you must draw your own conclusions :-)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T02:10:34.520",
"Id": "19122",
"ParentId": "19019",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "19025",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T11:00:16.690",
"Id": "19019",
"Score": "5",
"Tags": [
"performance",
"c",
"array"
],
"Title": "Counting letters program with ASCII-art graph"
}
|
19019
|
<p>I had a <a href="https://stackoverflow.com/questions/13552370/tree-view-filtering-does-not-return-all-the-files">question</a> about filtering tree view and returning just first match.</p>
<p>I've tried to create <code>list<treenode></code> and change the code. Is it possible improve the below code for finding nodes and child nodes that match my criteria?</p>
<pre><code>private List<TreeNode> FindNodeByValue(TreeNodeCollection nodes, string searchstring)
{
// Loop through the tree node collection
List<TreeNode> nodelist=new List<TreeNode>();
foreach (TreeNode node in nodes)
{
// Does the value match the search string?
if (node.Value.ToUpper().Contains (searchstring.ToUpper()))
// Yes it does match - return it
nodelist.Add(node);
// return nodelist;
else
{
// No it does not match - search any child nodes of this node
List<TreeNode> childNode = SearchChildNodes(node, searchstring);
// If the childNode is not null it was a match
if (childNode != null)
// Return the matching node
return childNode;
}
}
// If the matching node is not found return null
return null;
}
/// <summary>
/// This method searches a node's ChildNodes collection to find a matching value
/// with the incoming search string
/// It will iteratively call itself as it drills into each nodes child nodes (if present)
/// </summary>
/// <param name="parentNode">Parent node to search for a match</param>
/// <param name="searchstring">string to be matched with the Nodes Value property</param>
/// <returns>Treenode of the matching node if found. If not found it will be null</returns>
private List<TreeNode> SearchChildNodes(TreeNode parentNode, string searchstring)
{
List<TreeNode> nodelist2 = new List<TreeNode>();
// Loop through the child nodes of the parentNode passed in
foreach (TreeNode node in parentNode.ChildNodes)
{
// Does the value match the search string?
if (node.Value.ToUpper().Contains(searchstring.ToUpper()))
// Yes it does match - return it
nodelist2.Add(node);
//return nodelist2;
//return node;
else
{
// No it does not match - recursively search any child nodes of this node
List<TreeNode> childNode = SearchChildNodes(node, searchstring);
// If the childNode is not null it was a match
if (childNode != null)
childNode.Add(node);
// Return the matching node
return childNode;
}
}
// If the matching node is not found OR if there were no child nodes then return null
return null;
}
protected void Button1_Click(object sender, EventArgs e)
{
TreeNode trnode=FindNodeByValue(TreeView1.Nodes, fieldFilterTxtBx.Text);
if (trnode != null)
{
TreeView1.Nodes.Clear();
// TreeNode newnode = new TreeNode("Detail Engineering");
// TreeView1.Nodes.Add(newnode);
TreeView1.Nodes.Add(trnode);
TreeView1.ExpandAll();
}
else
{
Label1.Text = "No file found";
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T13:10:29.880",
"Id": "30352",
"Score": "1",
"body": "if you are trying to match multiple results, you should always check children, you are only doing that if a node does not match which i believe is wrong"
}
] |
[
{
"body": "<p>Currently you do not search sub nodes it a matching parent is found. This code fixes that problem and also simplifies the code by removing the unnecessary <code>SearchChildNodes</code> function. <br><br>If you only care about the first match use <code>var node = FindNodeByValue(TreeView1.Nodes, fieldFilterTxtBx.Text).FirstOrDefault();</code></p>\n\n<pre><code>private IEnumerable<TreeNode> FindNodeByValue(TreeNodeCollection nodes, string searchstring)\n{\n foreach (TreeNode node in nodes)\n {\n if (node.Value.IndexOf(searchstring, \n StringComparison.CurrentCultureIgnoreCase) >= 0)\n yield return node;\n else\n {\n foreach (var subNode in FindNodeByValue(node.ChildNodes, searchstring))\n yield return subNode;\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T14:22:02.707",
"Id": "19024",
"ParentId": "19023",
"Score": "2"
}
},
{
"body": "<p>To make sure that there will be no out of stack (I'm pretty sure JIT wouldn't be able to optimize out recursive calls through several helper objects built for implementing <code>IEnumerable</code>). Here is small modifications to version of @Magnus:</p>\n\n<pre><code>private IEnumerable<TreeNode> SearchNodesByValue(TreeNodeCollection nodes, string searchstring)\n{\n var stack = new Stack<T>(nodes.GetEnumerator());\n try\n {\n do\n {\n var frame = stack.Peek();\n var it = frame.Peek();\n if (!it.MoveNext())\n {\n frame.Pop().Dispose();\n continue;\n }\n var node = it.Current;\n if (node.Value.Contains(searchstring)) yield return node;\n else frame.Push(node.ChildNodes.GetEnumerator());\n } while(stack.Count > 0);\n }\n finally\n {\n // cleanup enumerators\n while(stack.Count > 0) stack.Pop().Dispose();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T13:10:21.070",
"Id": "19967",
"ParentId": "19023",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T13:05:25.337",
"Id": "19023",
"Score": "2",
"Tags": [
"c#",
"asp.net",
"tree",
"search"
],
"Title": "Tree node filtering with List<TreeNode>"
}
|
19023
|
<p>I am trying to reduce the total execution time of my code.</p>
<p>I have a GPS system which calculates routes between two points, and returns all points in between them.</p>
<p>I did a simple profile and the calculation of the route takes on average 30 ms while, from main thread input to main thread output, it takes almost 700ms to travel.</p>
<p>Do you have any suggestions on improving this?</p>
<p><strong>Definitions</strong></p>
<pre><code>#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
# include <process.h>
# define OS_WINDOWS
#else
# include <pthread.h>
# define sscanf_s sscanf
# define sprintf_s sprintf
#endif
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
# define MUTEX CRITICAL_SECTION
#else
# define MUTEX pthread_mutex_t
#endif
#ifdef OS_WINDOWS
# define EXIT_THREAD() { _endthread(); }
# define START_THREAD(a, b) { _beginthread( a, 0, (void *)( b ) ); }
#else
# define EXIT_THREAD() { pthread_exit( NULL ); }
# define START_THREAD(a, b) { pthread_t thread;\
pthread_create( &thread, NULL, a, (void *)( b ) ); }
#endif
</code></pre>
<p>As you can see, the mutexes on windows are defined as <code>CRITICAL_SECTION</code>:</p>
<p><strong>Variables and Structures</strong></p>
<pre><code>struct QuedData
{
int start;
int end;
int extraid;
AMX * script;
QuedData(int start_,int end_,int extraid_, AMX * script_)
{
start = start_;
end = end_;
extraid = extraid_;
script = script_;
}
};
struct PassData //thanks to DeadMG for improvements.
{
std::vector<cell> Paths;
int extraid;
AMX * script;
int MoveCost;
template<typename Iterator> PassData(Iterator begin, Iterator end, int extraid_, int MoveCost_, AMX * script_)
: Paths(begin, end)
{
extraid = extraid_;
MoveCost = MoveCost_;
script = script_;
}
~PassData()
{
Paths.clear();
}
};
vector <QuedData> QueueVector;
queue <PassData> PassVector;
</code></pre>
<p>This are the two variables and their structures which are important for transporting the data from input to output</p>
<p><strong>Mutex</strong></p>
<pre><code>#if defined OS_WINDOWS
struct Lock //thanks to 'doublep' from StackOverflow for this RAII solution, edited it
{
MUTEX mutex;
bool locked;
Lock (MUTEX mutex)
: mutex (mutex),
locked (false)
{
}
~Lock ()
{
release ();
}
bool acquire (int timeout = -1)
{
if (!locked && TryEnterCriticalSection(&mutex) != 0)
{
locked = true;
}
return locked;
}
int release ()
{
if (locked)
{
LeaveCriticalSection(&mutex); locked = false;
return true;
}
return false;
}
};
MUTEX mutex_q;
MUTEX mutex_p;
#else
struct Lock //and here is my little edit for linux
{
MUTEX& mutex;
bool locked;
Lock (MUTEX& mutex)
: mutex (mutex),
locked (false)
{ }
~Lock ()
{ release (); }
bool acquire (int timeout = -1)
{
if (!locked && pthread_mutex_lock (&mutex) == 0)
locked = true;
return locked;
}
int release ()
{
if (locked)
locked = (pthread_mutex_unlock (&mutex) == 1);
return !locked;
}
};
MUTEX mutex_q = PTHREAD_MUTEX_INITIALIZER;
MUTEX mutex_p = PTHREAD_MUTEX_INITIALIZER;
#endif
</code></pre>
<p>This is the code I use to avoid deadlocks / lockups etc:</p>
<p><strong>Initialization</strong></p>
<pre><code>PLUGIN_EXPORT bool PLUGIN_CALL Load( void **ppData )
{
#if defined OS_WINDOWS
InitializeCriticalSection(&mutex_q);
InitializeCriticalSection(&mutex_p);
#else
pthread_mutex_init (&mutex_q,NULL);
pthread_mutex_init (&mutex_p,NULL);
#endif
START_THREAD( Thread::BackgroundCalculator, 0);
return true;
}
</code></pre>
<p>Here I initialize the critical sections/mutexes where needed:</p>
<p><strong>Calculation Thread</strong></p>
<pre><code>#ifdef OS_WINDOWS
void Thread::BackgroundCalculator( void *unused )
#else
void *Thread::BackgroundCalculator( void *unused )
#endif
{
int startid;
int endid;
int extra;
AMX *amx;
vector <cell>way;
int costx;
while( true )
{
if(!QueueVector.empty())
{
Lock q (mutex_q);
Lock p (mutex_p);
if (q.acquire ())
{
startid = QueueVector.back().start;
endid = QueueVector.back().end;
extra = QueueVector.back().extraid;
amx = QueueVector.back().script;
QueueVector.pop_back();
q.release();
///////////////////////////////////////
/*LARGE_INTEGER frequency; // ticks per second
LARGE_INTEGER t1, t2; // ticks
double elapsedTime;
// get ticks per second
QueryPerformanceFrequency(&frequency);
// start timer
QueryPerformanceCounter(&t1);*/
///////////////////////////////////////
dgraph->findPath_r(xNode[startid].NodeID ,xNode[endid].NodeID,way,costx);
///////////////////////////////////////
//QueryPerformanceCounter(&t2);
//elapsedTime = (t2.QuadPart - t1.QuadPart) * 1000.0 / frequency.QuadPart;
///////////////////////////////////////
//cout << elapsedTime << " ms.\n";
///////////////////////////////////////
dgraph->reset();
while(p.acquire () == false)
{}
PassVector.push(PassData(way.begin(),way.end(),extra,costx,amx));
way.clear();
costx = 0;
p.release();
}
}
SLEEP(30);
//-------------------------
}
EXIT_THREAD();//should be never reached..
}
</code></pre>
<p>This is where the calculation of the route actually happens:</p>
<p><strong>Main thread - input</strong></p>
<pre><code>static cell AMX_NATIVE_CALL n_CalculatePath( AMX* amx, cell* params )
{
if(params[1] < 0 || params[1] > (MAX_NODES-1) || params[2] < 0 || params[2] > (MAX_NODES-1))
return 0;
Lock q (mutex_q);
int tries = 0;
while (q.acquire (1) == false && ++tries < 10)
{
}
if(q.locked)
{
QueueVector.push_back(QuedData(params[1],params[2],params[3],amx));
q.release ();
return 1;
}
return 0;
}
</code></pre>
<p>This is the function in the main thread which gets called from a 'script':</p>
<p><strong>Main thread - output</strong></p>
<pre><code>PLUGIN_EXPORT void PLUGIN_CALL
ProcessTick()
{
if(g_Ticked++ == g_TickMax)
{
if(!PassVector.empty())
{
Lock q (mutex_p);
int tries = 0;
while (q.acquire (1) == false && ++tries < 10)
{
}
if(q.locked)
{
int ptr;
float Cx;
for (std::vector<AMX *>::iterator a = amx_list.begin(); a != amx_list.end(); ++a)
{
if (!amx_FindPublic(* a, "GPS_WhenRouteIsCalculated", &ptr) && PassVector.front().script == *a)
{
Cx = (float)PassVector.front().MoveCost;
amx_Push(* a, amx_ftoc(Cx));
amx_Push(* a, PassVector.front().Paths.size());
cell * RawPath = new cell[PassVector.front().Paths.size()+1];
copy(PassVector.front().Paths.begin(),PassVector.front().Paths.end(),RawPath);
amx_PushArray(* a, &ppamx_addr, &ppamx_physAddr, RawPath, PassVector.front().Paths.size()+1);
amx_Push(* a, PassVector.front().extraid);
amx_Exec(* a, NULL, ptr);
amx_Release(* a,ppamx_addr);
free(RawPath);
}
}
PassVector.pop();
q.release ();
}
}
g_Ticked = 0;
}
}
</code></pre>
<p>Here the result is returned to the 'script'.</p>
<p>The way the route calculation happens:</p>
<ol>
<li>script calls <code>CalculatePath->function</code> in code</li>
<li>gets <code>executed->thread</code></li>
<li>calculates route->main thread calls script</li>
<li>passes the end results</li>
</ol>
<p>If you need the full code, it is located <a href="http://gpb.googlecode.com/files/RouteConnector_180.zip" rel="nofollow">here</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T20:02:33.277",
"Id": "30373",
"Score": "0",
"body": "Why don't you use the mutex objects on Windows? It surely does have them and critical section is anything but a mutex."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T20:07:54.457",
"Id": "30374",
"Score": "0",
"body": "it's not for sharing across multiple processes so I think I am supposed to use critical sections? Correct me if I am wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T20:35:52.333",
"Id": "30376",
"Score": "0",
"body": "You are wrong. Mutexes in Windows, if left unnamed (the usual case), are restricted to a process and are the fastest synchronization primitive."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T20:57:42.310",
"Id": "30380",
"Score": "0",
"body": "I did use Mutexes in the past exactly with this code which lead to this topic: http://stackoverflow.com/questions/9523532/mutex-cant-acquire-lock , it confuses me now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T12:24:56.353",
"Id": "30428",
"Score": "0",
"body": "Well, the answer in the question doesn't suggest that mutexes are exclusively inter-process. Or does it?"
}
] |
[
{
"body": "<p>I suggest to replace your code with the implementation of <a href=\"http://boost-sandbox.sourceforge.net/doc/html/lockfree.html\" rel=\"nofollow noreferrer\">boost.lockfree</a> and <a href=\"http://www.boost.org/doc/libs/1_52_0/doc/html/thread.html\" rel=\"nofollow noreferrer\">boost.thread</a> to be system independant.</p>\n\n<ul>\n<li>boost.lockfree for message passing (replacing yor queue vector with it)</li>\n<li>boost.thread (or standard threads if you have a c+11 compiler) to replace threading and synchronisation with platform agnostic calls (same interface as the standard c+11 thread interface)</li>\n</ul>\n\n<p>As for the mutex vs critical section debate, fork0 is wrong. look <a href=\"https://stackoverflow.com/questions/800383/what-is-the-difference-between-mutex-and-critical-section\">here for a proof</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T13:53:25.277",
"Id": "30433",
"Score": "0",
"body": "the boost.lockfree containers seem good, I have a RemoveFromQueue function in the script, sho an element should be removable at any position, is this possible with boost.lockfree, and any simple example code on running threads etc?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T13:54:10.940",
"Id": "30434",
"Score": "0",
"body": "else I will rewrite the RemoveFromQueue function or remove it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T14:18:55.150",
"Id": "30438",
"Score": "0",
"body": "lockfree can remove an object from the queue, but not from any position. only the top one with pop(), as it's a first in first out container. there is also a lifo queue (named stack). usually, on mutlithreaded queues, you only need fifo queues."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T14:22:20.663",
"Id": "30439",
"Score": "0",
"body": "if a function gets executed in a thread and only reads global variables which don't change, it's safe to execute that function in multiple threads?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T14:26:23.647",
"Id": "30440",
"Score": "0",
"body": "yes, it's safe if no other threads are going to change the variables."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T14:29:48.033",
"Id": "30441",
"Score": "0",
"body": "alright when I get home i'll try to optimize my code then if it works better I;ll tick the \"V\" :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T22:47:41.087",
"Id": "30490",
"Score": "0",
"body": "I downloaded and unpacked boost 1.52 but there isn't anything with \"lockfree\" there :o"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T22:54:00.240",
"Id": "30491",
"Score": "0",
"body": "ah I found it, at compile time I get 2 errors because the SDK I use already defines int32_t and unit32_t and boost does too, but when I uncomment the two typedefs there are thousands of errors..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T22:55:38.570",
"Id": "30492",
"Score": "0",
"body": "Error 1 error C2371: 'int32_t' : redefinition; different basic types Z:\\Profile\\Rafal\\Desktop\\RouteConnector\\181\\sampGDK\\EXTRACTED\\win32\\include\\sampgdk\\sdk\\amx\\amx.h 60 1 RouteConnectorPlugin"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T22:56:12.907",
"Id": "30493",
"Score": "0",
"body": "typedef long int int32_t;\n typedef unsigned long int uint32_t;"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T23:04:08.140",
"Id": "30494",
"Score": "0",
"body": "ok fixed that, trying to update code ; p"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T23:08:22.587",
"Id": "30495",
"Score": "0",
"body": "I cannot find the queue include... it isn't contained here: http://www.ohloh.net/p/lockfree where the hell do I get it ? ; o"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T23:24:25.807",
"Id": "30496",
"Score": "0",
"body": "well ok it's the fifo thingy, but so much errors.."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T12:23:54.513",
"Id": "19057",
"ParentId": "19027",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "19057",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T17:23:58.657",
"Id": "19027",
"Score": "2",
"Tags": [
"c++",
"optimization",
"multithreading",
"geospatial",
"pthreads"
],
"Title": "Multithreaded GPS system"
}
|
19027
|
<p>I have the following method that has been shortened for the sake of this review. The actual method has many more tasks. Essentially what I am trying to do is to create many tasks, fire them off, wait until they are all finished, and handle any exceptions generated. Does this look correct?</p>
<pre><code>public static void RefreshCoaterCaches()
{
try
{
CicApplication.CoaterDataLock.EnterWriteLock();
List<Task> alarmTasks = new List<Task>();
alarmTasks.Add(Task.Factory.StartNew(() =>
{
using (DistributorBackpressure44Logic logic = new DistributorBackpressure44Logic())
logic.RefreshDistributorBackpressure44Cache();
}));
alarmTasks.Add(Task.Factory.StartNew(() =>
{
using (DeltaPressureLogic logic = new DeltaPressureLogic())
logic.RefreshDeltaPressureCache();
}));
Task.WaitAll(alarmTasks.ToArray());
}
catch (System.AggregateException exception)
{
CicServerLogic.HandleUnexpectedAggregateException(exception.Flatten(), string.Empty);
}
catch (System.Exception exception)
{
CicServerLogic.HandleUnexpectedException(exception);
}
finally
{
CicApplication.CoaterDataLock.ExitWriteLock();
}
}
</code></pre>
<p>I then have this method to handle any AggregateException thrown:</p>
<pre><code>internal static void HandleUnexpectedAggregateException(AggregateException aggregateException)
{
try
{
foreach (Exception exception in aggregateException.InnerExceptions)
{
...
...
Do some stuff with the current exception, like logging etc.
...
}
}
catch (Exception)
{
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T01:52:59.417",
"Id": "30403",
"Score": "0",
"body": "I'm not 100%, but won't the first exception stop the unfinished tasks from running?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T11:18:04.483",
"Id": "30427",
"Score": "0",
"body": "@dreza: not it not. When first exception occur all started tasks will continue to execute."
}
] |
[
{
"body": "<p>I suggested to think about following:</p>\n\n<ol>\n<li>Extract every step into the separate asynchronous method</li>\n<li>Think about more careful locking technique. Asynchronous operations by its nature could be long running and using global write lock can degrade performance dramatically. Maybe its possible acquire locks only during processing results.</li>\n<li>Global exception handling: in general global exception handling is a code smell. Its really hard to create generic logic for different operations. I suggested to use such techniques with some tools like MEF, but avoid using its manually.</li>\n</ol>\n\n<p>Here slightly modified version of your code:</p>\n\n<pre><code>private static Task GetDistributorBackpressure44LogicAsync()\n{\n Task.Factory.StartNew( () =>\n {\n using (DistributorBackpressure44Logic logic = new DistributorBackpressure44Logic())\n logic.RefreshDistributorBackpressure44Cache();\n }\n}\n\nprivate static Task DeltaPressureLogicAsync()\n{\n Task.Factory.StartNew(() =>\n {\n using (DeltaPressureLogic logic = new DeltaPressureLogic())\n logic.RefreshDeltaPressureCache();\n }\n}\n\npublic static void RefreshCoaterCaches()\n{\n try\n {\n CicApplication.CoaterDataLock.EnterWriteLock();\n\n var t1 = GetDistributorBackpressure44LogicAsync();\n var t2 = DeltaPressureLogicAsync();\n\n // You can switch back to you list-based approach if you'll have\n // much more other operations\n Task.WaitAll(t1, t2);\n }\n catch (System.AggregateException exception)\n {\n // I'm really not sure that its a good idea to create \"generic\"\n // exception handling scheme. Maybe you should handle them manually right here.\n // And what is string.Empty is all about?\n CicServerLogic.HandleUnexpectedAggregateException(exception.Flatten(), string.Empty);\n }\n // You should not catch System.Exception thats why I removed it\n finally\n {\n CicApplication.CoaterDataLock.ExitWriteLock();\n }\n}\n</code></pre>\n\n<p>Now, about your generic exception handler (I mentioned already that this technique can lead to errors hiding and complicated \"generic\" logic) (see my comments right in the code):</p>\n\n<pre><code>internal static void HandleUnexpectedAggregateException(AggregateException aggregateException)\n{\n // What are we afraiding of, why we're using try/catch here?\n // We should now swallow unknown exception because it can lead to\n // hiding bugs in our code!\n try\n {\n // This technique is ok\n foreach (Exception exception in aggregateException.InnerExceptions) \n {\n ...\n ...\n Do some stuff with the current exception, like logging etc.\n ...\n }\n }\n catch (Exception)\n {\n // I strongly not recommended to use empty catch blocks!!\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T20:26:07.200",
"Id": "30475",
"Score": "0",
"body": "Thank you. What's the advantage of creating separate asynchronous methods?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T20:28:35.070",
"Id": "30478",
"Score": "0",
"body": "@RandyMinder: because its easier to read, compose (for example with new async features), reuse, easier to refactor to real async implementation (instead of calling synchronous methods asynchronously you can provide some other implementations later)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T11:30:48.080",
"Id": "19052",
"ParentId": "19028",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T17:27:09.440",
"Id": "19028",
"Score": "5",
"Tags": [
"c#",
"multithreading",
"exception-handling"
],
"Title": "AggregateException and Flatten"
}
|
19028
|
<p>I started reading about JavaScript patterns, and I really liked module pattern.
So I created some module:</p>
<pre><code>var App = (function (parent, $) {
function myPrivateFunc () {
// Some private stuff
}
return {
myPubFunc: myPrivateFunc,
publicFunction: function () {
// Do some stuff
}
};
})(App || {}, jQuery);
</code></pre>
<p>Now I want to call some functions on page but only functions I need on that specific page. I got idea to add data-modules attribute to body, and then load modules I demanded on that attribute. I did that this way:</p>
<pre><code>var modules = $('body').data('modules').split(" ");
for (var i = modules.length - 1; i >= 0; i--) {
App[modules[i]]();
}
</code></pre>
<p>My question is: Is this a good way to achieve what I wanted? I tested, it's working fine, but I'm a little suspicious about this dynamic calling. Is there better solutions (preferably not libraries) out there? If this is not good, why it isn't?</p>
|
[] |
[
{
"body": "<p>Instead of adding data-properties to the body tag, and waiting for / relying on jQuery, just use an inline script:</p>\n\n<pre><code><script type=\"text/javascript\">\n var modules = /* echo the needed modules here */;\n for (var i=0; i<modules.length; i++)\n App[modules[i]]();\n</script>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T16:38:23.347",
"Id": "30365",
"Score": "0",
"body": "This is just another style of this logic, and i like it, but i prefer jQuery. My question is about logic, not the style. Anyway thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T17:13:33.097",
"Id": "30366",
"Score": "0",
"body": "What do you mean by \"this logic\"? What else did you have in mind?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T17:22:47.233",
"Id": "30367",
"Score": "0",
"body": "By logic I mean on the way I'm calling functions. Is there better solutions for that. And is it my way secure? Does it affect on the speed? I read somewhere that i'm doing eval of whole script on this way, and that's bad. I don't know what that means."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T17:26:35.807",
"Id": "30368",
"Score": "1",
"body": "Calling functions is just calling functions, and can't be done anyhow else. What does this have to do with security? And calling functions is slower than not calling functions, but which speed of what should be affected? And no, you are not `eval`ing anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T17:38:33.080",
"Id": "30369",
"Score": "0",
"body": "When I said speed, I thought that it's faster when I call 2 functions I actually need on that page, then calling all functions. But maybe loop slow's down the process. \"Improper use of eval opens up your code for injection attacks\", that's what I meant by secure. You helped me a lot, thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T17:42:43.397",
"Id": "30370",
"Score": "1",
"body": "No, a loop is not slow; you won't recognize a difference to calling the modules successively (the loop might be inlined by the interpreter/compiler anyway :-). As you do not use `eval`, do not care about it."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T16:23:07.037",
"Id": "19031",
"ParentId": "19030",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "19031",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T16:17:58.480",
"Id": "19030",
"Score": "4",
"Tags": [
"javascript"
],
"Title": "Dynamic call of module pattern function"
}
|
19030
|
<p>I ran into the code below today, and my gut instinct tells me this is an expensive way to do a null check. The point the author was making was that if you changed the name of the object then you don't need to change the value of the string being thrown in the exception.</p>
<p>The proposed use would be:</p>
<pre><code>string cantBeNull=...;
Guard.IsNotNull(cantBeNull);
//instead of
if(cantBeNull == null) throw new ArgumentNullException("cantBeNull");
</code></pre>
<p>So Is this an acceptable way of checking for null? Is this overly expensive just to save you from not having the change the value passed to the exception? </p>
<p><strong>Code in question:</strong></p>
<pre><code>public static void IsNotNull<T>(Expression<Func<T>> expression) where T : class
{
if (expression == null)
throw new ArgumentNullException("expression");
var value = expression.Compile()();
var param = (MemberExpression)expression.Body;
var paramName = param.Member.Name;
if (value != null)
return;
throw new ArgumentNullException(paramName);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T19:45:51.707",
"Id": "30372",
"Score": "5",
"body": "I have a feeling this will be close to an order of magnitude slower than a simple `null` check. Yes, overly expensive."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T16:22:19.017",
"Id": "30451",
"Score": "1",
"body": "I feel like the next logical step for this code is to make it an extension method so you can just do a `cantBeNull.IsNotNull()` :)"
}
] |
[
{
"body": "<p>How often do you change parameter names? How often does the code run? Under any normal distribution of those, you should go with a minor code efficiency gain over a programmer efficiency gain. </p>\n\n<p>On the other hand, if you (for some bizarre reason) change the parameter name almost every time the code runs, the tradeoff is probably worth it.</p>\n\n<p>But just remember, that whether or not the string matches the actual parameter name, it should still let you find exactly which parameter was null so long as there isn't anywhere else in that function which throws an <code>ArugmentNullException</code> with the same string.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T07:13:59.180",
"Id": "30414",
"Score": "1",
"body": "Why would you change the parameter name almost every time the code runs? Apart from that, good answer!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T14:58:52.507",
"Id": "30442",
"Score": "1",
"body": "@Smasher - I really don't know, but that's the only scenario I could think of where dynamically pulling the parameter name would make sense. I suppose there could be some business logic reason to do so?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T15:16:49.480",
"Id": "30446",
"Score": "0",
"body": "How could business logic affect your code? That doesn't make sense. Maybe the content changes each time but not the name of the parameter itself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T16:20:39.430",
"Id": "30450",
"Score": "0",
"body": "@Smasher - Business logic may not have been the right term - I'm thinking of something ridiculous like \"Our coding standard says that all parameter names need to have the last date the function was edited appended in _20121127 format\"."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T22:19:32.520",
"Id": "19039",
"ParentId": "19032",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "19039",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T19:39:21.557",
"Id": "19032",
"Score": "4",
"Tags": [
"c#"
],
"Title": "Is this is good way to check for null?"
}
|
19032
|
<p>I have a class called <code>Task</code> that contain a member boolean variable <code>Completed</code>.</p>
<p>I created a list of <code>Task</code> objects in a variable called <code>Tasks</code>. </p>
<p>I have the following code, which sorts the objects depending on whether the Task is completed. (I want the incompleted tasks to be in the list first)</p>
<pre><code>private List<Task> GetSortedTask(List<Task> tasks)
{
List<Task> completedTaskList = new List<Task>();
List<Task> incompleteTaskList = new List<Task>();
for (int i = 0; i < tasks.Count; i++)
{
HelperObject T = task[i].getHelperObject();
if (T != null && T.Completed)
completedTaskList.Add(tasks[i]);
else
incompletetaskList.Add(tasks[i]);
}
//merge the two lists together
imcompleteTaskList.AddRange(completedTaskList);
return incompleteTaskList;
}
</code></pre>
<p>Is there a way to do this without creating so many lists? Thanks in advance</p>
<p>EDIT: Made my question a bit more specific since <code>orderBy</code> seems to be the correct answer, however my problem may be a bit more complicated than that.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T20:42:02.250",
"Id": "30378",
"Score": "1",
"body": "Just off the cuff, could you use tasks.OrderBy(p => p.Completed)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T20:45:47.193",
"Id": "30379",
"Score": "0",
"body": "@dreza I posted a vastly simplified version of the code, and I wasn't sure if OrderBy would work since it seemed like a Linq command and my class does not inhereit from IQueryable. But on second thought, it seems like it might work. I may have to edit my original question though\n\nEDITED question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T22:15:30.610",
"Id": "30391",
"Score": "2",
"body": "It doesn't matter if *your* class doesn't inherit from `IQueryable`, so long as the data structure containing it (`List`) does. `tasks.OrderBy(p => p.Completed)` should be perfectly sufficient, unless you want the other direction, in which case you can use `tasks.OrderByDescending(p => p.Completed)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T07:12:28.220",
"Id": "30413",
"Score": "0",
"body": "@dreza,Bobson Why not post this as an answer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T07:34:43.853",
"Id": "30416",
"Score": "0",
"body": "@Smasher Yep, more answers the better if it adds something to the existing ones..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T16:16:56.880",
"Id": "30448",
"Score": "0",
"body": "@Smasher - Not a bad idea. Answerified."
}
] |
[
{
"body": "<p>I think my original comment in regards to using OrderBy could still possibly still even with your latest edits (and BTW that code does not compile, there is no declared task object :)).</p>\n\n<p>How about something like:</p>\n\n<pre><code>var query = from task in tasks\n let helperTask = task.getHelperObject()\n select new\n {\n Completed = helperTask != null && helperTask.Completed,\n Task = task\n };\n\nreturn query.OrderBy(p => p.Completed).Select(p => p.Task).ToList();\n</code></pre>\n\n<p><strong>UPDATE:</strong>\nAnother excellent option suggested by <a href=\"https://codereview.stackexchange.com/users/2041/svick\">svick</a> to further refine and remove the anonymous object selection is something along the lines of:</p>\n\n<pre><code>var query = from task in tasks\n let helperTask = task.getHelperObject()\n orderby helperTask != null && helperTask.Completed\n select task;\n\nreturn query.ToList();\n</code></pre>\n\n<p>I guess if I could I would do away with ToList() altogether and return IEnumerable but that depends on the context of the operation. I also personally like using an intermediate variable here (<em>query</em>) as I think it just helps readability. All to their own on that front though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T21:06:51.147",
"Id": "30384",
"Score": "0",
"body": "I'm unsure about your where clause. Wouldn't that filter out some of the tasks if their cooresponding helperTask is Null rather than treat them as \"Not Completed\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T21:15:09.963",
"Id": "30387",
"Score": "0",
"body": "@Rhys modified the answer so that null helperTasks are not filtered now"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T17:43:40.267",
"Id": "30550",
"Score": "2",
"body": "I think you could simplify your code even more, you don't really need the anonymous object there: `from task in tasks\n let helperTask = task.getHelperObject()\n orderby helperTask != null && helperTask.Completed\n select task`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T19:11:14.030",
"Id": "30556",
"Score": "0",
"body": "@Svick excellent. Have updated the answer."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T20:55:58.120",
"Id": "19035",
"ParentId": "19033",
"Score": "8"
}
},
{
"body": "<p><code>tasks.OrderBy(p => p.Completed)</code> should do exactly what you're looking for, unless you want to sort in the other direction, in which case you can use <code>tasks.OrderByDescending(p => p.Completed)</code>. </p>\n\n<p>It doesn't matter if your class doesn't inherit from <code>IQueryable</code>, so long as the data structure containing it (<code>List</code>) does. That will enable you to use any LINQ functions via LINQ-to-Objects, because they're actually operating on the <code>List<Task></code>, not a <code>Task</code>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T16:16:44.897",
"Id": "19069",
"ParentId": "19033",
"Score": "2"
}
},
{
"body": "<p>I liked your original approach - it was fast. So, I changed it so that it now uses fewer lists.</p>\n\n<pre><code>private IEnumerable<Task> GetSortedTask(IList<Task> tasks)\n{\n var incompleteTasks = new List<Task>();\n foreach (Task task in tasks)\n {\n var taskHelper = task.getHelperObject();\n if (taskHelper != null && taskHelper.Completed)\n {\n yield return task;\n continue;\n }\n\n incompleteTasks.Add(task);\n }\n\n foreach (Task task in incompleteTasks)\n {\n yield return task;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-11T19:22:05.850",
"Id": "36642",
"Score": "0",
"body": "Nice, I always forget about using yield return"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-11T19:00:09.547",
"Id": "23750",
"ParentId": "19033",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "19035",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T20:32:48.350",
"Id": "19033",
"Score": "4",
"Tags": [
"c#",
"optimization",
"sorting"
],
"Title": "Sort List By Boolean"
}
|
19033
|
<p>Any suggestions to make this code clearer, more Pythonic, or otherwise better? I'm open to changes to the design as well as the code (but probably won't drop features or error checking since everything still in it has shown worth to me).</p>
<pre><code>"""
Parsing with PEGs, or a minimal usable subset thereof.
Background at http://bford.info/packrat/
"""
import re
def _memo(f):
"""Return a function like f but caching its results. Its arguments
must be hashable."""
memos = {}
def memoized(*args):
try: return memos[args]
except KeyError:
result = memos[args] = f(*args)
return result
return memoized
_identifier = r'[A-Za-z_]\w*'
def Parser(grammar, **actions):
r"""Make a parsing function from a PEG grammar. You supply the
grammar as a string of rules like "a = b c | d". All the tokens
making up the rules must be whitespace-separated. Each token
(besides '=' and '|') is a regex, a rule name, or an action
name. (Possibly preceded by '!' for negation: !foo successfully
parses when foo *fails* to parse.)
A regex token is either /<chars>/ or any non-identifier; an
identifier that's not a defined rule or action name is an
error. (So, an incomplete grammar gets you a BadGrammar exception
instead of a wrong parse.)
Results get added by regex captures and transformed by actions.
(Use keyword arguments to bind the action names to functions.)
The parsing function maps a string to a results tuple or raises
Unparsable. (It can optionally take a rule name to start from, by
default the first in the grammar.) It doesn't necessarily match
the whole input, just a prefix.
>>> parse_s_expression = Parser(r'''
... one_expr = _ expr !.
... _ = \s*
... expr = \( _ exprs \) _ hug
... | ([^()\s]+) _
... exprs = expr exprs
... | ''', hug = lambda *vals: vals)
>>> parse_s_expression(' (hi (john mccarthy) (()))')
(('hi', ('john', 'mccarthy'), ((),)),)
>>> parse_s_expression('(too) (many) (exprs)')
Traceback (most recent call last):
Unparsable: ('one_expr', '(too) ', '(many) (exprs)')
"""
parts = re.split(' ('+_identifier+') += ', ' '+re.sub(r'\s', ' ', grammar))
if not parts: raise BadGrammar("No grammar")
if parts[0].strip(): raise BadGrammar("Missing left hand side", parts[0])
if len(set(parts[1::2])) != len(parts[1::2]):
raise BadGrammar("Multiply-defined rule(s)", grammar)
rules = dict((lhs, [alt.split() for alt in (' '+rhs+' ').split(' | ')])
for lhs, rhs in zip(parts[1::2], parts[2::2]))
return lambda text, rule=parts[1]: _parse(rules, actions, rule, text)
class BadGrammar(Exception): pass
class Unparsable(Exception): pass
def attempt(parse, *args, **kwargs):
"Call a parser, but return None on failure instead of raising Unparsable."
try: return parse(*args, **kwargs)
except Unparsable: return None
def _parse(rules, actions, rule, text):
# Each function takes a position pos (and maybe a values tuple
# vals) and returns either (far, pos1, vals1) on success or (far,
# None, ignore) on failure (where far is the rightmost position
# reached in the attempt).
@_memo
def parse_rule(name, pos):
farthest = pos
for alternative in rules[name]:
pos1, vals1 = pos, ()
for token in alternative:
far, pos1, vals1 = parse_token(token, pos1, vals1)
farthest = max(farthest, far)
if pos1 is None: break
else: return farthest, pos1, vals1
return farthest, None, ()
def parse_token(token, pos, vals):
if re.match(r'!.', token):
_, pos1, _ = parse_token(token[1:], pos, vals)
return pos, pos if pos1 is None else None, vals
elif token in rules:
far, pos1, vals1 = parse_rule(token, pos)
return far, pos1, pos1 is not None and vals + vals1
elif token in actions:
f = actions[token]
if hasattr(f, 'is_peg'): return f(text, pos, vals)
else: return pos, pos, (f(*vals),)
else:
if re.match(_identifier+'$', token):
raise BadGrammar("Missing rule", token)
if re.match(r'/.+/$', token): token = token[1:-1]
m = re.match(token, text[pos:])
if m: return pos + m.end(), pos + m.end(), vals + m.groups()
else: return pos, None, ()
far, pos, vals = parse_rule(rule, 0)
if pos is None: raise Unparsable(rule, text[:far], text[far:])
else: return vals
# Some often-used actions:
def hug(*xs): return xs
def join(*strs): return ''.join(strs)
def position(text, pos, vals):
"A peglet action: always succeed, producing the current position."
return pos, pos, vals + (pos,)
position.is_peg = True
</code></pre>
<p>A particular I'm not sure about: maybe it should use the built-in SyntaxError exception? That seems to be meant for errors in <em>Python</em> syntax, but I'm not sure what's handiest.</p>
<p>A weakness: some functions use <code>pos</code>, <code>vals</code>, <code>pos1</code>, <code>vals1</code>, and while I deem this reasonable for locals related the way they are, maybe there are better names?</p>
<p>From <a href="https://github.com/darius/peglet" rel="nofollow">https://github.com/darius/peglet</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T08:35:21.547",
"Id": "465034",
"Score": "0",
"body": "https://medium.com/@gvanrossum_83706/peg-parsing-series-de5d41b2ed60"
}
] |
[
{
"body": "<p>Just last week, I was wondering what you were up to lately. :-)</p>\n\n<p>I've been working on nice PEG parsing for Python lately. I've written an adaptation of <a href=\"http://tinlizzie.org/ometa\" rel=\"nofollow\">OMeta</a>, named <a href=\"http://pypi.python.org/pypi/Parsley\" rel=\"nofollow\">Parsley</a>. So far I haven't implemented regex tokens. </p>\n\n<p>I wrote a custom <code>ParseError</code> exception class. I definitely think that the builtin <code>SyntaxError</code> should only be used for actual-Python syntax errors.</p>\n\n<p><code>Parser</code> reads a bit densely to me, both because of the regexes and because of the lack of newlines after colons.</p>\n\n<p>Otherwise it looks reasonable for your goals. I ended up wrapping memoization and location tracking into an <code>InputStream</code> object rather than passing indices around directly; this was partly because I wanted to be able to apply Parsley rules to iterables other than strings.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T00:32:40.333",
"Id": "30400",
"Score": "0",
"body": "Hi Allen! Thanks, I've reformatted Parser a bit (at github)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T00:37:43.380",
"Id": "30401",
"Score": "0",
"body": "I came across Parsley (and was reminded of PyMeta) after starting this -- it's on the to-read list now. The InputStream sounds like a good idea. At the moment I'm trying to figure out if a fancier library ought to be redesigned around tree parsing (which my fancier version of this can do, but as kind of an afterthought). Anyway, it tends to be more educational (if more time-consuming) to try to reinvent the wheel before studying others' and *then* seeing how they made it better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T05:45:32.047",
"Id": "30411",
"Score": "0",
"body": "I've got some prototype code for tree parsing using Parsley in development now. I'll trot it out in a few days. :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T22:41:48.640",
"Id": "19041",
"ParentId": "19034",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T20:49:15.833",
"Id": "19034",
"Score": "3",
"Tags": [
"python",
"parsing"
],
"Title": "PEG parser in Python"
}
|
19034
|
<p><strong>Thought 1</strong> </p>
<pre><code>public interface IRepository<T> : IDisposable where T : class
{
IQueryable<T> Fetch();
IEnumerable<T> GetAll();
IEnumerable<T> Find(Func<T, bool> predicate);
T Single(Func<T, bool> predicate);
T First(Func<T, bool> predicate);
void Add(T entity);
void Delete(T entity);
void SaveChanges();
}
</code></pre>
<p>with the above approach I will go like Repository and then have a Repository
with the implementation of methods written above.</p>
<p>I think this frees my tests from DbContext dependency. </p>
<p><strong>Thought 2</strong> </p>
<pre><code> public class RepositoryBase<TContext> : IDisposable where TContext : DbContext, new()
{
private TContext _DataContext;
protected virtual TContext DataContext
{
get
{
if (_DataContext == null)
{
_DataContext = new TContext();
}
return _DataContext;
}
}
public virtual IQueryable<T> GetAll<T>() where T : class
{
using (DataContext)
{
return DataContext.Set<T>();
}
}
public virtual T FindSingleBy<T>(Expression<Func<T, bool>> predicate) where T : class
{
if (predicate != null)
{
using (DataContext)
{
return DataContext.Set<T>().Where(predicate).SingleOrDefault();
}
}
else
{
throw new ArgumentNullException("Predicate value must be passed to FindSingleBy<T>.");
}
}
public virtual IQueryable<T> FindAllBy<T>(Expression<Func<T, bool>> predicate) where T : class
{
if (predicate != null)
{
using (DataContext)
{
return DataContext.Set<T>().Where(predicate);
}
}
else
{
throw new ArgumentNullException("Predicate value must be passed to FindAllBy<T>.");
}
}
public virtual IQueryable<T> FindBy<T, TKey>(Expression<Func<T, bool>> predicate,Expression<Func<T, TKey>> orderBy) where T : class
{
if (predicate != null)
{
if (orderBy != null)
{
using (DataContext)
{
return FindAllBy<T>(predicate).OrderBy(orderBy).AsQueryable<T>(); ;
}
}
else
{
throw new ArgumentNullException("OrderBy value must be passed to FindBy<T,TKey>.");
}
}
else
{
throw new ArgumentNullException("Predicate value must be passed to FindBy<T,TKey>.");
}
}
public virtual int Save<T>(T Entity) where T : class
{
return DataContext.SaveChanges();
}
public virtual int Update<T>(T Entity) where T : class
{
return DataContext.SaveChanges();
}
public virtual int Delete<T>(T entity) where T : class
{
DataContext.Set<T>().Remove(entity);
return DataContext.SaveChanges();
}
public void Dispose()
{
if (DataContext != null) DataContext.Dispose();
}
}
</code></pre>
<p>I could now have <code>CustomerRepository : RepositoryBase<Mycontext>,ICustomerRepository</code>
<code>ICustomerRepository</code> gives me the option of defining stuff like <code>GetCustomerWithOrders</code> etc... </p>
<p>I am confused as to which approach to take. Would need help through a review on the implementation first then comments on which one will be the easier approach when it comes to Testing and extensibility.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T21:32:43.510",
"Id": "30388",
"Score": "2",
"body": "Why not have both and have your RepositoryBase implement the IRepository interface?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T05:42:50.847",
"Id": "30410",
"Score": "0",
"body": "@dreza then, should the IRepository have methods like add , save , delete or should it have the find , get , fetch methods ? I guess both are addressing different concerns one set of methods is query and other is transactional logic, and the subsequent question is what are the benefits/drawbacks of making the RepositoryBase implement the IRepository interface ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T01:02:04.290",
"Id": "30497",
"Score": "0",
"body": "I would make the repository have methods like SingleOrDefault(), GetAll(), FirstOrDefault() rather than having to do .Fetch().SingleOrDefault() etc"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T14:21:33.843",
"Id": "30532",
"Score": "0",
"body": "About edit 2: Tests of the RepositoryBase has to be \"integrated\" since DbContext isn't abstract or have any good interface, but a nice trick is to use Database.SetInitializer(new DropCreateDatabaseAlways<YourContext>()) in those tests. Which means you always have a fresh DB for your integrated tests.\nIt's also useful to move the concrete Repository and UnitOfWork classes and tests into separate assemblies, so you don't have those dependencies in your business logic tests and classes. Otherwise you could always go buy TypeMock which can mock more or less anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T14:46:03.193",
"Id": "30534",
"Score": "0",
"body": "@Lars-Erik So RepositoryBase will be tested through an Integration test with a database. I should be able to however test my business logic through unit tests. My POCO classes are in a separate assembly and the repository is in a separate assembly. My unit tests project just has a reference to the Repository. Is that the correct structure ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T15:03:15.147",
"Id": "30538",
"Score": "0",
"body": "Keep two unit test projects. One that references the poco assembly (which doesn't have dependency on concrete uow/repo), and one that references both for integrated tests."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T15:31:44.360",
"Id": "30539",
"Score": "0",
"body": "What can I test in the project that references the POCO assembly ? I was expecting to text the logic in my repository in one project and have a db backed integration in another."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T16:20:57.280",
"Id": "30544",
"Score": "0",
"body": "The conrete repo is tightly copuled to your ORM (Entity Framework), so it is per definition DB backend integration. The repo interface however is not, so it can be mocked and used in business logic tests."
}
] |
[
{
"body": "<p>You should use <code>Expression<Func<T, bool>></code> as predicates on your interface and have the <code>RepositoryBase</code> implement that interface.\nBy only using <code>Func</code>, you won't get translation to L2E etc, but will have to enumerate the entire DB table before you can evaluate the <code>Func</code>.\nThe interface can be mocked, hence unit-tested without a physical db and also used with other ORMs.</p>\n\n<p>It's generally prefered to keep <code>SaveChanges</code> and the <code>DbContext</code> in a separate <code>IUnitOfWork</code> implementation. You can pass the <code>UnitOfWork</code> to the repository constructor, which can access an internal property on the UOW exposing the <code>DbContext</code>.</p>\n\n<p>By doing that you can share the same <code>DbContext</code> between repositories, and batch updates to several entity roots of different type. You also keep fewer open connections, which are the most expensive resource you have when it comes to DBs.</p>\n\n<p>Not to forget they can share transactions. :)</p>\n\n<p>Hence you should not dispose the DbContext in the Repository, the Repository really doesn't need to be disposable at all. But the UnitOfWork / DbContext must be disposed by something.</p>\n\n<p>Also, ditch the <code>OrderBy</code> predicate to <code>FindBy</code>. Since you return an <code>IQueryable</code>, and use an <code>Expression</code> for the predicate, you can keep building the Queryable after the call. For instance <code>repo.FindBy(it => it.Something == something).OrderBy(it => it.OrderProperty)</code>. It will still be translated to \"select [fields] from [table] where [predicate] order by [orderprop]\" when enumerated.</p>\n\n<p>Otherwise it looks good.</p>\n\n<p>Here's a couple of good examples:</p>\n\n<p><a href=\"http://blog.swink.com.au/index.php/c-sharp/generic-repository-for-entity-framework-4-3-dbcontext-with-code-first/\">http://blog.swink.com.au/index.php/c-sharp/generic-repository-for-entity-framework-4-3-dbcontext-with-code-first/</a></p>\n\n<p><a href=\"http://www.martinwilley.com/net/code/data/genericrepository.html\">http://www.martinwilley.com/net/code/data/genericrepository.html</a></p>\n\n<p><a href=\"http://www.mattdurrant.com/ef-code-first-with-the-repository-and-unit-of-work-patterns/\">http://www.mattdurrant.com/ef-code-first-with-the-repository-and-unit-of-work-patterns/</a></p>\n\n<p>And here's how I do it:</p>\n\n<p><strong>Model / Common / Business assembly</strong></p>\n\n<p>No references but BCL and other possible models (interfaces/dtos)</p>\n\n<pre><code>public interface IUnitOfWork : IDisposable\n{\n void Commit();\n}\n\npublic interface IRepository<T>\n{\n void Add(T item);\n void Remove(T item);\n IQueryable<T> Query();\n}\n\n// entity classes\n</code></pre>\n\n<p><strong>Business tests assembly</strong></p>\n\n<p>Only references Model / Common / Business assembly</p>\n\n<pre><code>[TestFixture]\npublic class BusinessTests\n{\n private IRepository<Entity> repo;\n private ConcreteService service;\n\n [SetUp]\n public void SetUp()\n {\n repo = MockRepository.GenerateStub<IRepository<Entity>>();\n service = new ConcreteService(repo);\n }\n\n [Test]\n public void Service_DoSomething_DoesSomething()\n {\n var expectedName = \"after\";\n var entity = new Entity { Name = \"before\" };\n var list = new List<Entity> { entity };\n repo.Stub(r => r.Query()).Return(list.AsQueryable());\n service.DoStuff();\n Assert.AreEqual(expectedName, entity.Name);\n }\n\n}\n</code></pre>\n\n<p><strong>Entity Framework implementation assembly</strong></p>\n\n<p>References Model <em>and</em> the Entity Framework / System.Data.Entity assemblies</p>\n\n<pre><code>public class EFUnitOfWork : IUnitOfWork\n{\n private readonly DbContext context;\n\n public EFUnitOfWork(DbContext context)\n {\n this.context = context;\n }\n\n internal DbSet<T> GetDbSet<T>()\n where T : class\n {\n return context.Set<T>();\n }\n\n public void Commit()\n {\n context.SaveChanges();\n }\n\n public void Dispose()\n {\n context.Dispose();\n }\n}\n\npublic class EFRepository<T> : IRepository<T>\n where T : class\n{\n private readonly DbSet<T> dbSet;\n\n public EFRepository(IUnitOfWork unitOfWork)\n {\n var efUnitOfWork = unitOfWork as EFUnitOfWork;\n if (efUnitOfWork == null) throw new Exception(\"Must be EFUnitOfWork\"); // TODO: Typed exception\n dbSet = efUnitOfWork.GetDbSet<T>();\n }\n\n public void Add(T item)\n {\n dbSet.Add(item);\n }\n\n public void Remove(T item)\n {\n dbSet.Remove(item);\n }\n\n public IQueryable<T> Query()\n {\n return dbSet;\n }\n}\n</code></pre>\n\n<p><strong>Integrated tests assembly</strong></p>\n\n<p>References everything</p>\n\n<pre><code>[TestFixture]\n[Category(\"Integrated\")]\npublic class IntegratedTest\n{\n private EFUnitOfWork uow;\n private EFRepository<Entity> repo;\n\n [SetUp]\n public void SetUp()\n {\n Database.SetInitializer(new DropCreateDatabaseAlways<YourContext>());\n uow = new EFUnitOfWork(new YourContext());\n repo = new EFRepository<Entity>(uow);\n }\n\n [TearDown]\n public void TearDown()\n {\n uow.Dispose();\n }\n\n [Test]\n public void Repository_Add_AddsItem()\n {\n var expected = new Entity { Name = \"Test\" };\n repo.Add(expected);\n uow.Commit();\n var actual = repo.Query().FirstOrDefault(e => e.Name == \"Test\");\n Assert.IsNotNull(actual);\n }\n\n [Test]\n public void Repository_Remove_RemovesItem()\n {\n var expected = new Entity { Name = \"Test\" };\n repo.Add(expected);\n uow.Commit();\n repo.Remove(expected);\n uow.Commit();\n Assert.AreEqual(0, repo.Query().Count());\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T18:06:39.900",
"Id": "30455",
"Score": "0",
"body": "Expression v/s Func ..nice catch.. the RepositoryBase has the correct predicate. OrderBy also looked useless to me. Will remove that. The link you provide have two different implementations in terms of passing context or passing context and entity type as Type parameters. Which one is the better one or are both the same and just a matter of style. I am somehow unable to get my head around this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T18:09:47.353",
"Id": "30456",
"Score": "0",
"body": "DbContext is a UoW in itself, so what would be the benefits the having a separate UoW ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T21:24:59.397",
"Id": "30483",
"Score": "0",
"body": "@ashutoshraina possibly to abstract the UoW itself. People do that thinking they're going to have to change their ORM or data storage eventually. In my experience, it never happens and thus the less you abstract the better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T10:59:22.597",
"Id": "30525",
"Score": "0",
"body": "It's generally better to mock an interface which doesn't have dependencies on libraries other than the BCL itself. Even if you won't change your ORM, your tests can run without depending on anything but the BCL. Hence the need to wrap DbContext. Won't be much anyway.\n\nTo make a point, we did this for EF 1 combined with the EF Poco Adapter project from codeplex. When migrating to EF 4, we had to swap out the old contexts and dbset implementations for the new ones, and benefited from having our own UOW and Repos."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T14:13:19.773",
"Id": "30530",
"Score": "0",
"body": "@Lars-Erik See my Edit 2."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T17:31:45.697",
"Id": "19075",
"ParentId": "19037",
"Score": "26"
}
},
{
"body": "<h2>Reinventing the wheel</h2>\n\n<p>If you need a generic repository class use IObjectSet for base type and implement it if needed (in production code it is not needed, in tests you can use an IList<> as backend).</p>\n\n<h2>Leek on the abstraction</h2>\n\n<p>Repositories aren't supposed to have Save method becouse if someone else is in a transactional moment in shared context then you (or the other guy) can trick each other. Please create an independent IUnitOfWork for this.</p>\n\n<pre><code>interface IUnitOfWork : IDisposable {\n void Commit();\n void Rollback();\n}\n\ninterface IDataStore {\n IUnitOfWork InUnitOfWork();\n IObjectSet<T> Set<T>() where T : class;\n}\n\nusing (var uow = _data.InUnitOfWork()) {\n _data.Set<Order>.AddObject(order);\n _data.Set<SomethingElse>.Remove(otherObject);\n\n uow.Comit();\n}\n</code></pre>\n\n<p>The tricky part is how you handles the transaction. I have created an ISession interface with some methods (BeginTransaction(), InTransaction, Commit(), Rollback()) and created a default implementation. In my default IUnitOfWork implementation the constructor recieves an ISession instance and starting a transaction with it. The ISession implementation has an inner counter to count how many other actor started it's own transaction. When an IUnitOfWork from the shared storage Commited the counter is decremented by 1 if someone says RollBack then everything is rolled back.</p>\n\n<h2>EDIT (Dec. 03)</h2>\n\n<p>Fixed the IUnitOfWork Dispose behavior: the default is Rollback() not Commit()</p>\n\n<p>In this way you can test your code easily.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T01:19:14.623",
"Id": "30778",
"Score": "1",
"body": "IObjectSet is a MS api specific interface, isn't it? You can't reuse it if you swap to say NHibernate or RavenDB if you don't abstract the repository too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T03:43:31.170",
"Id": "30783",
"Score": "0",
"body": "+1 for the Rollback @Lars-Erik shoulddn't rollback be there if we have the Save in the UnitOfWork ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T06:39:49.767",
"Id": "30796",
"Score": "0",
"body": "@Lars-Erik: the System.IDisposable is a Microsoft specific thing slong with all the power of the .NET has. The IObjectSet<TEntity> has no specific constraint on TEntity just a simple \"be a class\". So yes, you can and should reuse it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T18:50:00.220",
"Id": "30851",
"Score": "0",
"body": "AFAIK, the DbContext doesn't have rollback unless you create a transactionscope instance and roll back on that. I use UOW Dispose to rollback, since I probably don't want to continue the trans anyway.\n\n@Peter I guess I should look into IObjectSet, but I still really like to call it IRepository since it's a known and proven pattern name. IObjectSet isn't.. And it's 20 lines of code, so who really cares?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T20:24:44.043",
"Id": "30866",
"Score": "0",
"body": "20 lines of unnecessary code can make a big mess in the code base and why you would write plus code if it's already exists? Another thing that is where is .NET there is an IObjectSet<T>, in any .NET app."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T09:28:33.327",
"Id": "30887",
"Score": "0",
"body": "I still prefer known pattern names when it's that simple. You still have to adapt to the IObjectSet if the API doesn't support it, so why not adapt something with a \"better name\"?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T19:42:32.433",
"Id": "19211",
"ParentId": "19037",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "19075",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T20:58:03.127",
"Id": "19037",
"Score": "37",
"Tags": [
"c#",
"design-patterns",
"entity-framework"
],
"Title": "Entity Framework Generic Repository Pattern"
}
|
19037
|
<p>I had asked a first question about this class a while ago and got a few answers here which made me rewrite it completely.</p>
<p>I removed all statics and globals, added my variables as arguments for the constructor, and pass them again as reference through my constructor (for creating a controller from within a controller).</p>
<p>There is now a SVN with read-access: You have to do</p>
<blockquote>
<p><code>svn export https://babna.com/svn/_appui_pub ./public_html</code></p>
</blockquote>
<p>from an empty folder, and to reach public_html from your browser.</p>
<pre><code>namespace bbn\cls;
class mvc
{
use \bbn\traits\info;
private
$is_routed,
$is_controlled,
// The name of the controller
$dest,
// The path to the controller
$path,
// The controller file (with full path)
$controller,
// The mode of the output (dom, html, json, txt, xml...)
$mode;
public
// The data model
$data,
// The output object
$obj,
// The file extension of the view
$ext,
// The request sent to the server
$original_request,
// The first controller to be called at the top of the script
$original_controller,
// The list of used controllers with their corresponding request, so we don't have to look for them again.
$known_controllers = array(),
// The list of views which have been loaded. We keep their content in an array to not have to include the file again. This is useful for loops.
$loaded_views = array(),
// Mustage templating engine.
$mustache,
// Reference to $appui variable (that's my framework's name)
$appui,
// List of possible outputs with their according possible file extension
$outputs = array('dom'=>'html','html'=>'html','image'=>'jpg,jpeg,gif,png,svg','json'=>'json','pdf'=>'pdf','text'=>'txt','xml'=>'xml','js'=>'js'),
// List of possible and existing universal/default controller. First every item is set to one, then if a universal controller is needed, self::universal_controller() will look for it and sets the according array element to the file name if it's found and to false otherwise.
$ucontrollers = array(
'dom' => 1,
'html' => 1,
'image' => 1,
'json' => 1,
'pdf' => 1,
'text' => 1,
'xml' => 1,
'js' => 1
);
// Paths are in constants
const
cpath = 'mvc/controllers/',
mpath = 'mvc/models/',
vpath = 'mvc/views/',
opath = 'mvc/_output/';
public function __construct(&$appui,$parent='')
{
// The initial call should only have $appui as parameter
if ( is_object($appui) && isset($appui->params,$appui->post) ){
$this->mustache = new \Mustache_Engine;
$this->appui = $appui;
// If an available mode starts the URL params, it will be picked up
if ( count($this->appui->params) > 0 && isset($this->outputs[$this->appui->params[0]]) ){
$this->appui->mode = $this->appui->params[0];
array_shift($this->appui->params);
}
// Otherwise in the case there's a POST we'll throw back JSON
else if ( count($this->appui->post) > 0 ){
$this->appui->mode = 'json';
}
// Otherwise we'll return a whole DOM (HTML page)
else{
$this->appui->mode = 'dom';
}
$this->mode = $this->appui->mode;
$this->original_request = implode('/',$appui->params);
$path = $this->original_request;
}
// Another call should have the initial controler and the path to reach as parameters
else if ( is_string($appui) && is_object($parent) && isset($parent->original_request) ){
$this->original_request =& $parent->original_request;
$this->mustache =& $parent->mustache;
$this->appui =& $parent->appui;
$this->original_controller =& $parent->original_controller;
$this->known_controllers =& $parent->known_controllers;
$this->loaded_views =& $parent->loaded_views;
$this->ucontrollers =& $parent->ucontrollers;
$path = $appui;
while ( strpos($path,'/') === 0 ){
$path = substr($path,1);
}
while ( substr($path,-1) === '/' ){
$path = substr($path,0,-1);
}
$params = explode('/',$path);
if ( isset($params[0]) && isset($this->outputs[$params[0]]) ){
$this->mode = array_shift($params);
$path = implode('/',$params);
}
else{
$this->mode = $this->appui->mode;
}
}
if ( isset($path) ){
$this->route($path);
}
}
private function check_path()
{
$ar = func_get_args();
foreach ( $ar as $a ){
if ( strpos($a,'./') !== false || strpos($a,'../') !== false || strpos($a,'/') === 0 ){
die("The path $p is not an acceptable value");
}
}
return 1;
}
// This function returns the content of a view file and adds it to the loaded_views array.
private function add_view($p)
{
if ( !isset($this->loaded_views[$p]) && is_file(self::vpath.$p) ){
$this->loaded_views[$p] = file_get_contents(self::vpath.$p);
}
if ( !isset($this->loaded_views[$p]) ){
die("The view $p doesn't exist");
}
return $this->loaded_views[$p];
}
// This fetches the universal controller for the according mode if it exists.
private function universal_controller($c)
{
if ( !isset($this->ucontrollers[$c]) ){
return false;
}
if ( $this->ucontrollers[$c] === 1 ){
$this->ucontrollers[$c] = is_file(self::cpath.$c.'.php') ? self::cpath.$c.'.php' : false;
}
return $this->ucontrollers[$c];
}
// Adds the newly found controller to the known controllers array, and sets the original controller if it has not been set yet
private function set_controller($c, $f)
{
if ( !isset($this->known_controllers[$this->mode.'/'.$c]) ){
$this->known_controllers[$this->mode.'/'.$c] = $f;
}
if ( is_null($this->original_controller) && !empty($c) ){
$this->original_controller = $this->mode.'/'.$c;
}
}
// This directly renders content with arbitrary values using the existing Mustache engine.
public function render($view, $model)
{
return $this->mustache->render($view,$model);
}
// This looks for a given controller in the file system if it has not been already done and returns it if it finds it, false otherwise.
private function get_controller($p)
{
if ( !$this->controller )
{
if ( !is_string($p) ){
return false;
}
if ( isset($this->known_controllers[$this->mode.'/'.$p]) ){
$this->dest = $p;
$this->controller = $this->known_controllers[$this->mode.'/'.$p];
}
else{
if ( isset($this->appui->routes[$this->mode][$p]) && is_file(self::cpath.$this->mode.'/'.$this->appui->routes[$this->mode][$p].'.php') ){
$this->controller = self::cpath.$this->mode.'/'.$this->appui->routes[$this->mode][$p].'.php';
}
else if ( is_file(self::cpath.$this->mode.'/'.$p.'.php') ){
$this->controller = self::cpath.$this->mode.'/'.$p.'.php';
}
else if ( is_dir(self::cpath.$p) && is_file(self::cpath.$p.'/'.$this->mode.'.php') ){
$this->controller = self::cpath.$p.'/'.$this->mode.'.php';
}
else{
return false;
}
$this->dest = $p;
$this->set_controller($p,$this->controller);
}
}
return 1;
}
// This will fetch the route to the controller for a given path. Chainable
private function route($path='')
{
if ( !$this->is_routed && self::check_path($path) )
{
$this->is_routed = 1;
$this->path = $path;
$fpath = $path;
while ( strlen($fpath) > 0 )
{
if ( $this->get_controller($fpath) ){
break;
}
else{
$fpath = strpos($fpath,'/') === false ? '' : substr($this->path,0,strrpos($fpath,'/'));
}
}
if ( !$this->controller ){
$this->get_controller('default');
}
}
return $this;
}
// This will reroute a controller to another one seemlessly. Chainable
public function reroute($path='')
{
$this->is_routed = false;
$this->controller = false;
$this->is_controlled = null;
$this->route($path);
$this->check();
return $this;
}
// This function encloses the controller's inclusion
private function control()
{
if ( $this->controller && is_null($this->is_controlled) ){
ob_start();
require($this->controller);
$output = ob_get_contents();
ob_end_clean();
if ( isset($this->obj->error) ){
die($this->obj->error);
}
else if ( !isset($this->obj->output) ){
$this->obj->output = $output;
}
$this->is_controlled = 1;
}
}
// This will launch the control process. Chainable
private function process()
{
if ( $this->controller && is_null($this->is_controlled) ){
$this->obj = new \stdClass();
$this->control();
if ( $this->data && is_array($this->data) && isset($this->obj->output) ){
$this->obj->output = $this->render($this->obj->output,$this->data);
}
}
return $this;
}
private function get_view($path='', $mode='')
{
if ( $this->mode && !is_null($this->dest) && $this->check_path($path, $this->mode) ){
if ( empty($mode) ){
$mode = $this->mode;
}
if ( empty($path) ){
$path = $this->dest;
}
if ( isset($this->outputs[$mode]) ){
$ext = explode(',',$this->outputs[$mode]);
/* First we look into the loaded_views if it isn't there already */
foreach ( $ext as $e ){
$file1 = $mode.'/'.$path.'.'.$e;
$t = explode('/',$path);
$file2 = $mode.'/'.$path.'/'.array_pop($t).'.'.$e;
if ( isset($this->loaded_views[$file1]) ){
return $this->loaded_views[$file1];
}
else if ( isset($this->loaded_views[$file2]) ){
return $this->loaded_views[$file2];
}
else if ( is_file(self::vpath.$file1) ){
return $this->add_view($file1);
}
else if ( is_file(self::vpath.$file2) ){
return $this->add_view($file2);
}
}
}
}
return false;
}
private function get_model()
{
if ( $this->dest ){
$args = func_get_args();
foreach ( $args as $a ){
if ( is_array($a) ){
$d = $a;
}
else if ( is_string($a) && $this->check_path($a) ){
$path = $a;
}
}
if ( !isset($path) ){
$path = $this->dest;
}
if ( !isset($d) ){
$d = array();
}
if ( strpos($path,'..') === false && is_file(self::mpath.$path.'.php') ){
$appui =& $this->appui;
$file = self::mpath.$path.'.php';
$data = $d;
return call_user_func(
function() use ($appui, $file, $data)
{
include($file);
if ( isset($model) )
return $model;
}
);
}
}
return false;
}
// Processes the controller and checks whether it has been controlled or not.
public function check()
{
$this->process();
return $this->is_controlled;
}
// Returns the output object.
public function get()
{
if ( $this->check() )
return $this->obj;
return false;
}
// Checks if data exists
public function has_data()
{
return ( isset($this->data) && is_array($this->data) ) ? 1 : false;
}
// Returns the rendered result from the current mvc if successfully processed
public function get_rendered()
{
if ( isset($this->obj->output) )
return $this->obj->output;
return false;
}
// Merges the existing data if there is with this one. Chainable.
public function add_data($data)
{
$ar = func_get_args();
foreach ( $ar as $d )
{
if ( is_array($d) )
{
if ( !is_array($this->data) )
$this->data = $d;
else
$this->data = array_merge($this->data,$d);
}
}
return $this;
}
// Creates a new MVC instance, link to the parent. All controller calls outside the router should be done this way
public function add($d)
{
return new mvc($d,$this);
}
// Outputs the result.
public function output()
{
if ( $this->check() && $this->obj ){
if ( isset($this->obj->prescript) ){
if ( empty($this->obj->prescript) ){
unset($this->obj->prescript);
}
else{
$this->obj->prescript = \bbn\cls\str\text::clean($this->obj->prescript,'code');
}
}
if ( isset($this->obj->script) ){
if ( empty($this->obj->script) ){
unset($this->obj->script);
}
else{
$this->obj->script = \bbn\cls\str\text::clean($this->obj->script,'code');
}
}
if ( isset($this->obj->postscript) ){
if ( empty($this->obj->postscript) ){
unset($this->obj->postscript);
}
else{
$this->obj->postscript = \bbn\cls\str\text::clean($this->obj->postscript,'code');
}
}
switch ( $this->mode ){
case 'json':
if ( !ob_start("ob_gzhandler" ) ){
ob_start();
}
else{
header('Content-Encoding: gzip');
}
if ( isset($this->obj->output) ){
$this->obj->html = $this->obj->output;
unset($this->obj->output);
}
header('Content-type: application/json; charset=utf-8');
echo json_encode($this->obj);
break;
case 'dom':
case 'html':
case 'js':
case 'text':
case 'xml':
if ( !isset($this->obj->output) ){
header('HTTP/1.0 404 Not Found');
exit();
}
case 'dom':
case 'html':
if ( !ob_start("ob_gzhandler" ) ){
ob_start();
}
else{
header('Content-Encoding: gzip');
}
header('Content-type: text/html; charset=utf-8');
echo $this->obj->output;
break;
case 'js':
header('Content-type: application/javascript; charset=utf-8');
echo $this->obj->output;
break;
case 'text':
header('Content-type: text/plain; charset=utf-8');
echo $this->obj->output;
break;
case 'xml':
header('Content-type: text/xml; charset=utf-8');
echo $this->obj->output;
break;
case 'image':
if ( isset($this->obj->img) ){
$this->obj->img->display();
}
else{
header('HTTP/1.0 404 Not Found');
}
break;
default:
if ( isset($this->obj->file) ){
if ( !is_file($this->obj->file) ){
unset($this->obj->file);
}
}
if ( !isset($this->obj->file) ){
header('HTTP/1.0 404 Not Found');
exit();
}
header("X-Sendfile: ".$this->obj->file);
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename="' . basename($this->obj->file) . '"');
}
}
}
}
</code></pre>
<p>Here is the router:</p>
<pre><code>// Different environments personal settings
include_once('config/cfg.php');
// Setting up an environment
include_once('config/env.php');
// Creating $bbn and $appui vars
include_once('config/vars.php');
// Loading routes configuration
include_once('config/routes.php');
if ( defined('BBN_SESS_NAME') && $appui->db ){
// Loading users scripts
include_once('config/custom.php');
// Setting up the session
if ( !isset($_SESSION[BBN_SESS_NAME]) ){
include_once('config/session.php');
}
$bbn->mvc = new \bbn\cls\mvc($appui);
if ( !$bbn->mvc->check() ){
die('No controller has been found for this request');
}
else
{
array_push($_SESSION[BBN_SESS_NAME]['history'],$bbn->mvc->original_request);
if ( count($_SESSION[BBN_SESS_NAME]['history']) > $bbn->vars['history_max'] ){
array_shift($_SESSION[BBN_SESS_NAME]['history']);
}
}
$bbn->mvc->output();
}
</code></pre>
<p>Here's an example on how it works on a whole HTML document. 2 views are used: the DOM structure, and a list element that is a part of a multi-level menu with no depth limit.</p>
<p>The DOM view:</p>
<pre class="lang-html prettyprint-override"><code>...
</head>
<body itemscope itemtype="http://schema.org/WebPage">
<div id="example" class="k-content">
<div id="vertical">
<div id="top-pane" style="overflow:visible; width:100%">
<ul id="menu">{{{menu_content}}}</ul>
...
</code></pre>
<p>The HTML list element view (inside #menu):</p>
<pre class="lang-html prettyprint-override"><code>{{#menus}}
<li{{specs}}>
{{#icon}}
<i class="icon-{{icon}}"></i>
&nbsp; &nbsp; &nbsp;
{{/icon}}
{{{title}}}
{{#has_menus}}
<ul>
{{{content}}}
</ul>
{{/has_menus}}
</li>
{{/menus}}
</code></pre>
<p>And I have a nested model used by the controller for displaying the menu:</p>
<pre class="lang-php prettyprint-override"><code>array (
'menus' => array (
0 => array (
'title' => 'Hello',
'icon' => 'cloud',
'has_menus' => false
),
1 => array (
'title' => '1',
'icon' => 'user',
'has_menus' => 1,
'menus' => array (
0 => array (
'title' => '11',
'icon' => 'cloud',
'has_menus' => false
),
1 => array (
'title' => '12',
'icon' => 'wrench',
'has_menus' => false
),
2 => array (
'title' => '13',
'icon' => 'remove',
'has_menus' => 1,
'menus' => array (
0 => array (
'title' => '131',
'icon' => 'cloud',
'has_menus' => false
),
1 =>
...
</code></pre>
<p>Controller for the DOM:</p>
<pre class="lang-php prettyprint-override"><code>$this->data = array(
'site_url' => BBN_URL,
'is_dev' => BBN_IS_DEV ? 1 : "false",
'shared_path' => BBN_SHARED_PATH,
'static_path' => BBN_STATIC_PATH,
'year' => date('Y'),
'javascript_onload' => $mvc->get_view('init','js'),
'theme' => isset($_SESSION['atl']['cfg']['theme']) ? $_SESSION['atl']['cfg']['theme'] : false
);
$tmp = $this->add("html/menu");
if ( $tmp->check() ){
$this->data['menu_content'] = $tmp->get_rendered();
}
echo $this->get_view('_structure','dom');
</code></pre>
<p>Which is calling the controller for the nested menu:</p>
<pre class="lang-php prettyprint-override"><code>if ( !$this->has_data() ){
$this->data = $this->get_model();
}
if ( isset($this->data['menus']) && is_array($this->data['menus']) )
{
foreach ( $this->data['menus'] as $i => $m )
{
$tmp = $this->add("html/menu")->add_data($m);
if ( $tmp->check() ){
$this->data['menus'][$i]['content'] = $tmp->get_rendered();
}
}
}
echo $this->get_view();
</code></pre>
<p>Filesystem:</p>
<blockquote>
<p><img src="https://i.stack.imgur.com/iPNCE.png" alt="Filesystem"></p>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T16:48:23.473",
"Id": "30957",
"Score": "1",
"body": "MVC is about separating things in an application so a class names mvc not the best idea. I'm working on a MVC framework, and i have 80+ classes to serve just one request."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T17:11:23.287",
"Id": "30962",
"Score": "0",
"body": "The idea here is that the mvc class is not the controller, but the class which will put together the controllers, the models and the views. It is more a router."
}
] |
[
{
"body": "<p>Don't like it too much.</p>\n\n<p>Passing variables into functions as references always scare me because usually you cannot track anymore what's going on. <code>__construct(&appui,...)</code> is one such thing.</p>\n\n<p>References communicate to me the following: \"I expect this value to be not an object, and I expect the value to be changed inside, and the change also made intentionally effective on the outside.\" </p>\n\n<p>This communication is clearly wrong in your case: \na) Either you get an object - then the reference is not needed because objects are ALWAYS passed as reference.\nb) If you get a string, then you do nothing with the string but copy it to another variable.</p>\n\n<p>Additionally there are some cases where you copy values as references that seem unnecessary to me.</p>\n\n<p>Completely unrelated: Have you heard about autoloading? You seem to do some extensive stuff with paths to find your models for example, and then try to include them with a tricky wrapping.</p>\n\n<p>I assume models are classes. If they are, then autoloading will load them the very time they are first needed because some code stumples upon it's classname. Check \"PSR-0 autoloading\" to get more info.</p>\n\n<p>I just came across this part:</p>\n\n<pre><code>// Processes the controller and checks whether it has been controlled or not.\npublic function check()\n{\n $this->process();\n return $this->is_controlled;\n}\n\n// Returns the output object.\npublic function get()\n{\n if ($this->check() && $this->is_controlled)\n return $this->obj;\n return false;\n}\n</code></pre>\n\n<p>I would thing that inside <code>get()</code> the if might be easier made like this:</p>\n\n<pre><code> if ($this->check()) return $this->obj;\n</code></pre>\n\n<p>A final comment: I do not like the idea too much that you basically only have one controller class that does everything, and that your controllers are no real classes, but code fragments that act inside your single controller, stacking stuff.</p>\n\n<p>And I miss type hinting very much in your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T15:50:26.453",
"Id": "30952",
"Score": "0",
"body": "Thanks for the comments! The _output folder doesn't exist anymore, but is now included in the class. I removed references as arguments."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T15:52:06.330",
"Id": "30953",
"Score": "0",
"body": "True for \"controllers are no real classes, but code fragments that act inside your single controller\". I'll think about it. I'm updating my question with a SVN access if you or anyone is interested to give it a try."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T22:14:31.663",
"Id": "19313",
"ParentId": "19043",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T23:54:57.730",
"Id": "19043",
"Score": "3",
"Tags": [
"php",
"object-oriented",
"mvc"
],
"Title": "PHP MVC class with controller and nested model"
}
|
19043
|
<pre><code>a_star = # returns the goal node (or null if path not found). To reconstruct path follow the node.__src till null
(
start, # starting node
neighbors, # a function that takes in a node and returns list of neighbours
h, # admissable A* heuristic distance from goal i.e. heurisitic(x) <= distance(x,y) + heuristic(y) for all x,y
dist = (a,b) -> 1, # takes two nodes and returns distance between them (optional - default is 1)
isGoal = (x) -> h(x) is 0 # returns true iff node is goal (optional - assumes heurisitc(goal) = 0)
) ->
closed = {} # set of nodes already evaluated
q = {} # set of tentative nodes to be evaluated, the value is the 'f_score' (F = G + H)
g = [] # 'g-score' - the exact cost to reach this node from start
add = (node, parent) ->
node.__src = parent
g[node] = if parent? then g[parent] + dist parent, node else 0
q[node] = g[node] + h(node)
remove_best = ->
best = null
best = node for node,f of q when best is null or f < q[best]
if best? then closed[best] = true; delete q[best]
return best
add start, null
while true
c = remove_best()
if c is null or isGoal c then return c
add n, c for n in neighbours c when not closed[n] and (q[n] is null or g[c] + dist(c, n) <= g[n])
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T02:19:50.423",
"Id": "70297",
"Score": "0",
"body": "Out of curiosity, in what context are you implementing an A* algorithme in coffeescript? Note that \"for fun\" or \"to learn\" are 2 good answers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T02:27:40.877",
"Id": "70300",
"Score": "0",
"body": "Neither. I needed it for a client side puzzle game I wrote in HTML5 + AngularJs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T02:47:26.647",
"Id": "70302",
"Score": "0",
"body": "I see... I was thinking that javascript is not a the best fit for this kind of task but in the browser you have pretty much 2 options. Javascript or calling an api. Note that actionscript is not mentioned ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T02:49:35.593",
"Id": "70303",
"Score": "1",
"body": "I have to say that `add n, c for n in neighbours c when not closed[n] and (q[n] is null or g[c] + dist(c, n) <= g[n])` is quite long and does a lot of things for a single line. I feel like you are performing A* in one line."
}
] |
[
{
"body": "<p>I am not an expert on the A* algorithm. I'm suggesting changes based on the\n<a href=\"http://www.faqs.org/docs/artu/ch01s06.html\">Rules of Clarity, Simplicity, and Economy</a> and the code you provided,\nnot on an extensive knowlege of graph traversal methods.</p>\n\n<p>Extensive documentation inline is tricky to read. Consider using a standardized\ndocstring format like those in <a href=\"http://jashkenas.github.io/docco\">docco</a> or <a href=\"https://github.com/coffeedoc/codo\">codo</a> for detailed\ninline docs. </p>\n\n\n\n<pre class=\"lang-coffee prettyprint-override\"><code>###\n returns the goal node or null if path not found. Reconstruct path by\n following the goalNode.src until null\n\n @param [Object] start The node to start searching from\n @param [Object] options The options object\n\n @option [Function] neighbors Takes node, returns array of neighbors\n @option [Function] heuristic Takes node, returns A* heuristic\n @option [Function] isGoal Takes node, returns true if node is goal\n @option [Function] distance Takes two nodes returns distance between them\n\n @returns {Object} Returns the goal node with a tracable path to the start\n###\n</code></pre>\n\n<p>It's not clear which options you expect you be left as their default values\nmost frequently. If most options will be left as defaults most of the time,\nand the function will \"just work\" without configuration, use an <code>options</code>\nobject and set sensible defaults.</p>\n\n<pre class=\"lang-coffee prettyprint-override\"><code>aStar = (start, opts = {}) ->\n opts.neighbors or= (node) -> []\n opts.heuristic or= (node) -> 0\n opts.isGoal or= (node) -> opts.heuristic(node) is 0\n opts.distance or= (a, b) -> 1\n</code></pre>\n\n<p>If you want to find paths from many start points, you might\nsetup your function once and allow several calls, each providing a start point.</p>\n\n<pre class=\"lang-coffee prettyprint-override\"><code>AStar = (opts = {}) ->\n opts.distance or= (a, b) -> 1\n # ... and other defaults\n\n (start) ->\n # logic for calculating path from \"start\"\n\n# use it like this\nastar = AStar\n isGoal: -> yes\n neighbors: -> [1, 2, 3]\n\n# goal is the destination node (as it was in the original logic)\ngoal = astar {x: 1, y: 2}\n</code></pre>\n\n<p>Inside the logic function, remember that \"<a href=\"http://www.faqs.org/docs/artu/ch01s06.html\">Clarity is better than cleverness</a>\".\nSlightly longer, but much more descriptive names go a long way to making the\noperations easier to understand.</p>\n\n<pre class=\"lang-coffee prettyprint-override\"><code>(start) ->\n closed = {} # nodes already evaluated\n nodes = {} # key: node to be evaluated, value: f-score (F = G + H)\n gscore = [] # the exact cost to reach this node from start\n</code></pre>\n\n<p>Breaking the operations in to related sections makes it easier to follow.</p>\n\n<pre class=\"lang-coffee prettyprint-override\"><code> # constructing path\n addNode = (node, src) ->\n node.src = src\n gscore[node] = if src? then gscore[src] + opts.distance src, node else 0\n nodes[node] = gscore[node] + opts.heuristic(node)\n</code></pre>\n\n<p>Naming functions with verbs and naming functions that return booleans with <code>is</code>\nand <code>has</code> usually increases clarity. Verbs do things, so do functions. You\nwant the behavior of your code to be unsurprising to the person reading it.</p>\n\n<pre class=\"lang-coffee prettyprint-override\"><code> # selecting best path\n isBetter = (a, b) ->\n a is null or b < nodes[a]\n\n selectBest = (best = null) ->\n best = node for node, fscore of nodes when isBetter(best, fscore)\n closed[best] = yes if best?\n delete nodes[best]\n best\n</code></pre>\n\n<p>Break complex boolean questions into parts so the reader (which is also you,\nlater) can follow (with a minimal cognitive load) what you intend to be\ndetermining with your comparisons.</p>\n\n<pre class=\"lang-coffee prettyprint-override\"><code> # answers about current node\n isOpen = (node) ->\n not closed[node]\n\n isShorter = (a, b) ->\n nodes[a] is null or gscore[b] + opts.distance(a, b) <= gscore[a]\n\n isAvailable = (neighbor, node) ->\n isOpen(neighbor) and isShorter(neighbor, node)\n</code></pre>\n\n<p>The big loop that does all the work would be clearer if you could quickly see\nwhat situation would trigger the loop ending. <code>while true</code> is less communicative\nthan <code>doneSearching</code>.</p>\n\n<pre class=\"lang-coffee prettyprint-override\"><code> findGoal = (start) ->\n # insert start point\n addNode start, null\n\n # store the node in use\n node = null\n\n doneSearching = ->\n node = selectBest()\n return yes if node is null or opts.isGoal node\n no\n\n # find the shortest path in the current open set\n # stop looking when out of options or at the goal\n until doneSearching()\n for neighbor in getNeighbors node when isAvailable neighbor, node\n addNode neighbor, node\n node\n</code></pre>\n\n<p>Everything up to here defines the operations that will be used. This is the\nsingle point that triggers action in this function. Reducing the number of\nmoving parts makes tracing the logic path easier.</p>\n\n<pre class=\"lang-coffee prettyprint-override\"><code> findGoal(start)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-22T21:36:12.887",
"Id": "51450",
"ParentId": "19046",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "51450",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T01:46:45.387",
"Id": "19046",
"Score": "6",
"Tags": [
"coffeescript",
"pathfinding"
],
"Title": "CoffeeScript implementation of A* algorithm"
}
|
19046
|
<p><strong>Background</strong></p>
<p>My project performs software application management; it covers in-app purchasing, product provisioning, account management, etc. I've recently been tasked to add a cost reporting component.</p>
<p><strong>Code</strong></p>
<p>On the code level, I've spread out my model into a few classes that represent categories or interest areas, each requiring specific dependencies. Here's a rough outline:</p>
<p><em>models/base.class.php</em></p>
<pre><code>namespace Models;
class Base
{
protected $db; // PDO
public function __construct(PDO $db)
{
}
// helper functions such as data mappers for one or multiple rows
}
</code></pre>
<p><em>models/ordermodel.class.php</em></p>
<pre><code>namespace Models;
class OrderModel extends Base
{
protected $gateway; // payment gateway to handle purchases
public function __construct(PDO $db, Gateway $gateway)
{
parent::__construct($db);
$this->gateway = $gateway;
}
// methods for purchase, refund, subscription cancellation, etc.
public function updateInstallDetails(...);
public function refundPayment(...);
}
</code></pre>
<p><em>models/provisionmodel.class.php</em></p>
<pre><code>namespace Models;
class ProvisionModel extends Base
{
protected $account; // user account to "anchor" queries against
public function __construct(PDO $db, Entities\Account $account)
{
parent::__construct($db);
$this->account = $account;
}
// this method gets called when a software update took place
// it's called (indirectly) from a controller class
private function updateInstallDetails(...);
}
</code></pre>
<p>The individual classes are accessed via a factory:</p>
<pre><code>class Model
{
private static $repository = array();
/**
* Generic instance loader
*
* @param $name string
* @param $fn callback generates the object instance
*/
private static function getModelInstance($name, $fn)
{
if (!isset(self::$repository[$name])) {
self::$repository[$name] = $fn();
}
return self::$repository[$name];
}
public static function getOrderModel($gateway = null)
{
// TODO pass payment gateway object
return self::getModelInstance(__FUNCTION__, function() use ($gateway) {
if ($gateway) {
$gateway = GatewayFactory::load($gateway);
}
return new Models\OrderModel(SiteConfig::getDefaultDatabase(), $gateway);
});
}
}
</code></pre>
<p><strong>Problem</strong></p>
<p>The cost reporting component cross-cuts two main areas of the model, i.e. purchases, refunds and provisioning (shown above). Purchases and refunds of any product are recorded for royalty payments and provisioning keeps track of software updates (between versions there may be added or removed royalties).</p>
<p><strong>My possible solutions</strong></p>
<p>So I have a few options:</p>
<ol>
<li><p>Make both my classes aware of the reporting unit; this means extending the constructor and what not.</p></li>
<li><p>Apply Decorator pattern to "intercept" method calls.</p></li>
<li><p>Apply <strike>Observer</strike>Mediator pattern; each class will emit "interesting" events and the reporting unit will listen for them and make the appropriate changes to the database tables.</p></li>
</ol>
<p><strong>Questions</strong></p>
<p>Does it make sense to spread out my model into separate classes in the first place? Would it make more sense to make one big class that encompasses all my application logic?</p>
<p><strike>Observer</strike>Mediator pattern has its pros and cons; the advantage is that you can easily decouple units from each other, but the downside is that it's indeed decoupled. Are there other cons?</p>
<p>Is there another pattern I could apply to crack this? Is there some other major issue with my code?</p>
|
[] |
[
{
"body": "<p>First, use interfaces whenever possible and make your Factories return them.\nIf later you decide to change implementation or \"hot plug\" one at run-time, it will be feasible.</p>\n\n<p>I think that looking at frameworks like yii or ZF2 may helps a lot, hunt for design patterns in them !</p>\n\n<p>Like in zend, you may pass a \"ServiceManager\" and let your class grab dependencies from it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-08T13:49:49.967",
"Id": "34460",
"Score": "0",
"body": "ServiceManager is a Service Locator implementation which is not as good as anyone can think. Service locator is about of \"i know an all knowing stuff in the global hyperspace and i'm going to ask it to get me an instance of Blah\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-10T08:58:32.510",
"Id": "34592",
"Score": "0",
"body": "If dependecy injection is used properly, it can do miracles. Angularjs seems to be a very good example of it.\nServiceManager is an alternative to it. Instead of \"pushing\" dependecies, you permit to your objects to ask them.\nIt permit to say \"I want to store that thing so give me something to do it\" and you don't care about the actual implementation."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-08T11:53:18.940",
"Id": "21465",
"ParentId": "19053",
"Score": "0"
}
},
{
"body": "<h2>Model classes</h2>\n\n<p>Model classes should not have any hard dependency in their constructors especially not a PDO or similar stuff. Model can not have any business rule they are containing only data and that's all. Ofcourse if you have some mapping between model classes (Author <--> Books) then some of the relation informations have to be in the model (Mediator!) classes but that's all.</p>\n\n<p>Model classes should not have any knowledge about their storage type. It can be anything not just az SQL database handled with PDO. They can not have self managed CRUD methods (if they does then they become Active Record(s) which is a really bad thing (~God object), antipattern) (maybe factory methods are okay but these methods also can not have anything heavy (query database through a horrible static global accessible thing) inside).</p>\n\n<h2>CRUD</h2>\n\n<p>Mapped entities should have some kind of top level storage (like in .NET an ObjectContext) which is dealing the storage problem; handling SQL connections and providing transaction capabilities with an Unit of Work (Commit, Rollback) solution. The top level storage can have for example mapped SQL tables for querying from the underlaying storage, inserting into it, deleting from it. Other thing is that this top level storage is the responsible to track the changes in the entities. Of course we have to put some stuff in every model in the system (Mediator #2!) to handle this session but the main logic still in a state manager not in the models.</p>\n\n<h2>Repository</h2>\n\n<p>Repositories are tricky. With powerful ORM systems we can forget them if the business logic doesn't require another application level. What should a repository contain? Add, Delete, Query methods but no Save() or anything else (not even named query methods like: GetUserByEmailAddress($email)). You can use DAO classes for named queries which are operating one or more repository or on the entire object tree. Do not forget: not every entity has a repository! Only aggregate roots can have repository, for example: an Order model can have a repo but an OrderDetail can not becouse it belongs to an Order model and can not exists whithout it.</p>\n\n<h2>Static</h2>\n\n<p>In your example your are using in static context object which are containing state (your repository stuff) information which is bad. You will introduce a global state whith them which will bring more harm to your code then good (global hyperspace is inreliable, anyone can modify it).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-08T14:18:54.083",
"Id": "34490",
"Score": "0",
"body": "*\"Model can not have any business rule they are containing only data and that's all.\"* This is so wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-09T06:16:03.417",
"Id": "34538",
"Score": "0",
"body": "The models can contain business rule like stuff, for example a SocialSecurityNumber can have some validation stuff but nothing heavy code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-08T13:45:31.803",
"Id": "21468",
"ParentId": "19053",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T11:49:13.580",
"Id": "19053",
"Score": "5",
"Tags": [
"php",
"mvc"
],
"Title": "Spreading out model across multiple classes a good idea?"
}
|
19053
|
<p>I use the code below for filtering a treeview. Can this be improved?</p>
<pre><code>private IEnumerable<TreeNode> FindNodeByValue(TreeNodeCollection nodes, string searchstring)
{
foreach (TreeNode node in nodes)
{
if (node.Value.IndexOf(searchstring,
StringComparison.CurrentCultureIgnoreCase) >= 0)
yield return node;
else
{
foreach (var subNode in FindNodeByValue(node.ChildNodes, searchstring))
yield return subNode;
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
var query= FindNodeByValue(TreeView1.Nodes, fieldFilterTxtBx.Text);
if (query != null)
{
//TreeView1.Nodes[0].Expand();
//TreeView1.Nodes.Clear();
foreach (TreeNode node in query.ToList())
{
TreeView1.Nodes.Add(node);
}
// TreeNode newnode = new TreeNode("Detail Engineering");
// TreeView1.Nodes.Add(newnode);
TreeView1.ExpandAll();
}
else
{
Label1.Text = "No file found";
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T19:50:54.557",
"Id": "30464",
"Score": "0",
"body": "What do you mean by \"refresh and populate\"? Do you want to clear the list and just show matching nodes? Do you want to just jump to the matching node and expand down to it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T05:15:22.620",
"Id": "30516",
"Score": "0",
"body": "i need clear the list and just show matching nodes after button click"
}
] |
[
{
"body": "<p>What's the problem with your implementation? You clear the tree and add new (filtered) nodes. Somehow, <code>TreeView1.Nodes.Clear();</code> is under comment, so it may be supposed that you want to preserve full node structure. If so, just store it in memory:</p>\n\n<pre><code>var query = FindNodeByValue(PersistentNodeSet.Nodes, fieldFilterTxtBx.Text);\nif (query != null)\n{\n TreeView1.Nodes.Clear();\n foreach (TreeNode node in query.ToList())\n TreeView1.Nodes.Add(node);\n TreeView1.ExpandAll();\n}\n</code></pre>\n\n<p>And if you want the tree to preserve original structure, you need to use recursion in <code>FindNodeByValue()</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T11:27:49.960",
"Id": "19146",
"ParentId": "19054",
"Score": "2"
}
},
{
"body": "<p><strong>Button1_Click</strong> </p>\n\n<ul>\n<li><p>The var <code>query</code> can't be null. So replace it with <code>if (query.Any())</code> </p></li>\n<li><p>There is no need to call <code>ToList()</code> you can just iterate over the items. </p>\n\n<pre><code>foreach (TreeNode node in query)\n{\n TreeView1.Nodes.Add(node);\n\n}\n</code></pre>\n\n<p>but basically it doesn't make much sense, because first you search in <code>TreeView1.Nodes</code> and then you add the found items again to the treeview. </p></li>\n<li><p>If you reverse the logic of the <code>if</code> condition, you can save some horizontal spacing. </p>\n\n<pre><code>if (!query.Any())\n{\n Label1.Text = \"No file found\";\n return;\n}\n\nforeach (TreeNode node in query.ToList())\n{\n TreeView1.Nodes.Add(node);\n}\n\nTreeView1.ExpandAll();\n</code></pre></li>\n</ul>\n\n<p><strong>General remarks</strong> </p>\n\n<ul>\n<li>You should use braces <code>{}</code> for single <code>if</code> statements and loops, for your code to be less errorprone. </li>\n<li>Dead code should be deleted </li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-19T15:25:31.407",
"Id": "74179",
"ParentId": "19054",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T12:03:56.180",
"Id": "19054",
"Score": "1",
"Tags": [
"c#",
"asp.net"
],
"Title": "Filtering a TreeView"
}
|
19054
|
<p>I have a PL/pgSQL function with erratic performance:</p>
<pre><code>DECLARE
l RECORD;
events_for_machine integer;
before_event "PRD".events_log;
machines_ids integer[];
island_controller RECORD;
before_order "PRD".events_log;
before_detail "PRD".events_log;
before_pallete "PRD".events_log;
before_operation "PRD".events_log;
timer timestamp;
timer2 timestamp;
BEGIN
machines_ids = string_to_array(machines_ids_g,',')::integer[];
for l in
select m.*
from
"PRD".machines m
inner join
unnest(machines_ids) n(id) on n.id = m.id
where
m.start_work_date < begin_date_g
order by m.id
LOOP
SELECT * INTO island_controller FROM "STRUCT".island_machines WHERE machine_id=l.id;
RAISE NOTICE 'pobieram zdarzenie before dla maszyny %',l.id;
SELECT * INTO before_event FROM "PRD".events_log WHERE plc_time < begin_date_g AND (((event_type_id IN (1,51) AND machine_id = island_controller.controller_id AND island_id = island_controller.island_id))
OR (event_type_id IN (2000,2001) AND machine_id=l.id)) ORDER BY plc_time DESC LIMIT 1;
IF before_event.plc_time IS NOT NULL THEN
RAISE NOTICE 'Getting info about first machine work time struct element';
RETURN QUERY SELECT * FROM "PRD".events_log WHERE event_type_id = 113 AND machine_id=l.id AND plc_time < before_event.plc_time ORDER BY plc_time DESC LIMIT 1;
RETURN QUERY SELECT * FROM "PRD".events_log WHERE event_type_id = 102 AND machine_id=l.id AND plc_time < before_event.plc_time ORDER BY plc_time DESC LIMIT 1;
RETURN QUERY SELECT * FROM "PRD".events_log WHERE event_type_id = 111 AND machine_id=l.id AND plc_time < before_event.plc_time ORDER BY plc_time DESC LIMIT 1;
RETURN QUERY SELECT * FROM "PRD".events_log WHERE event_type_id = 1010 AND machine_id=l.id AND plc_time < before_event.plc_time ORDER BY plc_time DESC LIMIT 1;
RETURN NEXT before_event;
END IF;
RAISE NOTICE 'generuje zdarzenia wlasciwe dla maszyny %',l.id;
RETURN QUERY SELECT * FROM "PRD".events_log WHERE
(event_type_id = ANY ('{1,51}'::integer[]) AND (machine_id=island_controller.controller_id AND island_id = island_controller.island_id) AND (plc_time BETWEEN begin_date_g AND end_date_g))
OR (event_type_id = ANY ('{2000,2001,107}'::integer[]) AND machine_id=l.id AND (plc_time >= begin_date_g AND plc_time <= end_date_g))
OR ((event_type_id = ANY ('{101,102,103,301,1010}'::integer[]) OR ((event_type_id >= 5000) AND (event_type_id <= 5999))) AND machine_id=l.id AND plc_time >= begin_date_g AND plc_time <= end_date_g) ORDER BY plc_time;
RAISE NOTICE 'koniec dla maszyny %',l.id;
END LOOP;
END;
</code></pre>
<p>Sometimes the function execution time is ~9 seconds and sometimes ~40 seconds for the same arguments.</p>
<p>What does it depend on? What could be so inefficient?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-11T07:52:03.437",
"Id": "36579",
"Score": "2",
"body": "Parameter definition and other details in the header are essential. Always post a complete function - will help your chances on a response."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-05-05T23:52:44.500",
"Id": "309021",
"Score": "0",
"body": "Good formatting and wrapping of lines improves readability dramatically. SQL is one of those languages that should have it's lines broken."
}
] |
[
{
"body": "<p>I find this query difficult to read to begin with. Here are my comments:</p>\n\n<ol>\n<li><p>When you <code>DECLARE</code> a bunch of variables it is useful to name them such that they will be easy for another programmer to identify throughout the script. For example adding <code>v_</code> in front of them is a good way. Also calling a variable just <code>l</code> is pretty cryptic. </p></li>\n<li><p><code>select *</code> is sometimes not a good idea; that is, unless you actually <em>need</em> all of the columns. I see you use that a lot and it could be part of your performance issues. Part of why it may be problematic is also that your result set is unpredictable, if a column is added or dropped for instance, or renamed, your query would not be repeatable. It's better to get a \"column does not exist\" error than get unpredictable result set. Be explicit when you can.</p></li>\n<li><p>The lack of proper indenting in your script, as well as the lack of a proper explanation in your question (or as comments within your script), in addition to some of it being in Polish it seems, makes it very difficult to decrypt what you are doing here unless you provide more information. </p></li>\n<li><p>You have lots of variables, most of them holding lots of data (<code>select * into</code> etc.). This likely is affecting performance. Multiple levels of nested subqueries can also slow it down.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-25T13:00:10.100",
"Id": "179470",
"Score": "0",
"body": "There's nothing inherently wrong with `select *` from a performance perspective. If you're selecting all of the columns from a particular table, doing a `select *` is the same as specifying each and every column in your select statement. If you want to improve performance, you need to select only the columns you need."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-25T16:57:41.830",
"Id": "179518",
"Score": "0",
"body": "Thanks @cimmanon - That answer was long ago, I edited it to be worded better. Good catch!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-23T16:08:21.497",
"Id": "51550",
"ParentId": "19056",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T12:18:06.023",
"Id": "19056",
"Score": "5",
"Tags": [
"performance",
"sql",
"logging",
"postgresql",
"stored-procedure"
],
"Title": "Selecting and copying event log entries for some machine"
}
|
19056
|
<p>I modified <a href="http://labnol.org/?p=21060" rel="nofollow">Amit Agarwal's script</a> which checks the uptime of one website so that it now checks several sites. The script runs every 5 minutes, however, I kept receiving mails that a site was down and then 5 mins later that it was up again.</p>
<p>I adapted my code to only log a change if it persisted for two checks, like this:</p>
<pre><code>function siteUptimeCheck(url, row) {
var response, error;
var status = "status"+row.toString(); // status1, status2..
if (!ScriptProperties.getProperty(status))
ScriptProperties.setProperty(status, 200);
try { // try, catch, else
var success = true;
response = UrlFetchApp.fetch(url);
} catch(error) {
success = false;
insertData(status, url, row, error, response.getResponseCode(), "Site down: ");
return;
} if(success) {
insertData(status, url, row, "Up", response.getResponseCode(), "Site up: ");
}
}
function insertData(status, url, row, error, code, msg) {
if (ScriptProperties.getProperty(status) == code) {
return; // Return if there are no changes
} else if (ScriptProperties.getProperty(status) == 1) {
sheet.getRange(row,2).setValue(code);
if (code != 200) {
//create newdate log entry
sheet.getRange(row,3).setValue(newdate +" "+ error);
}
ScriptProperties.setProperty(status, code);
MailApp.sendEmail(email, msg, error);
} else {
ScriptProperties.setProperty(status, 1); // Marker for "something changed"
}
}
</code></pre>
<p>Are there better ways of solving this?</p>
|
[] |
[
{
"body": "<p>There is no <code>// try, catch, else</code> in javascript. </p>\n\n<p>Instead I would do:</p>\n\n<pre><code>var success = false, state = null;\ntry {\n response = UrlFetchApp.fetch(url); \n success = true;\n error = \"Up\";\n state = \"Site up: \";\n} catch(ex) {\n success = false; \n error = ex;\n state = \"Site down: \";\n}\n\ninsertData(status, url, row, error, response.getResponseCode(), state);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T21:55:05.093",
"Id": "62159",
"Score": "0",
"body": "Thanks James, I'll have a look at it in the next days and tick it, if it works for me! Much appreciated!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T02:04:58.103",
"Id": "36097",
"ParentId": "19061",
"Score": "3"
}
},
{
"body": "<ul>\n<li><code>ScriptProperties</code> has been depreciated and should be replaced with the <a href=\"https://developers.google.com/apps-script/reference/properties/properties-service\" rel=\"nofollow\">Properties Service</a>. </li>\n<li>Functions should have verb-noun names. Thus, <code>siteUptimeCheck</code> would be better named <code>checkSiteUptime</code>.</li>\n<li><code>200</code> is a magic number and should be given a meaningful variable name. (Preferably a constant, but I don't think GAS has constants.)</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-16T03:02:09.237",
"Id": "57152",
"ParentId": "19061",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "36097",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T13:36:35.487",
"Id": "19061",
"Score": "5",
"Tags": [
"beginner",
"google-apps-script"
],
"Title": "Checking site uptime with Google Docs"
}
|
19061
|
<p>Related:</p>
<p><a href="https://codereview.stackexchange.com/questions/18986/please-review-assembly-for-nios-2-interrupts">Nios 2 interrupt handler</a></p>
<pre><code>/*
* Main C program for nios2int 2012-10-31
* Assignment 6: Interrupts from
* timer_1 and de2_pio_keys4
*/
/* Include header file for alt_irq_register() */
#include "alt_irq.h"
/* Define the null pointer */
#define NULL_POINTER ( (void *) 0)
/* Define address for de2_pio_redled18 */
volatile int * const de2_pio_redled18_base = (volatile int *) 0x810;
/* The above means:
*
* de2_pio_redled18_base is a pointer variable.
* The pointer is allowed to point to a volatile int.
*
* The keyword "volatile" means that this int must be read (with a load
* instruction) every time the C program reads it, and written
* (with a store instruction) every time the C program writes to it.
* So the keyword "volatile" forbids the compiler to re-use old values
* of the int. Re-using old values, instead of reading them again from memory,
* is a very common optimization that the compiler can perform.
*
* We initialize the pointer to 0x810.
* 0x810 is an integer value, and not a pointer, so we must use a
* type-cast to tell the compiler that we really know what we are doing.
* The type-cast is the type-specification in parentheses.
* The type in the cast must be the same as the type of de2_pio_redled18_base.
*
* The keyword "const" means that we are not allowed to change this variable.
* The C compiler will give an error message if we write C code that tries
* to change a const. This can help you catch some common typing-mistakes.
*
* The "const" keyword has been placed very carefully. We can not change
* the pointer-variable itself, but we can change whatever value that
* the pointer-variable points to. So we can write to address 0x810
* without any error-messages from the compiler, but we cannot change
* de2_pio_redled18_base to point to something else.
*
* Note: the "volatile" keyword has also been placed very carefully, so that
* it is the int that becomes volatile and not something else.
*/
/* Define addresses etc for de2_pio_keys4 */
volatile int * const de2_pio_keys4_base = (volatile int *) 0x840;
volatile int * const de2_pio_keys4_intmask = (volatile int *) 0x848;
volatile int * const de2_pio_keys4_edgecap = (volatile int *) 0x84c;
const int de2_pio_keys4_intindex = 2;
const int de2_pio_keys4_irqbit = 1 << 2;
/* de2_pio_keys4_irqbit
* is a bit-mask with a 1 in the bit with index 2 */
/* Define addresses etc for de2_pio_toggles18 */
volatile int * const de2_pio_toggles18_base = (volatile int *) 0x850;
volatile int * const de2_pio_toggles18_intmask = (volatile int *) 0x858;
volatile int * const de2_pio_toggles18_edgecap = (volatile int *) 0x85c;
const int de2_pio_toggles18_intindex = 3;
const int de2_pio_toggles18_irqbit = 1 << 3;
/* de2_pio_toggles18_irqbit
* is a bit-mask with a 1 in the bit with index 3 */
/* Define addresses etc for timer_1 */
volatile int * const timer_1_base = (volatile int *) 0x920;
volatile int * const timer_1_status = (volatile int *) 0x920; /* same as base */
volatile int * const timer_1_control = (volatile int *) 0x924;
volatile int * const timer_1_period_low = (volatile int *) 0x928;
volatile int * const timer_1_period_high = (volatile int *) 0x92c;
volatile int * const timer_1_snaplow = (volatile int *) 0x930;
volatile int * const timer_1_snaphigh = (volatile int *) 0x934;
const int timer_1_intindex = 10;
const int timer_1_irqbit = 1 << 10;
/* timer_1_irqbit
* is a bit-mask with a 1 in the bit with index 10 */
/* Define address for de2_pio_hex_low28 */
volatile int * de2_pio_hex_low28 = (volatile int *) 0x9f0;
/* Define address for de2_pio_greenled9 */
volatile int * de2_pio_greenled9 = (volatile int *) 0xa10;
/* Define address for de2_uart_0 */
#define UART_0 ( (volatile int *) 0x860 )
/* Delay parameter for somedelay() */
#define DELAYPARAM (65535)
/* Delay parameter for bigdelay() */
#define BIGDELAYPARAM (33)
/*
* Define timeout count for timer_1
* Use 4999999 for the simulator (six 9's - 0.1 seconds),
* but 49999999 for the hardware (seven 9's - 1.0 seconds ).
*/
#define TIMER_1_TIMEOUT (4999999)
/* Define global variables. They are declared volatile,
* since they are modified by interrupt handlers. */
volatile int mytime = 0x5957; /* Time display */
volatile int myleds = 0; /* Green LEDs (local copy) */
/* Declare those functions that are defined in other files. */
int initfix_int( void ); /* in initfix_int.c */
void puttime( volatile int * ); /* in puttime_uart_0.c */
void tick ( volatile int * ); /* in your file tick.s */
//volatile int * irq_handler_toggles;
void out_char_uart_0( int c )
{
/* Wait until transmitter is ready */
while( (UART_0[2] & 0x40) == 0 );
/* Now send character */
UART_0[1] = c & 0xff;
}
/* This simple subroutine stalls
* execution for a short while. */
void somedelay( void )
{
int i = DELAYPARAM;
while( (i = i - 1) > 0);
}
/* This simple subroutine stalls
* execution for a long while. */
void bigdelay( void )
{
int j = BIGDELAYPARAM;
while( (j = j - 1) > 0) somedelay();
}
/*
* The n2_fatal_error function is called for unexpected
* conditions which most likely indicate a programming error
* somewhere in this file. The function prints "FATAL ERROR"
* using out_char_uart_0, lights an "Err" pattern on the
* seven-segment display, and then enters an infinite loop.
*/
void n2_fatal_error()
{
/* Define the pattern to be sent to the seven-segment display. */
#define N2_FATAL_ERROR_HEX_PATTERN ( 0xcbd7ff )
/* Define error message text to be printed. */
static const char n2_fatal_error_text[] = "FATAL ERROR";
/* Define pointer for pointing into the error message text. */
register const char * cp = n2_fatal_error_text;
/* Send pattern to seven-segment display. */
*de2_pio_hex_low28 = N2_FATAL_ERROR_HEX_PATTERN;
/* Print the error message. */
while( *cp )
{
out_char_uart_0( *cp );
cp = cp + 1;
}
/* Stop and wait forever. */
while( 1 );
}
/*
* Interrupt handler for de2_pio_keys4.
* The parameters are ignored here, but are
* required for correct compilation.
* The type alt_u32 is an Altera-defined
* unsigned integer type.
*
* To help debugging interruptible interrupt-handlers,
* this handler delays a long while when a key is pressed.
* However, there is no delay when the key is released.
*
* We keep a software copy of the LED value, since
* the parallel output ports are not program-readable.
*
* Example: we send out the value 1 on de2_pio_keys4,
* by executing *DE2_PIO_KEYS4_BASE = 1;
* Then we try to read the port by executing
* int test_val = *DE2_PIO_KEYS4_BASE; // WRONG
* The value of test_val is now undefined.
* The port returns some bits which are not related
* to the value we have written.
*
* The software copy of the LED value
* for this interrupt handler
* is the global variable myleds, defined above.
*/
void irq_handler_keys( void * context, alt_u32 irqnum )
{
alt_u32 save_value;
save_value = alt_irq_interruptible( de2_pio_keys4_intindex );
/* Read edge capture register of the de2_pio_keys4 device. */
int edges = *de2_pio_keys4_edgecap;
/* Clear edge capture register - writing
* any value clears all bits. */
*de2_pio_keys4_edgecap = 0;
/* If action on KEY0 */
if( edges & 1 )
{
/* If KEY0 is pressed now */
if( (*de2_pio_keys4_base & 1) == 0 )
{
/* Turn on green LED LEDG0
* in software copy of LED bits. */
myleds = myleds | 1;
/* Copy software LED bits to actual LEDs. */
*de2_pio_greenled9 = myleds;
/* Print an upper-case 'D' using out_char_uart_0. */
out_char_uart_0( 'D' );
/* Wait a long while */
bigdelay();
/* Print a lower-case 'd' using out_char_uart_0. */
out_char_uart_0( 'd' );
}
/* If KEY0 is released now */
else if( (*de2_pio_keys4_base & 1) != 0 )
{
/* Turn off green LED LEDG0
* in software copy of LED bits. */
myleds = myleds & 0xffffe;
/* Print an 'U' using out_char_uart_0. */
out_char_uart_0( 'U' );
/* Copy software LED bits to actual LEDs. */
*de2_pio_greenled9 = myleds;
}
alt_irq_non_interruptible( save_value );
}
}
/*
* Initialize de2_pio_keys4 for interrupts.
*/
void keysinit_int( void )
{
/* Declare a temporary for checking return values
* from system-calls and library functions. */
register int ret_val_check;
/* Allow interrupts from KEY0 only. */
*de2_pio_keys4_intmask = 1;
/* Set up Altera's interrupt wrapper for
* interrupts from the de2_pio_keys4 device.
* The function alt_irq_register will enable
* interrupts from de2_pio_keys4.
* Return value is zero for success,
* nonzero for failure. */
ret_val_check = alt_irq_register( de2_pio_keys4_intindex,
NULL_POINTER,
irq_handler_keys );
/* If there was an error, terminate the program. */
if( ret_val_check != 0 ) n2_fatal_error();
}
/*
* Interrupt handler for timer_1.
* The parameters are ignored here, but are
* required for correct compilation.
* The type alt_u32 is an Altera-defined
* unsigned integer type.
*/
void irq_handler_timer_1( void * context, alt_u32 irqnum )
{
alt_u32 save_value;
save_value = alt_irq_interruptible( timer_1_intindex );
*timer_1_status = 0; /* Acknowledge interrupt */
tick( &mytime );
puttime( &mytime );
out_char_uart_0( '\n' );
alt_irq_non_interruptible( save_value );
}
/*
* Initialize timer_1 for regular interrupts,
* once every timeout period.
* The timeout period is defined above,
* see definition of TIMER_1_TIMEOUT
*/
void timerinit_int( void )
{
/* Declare a local temporary variable
* for checking return values
* from system-calls and library functions. */
register int ret_val_check;
*timer_1_period_low = TIMER_1_TIMEOUT & 0xffff;
*timer_1_period_high = TIMER_1_TIMEOUT >> 16;
*timer_1_control = 7;
/* START bit (must always be a 1)
* CONT bit (timer restarts on timeout)
* ITO bit (interrupt on timeout) */
/* Set up Altera's interrupt wrapper for
* interrupts from the timer_1 device.
* Return value is zero for success,
* nonzero for failure. */
ret_val_check = alt_irq_register( timer_1_intindex,
NULL_POINTER,
irq_handler_timer_1 );
/* If there was an error, terminate the program. */
if( ret_val_check != 0 ) n2_fatal_error();
}
void irq_handler_toggles( void * context, alt_u32 irqnum )
{
alt_u32 save_value;
save_value = alt_irq_interruptible( de2_pio_toggles18_intindex );
out_char_uart_0((int) 'S'); //castar char code för S till funktionen.
*de2_pio_redled18_base = 0x0001;
bigdelay();
*de2_pio_redled18_base = 0x0000;
out_char_uart_0((int) 's');
*de2_pio_toggles18_edgecap = 0x0001; /* Acknowledge interrupt */
alt_irq_non_interruptible( save_value );
}
//void (* irq_handler_toggles) (void);
void toggles_init()
{
int check_value;
*de2_pio_toggles18_intmask = 0x0001; //enable toggle0 only
check_value = alt_irq_register( de2_pio_toggles18_intindex, NULL_POINTER, irq_handler_toggles );
if( check_value != 0 ) n2_fatal_error(); /* Change this to code for handling the error. */
}
int main()
{
/* Remove unwanted interrupts.
* initfix_int is supplied by KTH.
* A nonzero return value indicates failure. */
if( initfix_int() != 0 ) n2_fatal_error();
/* Initialize de2_pio_keys4 for
* interrupts. */
keysinit_int();
/* Initialize timer_1 for
* continuous timeout interrupts. */
timerinit_int();
toggles_init();
/* Loop forever. */
while( 1 )
{
out_char_uart_0('_'); /* print an underscore */
/* Programmed delay between underscores.
* Defined earlier in this file. */
somedelay();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-12T09:50:03.760",
"Id": "31260",
"Score": "1",
"body": "It doesn't make sense to declare registers as int, they should be unsigned int, or even better, uint32_t."
}
] |
[
{
"body": "<p>Nick, the code looks very clean and well organised. Nice on the eye.</p>\n\n<p>General comments:</p>\n\n<ul>\n<li><p>make local functions <code>static</code></p></li>\n<li><p>Comment noise. Many comments make the code worse by imparting no useful\ninformation. Your assignment doubtless requires that you comment your code,\nbut you also need to learn what not to write. Check with your supervisor\nbefore wholesale deletion of comments - which could loose you points.\nExamples of noise (there are many, many more):</p>\n\n<ul>\n<li><p>describing the meaning of 'volatile', 'const' etc should not be\nnecessary.</p></li>\n<li><p><code>de2_pio_keys4_irqbit is a bit-mask with a 1 in the bit with index 2</code> etc</p></li>\n<li><p><code>Define address for ...</code> etc</p></li>\n</ul></li>\n<li><p>also, many comments are wrapped at colum 50 or less. Let them extend to 80\n(but no further)</p></li>\n<li><p>delete all commented-out code</p></li>\n<li><p>functions defined in other files should have prototypes in a header shared\nby both files (unless defined in assembler).</p></li>\n<li><p>using <code>register</code> is generally pointless. The compiler has a better idea of\nwhat needs to go in a register than you.</p></li>\n<li><p>embedded constants are bad practice. You should normally define them\ntogether (or with the registers they apply to) using #define</p></li>\n</ul>\n\n<p>Detailed points:</p>\n\n<ul>\n<li><p>NULL_POINTER seems unnecessary. Just use 0</p></li>\n<li><p>all of your machine registers are defined as <code>volatile int</code> but for many, an\nunsigned type looks more applicable (those which do not hold a numeric\nvalue, such as bitmasks).</p></li>\n<li><p>why is UART_0 defined with a #define but all other registers use a const int\npointer?</p></li>\n<li><p>consider an alternative method of register access. In your method, all\naccess is through a pointer: <code>*de2_pio_keys4_edgecap = 0;</code> and <code>if(\n(*de2_pio_keys4_base & 1) == 0 )</code> </p>\n\n<p>In a small program like this it might be overkill, but it can be worth\nwrapping register access to avoid direct use of pointers:</p>\n\n<pre><code>static inline void clear_edgecap(void) \n{\n *de2_pio_keys4_edgecap = 0; \n}\n\nstatic inline int key0_is_pressed(void)\n{\n return (*de2_pio_keys4_base & 1) == 0;\n}\n</code></pre>\n\n<p>then the function calls are self-explanatory </p>\n\n<pre><code>clear_edgecap();\nif (key0_is_pressed()) {...}\n</code></pre>\n\n<p>Note that the functions are inline and so there is likely to be zero\noverhead. </p></li>\n<li><p>why not pass <code>char</code> to <code>out_char_uart_0</code> instead of <code>int</code> ?</p></li>\n<li><p>busy-looping in <code>out_char_uart_0</code> (and delay functions) would normally be a\nbad idea, but in the context of your project is perhaps necessary (I assume\nyou have no OS). I'd prefer to see the loop made clear with braces:</p>\n\n<pre><code> while ((UART_0[2] & UART_XMIT_READY) == 0) {\n /* Wait until transmitter is ready */\n }\n</code></pre>\n\n<p>note the #defined constant instead of 0x40</p></li>\n<li><p>delay functions:</p>\n\n<pre><code>int i = ...;\nwhile (--i > 0) {\n /* busy loop */\n}\n</code></pre></li>\n<li><p>in <code>n2_fatal_error</code>, N2_FATAL_ERROR_HEX_PATTERN might be better defined with\nother #defines (if there are others relating to the 7-seg display).</p></li>\n<li><p>printing of error message uses a loop calling <code>out_char_uart_0</code>. This\nmight be better as a simple function, <code>out_string_uart_0</code></p></li>\n<li><p><code>cp = cp + 1</code> is normally written <code>++cp</code></p></li>\n</ul>\n\n<p>In <code>irq_handler_keys</code></p>\n\n<ul>\n<li><p>function is heavily over-commented. Nearly all the comments are just noise.</p></li>\n<li><p>assign a value immediately:</p>\n\n<pre><code>alt_u32 save_value = alt_irq_interruptible(...);\n</code></pre></li>\n<li><p><code>de2_pio_keys4_base</code> is interrogated twice</p></li>\n<li><p>the saved value is restored only if the <code>edges & 1</code> branch was taken - is\nthis correct?</p></li>\n<li><p>for unused parameters, you can use a void cast to 'use' them and keep\nthe compiler from complaining.</p>\n\n<pre><code>(void) context;\n(void) irqnum;\n</code></pre></li>\n</ul>\n\n<p>In <code>keysinit_int</code>:</p>\n\n<ul>\n<li><p>I would use 'irq' rather than 'int' as an abbreviation for an interrupt\n(request)</p></li>\n<li><p>over-commented again. <code>Declare a temporary for checking ...</code> what use is\nthat to anybody?</p></li>\n<li><p>The comment on the <code>alt_irq_register</code> call should be\non the function declaration, not the call. The function name is poorly\nchosen as it gives the reader no idea of its purpose. Maybe <code>enable_altera_irq</code></p></li>\n<li><p><code>ret_val_check</code> is verbose: <code>ret</code> would suffice, but here you don't even\nneed a variable: </p>\n\n<pre><code> if (alt_irq_register(de2_pio_keys4_intindex, 0, irq_handler_keys) != 0) {\n n2_fatal_error();\n }\n</code></pre></li>\n</ul>\n\n<p>In <code>irq_handler_timer_1</code></p>\n\n<ul>\n<li>the function header would be better used to say the purpose of the function\n(briefly!)</li>\n</ul>\n\n<p>In <code>toggles_init</code></p>\n\n<ul>\n<li><p>here you use the name <code>check_value</code> instead of <code>ret_val_check</code>. Better to be\nconsistent. But note that the variable is not necessary (see above).</p></li>\n<li><p>need (void) parameter list</p></li>\n</ul>\n\n<p>In <code>main</code></p>\n\n<ul>\n<li>need (void) parameter list.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T20:05:11.117",
"Id": "19196",
"ParentId": "19065",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "19196",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T14:38:53.297",
"Id": "19065",
"Score": "0",
"Tags": [
"c",
"homework",
"embedded"
],
"Title": "C for Nios-2 IRQ handling"
}
|
19065
|
<p>I am trying to find all "link" elements that link to RSS feeds in a data structure created by clj-tagsoup. I wrote the following code, which seems to work fine. But: I come from a Java background and I am new to functional programming and clojure, so I am not sure if this is the right way to do it. Could you please give me some hints about what I could improve in the following code:</p>
<pre><code>(defn- matches-attributes [current-attributes required-attributes]
(reduce #(and %1 (= (second %2) ((first %2) current-attributes)))
true
required-attributes))
(defn- find-tag [tag-name current-tag attributes]
(if (= tag-name (tagsoup/tag current-tag))
current-tag
(filter #(and (= tag-name (tagsoup/tag %1))
(matches-attributes (tagsoup/attributes %1) attributes))
(tagsoup/children current-tag))))
(defn- find-rss-feed [page-result]
(let [document (tagsoup/parse-string (:body page-result))
head (first (find-tag :head document nil))
rss-links (if (nil? head)
nil
(find-tag :link head {:type "application/rss+xml"}))]
... do something with rss-links...))
</code></pre>
<p><strong>Edit</strong> To clarify a bit, what I am particularily interested in is if traversing the HTML tree the way I do it is the "right" was in a functional language. What I'm also interested in is if "filter" and "reduce" are a good choice as I use them, or if there is a better way. And, of course, I'd also appreciate general hints about what I could do better in this little program...</p>
|
[] |
[
{
"body": "<p>It's not bad, but we can make it a bit more idiomatic. Let's look at this function first:</p>\n\n<pre><code>(defn- matches-attributes [current-attributes required-attributes]\n (reduce #(and %1 (= (second %2) ((first %2) current-attributes)))\n true \n required-attributes))\n</code></pre>\n\n<p>The use of reduce is a bit odd, instead let's use every? Secondly, if current-attributes is a hash map or a set, then we can actually use it as a function. Since every? takes a predicate, we can rewrite the entire function as:</p>\n\n<pre><code>(defn- matches-attributes [current-attributes required-attributes]\n (every? (fn [tv tg] \n (= (current-attributes tg) tv))\n required-attributes))\n</code></pre>\n\n<p>On the last function, when-let will help you clean it up a bit more: </p>\n\n<pre><code>(defn- find-rss-feed [page-result]\n (let [document (tagsoup/parse-string (:body page-result))\n rss-links (when-let [head (first (find-tag :head document nil))]\n (find-tag :link head {:type \"application/rss+xml\"}))]\n ... do something with rss-links...))\n</code></pre>\n\n<p>Hopefully this helps a bit. Your code doesn't really support this, but the cool thing to remember is that Clojure collections are functions that return nil if the item doesn't exist. So for example:</p>\n\n<pre><code>=> (remove #{1 2 3} [1 2 3 4 5 6 7])\n(4 5 6 7)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T16:21:00.127",
"Id": "19072",
"ParentId": "19066",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "19072",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T15:32:29.870",
"Id": "19066",
"Score": "2",
"Tags": [
"clojure"
],
"Title": "Clojure: Find specific element in HTML tree"
}
|
19066
|
<p><a href="http://projecteuler.net/problem=83" rel="nofollow">Project Euler problem 83</a> asks:</p>
<blockquote>
<p>In the 5 by 5 matrix below,</p>
<pre><code>131 673 234 103 18
201 96 342 965 150
630 803 746 422 111
537 699 497 121 956
805 732 524 37 331
</code></pre>
<p>the minimal path sum from the top left to the bottom right, by moving left, right, up, and down, is</p>
<pre><code>131 → 201 → 96 → 342 → 234 → 103 → 18 → 150 → 111 → 422 → 121 → 37 → 331
</code></pre>
<p>and is equal to 2297.</p>
<p>Find the minimal path sum, in <a href="http://projecteuler.net/project/matrix.txt" rel="nofollow"><code>matrix.txt</code></a> (right click and 'Save
Link/Target As...'), a 31K text file containing a 80 by 80 matrix,
from the top left to the bottom right by only moving right and down.</p>
</blockquote>
<p>I have solved the project euler problem 83 using uniform cost search. This solution takes about 0.6s to solve. I want to know if anyone can get the code to run relatively faster without changing the general outline of the program.</p>
<pre><code>import bisect
f = open('matrix.txt')
matrix = [[int(i) for i in j.split(',')] for j in f]
def uniformCostSearch(startNode):
frontier = []
frontier.append(startNode)
closedSet = set()
while not len(frontier) == 0:
currentNode = frontier.pop(0)
if currentNode.x == 79 and currentNode.y == 79:
return currentNode.priority
else:
if not (currentNode.x, currentNode.y) in closedSet:
closedSet.add((currentNode.x, currentNode.y))
possibleMoves = currentNode.neighbors()
for move in possibleMoves:
if not (move.x, move.y) in closedSet:
try:
index = frontier.index(move)
if move.priority < frontier[index].priority:
frontier.pop(index)
bisect.insort_left(frontier, move)
except ValueError:
# move is not in frontier so just add it
bisect.insort_left(frontier, move)
return -1
class Node:
def __init__(self, x, y, priority=0):
self.x = x
self.y = y
self.priority = priority
def neighbors(self):
tmp = [Node(self.x + 1, self.y), Node(self.x, self.y + 1),
Node(self.x - 1, self.y), Node(self.x, self.y - 1),]
childNodes = []
for node in tmp:
if node.x >= 0 and node.y >= 0 and node.x <= 79 and node.y <= 79:
node.priority = self.priority + matrix[node.y][node.x]
childNodes.append(node)
return childNodes
def __eq__(self, node):
return self.x == node.x and self.y == node.y
def __ne__(self, node):
return not self.x == node.x and self.y == node.y
def __cmp__(self, node):
if self.priority < node.priority:
return -1
elif self.priority > node.priority:
return 1
else:
return 0
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T16:40:09.433",
"Id": "30452",
"Score": "2",
"body": "Why not use a classical Dijkstra?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T18:23:12.257",
"Id": "30457",
"Score": "0",
"body": "I turned the matrix into a graph and used a shortest path algorithm for this problem which got me the solution in 0.069s. I'll take a look through yours though and see if I can optimize it in anyway."
}
] |
[
{
"body": "<pre><code>import bisect\nf = open('matrix.txt')\nmatrix = [[int(i) for i in j.split(',')] for j in f]\n</code></pre>\n\n<p>You could consider using the numpy library, it'll handle multidimensional arrays more neatly and efficiently.</p>\n\n<pre><code>def uniformCostSearch(startNode):\n</code></pre>\n\n<p>Python convention is to use underscore_with_letters for function names and parameters</p>\n\n<pre><code> frontier = []\n frontier.append(startNode)\n</code></pre>\n\n<p>Use <code>frontier = [startNode]</code>, it'll be a touch faster</p>\n\n<pre><code> closedSet = set()\n while not len(frontier) == 0:\n</code></pre>\n\n<p>Use <code>while frontier:</code>, it does the same thing and due to less operations is going to be a bit faster. You should at least use <code>!=</code> rather then <code>not ==</code> </p>\n\n<pre><code> currentNode = frontier.pop(0)\n</code></pre>\n\n<p>Popping from the front of a list will be inefficient. Actually, what you really want is a priority queue, see python's deque module. </p>\n\n<pre><code> if currentNode.x == 79 and currentNode.y == 79:\n return currentNode.priority\n else:\n if not (currentNode.x, currentNode.y) in closedSet:\n</code></pre>\n\n<p>Move the <code>not</code> over next to <code>in</code> I think it reads clearer. I might also use a 2D array of bools rather then a set here.</p>\n\n<pre><code> closedSet.add((currentNode.x, currentNode.y))\n</code></pre>\n\n<p>There isn't really any reason to check if the node is in the set here, you can add the node multiple times. Just add it unconditionally.</p>\n\n<pre><code> possibleMoves = currentNode.neighbors()\n for move in possibleMoves:\n</code></pre>\n\n<p>No reason to store it in a local, just combine the previous two lines</p>\n\n<pre><code> if not (move.x, move.y) in closedSet:\n try:\n index = frontier.index(move)\n if move.priority < frontier[index].priority:\n frontier.pop(index)\n bisect.insort_left(frontier, move)\n</code></pre>\n\n<p>Move the last three lines into an else block. That'll make sure only your index line can actually throw things that'll get caught.</p>\n\n<pre><code> except ValueError:\n # move is not in frontier so just add it\n bisect.insort_left(frontier, move)\n</code></pre>\n\n<p>You do this in either case, I'd move it after the try/except block.\n return -1</p>\n\n<pre><code>class Node:\n def __init__(self, x, y, priority=0):\n self.x = x\n self.y = y\n self.priority = priority\n\n def neighbors(self):\n tmp = [Node(self.x + 1, self.y), Node(self.x, self.y + 1),\n Node(self.x - 1, self.y), Node(self.x, self.y - 1),]\n childNodes = []\n for node in tmp:\n if node.x >= 0 and node.y >= 0 and node.x <= 79 and node.y <= 79:\n</code></pre>\n\n<p>I suggest moving 79 into a constant. I'd also do <code>< 80</code> rather then <code><= 79</code>.</p>\n\n<pre><code> node.priority = self.priority + matrix[node.y][node.x]\n childNodes.append(node)\n</code></pre>\n\n<p>I'd use a yield here, and make this a generator</p>\n\n<pre><code> return childNodes\n\n def __eq__(self, node):\n return self.x == node.x and self.y == node.y\n</code></pre>\n\n<p>This bothers me because multiple nodes will compare equal despite having different priorities. </p>\n\n<pre><code> def __ne__(self, node):\n return not self.x == node.x and self.y == node.y\n\n def __cmp__(self, node):\n if self.priority < node.priority:\n return -1\n elif self.priority > node.priority:\n return 1\n else:\n return 0\n</code></pre>\n\n<p>This really bothers me because you aren't defining your comparisons in a consistent way. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T18:38:46.350",
"Id": "19079",
"ParentId": "19068",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T15:57:55.223",
"Id": "19068",
"Score": "2",
"Tags": [
"python",
"optimization",
"algorithm",
"project-euler"
],
"Title": "optimizing project euler #83 solution"
}
|
19068
|
<p>I have the following methods in <code>CacheUtil</code> class</p>
<pre><code>public void addCacheEntry(String key, Serializable entry) {
//add to cache
}
public void removeCacheEntry(String key) {
//remove from cache
}
public Serializable getCacheEntry(String key) {
Serializable entry = // get from cache
return entry;
}
</code></pre>
<p>And in the class where I use the cache, I have the following methods,</p>
<pre><code>public List<String> fetchList() {
List<String> aList = (List<String>) CacheUtil.getInstance().getCacheEntry("aList"); //IDE warns of unchecked casting
if(aList == null) {
aList = fetchFromDB():
CacheUtil.getInstance().addCacheEntry("aList", new ArrayList<String>(aList));
}
}
</code></pre>
<p>How could I have avoided the warning of unchecked cast? I can not change the methods in cache to store lists explicitly, as I want to store anything that is serializable in cache and that is just a library.</p>
<p>I believe there is a better way to do it.</p>
|
[] |
[
{
"body": "<p>You could change your CacheUtil class to the following:</p>\n\n<pre><code>public class CacheUtil {\n ...\n public void addCacheEntry(String key, Serializable entry) {\n //add to cache\n }\n\n public void removeCacheEntry(String key) {\n //remove from cache\n }\n\n public <T extends Serializable> T getCacheEntry(String key) {\n T entry = // get from cache (probably needs a cast to T)\n return entry;\n }\n}\n</code></pre>\n\n<p>which would allow you to get cached entries by type T without a cast:</p>\n\n<pre><code> public List<String> fetchList() {\n ArrayList<String> aList = CacheUtil.getInstance().getCacheEntry(\"aList\");\n if(aList == null) {\n aList = fetchFromDB():\n CacheUtil.getInstance().addCacheEntry(\"aList\", new ArrayList<String>(aList));\n }\n }\n</code></pre>\n\n<p>Notice that I was required to use ArrayList, because List is not Serializable on its own. You could take this one step farther and have getCacheEntry() return T without extends:</p>\n\n<pre><code> public <T> T getCacheEntry(String key) {\n T entry = // get from cache (may need a cast)\n return entry;\n }\n</code></pre>\n\n<p>But Im not sure I'd take that leap.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T03:51:18.617",
"Id": "30512",
"Score": "0",
"body": "Hi @johncari, thanks for the suggestion. Changing the method signature in CacheUtil to <T extends Serializable>, moves the unchecked cast warning to CacheUtil class (when casting entry to T). Is there anyway i can avoid that too? That warning is not bad?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T15:58:37.293",
"Id": "30542",
"Score": "0",
"body": "You could add this to the method to avoid the warning: @SuppressWarnings(\"unchecked\")"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-19T04:16:26.057",
"Id": "109432",
"Score": "0",
"body": "@SenthilKumar By moving the cast elsewhere and adding SuppressWarnings you wan't improve it. There are two problems: 1. You need `class CacheUtil<T extends Serializable>` so you can create type-safe caches (look at `List` or any such collection). 2. And then you can't use `CacheUtil.getInstance()`, which is a good thing as such a static method prevents you from using multiple caches."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T17:04:11.903",
"Id": "19074",
"ParentId": "19070",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "19074",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T16:16:50.613",
"Id": "19070",
"Score": "0",
"Tags": [
"java",
"cache"
],
"Title": "What is the better way to retrieve value from this cache implementaion?"
}
|
19070
|
<p>I needed to publish a message across the ESB (MassTransit) that will return a different type of object depending on how the message is processed. I wanted to implement this in a generic way so I could wire up other services with similar requirements in the same way.</p>
<p><strong>Publish a request</strong></p>
<pre><code>public IGenericResponse<TPayload> PublishRequest<TMessage, TPayload>(TMessage message, Type[] potentialResponseTypes)
where TMessage : class
{
IGenericResponse<TPayload> commandResult = null;
_bus.PublishRequest(message, c =>
{
foreach (Type responseType in potentialResponseTypes)
{
Type genericHandler = typeof(GenericHandler<,>).MakeGenericType(new[]{ responseType, typeof(TMessage)});
var handler = new Action<object>(result =>
{
commandResult = (IGenericResponse<TPayload>) result;
});
Activator.CreateInstance(genericHandler, new object[] {c, handler});
}
c.SetTimeout(10.Seconds());
});
return commandResult;
}
</code></pre>
<p><strong>Generic Handler to wire it up</strong></p>
<pre><code>internal class GenericHandler<TPayload, TMessage>
where TMessage : class
where TPayload : class
{
public GenericHandler(InlineRequestConfigurator<TMessage> configurator, Action<object> handler)
{
configurator.Handle<GenericResponse<TPayload>>(handler);
}
}
</code></pre>
<p>Thoughts?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-02T20:38:40.333",
"Id": "118232",
"Score": "0",
"body": "What type is the c variable you get when you publish a request? Is this your response? If so there's a much simpler solution that needs *way* less reflection."
}
] |
[
{
"body": "<p>It's possible, providing <code>c</code> is your response from the bus, to do a lot of this without needing Reflection. Instead we can use a separate method and the joys of implicit typing to work out the type of TResponse for us.</p>\n\n<p><strong>Proposed solution</strong></p>\n\n<pre><code>public IGenericResponse<TPayload> PublishRequest<TMessage, TPayload>(TMessage message, Type[] potentialResponseTypes)\n where TMessage : class\n{\n IGenericResponse<TPayload> commandResult = null;\n\n _bus.PublishRequest(message, response =>\n {\n foreach (Type responseType in potentialResponseTypes)\n {\n var genericHandler = CreateHandler(response, message);\n }\n\n c.SetTimeout(10.Seconds());\n });\n\n return commandResult;\n}\n\nprivate GenericHandler<TResponse, TMessage> CreateHandler<TResponse,TMessage>(TResponse response, TMessage message)\n{\n var handler = new Action<object>(result =>\n {\n commandResult = (IGenericResponse<TPayload>) result;\n });\n return new GenericHandler<TResponse, TMessage>(response, handler);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-02T20:46:11.190",
"Id": "64594",
"ParentId": "19071",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T17:04:18.037",
"Id": "19071",
"Score": "3",
"Tags": [
"c#"
],
"Title": "Handling multiple MassTransit response types"
}
|
19071
|
<p>My goal is to simulate a <a href="http://en.wikipedia.org/wiki/Shuffling#Pile_shuffle" rel="nofollow">Pile shuffle</a> of a vector. It takes 2 optional arguments for the number of piles to use and how many times to perform the shuffle.</p>
<p>As this is my first attempt at clojure code, I'm fairly sure I'm doing something terribly wrong here. I'm concerned with speed, efficiency, and indentation style. I'd also appreciate any pointers that would make this function more generic (maybe not restricting to vectors, but general collections).</p>
<pre><code>(defn pile
([cards] (pile cards 3 1))
([cards num_piles] (pile cards num_piles 1))
([cards num_piles times]
(loop [i 1
piles (transient (vec (map (fn [p] []) (range num_piles))))
the_pile 0]
(if (<= i (count cards))
(recur (inc i)
(assoc!
piles
the_pile
(vec (concat [(nth cards (dec i))]
(nth piles the_pile))))
(rem i num_piles))
(if (> times 1)
(pile (reduce into (persistent! piles)) num_piles (dec times) )
(vec (reduce into (persistent! piles))))))))
</code></pre>
|
[] |
[
{
"body": "<p>You need loop/recur very rarely in most code, and almost never for operating on collections/sequences. Using the standard library sequence functions, it’s possible to do the main pile shuffle with just a handful of expressions:</p>\n\n<pre><code>(->> (range (dec n) -1 -1) (mapcat #(take-nth n (drop % cards))) reverse)\n</code></pre>\n\n<p>It takes some getting used to, and familiarity with the Clojure standard library. When I was first getting started, I found it immensely helpful to read the clojure/core.clj code. It isn’t all idiomatic because it’s building the support for the idioms as it goes, but it demonstrates what Clojure makes possible and <em>how</em> it makes those things possible.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T17:44:36.283",
"Id": "19077",
"ParentId": "19073",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T16:49:53.247",
"Id": "19073",
"Score": "5",
"Tags": [
"performance",
"functional-programming",
"lisp",
"clojure",
"shuffle"
],
"Title": "Pile shuffle of a vector"
}
|
19073
|
<p>When you click open - a div slides out. If you click on the new div, an additional div slides out from under it. This is working great, but I need two things that I cant figure out!</p>
<ol>
<li><p>How can I condense the jQuery so I don't have to add a class to it every time I want a new slider? Is it possible to do a <code>.sibling</code> kind of thing, or something like <a href="http://jsfiddle.net/rs2QK/982/" rel="nofollow">this</a>?</p></li>
<li><p>I've tried making a close button, but I cannot get it to work the way I want. When you click close, I want the bottom div to close first, then the slide out div to close. And this button would need to work even if only one div is open.</p></li>
</ol>
<p><a href="http://jsfiddle.net/avXSd/67/" rel="nofollow">jsFiddle</a></p>
<pre><code>$(document).ready(function() {
$('.cambridge').hide();
$("#test").click(function () {
$(".cambridge").toggle("slide", { direction: "right" }, 1000);
});
$('.shopping').hide();
$("#test2").click(function () {
$(".shopping").toggle("slide", { direction: "up" }, 1000);
});
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T19:16:09.867",
"Id": "30461",
"Score": "0",
"body": "I figured out the second part! \n\nNow if you hit the close button, the bottom slider closes first, then the main slider closes second. \n http://jsfiddle.net/avXSd/78/\n\nI still think there is a way to condense this function so that I don't have to edit it every time I want to add a new div. Any thoughts?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-13T10:53:53.103",
"Id": "234283",
"Score": "0",
"body": "I don't understand your first question. What Css Class are you talking about? i don't see you're adding any class. \n\nRegarding the second question, you can use the complete callback function on the toggle fn.\n\n`// That's the second question\n $('#showmap').click(function() {\n $(\".shopping\").toggle(\"slide\", { direction: \"up\" }, 1000, function () {\n $(\".cambridge\").toggle(\"slide\", { direction: \"right\" }, 1000);\n });\n });`"
}
] |
[
{
"body": "<p>A quick review:</p>\n\n<p><strong>JSHint.com</strong></p>\n\n<ul>\n<li>Your code passes all checks, well done</li>\n</ul>\n\n<p><strong>Naming</strong></p>\n\n<ul>\n<li><code>test</code> and <code>test2</code> are unfortunate names for elements, I am sure you can come up with something better</li>\n</ul>\n\n<p><strong>Counter Proposal</strong></p>\n\n<p>Looking at the code, there is definitely repetition in making those sliders, you can extract what is common in to a function, and then use that function for any future sliders:</p>\n\n<p>(This is blatantly stolen/modified from the deleted answer):</p>\n\n<pre><code>$(document).ready(function() {\n\n function registerSlider( buttonId, sliderClass, direction){\n $(sliderClass).hide(); \n $(buttonId).click(function () {\n $(sliderClass).toggle(\"slide\", { direction: direction }, 1000);\n });\n } \n registerSlider(\"#test\", '.cambridge', 'right' );\n registerSlider(\"#test2\", '.shopping', 'up' );\n\n});\n</code></pre>\n\n<p><strong>Your questions</strong></p>\n\n<ol>\n<li><p>I showed in my counter proposal how you can condense the code, but I do believe you will need each time a distinct class</p></li>\n<li><p>Finding the answer to that question is not trivial (we would need a working sample), and not something codereview does. </p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-01-11T18:53:45.257",
"Id": "287733",
"Score": "1",
"body": "Haha, your answer tricked me into answering a 4 year old question as well. Well done. :D"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-01-11T17:24:54.743",
"Id": "152368",
"ParentId": "19076",
"Score": "1"
}
},
{
"body": "<p>Let me show you another way, how you can handle this. This solution will work with any number of slides. I hope this helps you. The basic idea is this:</p>\n\n<ul>\n<li>open a slide</li>\n<li>save this slide on a stack</li>\n<li>continue opening slides <em>or</em></li>\n<li>close one or more slides</li>\n</ul>\n\n<p>In case of closing it will close all slides up to the selected one. This way you don't need a <em>close all</em> button and you can't get a result where a \"<em>nested</em>\" slide is still open but its parent is closed.</p>\n\n<p><strong>HTML</strong></p>\n\n<p>To loosen the JavaScript from the markup I've introduced some <code>data-*</code>-attributes:</p>\n\n<ul>\n<li><code>data-slide=\"[name]\"</code></li>\n<li><code>data-id=\"[name]\"</code></li>\n<li><code>data-direction=\"[right|up]\"</code></li>\n</ul>\n\n<p><em>data-slide=\"[name]\"</em> represents a trigger for a slide. In your case:</p>\n\n<pre><code><div data-slide=\"slide-1\">Toggle Slider</div>\n</code></pre>\n\n<p><em>data-id=\"[name]\"</em> identifies a slide. Also information about the direction is stored here:</p>\n\n<pre><code><div class=\"cambridge slideout\" data-id=\"slide-1\" data-direction=\"right\"> \n</code></pre>\n\n<p><strong>JavaScript</strong></p>\n\n<pre><code>const DELAY = 1000;\nvar stack = [];\n\nfunction close(e) {\n var value = null;\n\n if (!stack.length) {\n return;\n }\n\n value = stack.pop();\n value.removeClass('active').toggle('slide', {direction: value.data('direction')}, DELAY);\n\n if (!e.length || e.data('id') != value.data('id')) {\n setTimeout(function() { close(e); }, DELAY);\n }\n}\n\n$('[data-slide]').click(function() {\n var e = $('[data-id=\"' + $(this).data('slide') + '\"]');\n\n if (!e.hasClass('active')) {\n e.addClass('active').toggle('slide', {direction: e.data('direction')}, DELAY);\n stack.push(e);\n } else {\n close(e);\n }\n});\n</code></pre>\n\n<p><strong>Advantages</strong></p>\n\n<ul>\n<li>HTML and JavaScript are more decoupled</li>\n<li>no class- or id-selectors necessary</li>\n<li>no <em>close all</em> function necessary (but you can simply call <code>close()</code> to close all slides anyway)</li>\n<li>no ghost slides are visible if you close a \"parent\" element</li>\n</ul>\n\n<p><strong>Further Improvements</strong></p>\n\n<p>This code can have side effects, when you open a slide while it's closing multiple others. This should be addressed.</p>\n\n<p><strong>jsFiddle Demo</strong></p>\n\n<p><a href=\"http://jsfiddle.net/1z5bjeve/\" rel=\"nofollow noreferrer\">Try before buy</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-01-11T19:07:45.570",
"Id": "287735",
"Score": "1",
"body": "Very nice answer ;) +1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-01-11T18:49:16.270",
"Id": "152377",
"ParentId": "19076",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T16:25:16.273",
"Id": "19076",
"Score": "5",
"Tags": [
"javascript",
"jquery",
"jquery-ui"
],
"Title": "jQuery Toggle Animation"
}
|
19076
|
<p>Here's a solution for a lazy groupBy when the iterator contents are assumed to be clustered (repeated elements next to each other) over the key:</p>
<pre><code>def clusteredGroupBy[B](h: Iterator[B])(f: B => _): Stream[Iterator[B]] = {
if (h.hasNext) {
val firstValue = h.next()
val projection = f(firstValue)
val (head, tail) = h.span(f(_) == projection)
(Iterator(firstValue) ++ head) #:: clusteredGroupBy[B](tail)(f)
} else Stream.empty
}
</code></pre>
<p>Any suggestions on how to improve this? Is there anything more native to Scala that does the same?</p>
|
[] |
[
{
"body": "<p>As far as I know, Scala doesn't have anything like you suggest. Your solution is short and fast.</p>\n\n<p>I tried to think of a solution that doesn't use mutable state and uses existing functions, without examining the structure directly. It is based on <code>Stream</code>s instead of <code>Iterator</code>s, which are imperative in their nature.</p>\n\n<p>The main idea can be expressed using a scanning function that sums together elements that are equal according to a given comparison function:</p>\n\n<pre><code>def scanKey[A](s: Seq[A], x: A)(implicit eq: Equiv[A]): Seq[A] =\n s match {\n case Seq(y, _*) if (eq.equiv(x,y)) => s :+ x;\n case _ => Seq(x);\n }\n</code></pre>\n\n<p>Instead of having an explicit key function I used an implicit equality witness.</p>\n\n<p>After applying this function, we have a stream of the same length, whose elements are those sums. What we need to do is get exactly those which are followed by a shorter (or equally sized) sequence. We can do this by zipping the stream and its tail augmented with an empty sequence and filter out just those where the size of a sequence doesn't increase:</p>\n\n<pre><code>def cluster[A](s: Stream[A])(implicit eq: Equiv[A]): Stream[Seq[A]] = {\n val seqs = s.scanLeft(Seq.empty[A])(scanKey[A] _)\n seqs.zip(seqs.tail append Stream(Seq.empty[A]))\n .collect({ case (xs, ys) if (!xs.isEmpty && (ys.size <= xs.size)) => xs })\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T12:59:54.730",
"Id": "28969",
"ParentId": "19078",
"Score": "0"
}
},
{
"body": "<p>I'd like to add a completely different answer. The task can be very well solved with a concept called <em>pipes</em> or <em>conduits</em> (also <em>iteratees</em>).</p>\n\n<p>I'll give a solution using my experimental library called <a href=\"https://github.com/ppetr/scala-conduit\" rel=\"nofollow\">scala-conduit</a> (disclaimer: I'm the author).</p>\n\n<p>A <code>Pipe[I,O,R]</code> is a thing that can read input elements of type <code>I</code> from one side (<code>request</code>) and emit output elements of type <code>O</code> on another side (<code>respond</code>). When it finishes, it produces a final result of type <code>R</code>. It decides on its own when it requests and when it responds. This is ideal for the task - we receive inputs and decide when to emit the cluster of equal elements. A pipe also knows when the input finishes. This was problematic with using <code>Stream</code>s or other native Scala collections, because folding, mapping, etc. don't notify the function that it hit the end. We didn't know easily when to output the last accumulated buffer. With <em>conduit</em> it is easy, our pipe will get notified when it runs out of input. The solution would look like this:</p>\n\n<pre><code>import conduit._\nimport conduit.Pipe._\nimport conduit.Util._\n\ndef cluster[A](implicit eq: Equiv[A]): Pipe[A,Seq[A],Unit] = {\n // no finalizers used here, import the empty implicit\n implicit val fin = Finalizer.empty;\n\n def loop(xs: Seq[A]): Pipe[A,Seq[A],Unit] =\n request(\n y => xs match {\n case Seq(x, _*) if eq.equiv(x, y) => loop(xs :+ y);\n case Seq() => loop(Seq(y));\n case _ => respond(xs, loop(Seq(y)))\n },\n // When upstream finishes producing output,\n // we just respond the buffer and finish.\n _ => if (xs.isEmpty) done else respond(xs)\n )\n\n loop(Seq.empty);\n}\n</code></pre>\n\n<p>The elements accumulated so far are kept in <code>loop</code>'s argument <code>xs</code>. When we hit an non-equal element, we respond the buffer and start with a new one. When we hit the end, we respond the buffer (if it's non-empty).</p>\n\n<p>Then we can construct a source pipe from an interator and combine the result into a collection:</p>\n\n<pre><code>def runCluster[A](xs: Iterator[A])(implicit eq: Equiv[A]): Seq[Seq[A]] =\n runPipe(fromIterator(xs) >-> cluster >-> toCol);\n\nprintln(runCluster(Stream(1,1,2,2,2,3,4,4,4,5).iterator));\n</code></pre>\n\n<p>Processing of pipes is single-threaded and fully lazy. A pipe is processed only if its downstream pipe requests an input and only until it produces its output, then it's suspended again. And if a pipe terminates (means stops receiving input), its upstream pipes are notified and any registered finalizers are executed.</p>\n\n<p>For example we could read the source values from a file, process it with <code>cluster</code> and do something with the clustered output. And if the right-most (sink) pipe decided to terminate early, the file would be automatically closed, without reading unneeded input.</p>\n\n<p>(We can't convert a pipe to an <code>Iterator</code> or to a lazy <code>Stream</code>. We must run it and extract its final, definite output. The reason is that if extracted values lazily, we wouldn't be able to detect when no more values are requested and finalizers should be run. However this is not a big problem, we simply build the whole computation from <code>Pipe</code>s.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T18:47:38.043",
"Id": "28992",
"ParentId": "19078",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "28992",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T18:30:17.213",
"Id": "19078",
"Score": "5",
"Tags": [
"scala"
],
"Title": "GroupBy over a clustered iterator in Scala"
}
|
19078
|
<p>This is my first C++ in many years. It's based on some stuff I found on the internet, including <a href="http://blogs.msdn.com/b/windowsappdev/archive/2012/09/04/automating-the-testing-of-windows-8-apps.aspx" rel="nofollow">a Microsoft article on a similar topic</a>. But I'm sure there are C++ idioms that might make this better or leaner (my main goal).</p>
<pre><code>#include <ShObjIdl.h>
#include <atlbase.h>
#include <wchar.h>
int wmain(int argc, wchar_t* argv[])
{
HRESULT hr = S_OK;
if (argc < 2)
{
hr = E_INVALIDARG;
wprintf(L"Supply an app ID (AppUserModelId) for the application to launch.");
return hr;
}
const wchar_t* appId = argv[1];
hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
if (FAILED(hr))
{
wprintf(L"Error initializing COM");
return hr;
}
CComPtr<IApplicationActivationManager> aam = nullptr;
hr = CoCreateInstance(CLSID_ApplicationActivationManager, nullptr, CLSCTX_LOCAL_SERVER, IID_PPV_ARGS(&aam));
if (FAILED(hr))
{
wprintf(L"Error creating ApplicationActivationManager");
CoUninitialize();
return hr;
}
hr = CoAllowSetForegroundWindow(aam, nullptr);
if (FAILED(hr))
{
wprintf(L"Error calling CoAllowSetForegroundWindow");
CoUninitialize();
return hr;
}
unsigned long pid = 0;
hr = aam->ActivateApplication(appId, nullptr, AO_NONE, &pid);
if (FAILED(hr))
{
wprintf(L"Error calling ActivateApplication");
CoUninitialize();
return hr;
}
CoUninitialize();
return 0;
}
</code></pre>
<p>Pretty small and simple, but I want to open-source this. And I definitely know the feeling of looking at JavaScript newbies' code and going "ugh! why didn't they just do <x>!" So I want to come across as a suave sophisticated C++ programmer instead ;)</p>
|
[] |
[
{
"body": "<p>One piece of feedback is that your error handling code is very repetitive. You are calling <code>CoUninitialize</code> in every failure block. That might seem OK for one cleanup task (though I'd tend to disagree), but once you have N things to clean up on failure (or even successful return), it gets to be a lot of effort and maintenance.</p>\n\n<p>There are a few ways around this that I've seen.</p>\n\n<ul>\n<li>Have a <em>single</em> block that cleans up (frees any buffers, unintializes COM, whatever). That goes at the end if your function. Make all failure and success paths reach this block.</li>\n</ul>\n\n<p>As an example of how you might do that in COM code, here's the \"wrong\" way:</p>\n\n<pre><code>hr = Foo();\nif (FAILED(hr))\n{\n Cleanup();\n}\n\nhr = Bar();\nif (FAILED(hr))\n{\n Cleanup();\n}\n\nCleanup();\n</code></pre>\n\n<p>There are several choices for the \"right\" way. One of them would be:</p>\n\n<pre><code>if (SUCCEEDED(hr))\n hr = Foo();\nif (SUCCEEDED(hr))\n hr = Bar();\n\nCleanup();\n</code></pre>\n\n<p>If you are not religiously opposed to <code>goto</code> (this probably makes more sense in C than C++), this approach is also common:</p>\n\n<pre><code> hr = Foo();\n if (FAILED(hr))\n goto cleanup;\n hr = Bar();\n if (FAILED(hr))\n goto cleanup;\n\ncleanup:\n Cleanup();\n</code></pre>\n\n<ul>\n<li>There are of course more C++ like (rather than C style) ways to prevent cleanup from becoming too much of a hassle. In particular it would probably be a better idea to wrap initialization and de-initialization in <a href=\"http://en.wikipedia.org/wiki/RAII\" rel=\"nofollow\">the RAII idiom</a>. In this example (COM initialization), you might have a class that (1) initializes COM, (2) tracks that it's been initialized, and (3) in its destructor, deinitializes COM if it has been initialized. Something like this: [nb: I am typing in a web form, it may not be perfect :-)]</li>\n</ul>\n\n<p>Example:</p>\n\n<pre><code>class ComInitialization\n{\n bool init;\npublic:\n\n ComInitialization() : init(false) {}\n\n HRESULT Initialize()\n {\n HRESULT hr = S_OK;\n\n if (!init)\n {\n hr = CoInitializeEx(/* ... */);\n if (SUCCEEDED(hr))\n {\n init = true;\n }\n }\n\n return hr;\n }\n\n ~ComInitialization()\n {\n if (init)\n {\n CoUninitialize();\n }\n }\n}\n</code></pre>\n\n<p>With this approach you can have simply:</p>\n\n<pre><code>ComInitialization comInit;\n\nhr = comInit.Initialize();\n</code></pre>\n\n<p>Then after this block, you can <code>return</code> in any place you like, success or failure, even throw exceptions, and COM will still get uninitialized.</p>\n\n<p>(Notice I didn't initialize COM in a constructor. This allows us to inspect the <code>HRESULT</code> on failure without wrapping it in an exception. I'm sure many would suggest wrapping <code>HRESULT</code>s in exceptions. This is not personally my taste. YMMV.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T20:17:46.897",
"Id": "30474",
"Score": "0",
"body": "Yeah I think that is the main point I need to attack. The problem is that I want custom error messages for each failure. Here's my newest attempt: https://gist.github.com/4156732\n\nI have to say, `goto` seems cleanest. The RAII style makes sense for larger apps but for this small file it increases the line count by a lot."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T20:28:06.040",
"Id": "30477",
"Score": "0",
"body": "@Domenic - Probably not worth fighting religious wars over, but good habits are good habits, large project or not. So I was trying to illustrate the spectrum. If it's C++ and not C I'd say RAII is probably the way to go. One problem with `goto` is that it is not exception safe."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T20:13:09.967",
"Id": "19087",
"ParentId": "19080",
"Score": "2"
}
},
{
"body": "<p>I second the RAII recommendation. It's the only same way to do resource management in the presence of exceptions. Even in a small program I would recommend it. For instance, are you certain none of the CComPtr operations you use can throw? Do you want to have to worry about that?</p>\n\n<p>With respect to error handling, my approach, back when I had to deal with COM, was to always <code>#import</code> the relevant .idl file when available. This causes the compiler to autogenerate some wrapper classes that do both reference counting and automatically convert HRESULTs to exceptions. The result was much more concise and readable code (at the expense of fully customized error messages, which was an acceptable tradeoff for my domain).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T21:49:50.120",
"Id": "19090",
"ParentId": "19080",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T19:01:04.160",
"Id": "19080",
"Score": "3",
"Tags": [
"c++",
"windows"
],
"Title": "C++ code to launch a Windows 8 app"
}
|
19080
|
<p>I'm building a generic flat file reader which looks something like this.</p>
<pre><code> public class GenericReader<TComposite, THeader, TData, TTrailer>
where TComposite : GenericComposite<THeader, TData, TTrailer>, new()
where THeader : new()
where TData : new()
where TTrailer : new()
{
public TComposite Read()
{
// read stuff, do parsing etc
var composite = new TComposite();
composite.Header = new THeader();
composite.Data = new TData();
composite.Trailer = new TTrailer();
return composite;
}
}
</code></pre>
<p>It could be consumed like so.</p>
<pre><code>var reader = new GenericReader<Composite<Header, Data, Trailer>, Header, Data, Trailer> ();
var composite = reader.Read();
Console.WriteLine(composite.Data.SomeProperty);
Console.ReadLine();
</code></pre>
<p>Here are the classes used.</p>
<pre><code>public class Composite<THeader, TData, TTrailer> : GenericComposite<THeader, TData, TTrailer>
{
}
public class GenericComposite<THeader, TData, TTrailer>
{
public THeader Header { get; set; }
public TData Data { get; set; }
public TTrailer Trailer { get; set; }
}
public class Header {
public string SomeProperty { get { return "SomeProperty"; } }
}
public class Data {
public string SomeProperty { get { return "SomeProperty"; } }
}
public class Trailer {
public string SomeProperty { get { return "SomeProperty"; } }
}
</code></pre>
<p>Is there a way how I could remove or encapsulate that generic type information in the GenericReader? I'm looking for an extra pair of eyes to show me something what I've been missing. We already did something with returning interfaces, and making the consumer do a cast, but that just moves the responsibility to the wrong location in my opinion, plus there is a small performance penalty.</p>
<p>Thanks.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T19:05:47.510",
"Id": "30460",
"Score": "1",
"body": "What is the thinking behind the Composite and GenericComposite classes? They seem the same to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T19:54:06.600",
"Id": "30466",
"Score": "0",
"body": "What's the intent of the Composite class in the first place? Why is that separate from the GenericReader?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T19:57:27.157",
"Id": "30467",
"Score": "0",
"body": "Composite class composites header, data and trailer, makes for one thing to return. You can see it as a logical file."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T20:39:29.953",
"Id": "30482",
"Score": "0",
"body": "@JeffVanzella You're absolutely right, it's not necessary. Now I can remove that first type parameter."
}
] |
[
{
"body": "<p>Having so many <code>new</code> operations -- seems like you'd want to use some kind of a factory, injected in the constructor, or the instances themselves injected in the constructor, instead of constructing the classes <em>inside</em> the constructor.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T19:50:11.410",
"Id": "30463",
"Score": "0",
"body": "The real imp uses a factory to create the instances. I'm doing more than composing my composite."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T19:41:01.453",
"Id": "19082",
"ParentId": "19081",
"Score": "2"
}
},
{
"body": "<p>I think the easiest way would be to create a factory type class. The create would take the 3 generics as generics, and the expected return type as a parameter. Then use reflection to create the instance. Before you say anything about using reflection, by creating generics in your function, you are inadvertently using reflection.</p>\n\n<pre><code>public class CompsiteFactory\n{\n public GenericComposite<THeader, TData, TTrailer> Create<THeader, TData, TTrailer>(Type compositeType)\n where THeader : new()\n where TData : new()\n where TTrailer : new()\n {\n var finalType =\n compositeType.MakeGenericType(new[] {typeof (THeader), typeof (TData), typeof (TTrailer)});\n\n var compositeInstance =\n (GenericComposite<THeader, TData, TTrailer>)\n Activator.CreateInstance(finalType);\n\n compositeInstance.Header = new THeader();\n compositeInstance.Data = new TData();\n compositeInstance.Trailer = new TTrailer();\n\n return compositeInstance;\n }\n}\n</code></pre>\n\n<p>Modify your GenericReader</p>\n\n<pre><code>public class GenericReader<THeader, TData, TTrailer>\n where THeader : new()\n where TData : new()\n where TTrailer : new()\n{\n private readonly CompsiteFactory _factory;\n\n public GenericReader(CompsiteFactory factory)\n {\n _factory = factory;\n }\n\n public GenericComposite<THeader, TData, TTrailer> Read(Type compositeType)\n {\n return _factory.Create<THeader, TData, TTrailer>(compositeType);\n }\n}\n\nvar factory = new CompsiteFactory();\nvar genericReader = new GenericReader<Header, Data, Trailer>(factory);\n\nvar composite = genericReader.GenericComposite(typeof(Composite<,,>));\n</code></pre>\n\n<p>And you have your instance of GenericComposite.</p>\n\n<p>I know that is not a true factory class, but it will work for this instance. If you want to do it properly, there is a lot of examples on best practices online.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T19:52:32.143",
"Id": "30465",
"Score": "0",
"body": "I'm doing more than composing my instance. The real imp uses something that creates the record instances."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T19:59:35.647",
"Id": "30469",
"Score": "0",
"body": "@JefClaes. If your doing more than what you are asking for in your review, perhaps post the real impl so reviewers have the real question to work off...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T20:02:56.593",
"Id": "30470",
"Score": "0",
"body": "@dreza - I think that's what the improperly formatted comment is supposed to indicate is happening in there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T20:15:00.950",
"Id": "30471",
"Score": "0",
"body": "What do you do with the record instances?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T20:30:05.563",
"Id": "30479",
"Score": "0",
"body": "@dreza I'm sorry, I put that in there from my mobile phone. Couldn't get it right."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T20:30:44.270",
"Id": "30480",
"Score": "0",
"body": "@JeffVanzella We convert them to XML in a consuming class."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T19:44:02.840",
"Id": "19084",
"ParentId": "19081",
"Score": "0"
}
},
{
"body": "<p>Why not simply replace </p>\n\n<pre><code>public class GenericReader<TComposite, THeader, TData, TTrailer> \n where TComposite : GenericComposite<THeader, TData, TTrailer>, new()\n where THeader : new()\n where TData : new()\n where TTrailer : new()\n{\n public TComposite Read()\n {\n // read stuff, do parsing etc \n var composite = new TComposite();\n\n composite.Header = new THeader();\n composite.Data = new TData();\n composite.Trailer = new TTrailer();\n\n return composite;\n } \n}\n</code></pre>\n\n<p>with </p>\n\n<pre><code>public class GenericReader<THeader, TData, TTrailer> \n where THeader : new()\n where TData : new()\n where TTrailer : new()\n{\n public GenericComposite<THeader, TData, TTrailer> Read()\n {\n // read stuff, do parsing etc \n var composite = new GenericComposite<THeader, TData, TTrailer>();\n\n composite.Header = new THeader();\n composite.Data = new TData();\n composite.Trailer = new TTrailer();\n\n return new composite;\n } \n}\n</code></pre>\n\n<p>?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T20:32:04.630",
"Id": "30481",
"Score": "0",
"body": "Because I didn't see it. How can I look over that? Thank you, changing that right now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T22:30:40.040",
"Id": "30487",
"Score": "1",
"body": "Sometimes, it just takes another pair of eyes. I've certainly been there, and that's exactly what this SE site is for! Glad to help."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T20:01:53.580",
"Id": "19086",
"ParentId": "19081",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T19:01:46.267",
"Id": "19081",
"Score": "1",
"Tags": [
"c#",
"generics",
"type-safety"
],
"Title": "Can I somehow tidy up this (overuse?) of generics?"
}
|
19081
|
<p>I wrote my first jQuery plugin. It counts characters in a similar way to what StackExchange uses for comment entries. You can <a href="http://jsfiddle.net/yHPg7/5/" rel="nofollow noreferrer">see it in action with this fiddle</a>.</p>
<p>I feel that it's messy, but I can't explain why. One of the default options is defined outside the defaults hash because it uses a self-reference, and the method for flashing the text seems out of place. I'm also a little worried about how it handles form submission, and its prevention when the minimum number of characters is not met.</p>
<p>I'm not very fluent with jQuery so I expect this to be atrocious. I would love to hear some feedback as to why, or how it could be improved.</p>
<p>The form is submitted via ajax, using Rails' unobtrusive JS.</p>
<pre><code>(function ($) {
"use strict";
$.fn.counter = function (options) {
var defaults = {
minimumSize: 15,
minimumWarning: " more to go...",
maximumSize: 25,
maximumWarning: " characters remaining...",
warningSize: 20,
targetClass: '.help-block'
};
defaults.defaultText = "Enter at least " + defaults.minimumSize + " characters.";
options = $.extend(defaults, options);
function count(elem) {
var size = elem.val().length, target = elem.siblings(options.targetClass);
if (size === 0) {
target.html(options.defaultText);
} else if (size < options.minimumSize) {
target.html((options.minimumSize - size) + options.minimumWarning);
} else if (size >= options.minimumSize && size < options.warningSize) {
target.html('&nbsp;');
} else if (size >= options.warningSize && size < options.maximumSize) {
target.html((options.maximumSize - size) + options.maximumWarning);
} else if (size >= options.maximumSize) {
elem.val(elem.val().substring(0, options.maximumSize));
target.html("0" + options.maximumWarning);
}
}
this.each(function () {
var elem = $(this);
count(elem);
elem.keyup(function () {
count(elem);
});
elem.closest('form').submit(function () {
if (elem.val().length < options.minimumSize) {
$(this).find(options.targetClass).fadeOut('fast').fadeIn('fast').fadeOut('fast').fadeIn('fast');
return false;
}
});
return elem;
});
};
})(jQuery);
</code></pre>
|
[] |
[
{
"body": "<p>I suggest storing your defaults in a location that can be reached by the developers, and automatically filling in the minsize if <code>minsize</code> is included in the default text. For example,</p>\n\n<pre><code>(function ($) {\n \"use strict\";\n\n $.fn.counter = function (options) {\n options = $.extend($.fn.counter.defaults, options);\n\n function defaultText() {\n return options.defaultText.replace(/minsize/ig,options.minimumSize);\n }\n function count(elem) {\n var size = elem.val().length, target = elem.siblings(options.targetClass);\n if (size === 0) {\n target.html(defaultText());\n } else if (size < options.minimumSize) {\n target.html((options.minimumSize - size) + options.minimumWarning);\n } else if (size >= options.minimumSize && size < options.warningSize) {\n target.html('&nbsp;');\n } else if (size >= options.warningSize && size < options.maximumSize) {\n target.html((options.maximumSize - size) + options.maximumWarning);\n } else if (size >= options.maximumSize) {\n elem.val(elem.val().substring(0, options.maximumSize));\n target.html(\"0\" + options.maximumWarning);\n }\n }\n\n this.each(function () {\n var elem = $(this);\n count(elem);\n elem.keyup(function () {\n count(elem);\n });\n elem.closest('form').submit(function () {\n if (elem.val().length < options.minimumSize) {\n $(this).find(options.targetClass).fadeOut('fast').fadeIn('fast').fadeOut('fast').fadeIn('fast');\n return false;\n }\n });\n return elem;\n });\n };\n\n $.fn.counter.defaults = {\n minimumSize: 15,\n minimumWarning: ' more to go...',\n maximumSize: 25,\n maximumWarning: ' characters remaining...',\n warningSize: 20,\n targetClass: '.help-block',\n defaultText: 'Enter at least minsize characters.'\n };\n})(jQuery);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T20:29:29.213",
"Id": "19089",
"ParentId": "19083",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "19089",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T19:41:52.373",
"Id": "19083",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "jQuery plugin to count characters"
}
|
19083
|
<p>I'm looking for feedback to improve this function. The purpose is to pass a noun and append the appropriate indefinite article ("a" or "an").</p>
<p>A known issue with this code is that it doesn't address words with a vowel sound but a consonant first letter, such as "honor" or "hour". I cannot include 'h' in the list of vowels, though; words like "home" or "horror" have a harder 'h' sound and use the article "a".</p>
<pre><code>function aan ($string) {
return (
in_array(
strtolower(substr($string, 0, 1)),
array('a','e','i','o','u')
) ? 'an' : 'a'
).' '.$string;
}
</code></pre>
<p>Current output:</p>
<pre><code>print 'Become '.aan('All-access').' member'; // Become an All-access member
print 'Become '.aan('Basic').' member'; // Become a Basic member
print 'It has been '.aan('interesting').' experience'; // It has been an interesting experience
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T16:23:17.630",
"Id": "32433",
"Score": "3",
"body": "The logic is flawed. In English, you can't base a/an on written form. You have to base it on word pronuncation. If you don't have the pronunciation for every word, you will never make it work. Common examples - \"a unit\" vs \"an uncle\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T15:05:24.243",
"Id": "36129",
"Score": "2",
"body": "@Sulthan ... as I mention in the second paragraph."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T03:56:18.687",
"Id": "62987",
"Score": "3",
"body": "it is unclear what kind of feedback you are looking for to improve this function. performance, readability, speed, efficiency...."
}
] |
[
{
"body": "<p>A tiny improvement to reduce a string concatenation:</p>\n\n<pre><code>function aan ($string) {\n return (\n in_array(\n strtolower(substr($string, 0, 1)),\n array('a','e','i','o','u')\n ) ? 'an ' : 'a '\n ).$string;\n}\n</code></pre>\n\n<p>In order to help get your logic for more cases (ie, your Honor or Hour examples), you may wish to visit the <a href=\"https://english.stackexchange.com/\">English StackExchange</a> to get help in figuring that logic out. Then you can code that as well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T15:26:17.477",
"Id": "20274",
"ParentId": "19085",
"Score": "2"
}
},
{
"body": "<p>It would be simpler to use <code>stristr()</code> and <code>$string[0]</code>.</p>\n\n<pre><code>function indefinite_article_heuristic($string) {\n return (stristr('aeiou', $string[0]) ? 'an ' : 'a ') . $string;\n}\n</code></pre>\n\n<p><code>stripos()</code> would probably be slightly more efficient, but you would have to do</p>\n\n<pre><code>function indefinite_article_heuristic($string) {\n return (FALSE === stripos('aeiou', $string[0]) ? 'a ' : 'an ') . $string;\n}\n</code></pre>\n\n<p>which looks icky.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T06:51:58.513",
"Id": "37867",
"ParentId": "19085",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "37867",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T19:58:14.987",
"Id": "19085",
"Score": "1",
"Tags": [
"php",
"strings"
],
"Title": "Indefinite article a/an"
}
|
19085
|
<p>I am very much interested in the <a href="http://ciprian-zavoianu.blogspot.de/2009/01/project-bandwidth-reduction.html" rel="nofollow">Reverse Cuthil McKee Algorithm</a>. I have seen Fortran and C or C++ implementations of it, and I decided that it would be a nice exercise to implement it in Python.
I know this algorithm is quite domain specific, but I would still be happy to see what kind of comments I get regarding:</p>
<ul>
<li>Correctness - I am not sure my only test case works for others, although I did some comparison to the Octave and Matlab version. </li>
<li>Speed - Of course a C version would be faster. However, is there some Python improvements which can be done? </li>
<li>Readability - Is this code clear enough to other peer programmers?</li>
</ul>
<p>The code:</p>
<pre><code>import numpy as np
def getDegree(Graph):
"""
find the degree of each node. That is the number
of neighbours or connections.
(number of non-zero elements) in each row minus 1.
Graph is a Cubic Matrix.
"""
degree = [0]*Graph.shape[0]
for row in range(Graph.shape[0]):
degree[row] = len(np.flatnonzero(Graph[row]))-1
return degree
def getAdjcncy(Mat):
"""
return the adjacncy matrix for each node
"""
adj = [0]*Mat.shape[0]
for i in xrange(Mat.shape[0]):
q=np.flatnonzero(Mat[i])
q=list(q)
q.pop(q.index(i))
adj[i] = q
return adj
def RCM_loop(deg,start, adj,pivots,R):
"""
Reverse Cuthil McKee ordering of an adjacency Matrix
"""
digar=np.array(deg)
# use np.where here to get indecies of minimums
if start not in R:
R.append(start)
Q=adj[start]
for idx, item in enumerate(Q):
if item not in R:
R.append(item)
Q=adj[R[-1]]
if set(Q).issubset(set(R)) and len(R) < len(deg) :
p = pivots[0]
pivots.pop(0)
return RCM_loop(deg,p,adj,pivots,R)
elif len(R) < len(deg):
return RCM_loop(deg,R[-1],adj,pivots,R)
else:
R.reverse()
return R
def test():
"""
test the RCM loop
"""
A = np.diag(np.ones(8))
print A
nzc=[[4],[2,5,7],[1,4],[6],[0,2],[1,7],[3],[1,5]]
for i in range(len(nzc)):
for j in nzc[i]:
A[i,j]=1
# define the Result queue
R = ["C"]*A.shape[0]
adj = getAdjcncy(A)
degree = getDegree(A)
digar=np.array(degree)
pivots = list(np.where(digar == digar.min())[0])
inl=[]
Res = RCM_loop(degree,0, adj,pivots,inl)
print degree
print adj
print "solution:", Res
print "correct:", [6,3,7,5,1,2,4,0]
if __name__ == '__main__':
test()
</code></pre>
|
[] |
[
{
"body": "<p>Regarding readability, it is generally a good practice to avoid using unnecessarily shortened forms like <code>adjcncy</code>, as it is only two characters short of adjacency. Also using R for result_queue is discouraged in general (subjective opinion).</p>\n\n<p>If there is no constraint on it being pure python, you may try Cython to get speeds closer to that of C, without moving too far away from the python syntax.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-12T23:53:03.943",
"Id": "94298",
"Score": "1",
"body": "Your remarks about variable names do constitute a valid [short answer](http://meta.codereview.stackexchange.com/a/1479/9357), since you are suggesting a concrete improvement. Your suggestion to switch to Cython might be more appropriate as a comment. Anyway, welcome to Code Review, and I hope you soon reach the 50 points needed to comment."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-12T20:22:27.690",
"Id": "54105",
"ParentId": "19088",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "54105",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-27T20:18:16.160",
"Id": "19088",
"Score": "6",
"Tags": [
"python",
"algorithm",
"matrix",
"numpy"
],
"Title": "Implementing the CutHill-McKee Algorithm"
}
|
19088
|
<p>Here I retrieve a collection of <code>causes</code> from the database. Along with the information from each <code>cause</code>, I want to send the number of <code>users</code> in each <code>cause</code>. This way works, but if experience has told me anything there is probably a much more efficient method to do this. How can I improve this?</p>
<pre><code> def index
@causes = Cause.near([params[:lat], params[:lng]],10)
@causes.each do |i|
i['count'] = i.users.count
end
respond_to do |format|
format.json { render json: {:success=> 1, :data_type => 'cause',:results => @causes} }
end
end
</code></pre>
|
[] |
[
{
"body": "<p>You can perform an inner-join on the users table and then group by the causes.id.</p>\n\n<pre><code>@causes = Cause\n .near([params[:lat], params[:lng]], 10)\n .joins('users')\n .group('causes.id')\n .select('causes.*, count(users) as count')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T16:06:16.653",
"Id": "30543",
"Score": "0",
"body": "Thanks for the answer! I'm not trying to be a smart ass, but is this better or just different? Can you explain why? Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T16:22:33.163",
"Id": "30545",
"Score": "2",
"body": "This is more efficient because the number of queries to database is reduced to one. It also places the work onto the database which is optimized for this task through caching and indexing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T18:31:39.093",
"Id": "30553",
"Score": "0",
"body": "Thanks for getting back to me. It doesn't seem to work. More info posted above :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T00:44:51.410",
"Id": "30574",
"Score": "0",
"body": "@user15872 What does `Cause.select('causes.id,count(users) as people').joins(:users).group('causes.id').first.people` output?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T04:27:04.093",
"Id": "30583",
"Score": "0",
"body": "Making progress. It gives the right answer as far as count is concerned: \"2\". It's not part of a hash though :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T15:06:34.690",
"Id": "30604",
"Score": "0",
"body": "I think it is there, try to render the JSON and it should be there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T16:35:21.733",
"Id": "30610",
"Score": "0",
"body": "Nope, still returns \"2\". The mystery continues... I posted some more of my model info, maybe there is something there that I'm not catching. Thanks again!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T16:52:51.207",
"Id": "30615",
"Score": "1",
"body": "You say its not in the hash but AR is not returning a hash it is returning a ActiveRecord::Relation. What it is printing to the screen is not necessarily what will be in the json. What does this show? Cause.select('causes.id,count(users) as people').joins(:users).group('causes.id').as_json"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T17:36:18.313",
"Id": "30618",
"Score": "0",
"body": "It worked! Thanks! I'm also pretty new to AR also. Last question, can you expand on your last comment a little more? I've been aware of the as_json function, but I've been just using the `render json:` method to send my responses. Is this bad practice? (This might be a stupid question as I might be missing something obvious.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T17:58:59.333",
"Id": "30621",
"Score": "0",
"body": "I think your way of using `render json:` is the best because it is idiomatic rails."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T20:57:41.153",
"Id": "30640",
"Score": "0",
"body": "This might be greedy but I have a small follow up.`Cause.near([params[:lat], params[:lng]],10).select('causes.*,count(users) as peeps').joins(:users).group('causes.id').as_json` works like a charm. I have a similar function, I can't get to work because I can't alias it in my SQL Statement.`Cause.distance_to([params[:lat], params[:lng]]).select('causes.*,count(users) as peeps').joins(:users).group('causes.id').where(\"users.id = #{current_user.id}\").as_json` As far as I am aware, `distance_to` will work on a single AR resource but won't give me the distance of item in the collection. Any ideas?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T22:09:46.613",
"Id": "30647",
"Score": "0",
"body": "I'm unfamiliar with geocoder but you can find out what the query is doing by running `Cause.distance_to([params[:lat], params[:lng]]).select('causes.*,count(users) as peeps').joins(:users).group('causes.id').where(\"users.id = #{current_user.id}\").to_sql`. Maybe that will provide you with the column names."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T04:15:44.353",
"Id": "19096",
"ParentId": "19095",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "19096",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T03:20:39.557",
"Id": "19095",
"Score": "2",
"Tags": [
"ruby",
"ruby-on-rails",
"active-record"
],
"Title": "ActiveRecord count"
}
|
19095
|
<p>How can I optimize the <code>if</code> condition in this snippet? The only one difference is <code>&& [self isCurrentPosition:i]</code>. How can I make it a single <code>if</code>, including the condition <code>val</code>?</p>
<p>Note: <code>self</code> is a category of <code>NSArray</code>.</p>
<pre><code>- (void) cleanTextfieldExcluding:(int)current checkPosition:(BOOL)val {
for ( int i=0; i<[self count]; i++ ) {
// -----------
if ( val ) { // this IF block is very bad
if ( i != current && [self isCurrentPosition:i] )
[self replaceObjectAtIndex:i withObject:@""];
} else {
if ( i != current )
[self replaceObjectAtIndex:i withObject:@""];
}
// -----------
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T10:18:33.827",
"Id": "30523",
"Score": "0",
"body": "you cannot merge it go a single if."
}
] |
[
{
"body": "<p>It seems that the code in <code>if</code> will be executed only if <code>i != current</code> and <code>val && [self isCurrentPosition:i]</code> or <code>!val</code>, so you could merge all the <code>if</code>s into one:</p>\n\n<pre><code>- (void) cleanTextfieldExcluding:(int)current checkPosition:(BOOL)val {\n for ( int i=0; i<[self count]; i++ ) {\n\n // -----------\n if ( (i != current) && (!val || [self isCurrentPosition:i]) ) {\n [self replaceObjectAtIndex:i withObject:@\"\"];\n }\n // -----------\n\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T15:32:23.923",
"Id": "30540",
"Score": "0",
"body": "just saw the answer below me and OMG it was better than mines(performs one less logic operation) so i updated mines too. :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T16:29:43.830",
"Id": "30546",
"Score": "0",
"body": "-1. Your answers are now the same because you copied his code (and didn't upvote his answer)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T11:28:16.943",
"Id": "19105",
"ParentId": "19101",
"Score": "3"
}
},
{
"body": "<p>the <code>(val · ¬cur · pos) | (¬val · ¬cur) = ¬cur (val·pos | ¬val) = ¬cur (pos | ¬val)</code>. So, the condition is </p>\n\n<pre><code>if ( (i != current) && (!val || [self isCurrentPosition:i]) ) {\n [self replaceObjectAtIndex:i withObject:@\"\"];\n }\n</code></pre>\n\n<p>You just must practise factoring out the common subexpressions and subprograms and learn how to use the Carnot maps for boolean minimization.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T12:24:22.137",
"Id": "19107",
"ParentId": "19101",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "19105",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T09:49:06.907",
"Id": "19101",
"Score": "6",
"Tags": [
"performance",
"objective-c"
],
"Title": "Cleaning a text field"
}
|
19101
|
<p>I have written a Python function which matches all files in the current directory with a list of extension names. It is working correctly.</p>
<pre><code>import os, sys, time, re, stat
def matchextname(extnames, filename):
# Need to build the regular expression from the list
myregstring = ""
for index in range(len(extnames)):
# r1 union r2 and so on operator is pipe(|)
# $ is to match from the end
if index < len(extnames) - 1:
myregstring = myregstring + extnames[index] + '$' + '|'
else:
myregstring = myregstring + extnames[index] + '$'
# getting regexobject
myregexobj = re.compile(myregstring)
# Now search
searchstat = myregexobj.search(filename)
if searchstat:
print 'Regex', filename
</code></pre>
<p>It is called like this:</p>
<pre><code>if __name__ == '__main__':
fileextensions = ['\.doc', '\.o', '\.out', '\.c', '\.h']
try:
currentdir = os.getcwd()
except OSError:
print 'Error occured while getting current directory'
sys.exit(1)
for myfiles in os.listdir(currentdir):
matchextname(fileextensions, myfiles)
</code></pre>
<p>Could you please review the code and suggest if there is any better way of doing this, or share any other comments related to errors/exception handling which are missing - or anything else in terms of logic?</p>
|
[] |
[
{
"body": "<p><a href=\"http://docs.python.org/2/library/stdtypes.html#str.endswith\"><code>.endswith()</code></a> accepts a tuple:</p>\n\n<pre><code>#!usr/bin/env python\nimport os\n\nfileextensions = ('.doc', '.o', '.out', '.c', '.h')\nfor filename in os.listdir(os.curdir):\n if filename.endswith(fileextensions):\n print(filename)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T18:15:32.110",
"Id": "30551",
"Score": "0",
"body": "Sebastian. Thanks a lot for your help. This is quite a nice approach, which you have shown"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T11:29:36.507",
"Id": "19106",
"ParentId": "19103",
"Score": "7"
}
},
{
"body": "<p>I think the way to code this, that most clearly indicates what you are doing, is to use <a href=\"http://docs.python.org/2/library/os.path.html#os.path.splitext\" rel=\"nofollow\"><code>os.path.splitext</code></a> to get the extension, and then look it up in a <a href=\"http://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset\" rel=\"nofollow\">set</a> of extensions:</p>\n\n<pre><code>import os.path\nextensions = set('.doc .o .out .c .h'.split())\n_, ext = os.path.splitext(filename)\nif ext in extensions:\n print(filename)\n</code></pre>\n\n<p>A couple of other comments on your code:</p>\n\n<ol>\n<li><p>There's no need to catch the <code>OSError</code> if all you're going to do is print a message and exit. (This will happen in any case if the exception is uncaught, so why go to the extra trouble?)</p></li>\n<li><p>If you actually want to build up a regular expression, then do it using <a href=\"http://docs.python.org/2/library/stdtypes.html#str.join\" rel=\"nofollow\"><code>str.join</code></a>. This avoids the need to have a special case at the end:</p>\n\n<pre><code>extensions = r'\\.doc \\.o \\.out \\.c \\.h'.split()\nmyregexobj = re.compile('(?:{})$'.format('|'.join(extensions)))\n</code></pre>\n\n<p>(Whenever you find yourself writing a loop over the <em>indexes</em> to a sequence, then you should think about rewriting it to loop over the <em>elements</em> of the sequence instead: this nearly always results in clearer and shorter code.)</p></li>\n<li><p>If you want to build a regular expression that exactly matches a string literal, you should use <a href=\"http://docs.python.org/2/library/re.html#re.escape\" rel=\"nofollow\"><code>re.escape</code></a> to escape the special characters, instead of escaping each one by hand. For example:</p>\n\n<pre><code>extensions = '.doc .o .out .c .h'.split()\nmyregexobj = re.compile('(?:{})$'.format('|'.join(map(re.escape, extensions))))\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T18:18:51.373",
"Id": "30552",
"Score": "0",
"body": "Thanks Gareth. Your explanation and all the methods that you have shared are excellent for learning. These really helped me to understand many new and better techniques. Thanks again."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T12:39:57.533",
"Id": "19108",
"ParentId": "19103",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "19108",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T11:20:29.880",
"Id": "19103",
"Score": "3",
"Tags": [
"python",
"regex"
],
"Title": "Python function to match filenames with extension names"
}
|
19103
|
<p>I have the following code in <a href="http://jsfiddle.net/oshirowanen/89uqU/" rel="nofollow">jsfiddle</a>. I have been told this this code is messy and not optimised. My question is, what about this is messy and unoptimised and how can it be tidied up and optimised to reduce file size and so it becomes more responsive?</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {
$( ".column" ).sortable({
connectWith: ".column",
handle: ".widget_header_icon, .widget_header_title",
start: function( event, ui ) {
$('.menu_button.active, .configure_button.active').click();
$('.menu_button, .configure_button').removeClass("active");
}
});
$(document).click(function(event) {
$('.menu_button.active, .configure_button.active').click();
$('.menu_button, .configure_button').removeClass("active");
});
$('.dropdown_left, dropdown_right').each(function() {
$(this).css('left', $(this).prev().position().left);
});
$('.menu_button, .configure_button').click(function(event) {
$(this).siblings('.menu_button.active, .configure_button.active').click();
$(this).toggleClass('active').next().toggle();
event.stopPropagation();
});
$('.widget_configure_button').click(function(event) {
var $nav3 = $(this),
$dd = $nav3.next('.dropdown');
$nav3.toggleClass('active');
$dd.css({
top: $nav3.outerHeight()+10,
right: 10
});
$nav3.hasClass('active') ? $dd.show() : $dd.hide();
});
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
font-family:arial;
font-size:12px;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
/**/
body
{
background:#F5F5F5;
}
.notification
{
background:#FFFFFF;
}
.inner_notification
{
width:983px; /*1003 max width without horizontal scroll for 1024x768 screens*/
margin:auto;
padding:10px;
background:#EEEEEE;
}
.header
{
background:#EEEEEE;
}
.inner_header
{
width:983px; /*1003 max width without horizontal scroll for 1024x768 screens*/
margin:auto;
padding:10px;
background:#DDDDDD;
}
.top_menu
{
background:#DDDDDD;
}
.inner_top_menu
{
width:1003px; /*1003 max width without horizontal scroll for 1024x768 screens*/
margin:auto;
position: relative;
background:#CCCCCC;
}
.menu_button {
float:left;
padding:10px;
cursor:pointer;
}
.configure_button {
float:right;
padding:10px;
cursor:pointer;
}
.widget_configure_button {
float:right;
padding:10px;
cursor:pointer;
}
.menu_button::selection, .configure_button::selection, .widget_configure_button::selection { background:transparent; }
.menu_button::-moz-selection, .configure_button::-moz-selection, .widget_configure_button::-moz-selection { background:transparent; }
.menu_button:hover, .configure_button:hover, .widget_configure_button:hover {
background-color:#ffffff;
}
.menu_button.active, .configure_button.active, .widget_configure_button.active {
padding:10px;
background-color:#ffffff;
z-index:1;
}
.dropdown
{
display:none;
background-color:#ffffff;
position:absolute;
top:40px;
padding:10px;
cursor:pointer;
}
.dropdown_left {
display:none;
background-color:#ffffff;
position:absolute;
top:32px;
padding:10px;
cursor:pointer;
z-index:20;
}
.dropdown_right
{
left: auto ! important;
right: 0;
}
.clearfix
{
clear:both;
}
.title
{
background:#CCCCCC;
}
.inner_title
{
width:983px; /*1003 max width without horizontal scroll for 1024x768 screens*/
margin:auto;
padding:10px;
background:#BBBBBB;
}
.content
{
background:#BBBBBB;
}
.inner_content
{
width:993px; /*1003 max width without horizontal scroll for 1024x768 screens*/
margin:auto;
padding:10px 0px 0px 10px;
background:#AAAAAA;
}
.column
{
width:331px;
float:left;
}
.widget
{
background:#EEEEEE;
padding:10px;
margin-bottom:10px;
margin-right:10px;
position:relative;
z-index:10;
}
.widget_header
{
background:#DDDDDD;
margin-bottom:10px;
overflow: hidden;
}
.widget_header_icon
{
padding:10px;
float:left;
cursor:move;
}
.widget_header_title
{
padding:10px;
float:left;
cursor:move;
background:#CCCCCC;
width:210px;
}
.widget_sub_header
{
background:#DDDDDD;
margin-bottom:10px;
padding:10px;
overflow: hidden;
}
.widget_content
{
background:#CCCCCC;
padding:10px;
margin-bottom:10px;
height:200px;
}
.widget_footer
{
background:#BBBBBB;
padding:10px;
}
.footer
{
background:#AAAAAA;
}
.inner_footer
{
width:983px; /*1003 max width without horizontal scroll for 1024x768 screens*/
margin:auto;
padding:10px;
background:#999999;
}
/*-------------*/
.ui-sortable-placeholder { background:#BBBBBB; visibility: visible !important; }
.ui-sortable-placeholder * { visibility: hidden; }
/*------------*/</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title></title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery-ui.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<link type="text/css" href="style.css" rel="stylesheet" />
</head>
<body>
<div class="notification">
<div class="inner_notification">
notification
</div>
</div>
<div class="header">
<div class="inner_header">
header
</div>
</div>
<div class="top_menu">
<div class="inner_top_menu">
<div class="menu_button">menu</div>
<div class="dropdown_left">
<div>icon Default 2</div>
<div>icon Reports 2</div>
<div>icon Other 2</div>
</div>
<div class="configure_button">(c)</div>
<div class="dropdown_left dropdown_right">
<div>icon Default 2</div>
<div>icon Reports 2</div>
<div>icon Other 2</div>
</div>
<div class="clearfix"></div>
</div>
</div>
<div class="title">
<div class="inner_title">
title
</div>
</div>
<div class="content">
<div class="inner_content">
<div class="column">
<div class="widget">
<div class="widget_header">
<div class="widget_header_icon">( i )</div>
<div class="widget_header_title">header title</div>
<div class="widget_configure_button">(c)</div>
<div class="dropdown">
<div>icon Default 3</div>
</div>
</div>
<div class="widget_sub_header">
sub header
</div>
<div class="widget_content">
content
</div>
<div class="widget_footer">
footer
</div>
</div>
<div class="widget">
<div class="widget_header">
<div class="widget_header_icon">( i )</div>
<div class="widget_header_title">header title</div>
<div class="widget_configure_button">(c)</div>
<div class="dropdown">
<div>icon Default 3</div>
</div>
</div>
<div class="widget_sub_header">
sub header
</div>
<div class="widget_content">
content
</div>
<div class="widget_footer">
footer
</div>
</div>
</div>
<div class="column">
<div class="widget">
<div class="widget_header">
<div class="widget_header_icon">( i )</div>
<div class="widget_header_title">header title</div>
<div class="widget_configure_button">(c)</div>
<div class="dropdown">
<div>icon Default 3</div>
</div>
</div>
<div class="widget_sub_header">
sub header
</div>
<div class="widget_content">
content
</div>
<div class="widget_footer">
footer
</div>
</div>
<div class="widget">
<div class="widget_header">
<div class="widget_header_icon">( i )</div>
<div class="widget_header_title">header title</div>
<div class="widget_configure_button">(c)</div>
<div class="dropdown">
<div>icon Default 3</div>
</div>
</div>
<div class="widget_sub_header">
sub header
</div>
<div class="widget_content">
content
</div>
<div class="widget_footer">
footer
</div>
</div>
</div>
<div class="column">
<div class="widget">
<div class="widget_header">
<div class="widget_header_icon">( i )</div>
<div class="widget_header_title">header title</div>
<div class="widget_configure_button">(c)</div>
<div class="dropdown">
<div>icon Default 3</div>
</div>
</div>
<div class="widget_sub_header">
sub header
</div>
<div class="widget_content">
content
</div>
<div class="widget_footer">
footer
</div>
</div>
<div class="widget">
<div class="widget_header">
<div class="widget_header_icon">( i )</div>
<div class="widget_header_title">header title</div>
<div class="widget_configure_button">(c)</div>
<div class="dropdown">
<div>icon Default 3</div>
</div>
</div>
<div class="widget_sub_header">
sub header
</div>
<div class="widget_content">
content
</div>
<div class="widget_footer">
footer
</div>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
<div class="footer">
<div class="inner_footer">
footer
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T18:37:35.673",
"Id": "30554",
"Score": "2",
"body": "There's a lot of code so I haven't gone through it all, but what strikes me is that you're not using classes very efficiently; you're namespacing everything, even when you don't need to. Instead of something like `widget_header` and `widget_header_icon` just call it `header` and `icon`. The css selector for the icon would then be `.widget .header .icon`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T10:05:58.877",
"Id": "30596",
"Score": "0",
"body": "@Flambino, I've already got a `.header` class for the header of the page. That is why I gave the header of the `.widget`'s a different class. Because I want both headers to have different styled. Plus, I will have a general `.icon` class and `.widget` icon classes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T12:44:27.237",
"Id": "30599",
"Score": "1",
"body": "I assume you are not interested in HTML (as you are *only* using `div` elements)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T13:00:29.437",
"Id": "30600",
"Score": "0",
"body": "What's the point of `ol, ul { list-style: none; }`??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T20:51:39.120",
"Id": "30709",
"Score": "3",
"body": "@oshirowanen You missed my point. Ok, you have an element with a `header` class already (in which case you should probably use the `<header>` _element_, or use an id attribute), but that's why CSS has selectors; a `.widget .header` selector will only style `header`-classed elements inside `widget`-classed elements. That's basic CSS."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T08:40:02.630",
"Id": "30727",
"Score": "0",
"body": "@unor, I am also interested in HTML."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T08:40:19.493",
"Id": "30728",
"Score": "0",
"body": "@ANeves, I don't know what you mean?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T09:22:39.487",
"Id": "30885",
"Score": "0",
"body": "@oshirowanen I mean, **why** do you remove the bullets from lists? What for? (The same applies to many other things from the css-reset; but those are more subjective, and thus harder to argue.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T09:25:56.210",
"Id": "30886",
"Score": "0",
"body": "@ANeves, I don't know to be honest, I'm just using a popular css-reset from http://meyerweb.com/eric/tools/css/reset/. I assume it's to remove it and if needed, assign a new style which will be the same for all browsers. But to be honest, I don't know."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T09:35:24.723",
"Id": "30888",
"Score": "0",
"body": "OK. You **should** assign a new style, then. See how in http://meyerweb.com/ui/meyerweb.css Meyer removes the bullet points in line 54 but adds them again in lines 157 and 158. Still, this is not as good as the original styling because it does not have different bullet styles for different levels, etc... and **this is why I disagree with the use of css-resets**."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-07T16:22:50.153",
"Id": "31070",
"Score": "0",
"body": "There's no obligation or reason to use `list-style`'s default bullets as long as the usage of the list element itself is justified in the semantical context. CSS is unrelated to the HTML meaning."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-07T19:20:21.983",
"Id": "31076",
"Score": "1",
"body": "@Flambino: `.widget .header` has several problems. 1. If you have a nested component, for example '.notification .header' inside of the widget, the styles will interfere with each other. This becomes very problematic in large projects. 2. Quoting Mozilla: \"The descendant selector is the most expensive selector in CSS. It is dreadfully expensive—especially if the selector is in the Tag or Universal Category.\" They recommend using `.treecell-header {…}` over `treehead > treerow > treecell {…}`. 3. Using simple selectors helps you avoid reliance on a specific DOM structure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-08T22:16:42.667",
"Id": "31099",
"Score": "0",
"body": "@AlexeyLebedev A fair argument. Though given the markup in the question, there are no nested `.header` elements to worry about in this case, hence my suggestion. As for child selectors, that's always a trade-off between flexibility and optimization. I'll pick flexibility, at least while everything's under development. To avoid the use of child selectors is to avoid one of the key strengths of CSS. Yes, it comes with an attached performance cost, but so does something like jQuery. Yet both things also come with a lot of benefits. So I don't think either of us is necessarily wrong or right."
}
] |
[
{
"body": "<p>Messy would imply that the code readability is bad, which is not the case. However...</p>\n\n<ol>\n<li><p>Your HTML is pretty much one big div. Semantics have value, so use\nproper elements for the adequate job. That's why we have semantic elements in\nthe first place. Also, there's little reason to use anything else than the HTML5 doctype in this day and age.\nOverall, your <strong>absolute lack of HTML semantics is the greatest issue</strong> as it produces most collateral damage.</p></li>\n<li><p>Meyer's reset, while popular, is rather obsolete today and goes unnecessarily far (check out normalize.css, you might prefer it). While CSS can be bent in almost any way as long as you're confident in the outcome, I would say you lack experience to prototype a layout correctly. Far too many specific classes, the structure can be more generalized and shared. While I haven't tried your code, it appears to be very static (one dimension change requiring more dependant changes).</p></li>\n<li><p>Your JS searches the DOM for the same elements too much and on every function execution, this is unnecessary. Define their instances and reuse them.</p></li>\n</ol>\n\n<p>If any of this is unclear, I'll be happy to go in further detail or expand the answer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-07T16:18:31.613",
"Id": "19393",
"ParentId": "19104",
"Score": "6"
}
},
{
"body": "<ol>\n<li><p>I'd create a Widget component. That would allow to create any number of Widgets without duplicating HTML, and all methods for widget manipulation would be grouped together.</p>\n\n<pre><code>var widget = new Widget({\n header: '...',\n content: '...'\n});\n</code></pre></li>\n<li><p>The variable names are not descriptive.</p>\n\n<pre><code>$dd -> $dropdownList\n$nav3 -> $dropdownButton\n</code></pre></li>\n<li><p>Selecting elements through <code>.next()</code> and <code>.prev()</code> is fragile, I'd select by class name instead.</p>\n\n<pre><code>// in the constructor...\n$dropdownList = $container.find('dropdown-list');\n// in the event handler...\n$dropdownList.toggle();\n</code></pre></li>\n<li><p>You can save some JavaScript by structuring HTML and CSS differently.\nIf you put the dropdown inside of the configure button, you wouldn't need to re-position it every time, or to hide it using JS. The event handler would be simplified to:</p>\n\n<pre><code>$configureButton.click(function() {\n $(this).toggleClass('active');\n});\n</code></pre></li>\n<li><p>Selectors such as <code>.title</code> and <code>.dropdown</code> are overly general. As the project grows larger, dozens of different header and dropdown variants appear, and they start to clash with each other. By then refactoring becomes hard, and people start adding <code>!important</code>, which makes the situation even worse.</p></li>\n<li><p><code>event.stopPropagation()</code> is usually really bad, it blocks events for other modules that need to hide their dropdowns, track clicks, or initialize some other behaviour.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-07T20:24:27.603",
"Id": "19395",
"ParentId": "19104",
"Score": "2"
}
},
{
"body": "<p>For someone to straight-up call this code messy is, I think, uncalled for. </p>\n\n<p>I agree with <a href=\"https://codereview.stackexchange.com/a/19393/20138\">mystrdat's answer</a> suggesting the lack of semantics is a big deal. This is low-hanging fruit for 'optimizing' the markup. However, I think you have some larger issues.</p>\n\n<p>The site is actually buggy.</p>\n\n<p>When I click and drag the 'header title' elements onto one another the relayout is not what I would expect. It's not difficult to get them all in one column or moving around almost unpredictably. I'm almost certain this is not the intended behavior, which makes it a bug and a pretty big one. I think this is the biggest problem as it simply doesn't work. IMHO, this is far more significant than whether the code is messy or optimized.</p>\n\n<p>When I tested in FF, the <code>widget_header_title</code> elements are too wide and this causes the <code>widget_configure_button</code> elements to be pushed down, making the <code>widget_header</code> elements to be twice as tall as you're going for (according to how it renders in Chrome). Changing the markup and CSS to the following fixes this, as far as I can tell:</p>\n\n<p>HTML</p>\n\n<pre><code><div class=\"widget_header\">\n <div class=\"widget_header_icon\">( i )</div>\n <div class=\"widget_configure_button\">(c)</div>\n <div class=\"widget_header_title\">header title</div> <!-- now 3rd item -->\n <div class=\"dropdown\">\n <div>icon Default</div>\n </div>\n</div>\n</code></pre>\n\n<p>CSS</p>\n\n<pre><code>/* taking out float and hard-coded width */\n.widget_header_title {\n padding: 10px;\n cursor: move;\n background: #CCC;\n overflow: hidden;\n}\n</code></pre>\n\n<p>However, this breaks breaks your dropdown code because the dropdown code relies on the <code>.next()</code> jQuery method. Relying on precise ordering of sibling elements in the DOM can yield brittle code. Maybe change this so the button and corresponding dropdown element are both inside a container element. This will be more stable, maintenance wise. An alternative is to add a <code>data-target</code> attribute (or something similar) on the button and set the value to a selector that will target the dropdown to toggle. The problem with this approach it generally requires the use of IDs.</p>\n\n<p>Container:</p>\n\n<pre><code><div class=\"dropdown_group\">\n <div class=\"menu_button\">menu</div>\n <div class=\"dropdown_left\">\n <div>icon Default 2</div>\n <div>icon Reports 2</div>\n <div>icon Other 2</div>\n </div>\n<div>\n</code></pre>\n\n<p>Related via data-target:</p>\n\n<pre><code><div class=\"menu_button\" data-target=\"#dropdown1\">menu</div>\n<div id=\"dropdown1\" class=\"dropdown_left\">\n <div>icon Default 2</div>\n <div>icon Reports 2</div>\n <div>icon Other 2</div>\n</div>\n</code></pre>\n\n<p>Your JS relies a lot on dispatching UI events to trigger other code you've written. This should absolutely be avoided. It's difficult to read and is inefficient. If there is an operation that's executed by a click-handler that you need to execute, make it available as a function and call it. If that won't work or is not an option, then take a different approach.</p>\n\n<p>Combining the two notes, your dropdown code could be written something like:</p>\n\n<p>HTML</p>\n\n<pre><code><div class=\"menu_wrap\">\n <button class=\"menu_button\">menu</button>\n <ul class=\"dropdown_left\">\n <li><a href=\"#some_link\">icon Default 2</a></li>\n <li><a href=\"#some_link\">icon Reports 2</a></li>\n <li><a href=\"#some_link\">icon Other 2</a></li>\n </ul>\n</div>\n</code></pre>\n\n<p>CSS</p>\n\n<pre><code>.menu_wrap {\n position: relative;\n}\n.menu_wrap.open > .dropdown_left {\n display: block;\n}\n</code></pre>\n\n<p>JS</p>\n\n<pre><code>$menu_wraps = $('.menu_wrap');\n\n$menu_wraps.on('click.dropdownToggler', function(e){\n var $this = $(this);\n if ($this.hasClass('open')) {\n $this.removeClass('open');\n } else {\n $menu_wraps.filter('.open').removeClass('open');\n $this.addClass('open');\n }\n return false;\n});\n\n$(document).on('click.dropdownCloser', function(e) {\n $menu_wraps.filter('.open').removeClass('open');\n});\n</code></pre>\n\n<p>Generally speaking, you may want to use CSS to position your dropdowns instead of JavaScript. Wrapping the dropdown elements in something like <code>menu_wrap</code> as noted above will make it possible to only use CSS for positioning the menus.</p>\n\n<pre><code>.menu_wrap {\n position: relative;\n}\n.dropdown_left {\n position: absolute;\n top: 100%;\n left: 10px;\n /* etc. */\n}\n</code></pre>\n\n<p>In your CSS, there are a lot of situations where you have a hardcoded width. I try to avoid this because it makes for brittle layouts (like the <code>widget_header_title</code> elements). For example:</p>\n\n<pre><code>.inner_footer {\n width: 983px;\n margin: auto;\n padding: 10px;\n background: #999;\n}\n</code></pre>\n\n<p>Can be written as:</p>\n\n<pre><code>.inner_footer {\n margin: 0 10px;\n padding: 10px;\n background: #999;\n}\n</code></pre>\n\n<p>For this to be centered you need a containing element that has the width set, but this container can contain the rest of your site. This way, you only have the width set in one place:</p>\n\n<p>HTML</p>\n\n<pre><code><body>\n <div class=\"container\">\n <section class=\"notification\">\n <div class=\"inner_notification\">\n notification\n </div>\n </section>\n\n <section class=\"header\">\n <div class=\"inner_header\">\n header\n </div>\n </section>\n\n <!-- etc -->\n\n </div><!-- .container -->\n</body>\n</code></pre>\n\n<p>CSS</p>\n\n<pre><code>.container {\n width: 1003px;\n margin: 0 auto;\n}\n</code></pre>\n\n<p>There are tradeoffs, as this doesn't have the various wide bands of color that fill the margins. For that, you would just want to add the <code>container</code> class to each of your ourtermost wrapping elements. But, you still have the width set in only one place in your CSS.</p>\n\n<pre><code> <div class=\"notification container\">\n <div class=\"inner_notification\">\n notification\n </div>\n </div>\n</code></pre>\n\n<p>Per mystrdat's remark, those wrapping elements (<code>.notification</code>) should really be <code><section></code> elements. And, the menu triggers (<code>configure_button</code>, <code>widget_configure_button</code> and <code>menu_button</code>) should be <code><button></code> elements. Your dropdowns should be <code><ul></code> elements. Your footer could be a <code><footer></code> element. That would all make it more \"semantic\" which is definitely a good thing and generally helps when it comes to what other developers think of your markup (since it was mentioned in the OP).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-10T15:25:58.173",
"Id": "19464",
"ParentId": "19104",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T11:25:48.663",
"Id": "19104",
"Score": "2",
"Tags": [
"javascript",
"performance",
"jquery",
"html",
"css"
],
"Title": "Web page with draggable boxes in a grid"
}
|
19104
|
<p>I'm looking for a better way to provide configuration options and improvements in general. I'm using the constructor injection pattern to get access to the Cache and Twitter class. <code>$callback</code> and <code>$params</code> are both part of an <code>$_GET</code> array.</p>
<p>I'm not happy with <code>$config</code> at all. Maybe it's better to add the whole <code>$_GET</code> array? But i'm not sure how to handle the <code>JSONP Callback</code>.</p>
<p>By the way the callback is added by jQuery and necessary to return a valid <code>JSONP</code>.</p>
<h2>Instantiation:</h2>
<pre><code>// setup config object
$config = (object) array(
'callback' => $_GET['jsonp_callback'],
'params' => $_GET,
);
// new instance of Cache
$cache = new Cache();
// new instance of TwitterAuth
$twitter = new TwitterAuth();
// new instance of tweet wrapper
$ctweet = new CTweet($cache, $twitter, $config->callback, $config->params);
</code></pre>
<h2>Array Data</h2>
<pre><code>Array
(
[jsonp_callback] => jQuery1820268558845622465_1354013902493
[include_entities] => true
[include_rts] => true
[screen_name] => my_screen_name
[count] => 3
)
</code></pre>
<p>The array is built by jQuery. Excluding the <code>[jsonp_callback]</code> all array entries are to retrieve API Data by the <code>TwitterAuth</code> class.</p>
<h2>Complete Class</h2>
<pre><code>/**
* CTweet
*
* This class gets json data from the twitter api,
* stores them into a flat file and returns the
* data as jsonp.
*
* @version 1.0
*/
class CTweet
{
/** @type string Cache expiration time */
private $expiration = "3600";
/** @type string Twitter API Status */
private $api_status = "statuses/user_timeline";
/** @type object Instance of Cache */
private $cache;
/** @type object Instance of TwitterOAuth */
private $twitter;
/** @type array TwitterOAuth API Params */
private $params;
/** @type object JSONP Callback */
private $callback;
/**
* Constructor
*
* @access public
* @param object $cache
* @param object $twitter
* @param string $callback
* @param array $params
*/
public function __construct( $cache, $api, $callback, $params )
{
if( is_array( $params ) ) {
$this->params = $params;
}
$this->cache = $cache;
$this->twitter = $api;
$this->callback = $callback;
$this->cachename = $this->cache->getCache();
}
/**
* Cache validation
*
* This Method deletes expired entries and regenerates cached data.
*
* @access private
* @param $cache string
* @return boolean
*/
private function validate_cache( $cache )
{
$this->cache->eraseExpired();
if ( ! $this->cache->isCached( $cache ) ) {
$this->refresh_cache();
}
return true;
}
/**
* Cache refreshing
*
* This Method generates the cache file and sets the cachname, data
* and the expiration time.
*
* @access private
* @see Cache::store() https://github.com/cosenary/Simple-PHP-Cache
*/
private function refresh_cache()
{
return $this->cache->store( $this->cachename, $this->twitter_api_call( $this->api_status, $this->params ), $this->expiration );
}
/**
* Get Cache
*
* This Method returns the cached data if cache validation was successfull
*
* @access private
* @param string
* @see Cache::retrieve() https://github.com/cosenary/Simple-PHP-Cache
* @return object
*/
private function get_json( $cache )
{
if ( $this->validate_cache( $cache ) ) {
$json = $this->cache->retrieve( $cache );
}
return $json;
}
/**
* Retrieve Data
*
* This Method retrieves and returned data from Twitter API.
*
* @access private
* @param $status string api status
* @param $params array return parameters
* @see TwitterOAuth::get() https://github.com/abraham/twitteroauth/blob/master/DOCUMENTATION
* @return object
*/
private function twitter_api_call( $status, $params )
{
return $this->twitter->get( $status, $params );
}
/**
* Has callback
*
* This Method returns true only if a JSONP Callback is available
*
* @access private
* @return boolean
*/
private function has_callback()
{
if ( isset( $this->callback ) ) {
$callback = true;
}
return $callback;
}
/**
* Output mimetype
*
* This Method returns a specified file header
*
* @access private
* @param $header string
*/
private function set_header( $header )
{
switch ( $header ) {
case "json":
$header = header( "content-type: application/json" );
break;
}
return $header;
}
/**
* JSONP callback
*
* This Method creates the a jsonp callback
*
* @access private
* @param $cache string
* @return jsonp
*/
private function get_jsonp( $cache )
{
return $this->callback . '(' . $this->get_json( $cache ) . ');';
}
/**
* Data
*
* This Method sets output mime type and returns jsonp if a callback is
* available, otherwise the return value is plain json.
*
* @access private
* @return object
*/
private function data( $cache )
{
if ( $this->has_callback() ) {
$data = $this->get_jsonp( $this->cachename );
} else {
$data = $this->get_json( $this->cachename );
}
$this->set_header( "json" );
return $data;
}
/**
* Public interface
*
* This Method return cached data to the client.
*
* @access public
* @return object
*/
public function get_data()
{
return $this->data();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>This post is a bit rambly, but here's a few things that jumped out at me:</p>\n<h2>Technicalities</h2>\n<pre><code>private $expiration = "3600";\n</code></pre>\n<p>Why is 3600 a string?</p>\n<hr />\n<pre><code>public function __construct( $cache, $api, $callback, $params )\n</code></pre>\n<p>When you're expecting a certain type, use typehints:</p>\n<pre><code>public function __construct(Cache $cache, TwitterOAuth $api, callable $callback, $params )\n</code></pre>\n<hr />\n<pre><code>private function get_json( $cache )\n{\n if ( $this->validate_cache( $cache ) ) {\n $json = $this->cache->retrieve( $cache );\n }\n return $json;\n}\n</code></pre>\n<p>That method is flawed. It's possible for it to execute and $json not be defined.</p>\n<p>I think what you're looking for is:</p>\n<pre><code>private function get_json( $cache )\n{\n if ($this->validate_cache( $cache ) ) {\n return $this->cache->retrieve( $cache );\n } else {\n return null;\n }\n}\n</code></pre>\n<hr />\n<pre><code>private function has_callback()\n{\n if ( isset( $this->callback ) ) {\n $callback = true;\n }\n return $callback;\n}\n</code></pre>\n<p>Same problem as your <code>get_json</code>.</p>\n<p>And, it can be simplified to:</p>\n<pre><code>private function has_callback()\n{\n return (isset($this->callback));\n}\n</code></pre>\n<p>Although, really, since you know that $this->callback always exists, you could use <code>return $this->callback !== null;</code> if you wanted.</p>\n<hr />\n<pre><code>if ( isset( $this->callback ) ) {\n</code></pre>\n<p>That probably doesn't do what you think it does. When <code>$this->callback = ''</code>, that's going to return true. That means that your jsonp stuff would return the non-sensical <code>(...);</code></p>\n<hr />\n<pre><code>$config = (object) array(\n 'callback' => $_GET['jsonp_callback'],\n 'params' => $_GET,\n);\n</code></pre>\n<p>There's no reason to use an object here. Just use an array.</p>\n<p>Also, I'm assuming that this is just sample code, but in real code, you shouldn't assume that indexes exist. If jsonp_callback isn't provided, this will issue a notice.</p>\n<hr />\n<h2>Design</h2>\n<pre><code>private function twitter_api_call( $status, $params )\n{\n return $this->twitter->get( $status, $params );\n}\n</code></pre>\n<p>I suppose as long as this stays private there's nothing particularly wrong with it. Seems a bit overkill though other than to save a few keystrokes.</p>\n<hr />\n<pre><code>private function set_header( $header )\n{\n switch ( $header ) {\n case "json":\n $header = header( "content-type: application/json" );\n break;\n }\n return $header;\n}\n</code></pre>\n<p>This method has quite a few problems:</p>\n<ul>\n<li>The name is wrong:\n<ul>\n<li>It doesn't <em>set</em> a header, it <em>sends</em> a header</li>\n<li><code>$header</code> isn't a header</li>\n</ul>\n</li>\n<li><code>header()</code> doesn't return anything</li>\n<li>Your switch, and by extension the <code>$header</code> parameter are useless. The method could just be called <code>sendJsonHeader</code>.</li>\n<li>Your class probably shouldn't be responsible for sending headers. That should happen one or more levels up.</li>\n<li>What if you wanted to embed the JSON content in JavaScript in an HTML page? Your class has then sent a header you don't want. (This is actually a problem in data())</li>\n</ul>\n<hr />\n<pre><code>/**\n * Public interface\n *\n * This Method return cached data to the client.\n * \n * @access public\n * @return object\n */\npublic function get_data()\n{\n return $this->data();\n}\n</code></pre>\n<p>There's no need to comment that it's public. Any IDE or program capable of parsing docs can parse visibilities.</p>\n<p>Also, if the code just proxies through to data(), perhaps get_data() should house data()'s code, and data() shouldn't exist.</p>\n<hr />\n<p>The public API of <a href=\"https://github.com/cosenary/Simple-PHP-Cache\" rel=\"nofollow noreferrer\">https://github.com/cosenary/Simple-PHP-Cache</a> isn't too bad (it's not great either though), but the interal code has quite a few "wtf?" snippets. I might consider using a different cache. (Also, this cache isn't very flexible. What if at some point your site became super popular and you want to move your cache from disk to memcached? There are a lot of cache classes that could handle that with 1 line of code changed.)</p>\n<hr />\n<p>The JSON/JSONP shouldn't be per-instance of the class, but rather per each time you call the data() method. What if you want to get the data as JSON once and JSONP once? Seems pointless to create a new object or have to set the callback.</p>\n<hr />\n<p>That brings me to my next point. This is a bit of an odd one since it's basically the purpose of your class, but your class probably shouldn't be returning JSON.</p>\n<p>Would you ever expect a method to return HTML? What about XML? So why does your method return JSON? Seems a bit odd and inflexible.</p>\n<p>At the same time though, your class could be seen as a renderer, I suppose. Renders <em>are</em> responsible for actually return HTML/XML/etc. The problem with that though is that rendering should be the <em>only</em> thing done. Your class is mixing the responsibilities of getting data and rendering said data.</p>\n<p>I would probably just return an array, or perhaps an object that models the data. That way, the consuming code could decide if it wants JSON or not.</p>\n<hr />\n<p>Either always pass a parameter to methods when necessary, or always use it as a property of the class. Mixing and matching those two approaches is a good sign that the property probably shouldn't actually be a property but rather should be passed to methods every time they're called.</p>\n<p>$params is a good example of this. The way it's being passed around, it feels like it should probably be a parameter to the data() method.</p>\n<p>Upon further examination, this is almost certainly true. What if you wanted to get data for two different usernames? Right now you'd have to create two different objects. That doesn't make sense though, unless the class purposely represents the data for <em>only</em> one username.</p>\n<hr />\n<p><code>CTweet</code> and <code>data()</code> are badly named. It might just be because I've been on twitter a grand total of about twice, but I have no idea what CTweet is (cached tweet?) nor what data() returns (the "cached data" in the documentation is very, very vague -- when you write your doc blocks, assume you've never seen the class before and are trying to figure out how to use it).</p>\n<hr />\n<p>A few other things about the overall design make me a bit uncomfortable, though I can't manage to pin point exactly what it is.</p>\n<p>I think the caching being intermingled with the API-interaction is part of it, though I unfortunately do not have much of a suggestion as to handle it better.</p>\n<p>I would probably keep the caching out of the class and just have your consuming code handle the caching. It seems like embedding the caching in a class inherently gives the class two responsiblities: caching, and whatever its original responsibility was.</p>\n<p>The problem with having the consuming code cache though is that you will get code duplication if you are consuming the code in two places. I suppose that's not really a problem though because that code should be factored out into a common method or some notion of an action if it's being duplicated.</p>\n<p>Overall, I'm not sure what the best way to handle caching is; I just know that the current way makes me a bit uneasy. (Think about it this way: how much of a pain would it be to toggle caching on and off? It should be simple in concept. Just kill the caching. In practice with this code though, it would get a bit painful.)</p>\n<p>I guess what might actually be making me uncomfortable is the entire class. What if you want to cache another snippet from the twitter api? Are you going to make an entirely new class? What if you want to use the data not as json? What if you wanted to use a different type of caching? What if you <em>didn't</em> want to cache? The class seems to have completely garbled together using the twitter API and caching. It seems like the class is trying to do two completely unrelated things (using the twitter API/caching data), and I'm afraid that mixture won't be manageable in the long run.</p>\n<hr />\n<p>Edit: Just read my post back, and wow, it's quite wordy/badly written. Am going to revise it later, but don't have time for now. Hopefully there's some clarity through the ramble :).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T23:09:15.027",
"Id": "30777",
"Score": "0",
"body": "WTF? Thank you very much for your feedback! I'm a bit speechless... give me some time to sort your answer :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T23:55:44.063",
"Id": "19199",
"ParentId": "19112",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "19199",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T15:21:00.290",
"Id": "19112",
"Score": "2",
"Tags": [
"php",
"optimization",
"object-oriented",
"design-patterns"
],
"Title": "Optimize PHP Class"
}
|
19112
|
<p>A multithreaded client server program to download image files. If you want to execute it on your machine you should change the file paths. Since there are four files to download the client makes the same number of connection attempts. The files sent by the FileServer will get repeated after the fourth connection attempt. In the File Server client app the file saving is done in new threads so as to not hamper the file downloading process. There is little interaction between client-server. </p>
<p>Here is the FileServer...</p>
<pre><code>public class FileServer {
private final ExecutorService exec = Executors.newCachedThreadPool();
final String[] fileNames = {
"C:\\Users\\clobo\\Pictures\\Ex1.jpg",
"C:\\Users\\clobo\\Pictures\\Ex2.jpg",
"C:\\Users\\clobo\\Pictures\\Ex3.jpg",
"C:\\Users\\clobo\\Pictures\\Ex4.jpg"
};
public void start() throws IOException {
ServerSocket socket = new ServerSocket(7777);
System.out.println("Waiting for client message...");
while (!exec.isShutdown()) {
try {
for (final String fileName : fileNames){
final Socket conn = socket.accept();
exec.execute(new Runnable() {
public void run() {
sendFile(conn,fileName);
}
});
}
} catch (RejectedExecutionException e) {
if (!exec.isShutdown())
log("task submission rejected", e);
}
}
}
public void stop() {
System.out.println("Shutting down server...");
exec.shutdown();
}
private void log(String msg, Exception e) {
Logger.getAnonymousLogger().log(Level.WARNING, msg, e);
}
public void sendFile(Socket conn, String fileName) {
File myFile = new File(fileName);
if (!myFile.exists()) {
log("File does not exist!",null);
}
// file does exist
System.out.println(Thread.currentThread().getName());
System.out.println("AbsolutePath:" + myFile.getAbsolutePath());
System.out.println("length: " + myFile.length());
if (myFile.exists()) {
try {
ObjectOutputStream oos = new ObjectOutputStream(
conn.getOutputStream());
oos.writeObject(myFile);
oos.close();
} catch (IOException e) {
log("IOException Error", e);
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
FileServer fs = new FileServer();
fs.start();
}
}
</code></pre>
<p>here is the FileServerClient...</p>
<pre><code>public class FileServerClient {
private final ExecutorService exec = Executors.newCachedThreadPool();
Frame myFrame = new Frame();
List<File> fileList = new ArrayList<File>();
public void receiveFileFromServer() throws Exception{
Socket sock = null;
InputStream socketInputStream = null;
String host = "localhost";
int port = 7777;
for (int i=0;i<4;i++) {
sock = new Socket(host, port);
socketInputStream = sock.getInputStream();
System.out.println("Connection successful...");
// recieve the file
ObjectInputStream ois = new ObjectInputStream(socketInputStream);
// file from server is deserialized
final File myfile = (File) ois.readObject();
fileList.add(myfile);
// deserialized file properties
System.out.println("AbsolutePath: " + myfile.getAbsolutePath());
System.out.println("FileName:" + myfile.getName());
System.out.println("length" + myfile.length());
exec.execute(new Runnable() {
public void run() {
saveFile(myfile);
}
});
}
}
private void saveFile(File myfile) {
FileDialog fileDialog = new FileDialog(myFrame,
"Choose Destination for "+ myfile.getName(), FileDialog.SAVE);
fileDialog.setDirectory(null);
fileDialog.setFile("enter file name here");
fileDialog.setVisible(true);
String targetFileName = fileDialog.getDirectory()
+ fileDialog.getFile() + ".jpg";
System.out.println("File will be saved to: " + targetFileName);
copyBytes(myfile, targetFileName);
}
private void copyBytes(File originalFile, String targetFileName) {
try {
FileInputStream in = new FileInputStream(originalFile);
FileOutputStream out = new FileOutputStream(targetFileName);
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
out.close();
in.close();
} catch (Exception e) {
log("IOException Error", e);
}
}
private void log(String msg, Exception e) {
Logger.getAnonymousLogger().log(Level.WARNING, msg, e);
}
public static void main(String[] args) throws Exception {
FileServerClient client = new FileServerClient();
client.receiveFileFromServer();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Nice basic example. I guess your next step is to develop a server that gets a file download request, including a file-name parameter, and sends back the corresponding result. </p>\n\n<p>See here <a href=\"http://www.binarytides.com/java-socket-programming-tutorial/\" rel=\"nofollow\">http://www.binarytides.com/java-socket-programming-tutorial/</a> for an example about network data exchange. See here <a href=\"http://tutorials.jenkov.com/java-multithreaded-servers/thread-pooled-server.html\" rel=\"nofollow\">http://tutorials.jenkov.com/java-multithreaded-servers/thread-pooled-server.html</a> for an example of a thread-pool based server that creates threads only when needed. The example is a bit out-dated, so they implement the ThreadPool class (came available in SDK only a few years ago), but of course you should keep using the version from the SDK.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T04:35:41.517",
"Id": "33057",
"Score": "0",
"body": "When I run Server on one system and client on another system, then, on client it shows Exception"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T05:18:34.847",
"Id": "33061",
"Score": "0",
"body": "and exception is on given link \n[link](http://www.scribd.com/doc/120758165/Exception-in-multi-Threaded-Web-Server-using-Thread-Pool)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T12:23:33.580",
"Id": "33083",
"Score": "0",
"body": "Sounds like the path to the requested file is wrong. Cannot say much more, without the code."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-12T21:02:57.897",
"Id": "19556",
"ParentId": "19113",
"Score": "0"
}
},
{
"body": "<p>Is this code really doing what is advertised?</p>\n\n<p>ObjectOutputStream.write(File) is writing the File object, not the contents of the file. So what we have here is the server pushing the path of a file to the client. The client code then creates a FileDialog, which doesn't wait for the user's input to get a second path on the client? Then a thread on the client runs to copy client(sourcePath) to client(destinationPath).</p>\n\n<p>If you want the server to send the file to the client, then at some point the server needs to open the file, and write the contents into the connection.outputStream.</p>\n\n<p>If two clients were trying to reach the server at the same time, they would each get a random list of file names, depending on the race condition in their own thread pools.</p>\n\n<p>Server.stop, in addition to shutting down the Executor, should also signal start() to quit accepting connections.</p>\n\n<p>Server.start() should probably be spelled \"run()\", given that it is an unending loop on the main thread. start() would be an acceptable spelling if socket.accept were running on a different thread (for instance, in your Executor).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-08T06:56:29.300",
"Id": "34050",
"ParentId": "19113",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T15:33:36.487",
"Id": "19113",
"Score": "3",
"Tags": [
"java",
"multithreading"
],
"Title": "Multithreaded Client-Server file downloading application"
}
|
19113
|
<p>Please review my classes and give me some advice to improve them. I have also put some additional questions in the code and I hope you can give me an answer for some of them.</p>
<p><strong>Database.php</strong></p>
<pre><code><?php
class Database
{
private static $dsn = 'mysql:host=localhost;dbname=knight;charset=UTF-8';
private static $user = 'root';
private static $pass = '';
private static $instance = null;
private function __construct()
{}
//is PDO+Singleton a good combination?
public static function getInstance()
{
if(!isset(self::$instance))
{
try
{
self::$instance = new PDO(self::$dsn, self::$user, self::$pass);
self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo 'Error found: '.$e->getMessage();
}
}
return self::$instance;
}
//Should i make methots prepare(), execute(), bindValue() etc. and why?
}
?>
</code></pre>
<p><strong>Validator.php</strong></p>
<pre><code><?php
class Validator
{
//All the methods are static, is this a good practice for a class like this?
public static function isValidMail($var)
{
return preg_match("/([\w\-]{3,40}+\@[\w\-]{3,120}+\.[\w\-]{2,6}+)/", $var);
}
public static function isLong($var, $max)
{
return(mb_strlen($var, 'UTF-8') > $max);
}
public static function isShort($var, $min)
{
return (mb_strlen($var, 'UTF-8') < $min);
}
public static function isValidID($var)
{
$var = (int)$var;
return ($var > 0);
}
}
</code></pre>
<p><strong>User.php</strong></p>
<pre><code><?php
class User
{
//Should I have properties such as username, password, email etc. and why?
private $db = null;
private $errors = array();
public function __construct($db)
{
$this->db = $db;
}
public function register($username, $pass, $mail)
{
if($this->validate($username, $pass, $mail))
{
$username = $this->filter($username);
$mail = $this->filter($mail);
$exists = $this->exists($username, $mail);
if(!$exists)
{
$pass = $this->hash($pass);
$time = time();
//Should I use exceptions for the SQL queries in this class?
$rs = $this->db->prepare("INSERT INTO users(username, mail, pass, date_reg) VALUES(:name, :mail, :pass, :time)");
$rs->execute(array(':name' => $username, ':mail' => $mail, ':pass' => $pass, ':time' => $time));
header('Location: index.php');
die();
}
else
{
$this->errors[] = 'Username or email already exists!';
}
}
if(count($this->errors > 0))
{
$this->showErrors();
}
}
public function login($username, $pass)
{
if($this->validate($username, $pass))
{
$username = $this->filter($username);
$exists = $this->exists2($username, $pass);
if($exists)
{
$_SESSION['logged'] = 1;
$_SESSION['data'] = $exists->fetch(PDO::FETCH_ASSOC);
header('Location: index.php');
die();
}
else
{
$this->errors[] = 'Wrong username or password!';
}
}
if(count($this->errors > 0))
{
$this->showErrors();
}
}
public function exists($username, $mail)
{
$exists = $this->db->prepare("SELECT user_id FROM users WHERE username = :name OR mail = :mail");
$exists->execute(array(':name' => $username, ':mail' => $mail));
return ($exists->rowCount() > 0);
}
public function exists2($username, $pass)
{
$pass = $this->hash($pass);
$exists = $this->db->prepare("SELECT * FROM users WHERE username = :name AND pass = :pass");
$exists->execute(array(':name' => $username, ':pass' => $pass));
if($exists->rowCount() > 0) return $exists;
return false;
}
public function validate($username, $pass, $mail = null)
{
if(Validator::isShort($username, 4)) $this->errors[] = 'Short username!';
elseif(Validator::isLong($username, 25)) $this->errors[] = 'Long username!!';
if(Validator::isShort($pass, 5)) $this->errors[] = 'Short password!';
if($mail !== null)
{
if(!Validator::isValidMail($mail))
{
$this->errors[] = 'Invalid email!';
}
}
return (count($this->errors) == 0);
}
public function getUserData($id)
{
if(Validator::isValidID($id))
{
$rs = $this->db->prepare("SELECT * FROM users WHERE user_id = ?");
$rs->execute(array($id));
if($rs->rowCount() == 1) return $rs->fetch(PDO::FETCH_ASSOC);
return false;
}
return false;
}
private function hash($var)
{
return hash('sha512', $var);
}
public function filter($var)
{
//Is htmlentities enough if I use PDO?
return htmlentities($var, ENT_QUOTES, 'UTF-8');
}
private function showErrors()
{
foreach($this->errors as $e)
{
//I am outputting text in the class, is that bad?
echo '<strong>'.$e.'</strong><br />';
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Let's first create some test code to show how this might all work to say register a new user. In your controller code to register a user which would accept POST :</p>\n\n<pre><code>$name = $_POST['name'];\n$password = $_POST['password'];\n$email = $_POST['email'];\n\n$db = Database::getInstance();\n$user = new User($db);\n$user->register($name, $password, $email);\n</code></pre>\n\n<p>Right off the bat, I see that I have to pass name, pw, email to the register method. Some improvement:</p>\n\n<pre><code>$name = $_POST['name'];\n$password = $_POST['password'];\n$email = $_POST['email'];\n\n$db = Database::getInstance();\n$user = new User($db);\n$user->setName($name);\n$user->setPassword($password);\n$user->setEmail($email);\n\nif ($user->register() !== true) {\n //show some sort of error page, utilize the $user object in your view\n //i.e. foreach ($user->getErrors() as $error)...\n} else {\n //show the success result page, utilize the $user object in your view\n}\n</code></pre>\n\n<p>The register method can perform validations as necessary and insert the appropriate db record.</p>\n\n<p>Onto the Database class. Hard coding the connection parameters is not very flexible. There's no real behavior behind your Database class other than a factory method to create an instance of itself. I think you'd be better off with a PDOFactory class which can accept a configuration (your db connection params) and return a single instance of a PDO object. Then, use the PDO object where needed.</p>\n\n<p>The Validation class could be extended to provide what you now have for static methods:</p>\n\n<pre><code>abstract class Validator\n{\n protected $value;\n\n public function setValue($value)\n {\n $this->value = $value;\n }\n\n abstract public function isValid();\n}\n\nclass EmailValidator extends Validator\n{\n public function isValid()\n {\n //implement your validation code and return true or false\n }\n}\n</code></pre>\n\n<p>Create subclasses for the rest.</p>\n\n<p>All this said, you should know that there are several frameworks which implement all of this already. I strongly recommend you look at either Zend Framework or Symfony. They've already thought of everything you are asking about here and more.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T20:09:02.037",
"Id": "30864",
"Score": "0",
"body": "Thank you very much for the answer, Rob! What do you think about the exceptions - when should I use them in these classes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T01:24:45.863",
"Id": "30876",
"Score": "0",
"body": "@Stanimir I am of the opinion that Exceptions should be thrown for, well, exceptional situations. Examples are: failed to connect to a service/database or unable to write to file - for things that normally work but in some instance did not."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T00:30:05.840",
"Id": "19240",
"ParentId": "19117",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "19240",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T17:49:16.110",
"Id": "19117",
"Score": "3",
"Tags": [
"php",
"object-oriented",
"validation",
"database"
],
"Title": "Database, User and Validator in PHP"
}
|
19117
|
<p>I have to write a Blackjack game for college using the Processing language. It has to be done in a strict object-oriented approach, so I can't make an object of a class in another class unless there is some connection.</p>
<p>We have to use a <code>Player</code> interface:</p>
<pre><code>interface Player {
// This is the interface you are expected to implement for both
// the computer controlled 'dealer' and the human player(s)
// You can change the return types for any of the items in the interface.
// You can also add arguments two the first two method listed below
void twist(/* you can add an argument here */); // This method should allow the player to add acard to their hand
void updateValueOfHand(/* you can add an argument here */); // Updates the the value of the cards the player has in their hand
void stick(); // Called when the player does not want to take another card
void updateScore(); // Updates the player's overall score (number of games they have won)
int getValueOfHand(); // Getter method for the value of the cards the player has in their hand
int getScore(); // Getter method for the player's overall score (number of games they have won)
void showHand(); // Used to display the player's hand on screen
void clearHand(); // Used at the end of a round to empty the cards in the player's hand
}
</code></pre>
<p>I have done a storyboard for the game:</p>
<pre><code>interface Player
class Card
class Deck extends Card
class Computer implements Player
class Human implements Player
</code></pre>
<p>I am planning to have a class called <code>ScoreTable</code> where I can keep and show the scores and a <code>Button</code> class where I can draw the buttons.</p>
<p>What kind of classes should I have? Should I have a <code>ScoreTable</code> class which implements Player, and also a standalone <code>Button</code> class?</p>
<p><img src="https://i.stack.imgur.com/ZzlYl.png" alt="enter image description here"></p>
<p><img src="https://i.stack.imgur.com/59U24.png" alt="enter image description here"></p>
|
[] |
[
{
"body": "<p>You are beginning to mix up the <em>business logic</em> with the <em>user interface</em>. You should (be able to) design a \"game driver\" class without regard to user interface. You want to keep your GUI code separate from your game logic code. And another OO paradigm is to create new objects separately and pass them into where they are used. </p>\n\n<p>I see a <code>Game</code> class ( \"Dealer\" might be a better name) that handles the cards, deals them to players, etc. Then your <code>ScoreTable</code> class wires-up it's buttons to the <code>Game</code> methods. For example a \"Deal\" button's click event handler might be <code>Game.DealCards()</code>.</p>\n\n<p>pseudo code for the idea:</p>\n\n<pre><code> Player me = new Computer();\n Player you = new Human();\n Game aNewGame = new Game (me, you); \n // I'm imagining that the game creates the card deck internally\n ScoreTable theCasino = new ScoreTable(aNewGame);\n\n // inside ScoreTable constructor...\n DealButton.onClick += aNewGame.DealCard();\n</code></pre>\n\n<p><strong>Suggestions</strong></p>\n\n<ol>\n<li>Classes and their interaction reflect real life. Write code that way. I.E. A \"Dealer\" deals \"Card\"s from a \"CardDeck\" to \"Player\"s. (Now I really like \"Dealer\" better than \"Game\" as a class name). Therefore the <code>Game</code> must have (references to the) <code>Player</code>s, so we pass player objects into the Game constructor.</li>\n<li>Think in terms of the <code>ScoreTable</code> only displaying the game, NOT actually playing the game. The <code>Game</code> class plays the game. Thus the <code>ScoreTable</code> must interact/communicate with <code>Game</code> to display what's going on.</li>\n<li>Think of <code>ScoreTable</code> as telling <code>Game</code> what to do and <code>Game</code> does it. For example you click \"Hit Me\" (<code>ScoreTable</code>) and that fires the <code>Game.DealCard()</code> method.</li>\n<li><code>BlackJackTable</code> sounds better to me than <code>ScoreTable</code> for that class name.</li>\n</ol>\n\n<blockquote>\n <p>Can i have a ScoreTable class which implements Player and a stand alone Button class?</p>\n</blockquote>\n\n<p>Do not do this. Think in real-life terms to keep things straight. A <code>ScoreTable</code> is a <code>Player</code>? That does not make sense. A <code>ScoreTable</code> has to display stuff on the screen so it is (inherits from) a Window - whatever the appropriate class is in Java.</p>\n\n<blockquote>\n <p>What kind of classes should i have? </p>\n</blockquote>\n\n<p>I see a <code>ScoreBoard</code> class. Your diagram inspired the thought. The diagram directly suggests the class would have an array (of hands) each element of which holds the final score for both players. This data structure, then, maps clearly to your UI concept. I see it as a separate class because it keeps score for <em>both</em> players, so it is inappropriate to be inside the (individual) Player class. A Player might have his score (hand) for the current game, but not past games, and certainly not the past games of a different player.</p>\n\n<p>*<em>Your Other classes *</em></p>\n\n<ul>\n<li>Card</li>\n<li>Deck - it's an stack of cards, it is not a card. And I mean \"stack\" in the way it behaves.</li>\n<li>Human - a Player that is stupid (we're going to click buttons to tell her what to do).</li>\n<li>Computer - a Player that knows by itself when to hold 'em and when to fold 'em</li>\n<li>Game - the dealer essentially. Shuffles and deals cards. </li>\n<li>ScoreTable - displays what's going on. \"Controls\" the Game via button clicking, etc.</li>\n<li>ScoreCard - keeps history of past game results.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T08:06:43.670",
"Id": "30586",
"Score": "0",
"body": "That's a good and comprehensive answer. :) I'd still like to stress out the importance of separating the business logic from the user interface. You should design the classes so that you can first develop a text-based UI and then, once you are happy with how the game logic functions, you can trivially replace it with a graphical UI. The UI could be used to load the Game class, which should then run the game. My point is that the UI should not host, say, the Deck or the ScoreBoard classes, it should only get them from the Game class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-15T03:35:45.180",
"Id": "133862",
"Score": "0",
"body": "I reckon this answer covers it very well."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T21:15:18.043",
"Id": "19121",
"ParentId": "19118",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T18:34:01.370",
"Id": "19118",
"Score": "1",
"Tags": [
"game",
"classes",
"playing-cards",
"processing"
],
"Title": "Organizing classes for Blackjack game"
}
|
19118
|
<p>For a homework assignment we have to write a class that simulates water breaking a floodbank (very simplistic 2D simulation).</p>
<p>My implementation works fine but I found that there were many downcasts (in my opinion, a flaw in Greenfoot's API, which should be using generic functions rather than functions that take classes as arguments, but I'm not sure if this is possible in Java since this is the first time I'm writing Java code).</p>
<p><code>Sandstone</code> and <code>Sand</code> both derive from <code>Actor</code>, which is from Greenfoot.</p>
<pre><code>import greenfoot.*;
public class Water extends Actor {
public Water() {
getImage().scale(64, 64);
}
public void act() {
if (((DoorbraakWorld)getWorld()).stopped) return;
if (Math.random() < 0.9) return;
int dx = 0, dy = 0;
switch ((int)(3.0 * Math.random())) {
case 0: dx = 0; dy = 1; break;
case 1: dx = 1; dy = 0; break;
case 2: dx = -1; dy = 0; break;
}
// The next line looks so incredibly ugly…
Sandstone sandstone = (Sandstone)getOneObjectAtOffset(dx, dy, Sandstone.class);
if (sandstone != null) {
getWorld().removeObject(sandstone);
getWorld().addObject(new Water(), getX() + dx, getY() + dy);
}
Sand sand = (Sand)getOneObjectAtOffset(0, 1, Sand.class);
if (sand != null) {
((DoorbraakWorld)getWorld()).stopped = true;
return;
}
}
}
</code></pre>
<p>Could I reduce the number of downcasts or is it normal for Java code to contain many downcasts? What else could I improve?</p>
|
[] |
[
{
"body": "<p>Downcasting can usually be avoided by using common methods in abstract types.</p>\n\n<pre><code> if (((DoorbraakWorld)getWorld()).stopped) return;\n</code></pre>\n\n<p>Is this the same as <code>getWorld().stopped()</code>?</p>\n\n<pre><code> // The next line looks so incredibly ugly…\n Sandstone sandstone = (Sandstone)getOneObjectAtOffset(dx, dy, Sandstone.class);\n if (sandstone != null) {\n getWorld().removeObject(sandstone);\n getWorld().addObject(new Water(), getX() + dx, getY() + dy);\n }\n</code></pre>\n\n<p>You can use the Actor type: <code>Actor sandstone = getOneObjectAtOffset(dx, dy, Sandstone.class)</code></p>\n\n<pre><code> Sand sand = (Sand)getOneObjectAtOffset(0, 1, Sand.class);\n</code></pre>\n\n<p>Here too: <code>Actor sand = getOneObjectAtOffset(0, 1, Sand.class);</code></p>\n\n<pre><code> ((DoorbraakWorld)getWorld()).stopped = true;\n</code></pre>\n\n<p>How about <code>greenfoot.stop()</code>?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T03:27:34.387",
"Id": "19124",
"ParentId": "19119",
"Score": "3"
}
},
{
"body": "<p>I suggest you just try removing the casts (one at a time) and seeing if the code still compiles.</p>\n\n<ul>\n<li>If it does, you've answered your question.</li>\n<li>If it does not, there is probably not much you can do about it ... especially if the root cause is poor API design in a 3rd-party library.</li>\n</ul>\n\n<p>(If <code>getOneObjectAtOffset</code> was declared as a generic function, then its declared return type could be the type of the <code>Class</code> object, and a downcast wouldn't be necessary. However: 1) the chances are that you would still require the <code>Class</code> parameter, and 2) there would still be a type cast happening behind the scenes when the result is assigned.)</p>\n\n<p>However, there is one place where the cast absolutely cannot be removed:</p>\n\n<pre><code>switch ((int)(3.0 * Math.random())) {\n</code></pre>\n\n<p>Without the <code>(int)</code> cast, the <code>switch</code> would be switching on a <code>double</code> value, and that is not legal in Java. (But I guess, you weren't referring to that cast ... because it is arguably not a \"downcast\" in the conventional sense.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T03:50:26.383",
"Id": "19126",
"ParentId": "19119",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "19124",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T18:44:53.120",
"Id": "19119",
"Score": "2",
"Tags": [
"java",
"casting"
],
"Title": "2D model simulating water breaking a floodbank"
}
|
19119
|
<p>I've written the following simple filter in Racket as my first Racket program and am wondering if I am writing it in an "idiomatic Racket style".</p>
<pre class="lang-scm prettyprint-override"><code>#! /usr/bin/env racket
#lang racket
(require racket/cmdline)
(define a-prolog-mode? (make-parameter #f))
;; parses the options passed on the command-line
(command-line
#:program "patoms"
#:once-any
[("-a" "--aprolog") "output as A-Prolog code"
(a-prolog-mode? #t)])
;; dlv-input? : string -> boolean
;; Returns True if the given text corresponds to the output of DLV
;; and False otherwise. DLV's output is prefixed by one of the following
;; strings: "DLV", "{", or "Best model".
(define (dlv-input? text)
(regexp-match? #rx"^DLV|^{|^Best model" text))
;; text->answer-sets : string -> list of strings
;; Returns a list comprised of all of the answer sets in the given text.
(define (text->answer-sets text)
(cond
[(dlv-input? text) (regexp-match* #rx"{(.*?)}" text #:match-select cadr)]
[else null]))
;; write-as-code : string
;; Writes the given answer set in plain text form to standard output.
(define (write-as-text answer-set)
(let ([literals (map string-trim (string-split answer-set ","))])
(cond
[(empty? literals) (printf "~a~n" "{}")]
[else (for-each (λ (literal) (printf "~a~n" literal)) literals)])
(printf "~a~n" "::endmodel")))
;; write-as-code : string
;; Writes the given answer set as A-Prolog code to standard output.
(define (write-as-code answer-set)
(let ([literals (map string-trim (string-split answer-set ","))])
(for-each (λ (literal) (printf "~a.~n" literal)) literals)
(printf "~a~n" "%%endmodel")))
;; main
;; Serves as the main function of the program. If a-prolog-mode is specified
;; by the user via the command-line, all of the answer sets that may be parsed
;; from standard input are written to standard output as A-Prolog. Otherwise
;; the answer sets are written in a plain text format.
(define (main)
(let* ([text (port->string (current-input-port))]
[answer-sets (text->answer-sets text)])
(cond
[(a-prolog-mode?) (for-each write-as-code answer-sets)]
[else (for-each write-as-code answer-sets)])))
(main)
</code></pre>
<p>In general, any and all feedback would be very much appreciated given that this is my first foray into Racket.</p>
<p>Thank you kindly in advance.</p>
|
[] |
[
{
"body": "<p>Overall, this is very pleasant code to review. Especially given you're new to the language. Your function names are follow convention such as the use of ending predicates with <code>?</code> and indicating conversions with <code>-></code>. The comments make this code easy to understand. So bravo, keep at it! That being said, here are some pretty minor suggestions.</p>\n\n<ol>\n<li><a href=\"http://www.ccs.neu.edu/home/matthias/Style/style/Choosing_the_Right_Construct.html#%28part._.Definitions%29\" rel=\"nofollow\">\"Favor define when feasible\"</a>. Your <code>let</code>'s and <code>let*</code>'s could be changed to internal <code>define</code>'s to decrease nesting.</li>\n<li>Change <code>(define (main) ...)</code> to <a href=\"http://docs.racket-lang.org/guide/Module_Syntax.html#%28part._main-and-test%29\" rel=\"nofollow\"><code>(module+ main ...)</code></a>. Submodule support added in June's 5.3 release make having main's and test's easier than ever.</li>\n<li>Within <code>main</code>, should one of the <code>cond</code> branches be using <code>write-as-text</code> instead of <code>write-as-code</code>? right now, both branches do the same thing. Along the same vein, the comment above <code>write-as-text</code> was copied but not changed from <code>;; write-as-code</code>.</li>\n<li>In racket, we have 3 ways of doing output, display, write, and print. Since your <code>write-as-text/code</code> functions use printing, I would change the names of those functions to be called <code>print-as-text/code</code></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T20:18:08.967",
"Id": "30636",
"Score": "0",
"body": "Thank you very much for the feedback. I have one more question - would it be better (or more idiomatic) to have a function which returns the appropriate writer (write-as-code or write-as-text) depending on the value of a-prolog-mode? This would seem to enable me eliminate the cond in the main module, but may increase some complexity. Is there a good rule of thumb regarding this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T22:23:06.240",
"Id": "30649",
"Score": "0",
"body": "Having a function like `(define (write-answer-set answer-set) ((if (a-prolog-mode?) write-as-code write-as-text) answer-set))` isn't a bad idea. Modules that define parameters often have helper functions that consult their defined parameter to \"do the right thing\" so that you don't have to."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T16:50:05.937",
"Id": "19157",
"ParentId": "19123",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "19157",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T02:42:40.810",
"Id": "19123",
"Score": "3",
"Tags": [
"scheme",
"racket"
],
"Title": "A Simple Unix Filter in Racket - Learning the Racket Way"
}
|
19123
|
<p>I've written a simple accordion using zepto js lib.</p>
<p>Looking for advice on how to improve this better.</p>
<p><strong>HTML</strong></p>
<pre><code><div class="box">
<span class="learn-more"><a href="#">Learn more</a></span>
<div class="more">
blah<br>
blah<br>
blah<br>
<span class="close"><a href="#">close</a></span>
</div>
</div>
<div class="box">
<span class="learn-more"><a href="#">Learn more</a></span>
<div class="more">
blah<br>
blah<br>
blah<br>
<span class="close"><a href="#">close</a></span>
</div>
</div>
</code></pre>
<p>
<strong>Javascript</strong></p>
<pre><code>$('.more').addClass('hide');
var learnMore = $('.learn-more'),
close = $('.close');
learnMore.click(function() {
$(this).hide().next('div').toggleClass('hide');
});
close.click(function() {
$(this).parent().toggleClass('hide');
$(this).parent().prev().show();
});
</code></pre>
<p>
<strong>Working demo</strong></p>
<p><a href="http://jsfiddle.net/s5x9A/" rel="nofollow">http://jsfiddle.net/s5x9A/</a></p>
<p>How can I prevent the page from jumping when I click on the empty anchor tags?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T03:59:33.157",
"Id": "30581",
"Score": "2",
"body": "You last question is more of a javascript question that belongs on StackOverflow right! I don't see a problem with you code. But you never know with edge cases."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T04:01:21.470",
"Id": "30582",
"Score": "1",
"body": "But the simple answer is you prevent the default click event.\n`$('.box .learn-more a, .box .close a').click(function(e){e.preventDefault();});`"
}
] |
[
{
"body": "<p>There are a couple of inconsistencies which you could tidy up. You're toggling classes to show/hide the div but using show/hide directly on the triggers. You're using chaining in one onClick but not in the other. And you're using the class to reference the accordion contents in one case, but the element name in the other.</p>\n\n<pre><code>$('.more').hide();\n\nvar learnMore = $('.learn-more'),\n close = $('.close');\n\nlearnMore.click(function() {\n $(this).hide().next('.more').show();\n});\n\nclose.click(function() {\n $(this).parent().hide().prev('.learn-more').show();\n});\n</code></pre>\n\n<p>\n<a href=\"http://jsfiddle.net/bN7U5/\" rel=\"nofollow\">Fiddle</a></p>\n\n<p>is one possible way of making everything consistent, although you may prefer to always toggle classes instead (or to add animations). </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T19:22:40.770",
"Id": "19165",
"ParentId": "19125",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T03:29:07.607",
"Id": "19125",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Multiple accordion on a page"
}
|
19125
|
<p>How can I write this PHP code better? It puts together an SQL query string from user input. The task is to return search results based on one or more text fields. The user can determine if partial matches are allowed.</p>
<pre><code>$compop = $allowpartial ? "LIKE" : "="; // use LIKE for wildcard matching
$any = $allowpartial ? "%" : ""; // SQL uses % instead of * as wildcard
$namecondstr = ($name === "") ? "TRUE" : ("Name $compop '$any$name$any'");
$citycondstr = ($city === "") ? "TRUE" : ("City $compop '$any$city$any'");
$itemnocondstr = ($itemno === "") ? "TRUE" : ("ItemNo $compop '$any$itemno$any'");
$ordernocondstr = ($orderno === "") ? "TRUE" : ("OrderNo $compop '$any$orderno$any'");
$serialcondstr = ($serial === "") ? "TRUE" : ("Serial $compop '$any$serial$any'");
$sortstr = ($name !== "") ? "Name" :
(($city !== "") ? "City" :
(($itemno !== "") ? "ItemNo" :
(($orderno !== "") ? "OrderNo" :
"Serial")));
$query = "SELECT * From Licenses
LEFT JOIN Items
ON Licenses.LicenseID = Items.LicenseID
WHERE $namecondstr
AND $citycondstr
AND $itemnocondstr
AND $ordernocondstr
AND $serialcondstr
ORDER BY $sortstr, Licenses.LicenseID";
</code></pre>
|
[] |
[
{
"body": "<h2>Use Prepared Statements</h2>\n\n<p>Your code is vulnerable to SQL injection attacks. Use PDO or mysqli prepared statements to avoid this. See <a href=\"https://stackoverflow.com/questions/583336/how-do-i-create-a-pdo-parameterized-query-with-a-like-statement-in-php\">this answer</a> for how to use PDO for this. If you are using mysql_* you should know that it is already in the deprecation process.</p>\n\n<h2>Miscellaneous</h2>\n\n<ul>\n<li>Consider using <a href=\"http://au1.php.net/manual/en/function.empty.php\" rel=\"nofollow noreferrer\">empty</a> to check for empty strings (see comment from Corbin below).</li>\n<li>Personally I would use an if else rather than have two identical ternary conditions.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T06:53:46.030",
"Id": "30584",
"Score": "0",
"body": "I use `mysql_real_escape_string()` whenever I get a parameter, I thought this would save me from SQL injections?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T07:15:55.870",
"Id": "30585",
"Score": "1",
"body": "I didn't see it in your code above and you said it came from user input, so I thought it needed to be said. I think `mysql_real_escape_string` is okay so long as you remember to use it everywhere that you need to. It will suck when mysql_* is no longer a part of core PHP due to deprecation though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T16:22:49.143",
"Id": "30609",
"Score": "1",
"body": "On a very pedantic note: it's worth mentioning that `empty($x)` and `$x === \"\"` are *not* equivalent. You of course never said that they are equivalent, but it could catch someone unfamiliar with empty by surprise."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T12:35:31.640",
"Id": "30890",
"Score": "0",
"body": "OK, I thought someone would comment on the (in my eyes pretty awful) chain of `AND TRUE AND TRUE...` terms if not all search criteria are specified by the user, or the rather dubious `\"Var $compop '$any$var$any'\"`, but since there are no answers that tell me how to avoid those, I accept your answer. Thanks a lot for the deprecation note, will change to `mysqli_...`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T06:37:31.780",
"Id": "19129",
"ParentId": "19128",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "19129",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T04:09:11.220",
"Id": "19128",
"Score": "4",
"Tags": [
"php",
"sql"
],
"Title": "Building an SQL query string"
}
|
19128
|
<p><img src="https://i.stack.imgur.com/61n3w.png" alt="enter image description here"></p>
<ol>
<li>Delete all matching ID</li>
<li><p>Insert new data</p>
<p>function <strong>add_date($id,$date)</strong> {</p>
<pre><code>mysql_query("DELETE FROM wp_opening_date WHERE Id='$id'");
$dates = explode(",",$date);
foreach ($dates as $date) {
$date = explode("/",$date);
$d = $date[0];
$m = $date[1];
$y = $date[2];
mysql_query("INSERT INTO wp_opening_date (Id, D, M, Y) VALUES ('$id','$d', '$m', '$y')");
}
mysql_close();
</code></pre>
<p>}</p></li>
</ol>
<p>And i using function like this</p>
<pre><code>$id = '277';
$dates = '01/10/2012,28/11/2012,27/11/2012,29/11/2012';
add_date($id,$dates);
</code></pre>
<p>Review my code + idea pls</p>
<p>The idea i will searching Ids by month or year or date</p>
|
[] |
[
{
"body": "<p>Well, there's nothing wrong as far as I can see here. The only thing I would check is that there is a suitable index on the <code>Id</code> field in database, so the delete query can be performed relatively quick.</p>\n\n<p>Another thing to consider is the size of your table. If you have <em>lots</em> of records in there, it can take considerable time to remove and re-add records again (due to indexing and re-indexing upon each delete/insert). In such case, I would simply add a flag to the database, marking those old dates as deleted and simply add new ones at the end of the table.</p>\n\n<p>Yet another thing that comes to my mind now is that you can gain even more performance-wise if you grouped those single inserts like so:</p>\n\n<pre><code>$vals = array();\nforeach ($dates as $date) { \n $date = explode(\"/\",$date);\n $d = $date[0];\n $m = $date[1];\n $y = $date[2];\n $vals[] = \"('$id', '$d', '$m', '$y')\";\n}\nmysql_query(\"INSERT INTO wp_opening_date (Id, D, M, Y) VALUES \".implode(',', $vals));\n</code></pre>\n\n<p>At last, please do not use <code>mysql_*</code> functions, they are now deprecated. See the PHP manual for <a href=\"http://php.net/manual/en/function.mysql-query.php\" rel=\"nofollow\"><code>mysql_query</code></a> for more info.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T08:14:58.237",
"Id": "30587",
"Score": "0",
"body": "Thanks so much, but where is DELETE ? , I will delete all first and add dates"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T08:15:42.900",
"Id": "30588",
"Score": "0",
"body": "I only included the updated part of code - the delete and function definition can stay where it is ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T08:17:23.197",
"Id": "30590",
"Score": "0",
"body": "Can you edit your code to full function ? , I will sure 100% that i learn from your is right :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T08:21:27.190",
"Id": "30591",
"Score": "0",
"body": "mysql_* functions now deprecated ? , How can i do it for all will work for PHP 5.3.2 + ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T08:25:59.520",
"Id": "30592",
"Score": "1",
"body": "sry, my bad... they are not deprecated *yet*, however they will be one day - so if you're making a new PHP application, it's best to choose one of the alternatives - see links in the warning message on `mysql_query` manual page"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T08:26:27.587",
"Id": "30593",
"Score": "0",
"body": "... meaning, your functions will still work, but their usage is simply discouraged."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T08:12:51.713",
"Id": "19133",
"ParentId": "19131",
"Score": "2"
}
},
{
"body": "<p>On first glance, I see a few problem areas with the code that could help with some of the pitfalls of the function you posted.</p>\n\n<ol>\n<li><p>Use of mysql functions are deprecated. Try to use the PDO driver if at all possible through use of the mysql driver they offer. The PDO driver is also much more robust and will allow for this function to not just be coupled to mysql.</p></li>\n<li><p>The way you are getting your date is VERY brittle. To assume that the date is in a format of XX/XX/XXXX is a poor assumption. Try using something that you can specify format to get the individual piece of the date. For example:</p>\n\n<pre><code>$dateObject = new \\DateTime($date);\n$d = $dateObject->format('d');\n$m = $dateObject->format('m');\n$y = $dateObject->format('Y');\n</code></pre></li>\n<li><p>Your parameters for the function are passed straight through to query. This makes you vulnerable to sql injection attacks in some cases. ALWAYS prepare your parameters. So we have;</p>\n\n<pre><code>mysql_query(\"DELETE FROM wp_opening_date WHERE Id=:ID\");\n</code></pre></li>\n<li><p>The final problem is one of testability. How can an automated test be run against this function to make sure it performs correctly. I think a better way would be to inject the connection object rather than to get it inside the function. This would allow you to inject dependencies and foster testability.</p></li>\n</ol>\n\n<p>To wrap it all up we have a final function of:</p>\n\n<pre><code> function addDates($id, $date)\n {\n try {\n $conn = new \\PDO(<Connection Info>);\n\n $delete = \"DELETE FROM wp_opening_date WHERE Id = :ID\";\n $stmt = $conn->prepare($delete);\n $stmt->bindParam(':ID', $id);\n $stmt->execute();\n\n $vals = array();\n $dates = explode(\",\", $date);\n foreach ($dates as $date) {\n $dateObject = new \\DateTime($date);\n $d = $dateObject->format('d');\n $m = $dateObject->format('m');\n $y = $dateObject->format('Y');\n\n $vals[] = \"('$id', '$d', '$m', '$y')\";\n }\n\n $insert = \"INSERT INTO wp_opening_date (Id, D, M, Y) VALUES \" . implode(',', $vals);\n $stmt = $conn->prepare($insert);\n $stmt->execute();\n }\n catch(\\PDOException $e) {\n < Do your failure logic here >\n }\n }\n</code></pre>\n\n<p>Or something along those lines....</p>\n\n<p>Hope this helps!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T15:56:44.487",
"Id": "19293",
"ParentId": "19131",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "19133",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T08:01:52.143",
"Id": "19131",
"Score": "1",
"Tags": [
"php",
"mysql",
"sql"
],
"Title": "Delete matching ID and insert new data"
}
|
19131
|
<p>Can I use <code>task.Wait();</code> like that? Note that when I call <code>task.Wait</code> the task is probably already finished.</p>
<p>And probably you can suggest better pattern.</p>
<pre><code>class A {
private Task task1;
private Task task2;
...
public void Connect() {
stayConnected = true;
task1 = Task.Factory.StartNew(....,
while (stayConnected) {
....
}
LongRunning);
task2 = Task.Factory.StartNew(....,
while (stayConnected) {
....
}
LongRunning);
}
private volatile bool stayConnected;
// should be synchronous. when return everything should be disconected
public void Disconnect() {
stayConnected = false;
task1.Wait();
task1 = null;
task2.Wait();
task2 = null;
}
}
</code></pre>
|
[] |
[
{
"body": "<p><code>Task.Wait()</code> should just return <code>true</code> if the task is completed, so sure you can. However, you should better use waiting with timeout or <code>TimeSpan</code> parameter if you have actions inside of <code>while { }</code> loop that can possibly cause a freeze.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T18:41:09.250",
"Id": "30628",
"Score": "0",
"body": "`Task.Wait()` without a timeout doesn't return anything."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T10:04:01.923",
"Id": "19140",
"ParentId": "19134",
"Score": "0"
}
},
{
"body": "<p>You can use a <code>CancellationToken</code> and <code>Task.WaitAll(...)</code> to do this...</p>\n\n<pre><code>public class A\n{\n private readonly CancellationTokenSource tokenSource = new CancellationTokenSource();\n private Task task1;\n private Task task2;\n\n public void Connect()\n {\n task1 = Task.Factory.StartNew(SomeWork, tokenSource.Token);\n task2 = Task.Factory.StartNew(SomeWork, tokenSource.Token);\n }\n\n public void Disconnect()\n {\n tokenSource.Cancel();\n Task.WaitAll(task1,task2);\n }\n\n public void SomeWork(object o)\n {\n CancellationToken token = (CancellationToken)o;\n while (!token.IsCancellationRequested)\n {\n Console.WriteLine(\"working...\");\n }\n }\n}\n</code></pre>\n\n<p>For more information on managed threads check <a href=\"http://msdn.microsoft.com/en-us/library/dd997364.aspx\" rel=\"nofollow\">this</a> and <a href=\"http://msdn.microsoft.com/en-us/library/ff963549.aspx\" rel=\"nofollow\">this</a> article on MSDN. Enjoy :D</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T15:54:32.153",
"Id": "30607",
"Score": "0",
"body": "why cancellationtoken is better than just \"volatile boolean\"? in general i prefer \"easy to port to c++\" code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T16:39:53.650",
"Id": "30611",
"Score": "0",
"body": "I think `CancellationToken` should be used when you want to cancel a `Task` prematurely. I think that's not the case here. Also, canceling the `Task` properly (which you didn't do) would mean `WaitAll()` would throw an exception."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T16:48:00.363",
"Id": "30614",
"Score": "0",
"body": "You can certainly use `volatile` if you want to keep it simple."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T17:01:30.953",
"Id": "30616",
"Score": "0",
"body": "@svick why does it throw an exception?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T17:51:34.583",
"Id": "30619",
"Score": "0",
"body": "@Alechandro Because the `Task`s would be canceled. `Wait()` and `WaitAll()` throw an exception when you wait on a canceled `Task`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-12T09:09:45.320",
"Id": "315144",
"Score": "0",
"body": "Do not use `volatile`, e.g. see the famous Joe Duffy blog post http://joeduffyblog.com/2008/06/13/volatile-reads-and-writes-and-timeliness/ If you really want to use a `bool` flag, wrap it around the simple `lock` statement (and some lock object)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T11:07:55.097",
"Id": "19145",
"ParentId": "19134",
"Score": "1"
}
},
{
"body": "<p>This seems like a reasonable approach to me. You could improve it a bit by using <code>Task.WaitAll()</code> but that won't change much.</p>\n\n<p>Also, I wouldn't set the fields to <code>null</code> unless I had good reason to do it. Yeah, those <code>Task</code>s are not useful for anything anymore, but they are also almost free.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T18:45:21.613",
"Id": "19163",
"ParentId": "19134",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T08:18:34.040",
"Id": "19134",
"Score": "3",
"Tags": [
"c#"
],
"Title": "Using Task.Wait() for waiting while task is finished (even if it already finished)"
}
|
19134
|
<p>Using Rails 3.2. I have the following code:</p>
<pre><code># photo.rb
class Photo < ActiveRecord::Base
after_create :associate_current_user
after_save :increase_user_photos_count
after_destroy :decrease_user_photos_count
private
def associate_current_user
current_user = UserSession.find.user
self.user_id = current_user.id
end
def increase_user_photos_count
current_user = UserSession.find.user
User.increment_counter(:photos_count, current_user.id)
end
def decrease_user_photos_count
current_user = UserSession.find.user
User.decrement_counter(:photos_count, current_user.id)
end
end
</code></pre>
<p>Before a new record is created, it searches for the <code>current_user</code>. This is alright if it's just 1 new record at a time. But if there are 100 records to be created, it's gonna search for the same <code>current_user</code> 100 times. There is definitely performance issue.</p>
<ol>
<li><p>How should I refactor this so that the app takes the first query result and reuse it for the next 99 times?</p></li>
<li><p>After refactoring, does this affect other users who are also uploading their photos using their accounts?</p></li>
</ol>
<p><strong>Note:</strong> For some reasons, I can't use the <code>counter_cache</code>.</p>
|
[] |
[
{
"body": "<p>Remove the callback, and call that code at the level where it's used best.</p>\n\n<p>I.e.:</p>\n\n<p>When you create a batch of records:</p>\n\n<pre><code>#find and cache user\nuser = UserSession.find.user\n# create your 100 records however you want... this is a dumb example\n100.times { Post.create!(user: user) }\n</code></pre>\n\n<p>When you're in a controller, you want to do the same thing, except you're just creating one post.</p>\n\n<pre><code>user = UserSession.find.user\nPost.create!(user:user, some:other, params:go_here)\n</code></pre>\n\n<p>Now that I've written it, it appears if you wanted to DRY up this example, you could wrap it in some class like this:</p>\n\n<pre><code>class CreatesPosts\n def self.create(num_records = 1, user = UserSession.find.user)\n num_records.times { Post.create!(user:user) }\n # might need to tweak to vary up the Post attributes\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T15:01:01.067",
"Id": "30603",
"Score": "0",
"body": "For some reasons, it doesn't utilize the `photos_controller.rb` at all. I was using this example to upload the photos: http://www.tkalin.com/blog_posts/multiple-file-upload-with-rails-3-2-paperclip-html5-and-no-javascript"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T13:01:48.997",
"Id": "19149",
"ParentId": "19135",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T08:47:49.143",
"Id": "19135",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Reuse object in model in Rails"
}
|
19135
|
<p>Is it possible to write this method in a prettier way?</p>
<pre><code>public static string ByteArrayToString(byte[] byteArray)
{
var hex = new StringBuilder(byteArray.Length * 2);
foreach (var b in byteArray)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
</code></pre>
|
[] |
[
{
"body": "<p>There are popular topics on StackOverflow that cover this exact question: </p>\n\n<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa\">How do you convert Byte Array to Hexadecimal String, and vice versa?</a></p></li>\n<li><p><a href=\"https://stackoverflow.com/questions/623104/c-sharp-byte-to-hex-string\">byte[] to hex string</a></p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-22T18:50:29.283",
"Id": "476463",
"Score": "0",
"body": "It seems that just as on StackOverflow, [consensus here](https://codereview.meta.stackexchange.com/a/9036/7251) is that link-only answers aren't preferable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-23T19:16:03.650",
"Id": "476569",
"Score": "0",
"body": "This answer refers to internal stackoverflow links, not external. Basically it says “this question has already been answered”. I don’t see any reason to copy/paste the code from similar answers."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T09:04:23.030",
"Id": "19137",
"ParentId": "19136",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "19137",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T08:57:20.923",
"Id": "19136",
"Score": "2",
"Tags": [
"c#",
"array"
],
"Title": "Best way convert byte array to hex string"
}
|
19136
|
<p>It work's at Smartphone(Android 2.3.3) but Tablet(Android 4.0) => Force Close!!</p>
<pre><code> public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost); // HERE FORCE CLOSE, why???
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
</code></pre>
<p>Any suggestion with example?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T15:34:46.017",
"Id": "30606",
"Score": "0",
"body": "Try adding yet another catch block like this: `catch (Throwable t) { t.printStackTrace(); }` Then see what it prints to your error log."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-15T18:18:35.690",
"Id": "32929",
"Score": "0",
"body": "because you are networking on the uithread. next time : read the stacktrace, find the exception name, google it."
}
] |
[
{
"body": "<p>You should remember this.</p>\n\n<blockquote>\n <p>From Android 3.x Honeycomb or later, you cannot perform Network IO on\n the UI thread and doing this throws\n android.os.NetworkOnMainThreadException. You must use <strong>Asynctask</strong>\n .</p>\n</blockquote>\n\n<p>You have to put your <code>getXmlFromUrl(..)</code> code inside <strong>Asynctask</strong> method</p>\n\n<p>For more Information Refer this Link\n<a href=\"http://developer.android.com/reference/android/os/AsyncTask.html\" rel=\"nofollow\">http://developer.android.com/reference/android/os/AsyncTask.html</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T06:26:39.503",
"Id": "20698",
"ParentId": "19139",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T09:58:48.383",
"Id": "19139",
"Score": "1",
"Tags": [
"java",
"android"
],
"Title": "Force Stop by Error in httpClient.execute(httpPost);"
}
|
19139
|
<p>I have 3 nested <code>NSEnumeration</code> loops, which are used to get the textfields of a custom cell, in a custom table in a custom view in a controller.</p>
<p>How can I make this code more readable and more optimizated?</p>
<pre><code>- (void) textfieldsOperations:(APOperation)op
{
__block int Valid = 0;
__block NSArray *sub = _Table.subviews;
__block MyCell *cell = nil;
__block UIView *view = nil;
__block NSMutableArray *ret = [NSMutableArray arrayWithCapacity:5];
[sub enumerateObjectsUsingBlock:^(id c, NSUInteger index, BOOL *stop)
{
if ( [c isKindOfClass:[MyCell class]] ) {
cell = c;
[cell.subviews enumerateObjectsUsingBlock:^(id v, NSUInteger index, BOOL *stop)
{
if ( [v isKindOfClass:[UIView class]] ) {
view = v;
[view.subviews enumerateObjectsUsingBlock:^(id t, NSUInteger index, BOOL *stop)
{
if ( [t isKindOfClass:[MyTextField class]] )
{
MyTextField *txt = t;
switch ( op )
{
case APOperationClear:
// something with "txt"
break;
case APOperationEnableSearch:
// something with "valid"
break;
case APOperationGetText:
// something with "txt"
break;
case APOperationPos: {
// something with "txt"
break;
}
}
}
}];
}
}];
}
}];
//[...]
}
</code></pre>
|
[] |
[
{
"body": "<p>honestly: this code should be replaced completely.</p>\n\n<p>you dont give any informations about how your MyCell and MyTextField look like, so I can just give you a general advice: Let MyTextField have a delegate it can call if a certain operation is triggered on it.</p>\n\n<p>ie it could call <code>textField:(MyTextField *)textField didTriggerOperation:(APOperation)op</code> and the implementation would be similar to:</p>\n\n<pre><code>-(void)textField:(MyTextField *)textField didTriggerOperation:(APOperation)op\n{\n if(textField == self.descriptionTextField){\n if(op){\n switch ( op )\n {\n case APOperationClear:\n // something with \"txt\"\n break;\n case APOperationEnableSearch:\n // something with \"valid\"\n break;\n case APOperationGetText:\n // something with \"txt\"\n break;\n case APOperationPos: {\n // something with \"txt\"\n break;\n }\n }\n }\n\n }\n}\n</code></pre>\n\n<p>your textField would call is when the operation was triggered like</p>\n\n<pre><code>[self.delegate textField:self didTriggerOperation:operation];\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-12T01:35:09.263",
"Id": "19515",
"ParentId": "19141",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "19515",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T10:44:11.670",
"Id": "19141",
"Score": "1",
"Tags": [
"performance",
"array",
"objective-c"
],
"Title": "Optimize nested enumerate blocks?"
}
|
19141
|
<p>I would like to share my class IDF. Any suggestions/modification?</p>
<pre><code>public class IDFMeasure
{
private readonly string[] _docs;
private readonly int _numDocs;
private int _numTerms;
private List<string> _terms;
private float[][] _InverseDocFreq;
private int[] _docFreq;
private readonly Dictionary<string, int> _wordsIndex = new Dictionary<string, int>();
public IDFMeasure(string[] documents)
{
_docs = documents;
_numDocs = documents.Length;
MyInit();
}
private List<string> GenerateTerms(string[] docs)
{
return docs.SelectMany(doc => ProcessDocument(doc)).Distinct().ToList();
}
private IEnumerable<string> ProcessDocument(string doc)
{
return doc.Split(' ')
.GroupBy(word => word)
.OrderByDescending(g => g.Count())
.Select(g => g.Key)
}
private int GetTermIndex(string term)
{
return _wordsIndex[term];
}
private void MyInit()
{
_terms = GenerateTerms(_docs);
_numTerms = _terms.Count;
_docFreq = new int[_numTerms];
for (var i = 0; i < _terms.Count; i++)
{
_wordsIndex.Add(_terms[i], i);
}
GenerateDocumentFrequency();
GenerateInverseDocfrequency();
}
private float Log(float num)
{
return (float) Math.Log(num); //log2
}
private void GenerateDocumentFrequency()
{
_InverseDocFreq = new float[_numDocs][];
for (var i = 0; i < _numDocs; i++)
{
_InverseDocFreq[i] = new float[_numTerms];
var curDoc = _docs[i];
var freq = GetWordFrequency(curDoc);
foreach (var entry in freq)
{
var word = entry.Key;
var termIndex = GetTermIndex(word);
_docFreq[termIndex]++;
}
}
}
private void GenerateInverseDocfrequency()
{
for (var i = 0; i < _numDocs; i++)
{
var curDoc = _docs[i];
var freq = GetWordFrequency(curDoc);
foreach (var entry in freq)
{
var word = entry.Key;
var termIndex = GetTermIndex(word);
_InverseDocFreq[i][termIndex] = Log((_numDocs)/
(float) _docFreq[termIndex]);
}
}
}
private Dictionary<string, int> GetWordFrequency(string input)
{
return input.Split(' ').GroupBy(x => x)
.OrderByDescending(g => g.Count())
.ToDictionary(g => g.Key, g => g.Count());
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The layout and naming conventions look good. Thank you for that.</p>\n\n<p>_InverseDocFreq should be renamed _inverseDocFreq to keep with conventions and also stay consistent in your code.</p>\n\n<p>I also think _terms should be an IList. This just eliminates a bunch of the unneeded operations.</p>\n\n<p>you are missing a ; after this statement in <code>ProcessDocument</code></p>\n\n<pre><code>return doc.Split(' ')\n .GroupBy(word => word)\n .OrderByDescending(g => g.Count())\n .Select(g => g.Key)\n</code></pre>\n\n<p>I'm not sure why you are using <code>MyInit</code>, the constructor is the only place that is called. I would move the code into the constructor, then you can make <code>_numTerms</code>, <code>_terms</code>, and <code>_docFreq</code> readonly.</p>\n\n<p>I would rename <code>_wordsIndex</code> to <code>_wordIndex</code> because it is really only and index for each word. I would also move the new into the constructor.</p>\n\n<p>The for loop where you are filling the terms into the _wordIndex dictionary could be moved to its own method, I called it FillWordIndexWithTerms(), and it looks like</p>\n\n<pre><code>private void FillWordIndexWithTerms()\n{\n for (var termIndex = 0; termIndex < _terms.Count; termIndex++)\n {\n _wordIndex.Add(_terms[termIndex], termIndex);\n }\n}\n</code></pre>\n\n<p>I renamed i to termIndex to give it a bit better meaning in your code, and make it easier to read.</p>\n\n<p>The constructor now looks like</p>\n\n<pre><code>public IDFMeasure(string[] documents)\n{\n _docs = documents;\n _numDocs = documents.Length;\n\n _terms = GenerateTerms(_docs);\n _numTerms = _terms.Count;\n\n _docFreq = new int[_numTerms];\n _wordIndex = new Dictionary<string, int>();\n\n FillWordIndexWithTerms();\n GenerateDocumentFrequency();\n GenerateInverseDocfrequency();\n}\n</code></pre>\n\n<p>In the <code>GenerateTerms</code> method, I would change the input parameter to an IEnumerable. You could also use a method group in the linq statement, you don't need the lamba. The function can also be made static.</p>\n\n<pre><code>private static IList<string> GenerateTerms(IEnumerable<string> docs)\n{\n return docs.SelectMany(ProcessDocument).Distinct().ToList();\n}\n</code></pre>\n\n<p><code>ProcessDocument</code> looks good.</p>\n\n<p><code>GetTermIndex</code> looks good.</p>\n\n<p><code>Log</code> could be made static. Other than that it looks good.</p>\n\n<p>I would move the inner ForEach in <code>GenerateDocumentFrequency</code> to its own method. This will reduce nesting.</p>\n\n<pre><code>private void GenerateDocumentFrequency()\n{\n _inverseDocFreq = new float[_numDocs][];\n\n for (var i = 0; i < _numDocs; i++)\n {\n _inverseDocFreq[i] = new float[_numTerms];\n\n var curDoc = _docs[i];\n var freq = GetWordFrequency(curDoc);\n\n CalculateTermFrequency(freq);\n }\n}\n</code></pre>\n\n<p>The ForEach can also be simplified using Linq.</p>\n\n<pre><code>private void CalculateTermFrequency(Dictionary<string, int> freq)\n{\n foreach (var termIndex in freq.Select(entry => GetTermIndex(entry.Key)))\n {\n _docFreq[termIndex]++;\n }\n}\n</code></pre>\n\n<p>In <code>GenerateInverseDocfrequency</code> I would rename i to currentDocument. The nested ForEach should be moved to its own method, <code>CalculateInverseDocumentFrequency</code>.</p>\n\n<pre><code>private void GenerateInverseDocfrequency()\n{\n for (var currentDocument = 0; currentDocument < _numDocs; currentDocument++)\n {\n var curDoc = _docs[currentDocument];\n var freq = GetWordFrequency(curDoc);\n\n CalculateInverseDocumentFrequency(currentDocument, freq);\n }\n}\n\nprivate void CalculateInverseDocumentFrequency(int currentDocument, Dictionary<string, int> freq)\n{\n foreach (var termIndex in freq.Select(entry => entry.Key).Select(GetTermIndex))\n {\n _inverseDocFreq[currentDocument][termIndex] = Log((_numDocs)/\n (float) _docFreq[termIndex]);\n }\n}\n</code></pre>\n\n<p><code>GetWordFrequency</code> could be made static. Other than that it looks good.</p>\n\n<p>Overall, nice code to read, the suggestions are just minor clean-up. I really liked the way you used methods to separate different operations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T18:00:22.567",
"Id": "30623",
"Score": "0",
"body": "The `ProcessDocument` in `GenerateTerms` **needs an object reference for the non-static method** !! This the error I got. Could you review it again please ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T18:08:55.457",
"Id": "30624",
"Score": "0",
"body": "I changed the _terms to an IList...I mentioned it there. I didn't think about the static and ProcessDocument. Just remove it :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T18:15:14.433",
"Id": "30626",
"Score": "0",
"body": "The static from ProcessDocument"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T20:11:00.540",
"Id": "30634",
"Score": "0",
"body": "I think a single more complicated `Select()` would be better than two simple ones: `freq.Select(entry => GetTermIndex(entry.Key))`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T20:24:50.450",
"Id": "30638",
"Score": "0",
"body": "You are right, I totally missed that. Change has been made"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T17:21:09.560",
"Id": "19159",
"ParentId": "19143",
"Score": "4"
}
},
{
"body": "<p>In addition to Jeff's changes (I completely agree with all of them) here are my 2 cents:</p>\n\n<p>I assume this class may process large number of documents, so it's better to switch it to using streaming techniques where you are not required to keep all the data in memory.</p>\n\n<p>So, let's start with constructor... it's usually better to move time-consuming logic out of constructor, e.g. you may later want to introduce asynchronous implementation. So we get rid of constructor and move all the logic into <code>Load</code> method.</p>\n\n<p>By following \"streaming\" technique it should receive IEnumerable instead of pre-loaded array of documents. We will calculate all the stats for each document and then forget about it, so all the arrays that expected a known number of terms and documents should become lists (except <code>_inverseDocFreq</code> as it have to be calculated later, when the total number of docs is known). Here is the resulting code for your class:</p>\n\n<pre><code>public class IDFMeasure\n{\n private readonly List<string> _terms = new List<string>();\n\n /// <summary> contains the number of documents containing certain word. Index corresponds to word index. </summary>\n private readonly List<int> _docFreq = new List<int>();\n private readonly Dictionary<string, int> _wordIndex = new Dictionary<string, int>();\n\n private float[][] _inverseDocFreq;\n\n public void Load(IEnumerable<string> documents)\n {\n List<int[]> documentWordIndexes = new List<int[]>();\n\n foreach (var document in documents)\n {\n var termStatistics = GenerateTermStatistics(document);\n\n AddMissingTermsToIndex(termStatistics);\n GenerateDocumentFrequency(termStatistics);\n documentWordIndexes.Add(GetDocumentWordIndexes(termStatistics));\n }\n\n _inverseDocFreq = GenerateInverseDocfrequency(documentWordIndexes);\n }\n\n ///<summary> Extracts all unique terms from document along with the number of occurrences. </summary>\n private static Dictionary<string, int> GenerateTermStatistics(string document)\n {\n return document.Split(' ')\n .GroupBy(x => x)\n .ToDictionary(g => g.Key, g => g.Count());\n }\n\n ///<summary>Adds missing terms to terms index. </summary>\n private void AddMissingTermsToIndex(Dictionary<string, int> termStatistics)\n {\n foreach (var missingTerm in termStatistics.Keys.Where(term => !_wordIndex.ContainsKey(term)))\n {\n _wordIndex[missingTerm] = _terms.Count;\n _terms.Add(missingTerm);\n _docFreq.Add(0); //to make sure that list is of the same size as _terms\n }\n }\n\n private void GenerateDocumentFrequency(Dictionary<string, int> termStatistics)\n {\n foreach (var term in termStatistics.Keys)\n _docFreq[_wordIndex[term]]++;\n }\n\n private int[] GetDocumentWordIndexes(Dictionary<string, int> termStatistics)\n {\n return termStatistics.Keys.Select(term => _wordIndex[term]).ToArray();\n }\n\n private float[][] GenerateInverseDocfrequency(ICollection<int[]> documentWordIndexes)\n {\n return documentWordIndexes\n .Select(ints => BuildInverseIndexForDocument(documentWordIndexes.Count, ints))\n .ToArray();\n }\n\n private float[] BuildInverseIndexForDocument(int docCount, IEnumerable<int> documentWordIndex)\n {\n var result = new float[_terms.Count];\n\n foreach (var termIndex in documentWordIndex)\n result[termIndex] = (float)Math.Log((docCount / (float)_docFreq[termIndex]));\n\n return result;\n }\n}\n</code></pre>\n\n<p>I preserved counting the number of term occurrences within document even though it is never used in your code, because most likely you would want to use it at some point later.</p>\n\n<p>I removed <code>Log</code> method (it's used only in one place, and it basically does the same as <code>Math.Log</code>, so there is no need in separate method.</p>\n\n<p>Note how <code>_wordIndex</code> dictionary and <code>_terms</code> are dynamically populated in <code>AddMissingTermsToIndex</code> as we find new terms in documents.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T20:13:53.663",
"Id": "30635",
"Score": "1",
"body": "I don't think having a public method that has to be called before the object can be used is a good idea. That's exactly what constructors are for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T09:47:43.140",
"Id": "30653",
"Score": "0",
"body": "@svick I would agree with you if the only thing done there is initialization. It's like `XmlSchema` class, you can initialize it, and then call Compile to prepare it (in our case - to calculate document stats). If there will be millions of 1-2MB documents submitted, the time for required for parsing would be significant. You can't make constructor async, but it's quite easy to rewrite method to run async"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T09:52:02.120",
"Id": "30655",
"Score": "0",
"body": "@Qaesar the class you provided doesn't have public properties or methods, so I don't know what do you expect as result. If the only thing that you're interested in is `_inverseDocFreq` then you can actually return that value in Load method (and rename it correspondingly). The code corresponding to your's is following:\n `var tf = new IDFMeasure();\n tf.Load(allDocs);`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T16:43:14.900",
"Id": "30698",
"Score": "0",
"body": "@Qaesar I don't like premature optimizations but if you touched this topic... Are you sure about same performance? I optimized solution to parse documents only once (extract terms and group them), and in both yours and Jeff's variants the same document is parsed 3 times. So my solution should be roughly 2 times faster then yours or Jeff's. And yours/Jeff's solutions should perform about the same since Jeff suggested cosmetic changes that should not affect performance much."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T19:57:45.177",
"Id": "19168",
"ParentId": "19143",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "19159",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T10:50:50.860",
"Id": "19143",
"Score": "5",
"Tags": [
"c#"
],
"Title": "Inverse Document Frequency (IDF) implementation"
}
|
19143
|
<p>My implementation contains a <code>SpriteComponent</code> class which has a <code>Z</code> property; I use this to determine the order in which to draw my entities (higher Z = drawn on top). It's a simple integer.</p>
<p>What I'm worrying about (premature optimization, I suspect) is the runtime complexity of the function which gets the list of all the <code>SpriteComponents</code> to draw, in order of their Z attribute:</p>
<pre><code>List<IEntity> entitiesToDraw = currentScreen.Entities
.Where(e => e.HasComponent<SpriteComponent>())
.OrderBy(e => e.GetComponent<SpriteComponent>().Z)
.ToList();
</code></pre>
<p>From what I've read, <code>OrderBy</code> uses QuickSort, which is \$O(n log n)\$, but I'm not sure about <code>Where</code>. </p>
<p>I can reasonably assume:</p>
<ul>
<li>1000+ entities can concurrently exist</li>
<li>90% or more of entities have a <code>SpriteComponent</code> in them</li>
<li>Changing the <code>Z</code> of a sprite happens fairly infrequently for most sprites</li>
</ul>
<p>My questions are:</p>
<ul>
<li>Should I be worrying about this call at all?</li>
<li>If so, how can I reduce the runtime complexity, and/or cache the results reliably?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-18T15:14:11.920",
"Id": "192246",
"Score": "0",
"body": "I wouldn't worry about this until it becomes a problem, but once it has consider maintaining the list of entities on screen that have `SpriteComponents` (i.e. cache them) so that the `Where` isn't needed. Additionally in this scenario you probably could tell it to only sort when an item is Add/Removed from the screen which I'm guessing is a lot less frequent than the draw calls."
}
] |
[
{
"body": "<blockquote>\n <p>Not sure about Where</p>\n</blockquote>\n\n<p><code>Where</code> method (if applied to <code>IEnumerable<T></code>) is O(N) operation, and it's a lazy operation so it will do the filtering while consumer reads the result.</p>\n\n<blockquote>\n <p>Should I be worrying about this call at all?</p>\n</blockquote>\n\n<p>The best way to answer this question is to measure the performance and see if it satisfies you. If not - then start thinking about caching results and refreshing them instead of calculating from scratch.</p>\n\n<blockquote>\n <p>If so, how can I reduce the runtime complexity, and/or cache the results reliably?</p>\n</blockquote>\n\n<p>It's hard to suggest good solution based on the information you've provided... Will the number of entities change over time? Can they \"loose\" SpriteComponent?</p>\n\n<p>Assuming that the number of entities is the same and only Z will slightly change you can cache the sorted list from previous run, and apply <a href=\"http://en.wikipedia.org/wiki/Timsort\" rel=\"nofollow\">TimSort</a> or <a href=\"http://www.sorting-algorithms.com/\" rel=\"nofollow\">Insertion sort</a> (you would need to implement it yourselves or grab from <a href=\"https://en.wikibooks.org/wiki/Algorithm_implementation/Sorting/Insertion_sort#C.23\" rel=\"nofollow\">Wikipedia</a>) to nearly-sorted list.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T17:57:20.157",
"Id": "19160",
"ParentId": "19147",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "19160",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T11:54:24.000",
"Id": "19147",
"Score": "2",
"Tags": [
"c#",
"xna",
"monogame"
],
"Title": "Sorting entities by Z in every call to Draw"
}
|
19147
|
<p>I'm fairly new to Arduino and C++ in general, coming from a heavy Python background. The code below is functional, but my lack of C++ knowledge is keeping me from spotting any errors in style, idioms and other good practices.</p>
<p>Not all of the library code is used by the example, as I tried to keep that to the minimum (the functions there are simply more of the same).</p>
<p>While this is one of my first steps into embedded programming, please point out all that you believe is wrong or need improving. I'd rather know what to improve than continue with a false sense of accomplishment :-)</p>
<h2>hypno.h</h2>
<pre><code>#include <Arduino.h>
class HypnoDisc {
public:
HypnoDisc(
byte ledCount,
byte pwmLevels = 5,
byte latch = 7,
byte clock = 6,
byte data = 5);
void
begin(void),
addLight(void),
clockwiseDrop(void),
clockwiseSpin(void),
clockwiseWipe(void),
updateLights(void);
boolean
allDotsLanded(void),
discEmpty(void),
discFull(void);
byte
ledCount;
private:
byte
clockPin, latchPin, dataPin,
pwmMaxLevel,
pwmStep,
*ledStates;
void
latchDown(void),
latchUp(void),
setLength(byte length);
};
</code></pre>
<h2>hypno.cpp</h2>
<pre><code>#include "hypno.h"
HypnoDisc::HypnoDisc(byte ledCountInit, byte pwmLevels, byte latch, byte clock, byte data) {
setLength(ledCountInit);
pwmMaxLevel = pow(2, (pwmLevels - 1));
pwmStep = 0;
latchPin = latch;
clockPin = clock;
dataPin = data;
}
void HypnoDisc::begin(void) {
// Initiates the disc and sets the output to all-dark
pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, OUTPUT);
updateLights();
}
void HypnoDisc::setLength(byte length) {
// Sets the number of output LEDs on the controller, so that animations on the
// disc run as expected (with the wrap where it should be).
if (ledStates != NULL) {
free(ledStates);
}
if (NULL != (ledStates = (byte *)malloc(length))) {
memset(ledStates, 0x00, length);
ledCount = length;
} else { // malloc failed
ledCount = 0;
}
}
void HypnoDisc::latchDown(void) {
// Starts the
digitalWrite(latchPin, LOW);
}
void HypnoDisc::latchUp(void) {
// Stop clocking in data
digitalWrite(latchPin, HIGH);
}
void HypnoDisc::addLight(void) {
// Adds a light at the start of the array
ledStates[0] = pwmMaxLevel;
}
boolean HypnoDisc::allDotsLanded(void) {
// Indicates that all dots are stacked at the end of the array.
// This is also true for a completely empty array.
boolean endOfLanded = false;
for (byte i = ledCount; i-- > 0;) {
if (ledStates[i] < pwmMaxLevel) {
endOfLanded = true;
} else if (ledStates[i] > 0 && endOfLanded) {
return false;
}
}
return true;
}
boolean HypnoDisc::discEmpty(void) {
// Indicates whether the disc is completely empty (trails count as non-empty).
for (byte i = ledCount; i-- > 0;) {
if (ledStates[i] > 0) return false;
}
return true;
}
boolean HypnoDisc::discFull(void) {
// Indicated whether the disc is fully filled with active dots.
for (byte i = ledCount; i-- > 0;) {
if (ledStates[i] < pwmMaxLevel) return false;
}
return true;
}
void HypnoDisc::clockwiseDrop(void) {
// Spins the output LEDs clockwise.
// Lights at the end of the array remain there, and additional Lights that
// fall down are added to a growing arc of max-brightness LEDs.
byte current, next;
for (current = ledCount; --current > 0;) {
next = current - 1;
if (ledStates[current] < pwmMaxLevel) {
ledStates[current] = ledStates[next];
ledStates[next] >>= 1;
} else if (ledStates[next] < pwmMaxLevel) {
ledStates[next] >>= 1;
}
}
}
void HypnoDisc::clockwiseSpin(void) {
// Spins the output LEDs clockwise.
// Lights at the end of the array are moved to the start, making them go round.
byte current, next;
byte lastValue = ledStates[ledCount - 1];
for (current = ledCount; --current > 0;) {
next = current - 1;
ledStates[current] = ledStates[next];
ledStates[next] >>= 1;
}
ledStates[0] = max(ledStates[0], lastValue);
ledStates[ledCount - 1] = max(ledStates[ledCount - 1], lastValue >> 1);
}
void HypnoDisc::clockwiseWipe(void) {
// Spins the output LEDs clockwise.
// Lights at the end of the array are moved off the disc entirely.
byte current, next;
for (current = ledCount; --current > 0;) {
next = current - 1;
ledStates[current] = ledStates[next];
ledStates[next] >>= 1;
}
}
void HypnoDisc::updateLights(void) {
// Writes out the current LED-states with simple software PWM
// This should be called often for good brightness control (>500Hz ideally)
latchDown();
byte i, j, shiftData;
for (i = 0; i < ledCount / 8; i++) {
for (j = 0; j < 8; j++) {
bitWrite(shiftData, j, (ledStates[i * 8 + j] > pwmStep));
}
shiftOut(dataPin, clockPin, LSBFIRST, shiftData);
}
latchUp();
pwmStep = ++pwmStep % pwmMaxLevel;
}
</code></pre>
<h2>HypnoDisc.ino</h2>
<pre><code>/* Flying dots on a circular board */
#include "hypno.h"
const byte updateInterval = 30;
const byte ringSize = 24;
HypnoDisc disc = HypnoDisc(ringSize);
void setup() {
disc.begin();
}
void loop() {
// Creates a set of
byte divisors[] = {12, 8, 6};
for (byte div = 0; div < sizeof(divisors); div++) {
for (byte i = disc.ledCount * 4; i-- > 0;) {
if (i % divisors[div] == 0) {
disc.addLight();
}
disc.clockwiseSpin();
updateFor(updateInterval);
}
wipe();
}
}
void updateFor(byte timeout) {
// Update (PWM) the outputs without movement for `timeout` milliseconds.
long currentMillis = millis();
while (millis() - currentMillis < timeout) {
disc.updateLights();
}
}
void wipe(void) {
// Wipe the output disc clean one step at a time.
while (!disc.discEmpty()) {
disc.clockwiseWipe();
updateFor(updateInterval);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-31T15:04:14.787",
"Id": "53797",
"Score": "0",
"body": "I am going to have to get back into Arduino again! I miss this stuff"
}
] |
[
{
"body": "<p>I'm going to preface this with the fact that I'm not quite sure what (if any) restrictions the Arduino may impose on the C++ you can use. Since you've tagged it as C++, I'm going to assume you can use C++ as you would on any other platform.</p>\n\n<pre><code>void\n begin(void),\n addLight(void),\n clockwiseDrop(void),\n clockwiseSpin(void),\n clockwiseWipe(void),\n updateLights(void);\n</code></pre>\n\n<p>I don't like this at all. I'd (strongly) prefer:</p>\n\n<pre><code>void begin();\nvoid addList():\nvoid clockwiseDrop();\nvoid clockwiseSpin();\nvoid clockwiseWipe():\nvoid updateLights();\n</code></pre>\n\n<p>This isn't (at least according to the tag), so the <code>(void)</code> in the parameter list to specify that they take no parameters is entirely unnecessary. </p>\n\n<pre><code>HypnoDisc::HypnoDisc(byte ledCountInit, byte pwmLevels, byte latch, byte clock, byte data) {\n setLength(ledCountInit);\n pwmMaxLevel = pow(2, (pwmLevels - 1));\n pwmStep = 0;\n latchPin = latch;\n clockPin = clock;\n dataPin = data;\n}\n</code></pre>\n\n<p>It looks like these should be handled in a member initializer list instead of assignments in the body of the ctor. The one that initially looks like an exception is the call to setlength, but from the looks of things, that should really be as well--but with <code>ledcount</code> and <code>ledstates</code> replaced by a <code>std::vector<byte></code>, at which point it can be initialized in the initializer list, just like the rest. For the moment, I'll assume you've done this.</p>\n\n<pre><code>HypnoDisc::HypnoDisc(byte ledCount, byte pwmLevels, byte latch, byte clock, byte data) \n : ledstates(ledcount), \n pwmMaxLevel(1 << pwmLevels), \n pwmStep(0), \n latchPin(latch),\n clockPin(clock)\n dataPin(data)\n{ }\n</code></pre>\n\n<p>As mentioned above, <code>setLength</code>:</p>\n\n<pre><code>void HypnoDisc::setLength(byte length) {\n // Sets the number of output LEDs on the controller, so that animations on the\n // disc run as expected (with the wrap where it should be).\n if (ledStates != NULL) {\n free(ledStates);\n }\n if (NULL != (ledStates = (byte *)malloc(length))) {\n memset(ledStates, 0x00, length);\n ledCount = length;\n } else { // malloc failed\n ledCount = 0;\n }\n}\n</code></pre>\n\n<p>...should be replaced with something like <code>std::vector<byte> ledStates;</code>. If you can't use <code>std::vector</code>, you should still really do a vector-like class of your own instead of trying to embed its functionality into the parent class.</p>\n\n<pre><code>boolean HypnoDisc::discEmpty(void) {\n // Indicates whether the disc is completely empty (trails count as non-empty).\n for (byte i = ledCount; i-- > 0;) {\n if (ledStates[i] > 0) return false;\n }\n return true;\n}\n</code></pre>\n\n<p>Assuming the previous modification, this can be done with:</p>\n\n<pre><code>return std::allof(ledStates.begin(), ledStates.end(), [](byte b) {return b == 0; });\n</code></pre>\n\n<p>Likewise with <code>discFull</code>.</p>\n\n<pre><code>void HypnoDisc::updateLights(void) {\n // Writes out the current LED-states with simple software PWM\n // This should be called often for good brightness control (>500Hz ideally)\n latchDown();\n byte i, j, shiftData;\n for (i = 0; i < ledCount / 8; i++) {\n for (j = 0; j < 8; j++) {\n bitWrite(shiftData, j, (ledStates[i * 8 + j] > pwmStep));\n }\n shiftOut(dataPin, clockPin, LSBFIRST, shiftData);\n }\n latchUp();\n pwmStep = ++pwmStep % pwmMaxLevel;\n}\n</code></pre>\n\n<p>Based on the usage pattern, I think I'd move <code>latchUp</code> and <code>latchDown</code> into the ctor and dtor of a separate class:</p>\n\n<pre><code>struct latch {\n latch() { /* same code as your current `latchDown` */ }\n ~latch() { /* same as your current `latchUp */ }\n};\n</code></pre>\n\n<p>Then updateLights simplifies a little bit to:</p>\n\n<pre><code>void HypnoDisc::updateLights() {\n latch l;\n for (byte i=0; i<ledCount; i++)\n for (byte j=0; j<8; j++)\n bitWrite(shiftData, j, (ledStates[i*8+j] > pwmStep));\n}\n</code></pre>\n\n<p>It's also worth at least considering writing a little <code>byteWrite</code> function that handles calling <code>bitWrite</code> in a loop for an entire byte's worth of data.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T21:52:07.123",
"Id": "76842",
"Score": "0",
"body": "That's a lot of useful pointers, thanks Jerry. The use of vector<byte> makes things a lot nicer and the initializer list makes things better. That has allowed me to make the pins used for the disc `const` as well. Unfortunately, allof is not implemented in either the Arduino stdlib or the [StandardCPlusPlus](https://github.com/maniacbug/StandardCplusplus/) library, so it now uses an iterator and some inline code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T21:55:14.070",
"Id": "76843",
"Score": "0",
"body": "I'm not sure how you meant the `struct latch` block to work. putting the latch on the `class HypnoDisc` the compiler complained a lot about using non-static members. I currently have a method `HypnoDisc::toggleLatch()` that returns an instance of my `struct latch`. The latch is initialized with the `latchPin` and the ctor/dtor toggle the pin state. Is there a nicer way of doing that?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T05:16:07.323",
"Id": "43839",
"ParentId": "19148",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T12:52:37.720",
"Id": "19148",
"Score": "3",
"Tags": [
"c++",
"arduino"
],
"Title": "Feedback on Arduino class for LED circle animations"
}
|
19148
|
<p>I have created a nice url structure for my site.</p>
<p>In my .htaccess I have:</p>
<pre><code>FallBackResource /index.php
</code></pre>
<p>And in my router class I have:</p>
<pre><code>class init {
function __construct($url)
{
$URLElements = explode('/', $url) ; // Adjust if needed.
if($url)
{
$class = $URLElements[0] ;
if(substr_count($url, '/') == 1)
{
$method = $URLElements[1] ;
}
}
if(($t = substr_count($url, '/')) > 1)
{
for($i=2;$i<$t+1;$i++) {
echo $URLElements[$i].'<br />';
}
}
}
}
</code></pre>
<p>Is this ok and what are your thoughts (how can it be improved etc)?</p>
|
[] |
[
{
"body": "<p>There's not really much to review here, but a few quick items:</p>\n\n<ul>\n<li>This is going to sound weird at first glance, but you have a route() method that takes a path instead of depending directly on the request uri.\n<ul>\n<li>A router's job is to route. By hard coding the <code>$_SERVER['REQUEST_URI']</code>, you've made it limited to one data source.</li>\n<li><code>route($path)</code> would be much more flexible, and it would mean that one object could be used for routing more than 1 time.</li>\n<li>Think about test driven design. How would you test a hard coded <code>$_SERVER['REQUEST_URI']</code>? (Other than putting a hacky assignment to it somewhere)</li>\n</ul></li>\n<li>Never assume that array indexes exist\n<ul>\n<li>If someone goes to <code>index.php</code> or <code>/foo</code>, so on, then <code>$URLElements</code> might not have 2 elements</li>\n</ul></li>\n<li>As it is, your class does nothing useful -- you probably know that though :)\n<ul>\n<li>A major improvement would be making it actually do something :)</li>\n</ul></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T17:02:09.273",
"Id": "30617",
"Score": "0",
"body": "Thanks, I have implemented your comments (see edit). Yes it doesn't really do anything yet, I will be putting in all the stuff like class_exists and validation etc shortly."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T16:11:35.793",
"Id": "19155",
"ParentId": "19152",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "19155",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T14:04:41.970",
"Id": "19152",
"Score": "2",
"Tags": [
"php",
".htaccess"
],
"Title": "Can my router code be improved?"
}
|
19152
|
<p>See <a href="https://codereview.stackexchange.com/questions/18982/randomizing-and-mutating-algo-class-style">Randomizing and mutating algo class - style</a></p>
<p>I'm looking for a review of the functionality of this code, answers to the above question which also describes the code use focus on style instead.</p>
<p>Below is the updated code since the style feedback.</p>
<p><code>algo</code> is an algorithm that is dynamic. <code>algo</code> instances can be created, asked to become random, mutated and also run. They can be set to remember changes they make to themselves between runs or not. They also output values, these could be used for anything from value sequences such as mathematical number sequences to controls for a bot in a game. It's straightforward to specify limits on memory or computation steps for each as well and needless to say are entirely sandboxed.</p>
<p>By sandboxed I mean that they only compute and produce output as described, they cannot for example use local or global variables, print to the console, <code>#include</code> or write to files.</p>
<p><code>algo</code>s can be used where algorithms need to be portable and must be only able to calculate/compute. There is no distinction between data and instructions in an <code>algo</code>.</p>
<p>A use is as values for directed search for algorithms such as with evolutionary algorithms, MCTS or others.</p>
<p>Another is in a data file that includes algorithms, like an image that includes its own way to decompress itself, that can therefore be constructed using the specific image that is to be decompressed.</p>
<p>They are deliberately general, being a component that could be used in many contexts and conceptually simple, as a number is.</p>
<pre><code>// by Alan Tennant
// Nov 2012
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib> // for rand and abs
#include <ctime>
class algo
{
public:
std::vector<unsigned short> code;
std::vector<unsigned int> output;
bool debug_info;
algo()
{
reset1(false);
instructions_p = 11;
debug_info = true;
}
void random(unsigned int size)
{
code.clear();
output.clear();
for(unsigned int n = 0; n < size; n++)
code.push_back(rand() % instructions_p);
reset1(true);
}
void run(
unsigned long most_run_time,
unsigned int largest_program,
unsigned int largest_output_size,
bool reset)
{
if (reset && !is_reset_p)
{
reset1(true);
output.clear();
code2 = code;
code_pos = 0;
}
is_reset_p = false;
size_t code_size = code2.size();
if (debug_info && !can_resume_p)
std::cout<<"can't resume, reset first"<<std::endl;
if(code_size == 0 || most_run_time == 0)
{
out_of_time_p = true;
out_of_space_p = false;
run_time_p = most_run_time;
}
else if (can_resume_p)
{
unsigned short instruction;
bool cont = true;
if(debug_info) {
std::cout<<"size: "<<code_size<<std::endl<<std::endl;}
while(cont)
{
instruction = code2[code_pos] % instructions_p;
if(debug_info) {std::cout<<code_pos<<", ";}
code_pos = (code_pos + 1) % code_size;
switch(instruction)
{
case 0:
if(debug_info) {std::cout<<"end";}
cont = false;
can_resume_p = false;
break;
case 1:
if(debug_info) {
std::cout<<"goto p1";}
code_pos = code2[(code_pos + 1) % code_size];
break;
case 2:
if(debug_info) {
std::cout<<"if value at p1 % 2 = 0 then goto p2";}
if(code2[code2[code_pos] % code_size] % 2 == 0) {
code_pos = code2[(code_pos + 1) % code_size];}
else {
code_pos += 2;}
break;
case 3:
if(debug_info) {std::cout<<"value at p1 = value at p2";}
code2[code2[code_pos] % code_size] =
code2[code2[(code_pos + 1) % code_size] % code_size];
code_pos += 2;
break;
case 4:
if(debug_info) {
std::cout<<"value at p1 = value at p2 + value at p3";}
code2[code2[code_pos] % code_size] = (
code2[code2[(code_pos + 1) % code_size] % code_size] +
code2[code2[(code_pos + 2) % code_size] % code_size]
) % USHRT_MAX;
code_pos += 3;
break;
case 5:
{
if(debug_info)
{std::cout<<"value at p1 = value at p2 - value at p3";}
long v1 =
(long)code2[code2[(code_pos + 1) % code_size] % code_size] -
code2[code2[(code_pos + 2) % code_size] % code_size];
code2[code2[code_pos] % code_size] = abs(v1) % USHRT_MAX;
code_pos += 3;
}
break;
case 6:
{
if(debug_info) {std::cout<<"toggle value at p1";}
size_t v1 = code2[code_pos] % code_size;
unsigned short v2 = code2[v1];
if(v2 == 0) {code2[v1] = 1;}
else {code2[v1] = 0;}
code_pos++;
}
break;
case 7:
if(debug_info) {
std::cout<<"output value at p1";}
output.push_back(code2[code2[code_pos] % code_size]);
code_pos++;
break;
case 8:
if(debug_info) {std::cout<<"increase size";}
code2.push_back(0);
break;
case 9:
{
if(debug_info) {std::cout<<"increment value at p1";}
size_t v1 = code2[code_pos] % code_size;
code2[v1] = (code2[v1] + 1) % USHRT_MAX;
code_pos++;
}
break;
case 10:
{
if(debug_info) {std::cout<<"decrement value at p1";}
size_t v1 = code2[code_pos] % code_size;
code2[v1] = abs((code2[v1] - 1) % USHRT_MAX);
code_pos++;
}
break;
}
if(debug_info) {std::cout<<std::endl;}
run_time_p++;
code_size = code2.size();
code_pos = code_pos % code_size;
if(run_time_p == most_run_time) {
cont = false; out_of_time_p = true;}
if(code_size > largest_program)
{
cont = false;
can_resume_p = false;
out_of_space_p = true;
if (debug_info)
std::cout<<"became too large"<<std::endl;
}
if(output.size() > largest_output_size)
{
cont = false;
can_resume_p = false;
output.pop_back();
if (debug_info)
std::cout<<"too much output"<<std::endl;
}
}
if (debug_info)
{
std::cout<<std::endl<<"size: "<<code_size<<std::endl<<
std::endl<<"output: "<<std::endl;
size_t output_size = output.size();
for (size_t t = 0; t < output_size; t++)
std::cout<<output[t]<<std::endl;
}
}
}
void mutate(unsigned int largest_program)
{
output.clear();
size_t size;
// special mutations
while(rand() % 4 != 0) // 3/4 chance
{
size = code.size();
if(rand() % 2 == 0) // 1/2 chance
{
// a bit of code is added to the end (would prefer inserted anywhere)
if(size < largest_program)
code.push_back(rand() % instructions_p);
}
else
{
// a bit of code is removed from the end (would prefer removed from anywhere)
if(size != 0)
code.pop_back();
}
// a section of code is moved, not yet implemented.
}
// mutate bits of the code
size = code.size();
if (size > 0)
{
unsigned int most_mutation =
static_cast<unsigned int>(size * 0.1); // static_cast to support GCC
if(most_mutation < 9)
most_mutation = 8;
unsigned int mutation = rand() % most_mutation;
for(unsigned int n = 0; n < mutation; n++)
code[rand() % size] = rand() % instructions_p;
}
reset1(true);
}
#pragma region
unsigned long run_time()
{
return run_time_p;
}
bool out_of_time()
{
return out_of_time_p;
}
bool out_of_space()
{
return out_of_space_p;
}
bool can_resume()
{
return can_resume_p;
}
bool is_reset()
{
return is_reset_p;
}
private:
bool can_resume_p, is_reset_p,
out_of_time_p, out_of_space_p;
unsigned int code_pos;
unsigned short instructions_p;
unsigned long run_time_p;
std::vector<unsigned short> code2;
void reset1(bool say)
{
out_of_time_p = false;
out_of_space_p = false;
run_time_p = 0;
code2 = code;
code_pos = 0;
can_resume_p = true;
is_reset_p = true;
if (say && debug_info)
std::cout<<"reset"<<std::endl;
}
#pragma endregion
};
int main()
{
srand((unsigned int)time(NULL));
algo a = algo();
a.random(50);
std::cout<<std::endl<<std::endl;
a.run(10, 100, 10, false);
std::cout<<std::endl<<std::endl;
a.run(10, 100, 10, false);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-26T12:47:45.550",
"Id": "79160",
"Score": "1",
"body": "\"Below is the updated code since the style feedback\": it still lacks many improvements suggested in the previous feedbacks (`#pragma region` is still there, you stil use `USHRT_MAX`...)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-27T19:00:52.433",
"Id": "79429",
"Score": "0",
"body": "This is from some time ago and I'm not working on it anymore. I actioned much of the style feedback, but some I preferred to leave as before."
}
] |
[
{
"body": "<p>It is a bit hard to tell what <code>algo</code> does. For one thing, some of its data members are all <code>public</code>, but they should all be <code>private</code>. There's also quite a bit of inline code, making it hard to read. For this, I'd recommend putting the implementation details in a separate file, and just have declarations in this file.</p>\n\n<p>Your \"gutted-out\" class may look like this:</p>\n\n<pre><code>class algo\n{\n private:\n std::vector<unsigned short> code;\n std::vector<unsigned int> output;\n bool debug_info;\n bool can_resume_p, is_reset_p,\n out_of_time_p, out_of_space_p;\n unsigned int code_pos;\n unsigned short instructions_p;\n unsigned long run_time_p;\n std::vector<unsigned short> code2;\n void reset1(bool say);\n\n public:\n algo();\n void random(unsigned int size);\n void run(\n unsigned long most_run_time,\n unsigned int largest_program,\n unsigned int largest_output_size,\n bool reset);\n void mutate(unsigned int largest_program);\n\n unsigned long run_time()\n {\n return run_time_p;\n }\n bool out_of_time()\n {\n return out_of_time_p;\n }\n bool out_of_space()\n {\n return out_of_space_p;\n }\n bool can_resume()\n {\n return can_resume_p;\n }\n bool is_reset()\n {\n return is_reset_p;\n }\n};\n</code></pre>\n\n<p>From here, you can get a better idea of what it's really doing. You can easily focus on the definition and implementation separately. It'll also avoid having everything inlined, which is done automatically within a class declaration (but single-line functions, such as getters and setters, are still okay to have).</p>\n\n<p><strong>Misc.:</strong></p>\n\n<ul>\n<li><p>User-defined type names generally start with a capital letter (this separates them from variables and functions), so <code>algo</code> should be <code>Algo</code>.</p></li>\n<li><p>Some of your names are unclear. Does <code>code</code> actually contain code? Does <code>output</code> contain data that will be outputted? What is <code>code_pos</code>?</p></li>\n<li><p>If a member function doesn't modify any data members, it should be <code>const</code>. This would apply to all of the <code>bool</code> functions.</p></li>\n<li><p>You don't need to invoke the default constructor yourself when creating an object:</p>\n\n<blockquote>\n<pre><code>algo a = algo();\n</code></pre>\n</blockquote>\n\n<p>It will already be invoked upon object-creation:</p>\n\n<pre><code>algo a;\n</code></pre></li>\n<li><p>You have <code>std::endl</code> scattered around the code, which you don't really need. It also flushes the buffer, which is slower.</p>\n\n<p>If you need a newline, simply output a <code>\\n</code>:</p>\n\n<pre><code>std::cout << \"This prints two newlines at the end\\n\\n\";\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-29T22:47:29.210",
"Id": "58445",
"ParentId": "19153",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T15:19:45.190",
"Id": "19153",
"Score": "5",
"Tags": [
"c++",
"algorithm",
"search",
"random",
"simulation"
],
"Title": "Randomizing and mutating algo class - functionality"
}
|
19153
|
<p>Despite being the clever Java coder I am, I noticed I know way too little about various design patterns. The <a href="http://en.wikipedia.org/wiki/Builder_pattern" rel="nofollow">builder pattern</a> caught my eye as something to learn, as I have certainly seen my fair share of telescopic constructors already.</p>
<p>So, I decided to give it a try. The following is a really simple class represents a cell in a table of data. So far a cell can have text (its contents) and a URL (if it is to be rendered as a hyperlink), but I could see myself adding other parameters as well, so there's an inner static class called <code>CellBuilder</code> as well. </p>
<pre><code>import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A class that represents data in a table cell.
*/
public class CellData {
/** The text that's displayed in the cell. **/
private final String text;
/** The URL to which the text should link to, if any. **/
private final URL url;
private CellData(CellBuilder builder) {
this.text = builder.text;
this.url = builder.url;
}
public String getText() {
return text;
}
public URL getUrl() {
return url;
}
/** A builder to avoid telescopic constructors. **/
public static class CellBuilder {
private String text = "";
private URL url = null;
public CellBuilder text(String text) {
this.text = text;
return this;
}
public CellBuilder url(String url) {
try {
this.url = new URL(url);
} catch (MalformedURLException ex) {
Logger.getLogger(CellData.class.getName()).log(Level.SEVERE, null, ex);
}
return this;
}
public CellData build() {
return new CellData(this);
}
}
}
</code></pre>
<p>A new cell would then be created, for example, like this:</p>
<pre><code>CellData cell = new CellData.CellBuilder().text("hello").url("http://www.example.com/foo").build();
</code></pre>
<p>Now, I don't know about you, but to me that doesn't look much more easier or cleaner than doing it the traditional way, by passing those arguments to the cell in its constructor. :( Yet another way would be to do it like this:</p>
<pre><code>CellData cell = new CellData();
cell.setText("hello");
cell.setUrl("http://www.example.com/foo");
</code></pre>
<p>Why shouldn't I do it like that either? I wonder if this particular use case is still too simple to get the best out of this design pattern, or if I'm doing something else completely wrong?</p>
<p>Notice that this doesn't strictly conform to the architecture presented in Wikipedia, but that's because I read about this way from some other source where it was more like this, and the Wikipedia way with about five classes felt like too complicated for a simple matter like this.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T17:59:52.193",
"Id": "30622",
"Score": "1",
"body": "Guava uses the builder pattern frequently in their helper/utility classes. These classes are intended to be highly customizable to a user's specific situation while remaining fluent/easy to use. A concrete object with less than 5 parameters is probably too simple to bother with a Builder. Examples: http://code.google.com/p/guava-libraries/wiki/CommonObjectUtilitiesExplained"
}
] |
[
{
"body": "<p>The builder pattern really shines when you have complex logic around what you are trying to construct. I use this pattern frequently in my unit test projects. If I need to setup some dependencies that require mocking, but the interactions aren't central to my test, then I don't want to see it in my test. A builder is also useful for setting defaults that are required by the object under test, but again, not central to what I am trying to test. Putting all this code in a builder gets it out of the way. It also keeps the code DRY (Don't Repeat Yourself), so that if there is a change to how that object is instantiated, there is only one place to fix all my broken tests.</p>\n\n<p>If you don't have this kind of complexity in your object, then I wouldn't bother with the pattern.</p>\n\n<p>If you are looking for a way to avoid a long constructor parameter list, I would suggest waiting until it gets long, and then evaluating what your class is doing. Perhaps some parameters are only needed during the execution of some method. If that's the case, just pass those parameters in when you call the method. If you feel you can't do that, then maybe the class is starting to violate the Single Responsibility Principle. Look to see where those parameters are used, and maybe you can identify which ones go together, and split out another class.</p>\n\n<p>It's a useful pattern, but I think your initial assessment is right: that this use case is too simple for it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T17:03:17.170",
"Id": "19158",
"ParentId": "19154",
"Score": "0"
}
},
{
"body": "<p>Your building pattern is just right. But the situation (as elsewehere mentioned) to use the building pattern is not. Imagine a situation where there is a (in your case) celldata base class:</p>\n\n<pre><code> class CellData {\n }\n</code></pre>\n\n<p>This class is the base of other, more specific, celldata class:</p>\n\n<pre><code> class CellData_2 extends CellData {\n }\n</code></pre>\n\n<p>etc.</p>\n\n<p>Now imagine the choice of which specific celldata you are requiring, depending on the given URL your builder method starts to look something like this:</p>\n\n<pre><code> public CellData build (String URL) {\n if (URL complies to case 1) {\n return new CellData_1;\n ...\n }\n</code></pre>\n\n<p>That's where the builder pattern should be used.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T21:43:18.267",
"Id": "30644",
"Score": "2",
"body": "I think you’re confusing the builder pattern with the factory method pattern. While dynamic constructor dispatch *can* be done by the builder, that’s not its main purpose. The main purpose is exactly what OP has said (but his use-case is rather restricted). Consider Java’s `StringBuilder` class. No inheritance or dynamic dispatch is used here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T21:23:14.920",
"Id": "30711",
"Score": "0",
"body": "Thanks for you answer, @dmaij. :) It would make sense to me to add some factory-like features to the builder like this."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T18:42:22.030",
"Id": "19162",
"ParentId": "19154",
"Score": "4"
}
},
{
"body": "<p>Builders are often employed when complex structures or records with lots of attributes need to be set. But more simply they are used to keep an object immutable. A prime example of that is the <code>StringBuilder</code> class which is used to build immutable <code>String</code>s: the object isn’t very complex – in fact, in terms of data it’s as easy as it gets – but the logic to <em>create</em> them might be.</p>\n\n<p>The <code>StringBuilder</code> class is needed because strings themselves are immutable for performance (and other) reasons. As a consequence, lots of operations on strings create new strings. If many such operations are chained, this becomes inefficient. The <code>StringBuilder</code> class mitigates that by providing a <em>mutable</em> string which can be modified repeatedly, and only <em>then</em> transformed into an immutable string.</p>\n\n<p>Another example from one of my projects was a complex class which represented <a href=\"https://en.wikipedia.org/wiki/Petri_net\" rel=\"nofollow\">a special class of graphs</a>. Again, for performance reasons and to keep its API simple, this class was designed to be immutable. So in order to to <em>create</em> and <em>mutate</em> graphs I provided a builder class which exposed methods for modifying its internal graph structure, and a conversion method to an immutable graph.</p>\n\n<p><a href=\"http://www.javapractices.com/topic/TopicAction.do?Id=29\" rel=\"nofollow\">Immutability is a highly recommended feature</a> of classes. This is why you shouldn’t choose the second method you proposed, i.e. have a class with lots of setters. In fact, <a href=\"http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html\" rel=\"nofollow\">setters are often code smell</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T21:21:27.920",
"Id": "30710",
"Score": "0",
"body": "Hey, thanks for the interesting links! So far this seems like the best answer. I didn't even think of the pattern being useful with regards to immutability, but now that you mentioned it with that link, it actually makes a lot of sense. Although I'm still going to have to meditate on the recommendation of making most classes immutable. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-24T17:10:11.333",
"Id": "67111",
"Score": "0",
"body": "It's too bad that the `String`/`StringBuilder` [or `StringBuffer`] pattern used for storing collections of characters wasn't carried through with other types of collection. Even if converting an immutable collection to a mutable one, modifying it, and converting it back to an immutable one would require a full data copy for each direction of conversion, it would eliminate the need for many other defensive-copy operations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-24T21:22:08.777",
"Id": "67170",
"Score": "0",
"body": "@supercat What’s wrong with `Collections.unmodifiable*` then? Back when I used Java I used that obsessively. Granted, that’s “only” interface immutability but as far as I’m concerned it’s enough. It’s only one step more complicated to mutate a string."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-24T21:46:07.613",
"Id": "67172",
"Score": "0",
"body": "@KonradRudolph: If code receives a `List<String>` and wishes to take a snapshot of its contents, is there any way by which it can know whether it needs to create a new object holding those items, or whether storing a reference to the received object would be sufficient?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-24T22:56:12.033",
"Id": "67188",
"Score": "0",
"body": "Ah well, no, not that I know of."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-25T21:48:32.910",
"Id": "67287",
"Score": "0",
"body": "@KonradRudolph: Am I wrong in thinking that passing around references to collections that are in fact never going to change is a common way of passing around the contents thereof, and that it's common for code to want to hold onto the contents of collections received in such fashion? I find it curious that neither Java nor .NET provides an easy way to pass a reference to a collection which the recipient can regard as a permanent snapshot of itself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-26T12:10:33.980",
"Id": "67356",
"Score": "0",
"body": "@supercat Yes, agreed."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T21:49:18.897",
"Id": "19172",
"ParentId": "19154",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "19172",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T15:25:38.267",
"Id": "19154",
"Score": "0",
"Tags": [
"java",
"design-patterns"
],
"Title": "Am I getting the builder pattern right?"
}
|
19154
|
<p>This question is related to this thread
<a href="https://stackoverflow.com/questions/13630584/the-best-method-for-handling-bibtex-files/13631021#13631021">StackOverflow</a></p>
<p>I would like to share with you my code, that is supposed to read a bibtex file and perform some analysis on it.</p>
<p>The code works fine, but I'm uncomfortable with the chosen data structure (list of dictionaries).</p>
<p>By posting the code here I hope to get feedback from this community and hopefully enhance the code.</p>
<pre><code># perform some tests on ped.bib related to the pdf-directory (pdfdir)
# activate one or more tests by setting those control variables to 1
# 1. is_check_file: check objects with no or empty file entry
# 2. is_check_double_file: check if two or more different objects have the same pdf entry
# 3. is_check_unused_files: check <pdfdir> for unsused files
import os, sys, glob, copy
from os import path, access, R_OK # W_OK for write permission.
from operator import itemgetter
#-------- control parameter ---------
is_check_file = 0
is_check_double_file = 0
is_check_unused_files = 1
#------------------------------------
ROOT = os.getenv("HOME") # Home directory
#ROOT = path.expanduser("~") # works on all platforms
pdfdir = ROOT + '/lit/pdf/'
print 'pdfdir', pdfdir
debug = 0 # shutdown debug/info messages
bib_data = open('ped.bib')
words = ['author', 'title', 'journal', 'year', 'volume', 'comment', 'issue', 'owner', 'file', 'timestamp', 'booktitle', 'editor', 'publisher', 'number', 'part', 'keywords', 'doi', 'month', 'organization', 'url']
#------------------------------------------------------------------------------
def check_missing_pdf(element):
"""
following testes:
1. element has no file entry
2. element has empty file entry
3. element has file entry with inexistant pdf-file
"""
#check missing files
if not element.has_key('file'): # element has no file
print >>sys.stderr, '==== %s has no file entry'%element.get('key')
elif not element.get('file'): # .. or file is empty
print >>sys.stderr, '**** %s has empty file entry'%element.get('key')
else:
# we have a file entry -----> check its existance in the pdf dir
pdffile = pdfdir + element.get('file')
if not( path.exists(pdffile) and path.isfile(pdffile) and access(pdffile, R_OK)):
print >>sys.stderr, '#### %s with file entry [%s]: Either file is missing or is not readable'%(element.get('key'), element.get('file'))
#------------------------------------------------------------------------------
def check_doubles(elements):
"""
check if two or more different objects have the same pdf-file
"""
doubles = {}
for element in elements:
pdffile = element.get("file")
key = element.get("key")
if not doubles.has_key(pdffile):
doubles[pdffile] = [key]
else:
doubles[pdffile].append(key)
for f, k in doubles.iteritems():
if f and len(k) > 1: # if f excludes case f == None
print >>sys.stderr, "Keys:", k, "have the same file <%s>"%f
#------------------------------------------------------------------------------
def check_unused_files(elements):
"""
check dir pdfdir ("lit/pdf") for pdf-files that are not used
in the ped.bib
"""
pdf_files = glob.glob( pdfdir + "*.pdf") # pdfs in lit/pdf/
dummy_files = copy.copy(pdf_files) # list of unused files
for pdf in pdf_files:
for element in elements:
element_pdf = element.get("file")
if element_pdf is None:
continue
element_pdf = path.basename(element_pdf)
if path.basename(pdf) == element_pdf:
dummy_files.remove(pdf)
break # check next files
if dummy_files:
print >>sys.stderr, "%d files are not used:"%len(dummy_files)
for f in dummy_files:
print >>sys.stderr, "---->",path.basename(f)
#------------------------------------------------------------------------------
def putWord(string, dic, line):
"""
extract from <line> the value of the key <string> and put it in <dic>
"""
tmp = line[1].strip(' { } , .').split(':')
# some files are like this :llll:aaaa. So tmp[0] is here == ''
if not tmp[0]:
dic[string] = tmp[1]
else:
dic[string] = tmp[0]
#------------------------------------------------------------------------------
def getElement(f):
"""
get ONE element from file f.
return dict
"""
dic = {}
for line in f:
line = line.strip(' \n\r')
if not line:
continue
#get <key> and <type>
if line[0] == '@':
sline = line.split('{')
typ = sline[0][1:]
if typ == 'comment': # ignore jabref-meta
continue
dic['type'] = typ.strip(',')
key = sline[1].strip(',')
if debug:
print >> sys.stderr, '--------> type: <%s>'%typ
print >> sys.stderr, '--------> key: <%s>'%key
dic['key'] = key
line = line.split('=')
for word in words:
if line[0].strip(' ') == word:
putWord(word, dic, line)
if debug:
print >> sys.stderr, '--------> %s: <%s>'%(word, line[1].strip(' { },.') )
# check for last line of element
if line[0] == '}':
if debug:
print >> sys.stderr, '---------------------------------'
return dic
#------------------------------------------------------------------------------
#----------------------- get content of file in elements ------------------------------
elements = []
while True:
dic = getElement(bib_data)
if not dic:
sorted(elements, key=itemgetter('key'))
break
elements.append( dic )
#------------------------------------------------------------------------------
if is_check_file:
print "check missing files ..."
for element in elements:
check_missing_pdf(element)
if is_check_double_file:
print "check double files ..."
check_doubles(elements)
if is_check_unused_files:
print "is_check_unused_files ..."
check_unused_files(elements)
`
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T15:06:45.890",
"Id": "41100",
"Score": "0",
"body": "Could you describe in an example what the code is supposed to do?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T17:08:42.227",
"Id": "41110",
"Score": "0",
"body": "Well the last \"ifs\" are three different examples what you could do with this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T19:11:49.183",
"Id": "64465",
"Score": "0",
"body": "Parsing [BibTeX](http://www.bibtex.org/Format/) is a non-trivial task. You would probably be better off using an existing [library](http://www.pybliographer.org), or at least studying how the library is implemented."
}
] |
[
{
"body": "<p>I would stop using the <code>print >> sys.stderr</code> and use the <a href=\"http://docs.python.org/2/library/logging.html\" rel=\"nofollow\">logging module</a>.</p>\n\n<p>EDIT: Why i suggested the use of the logging module. The reason it is easier to put a timestamp in each message, and when you want to remove log messages, you won’t get them confused for real print() calls.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T17:01:31.860",
"Id": "38706",
"ParentId": "19161",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T18:02:15.393",
"Id": "19161",
"Score": "5",
"Tags": [
"python"
],
"Title": "Data structure for handling bibtex files"
}
|
19161
|
<p>I made a mobile store, with prices in Indian rupees. Now I went for nested switch over functions, because I wanted to try out something new - biggest mistake in my life.</p>
<p>Since 3 days I've been trying to perfect it, it just won't happen. I have to make sure the menu shows again if negative number or a character is entered. There is <code>try</code>-<code>catch</code> for this, but it's bugging me.</p>
<p>Now my coding is huge and I'm not sure I can post the whole thing here.</p>
<p>I cut out the 4th case in <code>switch (ch)</code> to get some space.</p>
<pre><code>import java.io.*;
import java.util.Date;
class Mobile_Store_Project
{
public static void main (String[] args) throws IOException
{
InputStreamReader isr=new InputStreamReader (System.in);
BufferedReader br=new BufferedReader (isr);
int ch=0,a,gt=0;
int pr[]=new int [10];
int qu[]=new int [10];
String x[]=new String[10];
for (a=0;a<100;a++)
{
try
{
System.out.println(" Welcome to the Mobile Store. We have mobiles of all major manufacturers. \n \n Menu: \n 1)Apple \n 2)Samsung \n 3)Nokia \n 4)HTC \n 5)Bill \n 6)Exit \n Enter the number of your choice.");
ch=Integer.parseInt(br.readLine());
switch (ch)
{
case 1: int g;
System.out.println("Apple makes the popular iPhones. We are currently stocking: \n 1)iPhone 5 \n 2)iPhone 4S \n 3)iPhone 4 \n 4) Back \nEnter the no of your choice.");
g=Integer.parseInt(br.readLine());
if (g<0)
{
System.out.println("Negative numbers not allowed. Lets try this again. Lets try this again.");
g=0;
continue;
}
switch (g)
{
case 1: int c1;
System.out.println("The iPhone 5 is the latest iPhone. Specifications: \n 1)4 inch retina display screen \n 2)OS: iOS 6 \n 3)8MP Camera with Panorama,HDR option. \n \n There are 6 options available.");
System.out.println ("1)16 GB White. Price Rs.45,504 \n 2)16 GB Black. Price Rs.45,504 \n 3)32 GB White.Price Rs.48,708 \n 4)32GB Black.Price Rs.48,708 \n 5)64 GB White. Price Rs.50,434 \n 6)64GB Black. Price Rs.50,434 \n Enter the number of your choice");
c1=Integer.parseInt(br.readLine());
if (c1<0)
{
System.out.println("Negative numbers not allowed. Lets try this again. Lets try this again.");
c1=0;
continue;
}
switch (c1)
{
case 1: x[a]="iPhone 5 16GB White ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=45504;
a++;
break;
case 2: x[a]="iPhone 5 16GB Black ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=45504;
break;
case 3: x[a]="iPhone 5 32GB White ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=48708;
break;
case 4: x[a]="iPhone 5 32GB Black ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=48708;
break;
case 5: x[a]=("iPhone 5 64GB White ");
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=50434;
break;
case 6: x[a]="iPhone 5 16GB White ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=50434;
break;
default: System.out.println("Oops, lets try this again.");
}
break;
case 2: int c2;
System.out.println("The iPhone 4S is the next popular phone from Apple. The specs are quite similar to the iPhone 5. Specifications: \n 1)3.5 inch retina display screen \n 2)OS: iOS 5 (Upgradable to iOS 6) \n 3)8MP Camera with Panorama,HDR option. \n \n There are 6 options available.");
System.out.println ("1)16 GB White. Price Rs.30,504 \n 2)16 GB Black. Price Rs.30,504 \n 3)32 GB White.Price Rs.35,708 \n 4)32GB Black.Price Rs.35,708 \n 5)64 GB White. Price Rs.40,434 \n 6)64GB Black. Price Rs.40,434 \n Enter the number of your choice");
c2=Integer.parseInt (br.readLine());
if (c2<0)
{
System.out.println("Negative numbers not allowed. Lets try this again. Lets try this again.");
c2=0;
continue;
}
switch (c2)
{
case 1: x[a]="iPhone 4S 16GB White ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=30504;
break;
case 2: x[a]="iPhone 4S 16GB Black ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=30504;
break;
case 3: x[a]="iPhone 4S 32GB White ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=35708;
break;
case 4: x[a]="iPhone 4S 32GB Black ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=35708;
break;
case 5: x[a]="iPhone 4S 64GB White ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=40434;
break;
case 6: x[a]="iPhone 4S 16GB White ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=40434;
break;
default: System.out.println("Oops, lets try this again.");
}
break;
case 3: int ch3;
System.out.println("The iPhone 4 was the first iPhone to sport the glass and aluminium look. Specifications: \n 1)3.5 inch retina display screen \n 2)OS: iOS 4 (Upgradable to iOS 6) \n 3)5MP Camera with HDR option. \n \n There are 6 options available.");
System.out.println ("1)16 GB White. Price Rs.20,104 \n 2)16 GB Black. Price Rs.20,104 \n 3)32 GB White.Price Rs.23,658 \n 4)32GB Black.Price Rs.23,658 \n 5)64 GB White. Price Rs.27,123 \n 6)64GB Black. Price Rs.27,123 \n Enter the number of your choice");
ch3=Integer.parseInt(br.readLine());
if (ch3<0)
{
System.out.println("Negative numbers not allowed. Lets try this again. Lets try this again.");
ch3=0;
continue;
}
switch (ch3)
{
case 1: x[a]="iPhone 4 16GB White ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=20104;
break;
case 2: x[a]="iPhone 4 16GB Black ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=20104;
break;
case 3: x[a]="iPhone 4 32GB White ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=23658;
break;
case 4: x[a]="iPhone 4 32GB Black ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=23658;
break;
case 5: x[a]="iPhone 4 64GB White ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=27123;
break;
case 6: x[a]="iPhone 4 16GB White ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=27123;
break;
default: System.out.println("Oops, lets try this again.");
}
break;
case 4:
break;
default: System.out.println("Oops, lets try this again.");
}
break;
case 2: System.out.println("Samsung has revolutionized the smartphone market with it's amazing phones. We are currently stocking: \n 1)Galaxy S3 \n 2)Galaxy S Duos \n 3)Note 2 \n 4) Back \n Enter the number of you choice");
int ch1;
ch1=Integer.parseInt(br.readLine());
if (ch1<0)
{
System.out.println("Negative numbers not allowed. Lets try this again. Lets try this again.");
ch1=0;
continue;
}
switch (ch1)
{
case 1: System.out.println ("The Samsung Galaxy S3 is one of the most popular selling Android devices, selling 30 million+ of them. Specifications: \n 1)4.7 inch AMOLED Screem \n 2)8MP Camera \n 3)1.4 GhZ Quad Core Processor\n There is only one memory option available, 16 GB, but there are two colour options available: \n 1)Marble White. Price Rs.31,454 \n 2)Pebble Blue. Price Rs.31,454 \n Enter the number of your choice. ");
int cho1;
cho1=Integer.parseInt (br.readLine());
if (cho1<0)
{
System.out.println("Negative numbers not allowed. Lets try this again. Lets try this again.");
cho1=0;
continue;
}
else if (cho1==1)
{ x[a]="Samsung Galaxy S3 16 GB Marble White";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=31454;
}
else if (cho1==2)
{ x[a]="Samsung Galaxy S3 16 GB Pebble Blue";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=31454;
}
else
System.out.println("Oops. Lets try this again.");
break;
case 2: System.out.println ("The Samsung Galaxy S Duos is the look alike of S3, but with lower specs and dual sim option. Specifications: \n 1)1GhZ Dual Core processor \n 2)5 MP Camera \n 3)Android 4.0.4 Ice Cream Sandwich \n There is only one option available: 1)8GB White. Price Rs.14,999. \n Enter 1 to select.");
int ch2;
ch2=Integer.parseInt (br.readLine());
if (ch2<0)
{
System.out.println("Negative numbers not allowed. Lets try this again. Lets try this again.");
ch2=0;
continue;
}
else if (ch2==1)
{
x[a]="Samsung Galaxy S Duos 8GB White ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=14999;
}
if (ch2>1)
{
System.out.println("Oops. Lets try this again.");
ch2=0;
continue;
}
break;
case 3: System.out.println ("The Samsung Galaxy Note 2 is the sucessor of the sucessful Galaxy Note. Specifications: \n 1)5.5 inch screen \n 2)Android 4.1 Jelly Bean \n 3)1.5 GhZ Quad Core Processor \n 4)S Pen for super productivity \n The phone is available for Rs.38,656 and only in white option. \n Enter 1 to select.");
int ch3;
ch3=Integer.parseInt(br.readLine());
if (ch3<0)
{
System.out.println("Negative numbers not allowed. Lets try this again. Lets try this again.");
ch3=0;
continue;
}
else if (ch3==1)
{
x[a]="Samsung Galaxy Note 2 16 GB White ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");;
pr[a]=38656;
}
if (ch3>1)
{
System.out.println("Oops. Lets try this again.");
ch3=0;
continue;
}
break;
case 4:
break;
default: System.out.println("Oops, lets try this again.");
}
break;
case 3: System.out.println("Nokia is a household name. Everyone has owned atleast one Nokia phone in their life. We are currently stocking: \n 1)Nokia Lumia 920 \n 2)Nokia Lumia 820 \n 3) Nokia Lumia 510. \n 4) Back \n Enter the number of your choice");
int ch2;
ch2=Integer.parseInt (br.readLine());
if (ch2<0)
{
System.out.println("Negative numbers not allowed. Lets try this again. Lets try this again.");
ch2=0;
continue;
}
switch (ch2)
{
case 1: System.out.println ("The Nokia Lumia 920 is a beautiful looking device. Specifications: \n 1)4.5 inch PureMotion+ screen \n 2)Windows Phone 8 OS \n 3)8.7MP Pureview+ Camera with Optical Image Stabilization (OIS) \n There is only one memory option available, 32 GB. There are 3 color options available : \n 1)Blue. Price Rs.27,545 \n 2)Red. Price Rs.27,545 \n 3)Yellow. Price Rs.27,545 \n Select the number of your choice.");
int cho1;
cho1=Integer.parseInt (br.readLine ());
if (cho1<0)
{
System.out.println("Negative numbers not allowed. Lets try this again. Lets try this again.");
cho1=0;
continue;
}
switch (cho1)
{
case 1:x[a]="Nokia Lumia 920 Blue 32 GB ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=27545;
break;
case 2:x[a]="Nokia Lumia 920 Red 32 GB ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=27545;
break;
case 3:x[a]="Nokia Lumia 920 Yellow 32 GB ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=27545;
break;
default: System.out.println("Oops, lets try this again.");
}
break;
case 2:System.out.println ("The Nokia Lumia 820 is another great phone from Nokia. Specifications: \n 1)4.5 inch PureMotion+ screen \n 2)Windows Phone 8 OS \n 3)8 MP Camera \n There is only 32 GB memory option available. There are 3 colour choice available: \n 1)Blue. Price Rs.22,545 \n 2)Red. Price Rs.22,545 \n 3)Yellow. Price Rs.22,545 \n Select the number of your choice.");
int cho2;
cho2=Integer.parseInt(br.readLine());
if (cho2<0)
{
System.out.println("Negative numbers not allowed. Lets try this again. Lets try this again.");
cho2=0;
continue;
}
switch (cho2)
{
case 1: x[a]="Nokia Lumia 820 32GB Blue ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=22545;
break;
case 2: x[a]="Nokia Lumia 820 32GB Red ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=22545;
break;
case 3: x[a]="Nokia Lumia 820 32GB Yellow ";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=22545;
break;
default: System.out.println("Oops, lets try this again.");
}
break;
case 3: System.out.println ("The Nokia Lumia 510 is a budget Windows Phone from Nokia. Specifications: \n 1)3.7 inch screen \n 2)5MP Camera \n 3)Windows Phone 7.5 (Upgradable to 7.8) \n There are 2 colour options available: \n 1)Black. Price Rs.9999 \n 2)White. Price Rs.9999 \n Enter the number of your choice.");
int cho3;
cho3=Integer.parseInt (br.readLine());
if (cho3<0)
{
System.out.println("Negative numbers not allowed. Lets try this again. Lets try this again.");
cho3=0;
continue;
}
else if (cho3==1)
{
x[a]="Nokia Lumia 510 4GB Black";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=9999;
}
else if (cho3==2)
{
x[a]="Nokia Lumia 510 4GB White";
System.out.println("How many do you want to buy?");
qu[a]=Integer.parseInt (br.readLine());
System.out.println(qu[a]+" "+x[a]+"Added to cart.");
pr[a]=9999;
}
else
{
System.out.println("Oops. Lets try this again.");
continue; }
break;
case 4:
break;
default: System.out.println("Oops, lets try this again.");
}
break;
case 5: //Printing bill
Date date = new Date();
System.out.println("\t\t\t\t\t\tMobile Store\n");
System.out.println("\t\t\t\t\t\t\t\t\tBill Date : "+date.toString()+"\n");
int i,j=1;
System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
System.out.println("Sr.No "+setSpace("ITEM",17)+" "+setSpace("PRICE",17)+" "+setSpace("QUANTITY",12)+" "+setSpace("TOTAL",25));
System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
for (a=0;a<qu[a];a++)
{
System.out.println(j+" "+setSpace(""+x[a],25)+" "+setSpace(""+pr[a],20)+" "+setSpace(""+qu[a],20)+" "+setSpace(""+pr[a]*qu[a],20));
j++;
gt+=pr[a]*qu[a];
}
System.out.println("\t\t\t\t\tGrand Total :- Rs"+(gt)+"/-\n\n\n");
System.out.println("\t\t\t\tThank you. Visit Again.");
System.exit(0);
break;
} // End of main switch
}
catch(NumberFormatException nfe)
{
System.out.println("Oops. Lets try this again.");
ch=0;
}
}
}
static String setSpace(String data,int size) // Aligning the bill
{
int len=data.length();
if(len<size)
{
for(int i=0;i<size-len;i++)
{
data+=" ";
}
}
else
{
data=data.substring(0,size-2);
data+="..";
}
return data;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T19:15:35.117",
"Id": "30629",
"Score": "1",
"body": "Hi Siddharth. What exactly is your problem? Is it that you want a review of the code or it's just not working. If the latter you will likely find more assistance on this on Stack overflow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T19:17:41.153",
"Id": "30630",
"Score": "0",
"body": "I want a review. Do you think it's sensible to use Nested Switch and Try Catch?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T19:38:14.317",
"Id": "30632",
"Score": "3",
"body": "You said it yourself. Using a nested switch over functions is the biggest mistake you've made. Especially when it's that long. You've broken several good coding practices here. Try searching this site for DRY and SOLID principles and patterns and you'll get a whole lot of input on doing it better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T22:18:55.967",
"Id": "30648",
"Score": "0",
"body": "It can be easily crashed by entering a non-number string. Nice to check for negative numbers but you have to check if it's really a number first."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-08T18:36:04.877",
"Id": "144733",
"Score": "0",
"body": "Your `public static void main()` was missing `String[] args`. I've added it for you (against our normal policy not to edit the code in a question)."
}
] |
[
{
"body": "<p>Crikey there's alot of duplicated code in there. Before I would even consider reviewing it too closely you might want to think about refactoring all those copy and pasted case statements into one method</p>\n\n<ol>\n<li><p>Remove code that has very likely been \"<strong>copied and pasted</strong>\". Oh how I cringe at copy and pasted code:</p>\n\n<pre><code>x[a]=\"iPhone 5 16GB Black \";\nSystem.out.println(\"How many do you want to buy?\");\nqu[a]=Integer.parseInt (br.readLine());\nSystem.out.println(qu[a]+\" \"+x[a]+\"Added to cart.\");\npr[a]=45504;\n</code></pre>\n\n<p>into something like</p>\n\n<pre><code>case 1:\n capturePhoneSelection(a, \"iPhone 5 16GB White\", 45504);\n a++;\n break; \n</code></pre>\n\n<p>where the method would be something like (x, qu and pr could be class instance variables):</p>\n\n<pre><code>int capturePhoneSelection(int selection, string phoneTitle, int pr) {\n x[selection]=phoneTitle;\n\n System.out.println(\"How many do you want to buy?\");\n qu[selection]=Integer.parseInt (br.readLine());\n\n System.out.println(qu[selection]+\" \"+x[selection]+\"Added to cart.\");\n pr[selection]=pr;\n\n return selection++;\n}\n</code></pre></li>\n<li><p>Change your variable names into something that other people not reading your code can easily understant. i.e what the heck is variable a, pr and qu supposed to represent?</p></li>\n<li><p>Going on from <em>point 1</em>. Break that main up into many smaller functions. By doing this you will notice duplicated code and so eliminate alot</p></li>\n<li><p>And No, a nested switch is probably not a good idea but I haven't reviewed it in enough detail to fully comment that.</p></li>\n</ol>\n\n<p>These might be a good place to start. After making these changes I'm sure there'll be even more room to refactor and review and in this process it's always good to manage in an iterative process.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T21:55:45.520",
"Id": "30645",
"Score": "0",
"body": "Don't forget the use of arrays instead of `switch` statements."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T22:02:45.483",
"Id": "30646",
"Score": "0",
"body": "@Sulthan yes, good option. I thought might be worthwhile to suggest something like that after the OP had done an initial round of refactoring??"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T19:35:57.353",
"Id": "19167",
"ParentId": "19164",
"Score": "5"
}
},
{
"body": "<blockquote>\n <p>Now I went for nested switch over functions, cause I wanted to try out\n something new- biggest mistake in my life.</p>\n</blockquote>\n\n<p>I hope you never think that's a good idea again.</p>\n\n<p>You could also really use a function to show a menu:</p>\n\n<pre><code>int showMenu(String header, String [] options)\n{ ... }\n</code></pre>\n\n<p>This function takes the menu information as arguments, and would return the selected option. It would handle all the pieces about redisplaying the menu, etc.</p>\n\n<p>The whole thing would be way better if it would read the information from an external file rather then putting all of that in the code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T21:04:30.513",
"Id": "19170",
"ParentId": "19164",
"Score": "4"
}
},
{
"body": "<p>Normally I'd give more detailed advice and break things down but there is a lot wrong there. \nToo much to tackle in a simple review. </p>\n\n<p>There seems to be a lack of understanding of the finer points of program design and architecture. That's fine though. We all have to learn things for the first time at least once!</p>\n\n<p>I would recommend picking up something like:</p>\n\n<p><a href=\"http://rads.stackoverflow.com/amzn/click/0596007124\" rel=\"nofollow\">Head First Design Patterns.</a></p>\n\n<p>It will explain ways of making code reusable and how to design around a problem. </p>\n\n<hr>\n\n<p>As a general rule, a switch statement is a code smell. You are saying that a series of alternate steps need to be done, The only time you should use a Switch is when those steps are always the same.</p>\n\n<p>for example, switching on days of the week is fine. there will never be the need to add one. </p>\n\n<p>In your case, you might want to add additional products, so looping through a collection of actions is better.</p>\n\n<p>Then, in the case you need a new product option you add it to the list. </p>\n\n<p>e.g:</p>\n\n<p>(now this is a simplified pseudocode mish mash version guys, not meant to be code reviewed :P)</p>\n\n<pre><code> string[] displays;\n int[] ProductPurchases;\n\n ... main()\n {\n ShowProducts();\n while(userChoice.equals(\"exit\"))\n {\n \"Which Item Would you like to buy\"...\n userChoice = ReadLine();\n if(userChoice > 0 && userChoice < displays.Length)\n {\n \"How Many\"...\n int amount = ParseInput();\n ProductPurchases[userChoice] = amount;\n }\n\n }\n ShowPurchases();\n\n }\n\n\n void ShowProducts()\n{\n for(int i = 0;i < displays.length; i++)\n {\n System.out.print(displays[i]);\n System.out.print(\"**********\");\n }\n}\n\n void ShowPurchases()\n{\n for(int i = 0;i < displays.length; i++)\n {\n if(ProductPurchases[i] != 0)\n { \n System.out.print(\"You Ordered \"+ProductPurchases[i]+\" of \"+displays[i]);\n System.out.print(\"**********\");\n }\n }\n}\n</code></pre>\n\n<p>So see how the ability to add products is far simpler, I know it does not have some of the nested menu features you had, but if you had some custom classes in there to store things and managed the state using a command/state pattern you could even do nested menus cleanly. </p>\n\n<p>Good luck!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-08T18:24:46.673",
"Id": "79955",
"ParentId": "19164",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T19:11:04.690",
"Id": "19164",
"Score": "4",
"Tags": [
"java",
"console",
"e-commerce"
],
"Title": "Text menu shopping cart for mobile phone store"
}
|
19164
|
<p>i am trying to implement factory pattern for getting XML Document from server</p>
<p>(using javax.xml.parsers.DocumentBuilder)</p>
<p>I have the classes below for now, could you give your opinion ? Does the structure make sense for this pattern? </p>
<p><strong>DocumentGeneratorFactory</strong> (abstract factory)</p>
<pre><code>public interface DocumentGeneratorFactory {
public Document createDocument(String scheme, String authority,
String path, HashMap<String, String> parameters)
throws ParserConfigurationException, SAXException, IOException;
public Document createDocument(String scheme, String authority,String path)
throws ParserConfigurationException, SAXException, IOException;
}
</code></pre>
<p><strong>ProductDocumentGeneratorFactory</strong> (Concreate factory)</p>
<pre><code>public class ProductDocumentGeneratorFactory implements
DocumentGeneratorFactory {
public Document createDocument(String scheme, String authority,
String path, HashMap<String, String> parameters)
throws ParserConfigurationException, SAXException, IOException {
Uri.Builder uri = new Uri.Builder();
uri.scheme(scheme);
uri.authority(authority);
uri.path(path);
Set<Map.Entry<String, String>> set = parameters.entrySet();
for (Map.Entry<String, String> params : set) {
uri.appendQueryParameter(params.getKey(), params.getValue());
}
URL url = new URL(uri.toString());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
return doc;
}
public Document createDocument(String scheme, String authority, String path)
throws ParserConfigurationException, SAXException, IOException {
Uri.Builder uri = new Uri.Builder();
uri.scheme(scheme);
uri.authority(authority);
uri.path(path);
URL url = new URL(uri.toString());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
return doc;
}
}
</code></pre>
<p><strong>Request</strong> (Abstract Product)</p>
<pre><code>public abstract class Request {
Document doc;
HashMap<String, String> queryStrings;
abstract void prepareRequest() throws ParserConfigurationException, SAXException, IOException;
}
</code></pre>
<p><strong>ProductRequest</strong> (Product)</p>
<pre><code>public class ProductRequest extends Request{
ProductDocumentGeneratorFactory DocumentGeneratorFactory;
HashMap<String, String> queryStrings;
public ProductRequest(ProductDocumentGeneratorFactory DocumentGeneratorFactory,HashMap<String, String> queryStrings){
this.DocumentGeneratorFactory = DocumentGeneratorFactory;
this.queryStrings = queryStrings;
}
@Override
void prepareRequest() throws ParserConfigurationException, SAXException, IOException {
doc = this.DocumentGeneratorFactory.createDocument("http", "ip-address", "default.aspx",this.queryStrings);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Makes sense, but you should DRY up your concrete factory at least. Forgive me my rusty Java, but something like this:</p>\n\n<pre><code>public class ProductDocumentGeneratorFactory implements\n DocumentGeneratorFactory {\n\n public Document createDocument(String scheme, String authority, String path)\n throws ParserConfigurationException, SAXException, IOException {\n\n Uri.Builder uri = createUri(scheme, authority, path);\n Document doc = createDocument(uri);\n return doc;\n }\n\n public Document createDocument(String scheme, String authority,\n String path, HashMap<String, String> parameters)\n throws ParserConfigurationException, SAXException, IOException {\n\n Uri.Builder uri = createUri(scheme, authority, path);\n appendParameters(uri, parameters);\n Document doc = createDocument(Uri.Builder uri);\n return doc;\n }\n\n private Uri createUri(string scheme, string authority, string path)\n {\n Uri.Builder uri = new Uri.Builder();\n uri.scheme(scheme);\n uri.authority(authority);\n uri.path(path);\n return uri;\n }\n\n private Document createDocument(Uri.Builder uri)\n {\n URL url = new URL(uri.toString());\n\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n DocumentBuilder db = dbf.newDocumentBuilder();\n Document doc = db.parse(new InputSource(url.openStream()));\n doc.getDocumentElement().normalize();\n\n return doc\n }\n\n private void appendParameters(Uri.Builder uri, HashMap<string,string> parameters)\n {\n Set<Map.Entry<String, String>> set = parameters.entrySet();\n for (Map.Entry<String, String> params : set) {\n uri.appendQueryParameter(params.getKey(), params.getValue());\n }\n }\n}\n</code></pre>\n\n<p>Of course you can expand on that by employing the <a href=\"http://www.google.com/url?sa=t&rct=j&q=&esrc=s&frm=1&source=web&cd=1&cad=rja&ved=0CDIQFjAA&url=http://en.wikipedia.org/wiki/Template_method_pattern&ei=S_W5UOzEC6zZ4QTStYGwBg&usg=AFQjCNHmRc7_Y0pUONKtb-4ToYLl5Xo_Ug&sig2=-6mD6B9d3DHrNxsAF-iscw\" rel=\"nofollow\">template pattern</a> for the extra parameter settings.</p>\n\n<p>I would also look into extracting the parameters to a \"<a href=\"http://c2.com/cgi/wiki?ParameterObject\" rel=\"nofollow\">parameter object</a>\" instead of several parameters.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T12:21:42.083",
"Id": "19205",
"ParentId": "19173",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "19205",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T22:32:20.077",
"Id": "19173",
"Score": "1",
"Tags": [
"java",
"object-oriented",
"design-patterns"
],
"Title": "Factory pattern for getting xml data"
}
|
19173
|
<p>My apology, I am quite new to posting a question in this forum.</p>
<p>I had a task where I was supposed to write a solution to sort entries(Name, score - in an array/list) in order of score and generate ranking based on higher score to lower scores.</p>
<p>I tried doing that, code is working what it was supposed to do but it seems very ambiguous and tightly coupled, I can't even write a unit test for it.</p>
<p>Could someone have a look and suggest do I need to minimize and simplify this class so that I can write a Unit Test class for this.</p>
<blockquote>
<p>I have pasted main method class, If anyone wants me to paste other
relevent classes as well so do ask me please.</p>
</blockquote>
<p>Any suggestion(s)/workaround(s) would be much appreciated.</p>
<p>Many thanks,</p>
<pre><code>public class JournalAnalyzer {
final static int LENGTH_OF_JOURNAL = 5; //Length Journal array
static int count = 0;
static Integer ranking = 1;
static Journal[] journals = new Journal[LENGTH_OF_JOURNAL];
static ArrayList<Journal> list = new ArrayList<Journal>();
static Object[] scoreList = new Object[LENGTH_OF_JOURNAL];
static String journalName;
static Double journalScore;
static Integer journalRank;
static Boolean journalReview;
private static void initData(Journal[] journals) {
journals[0] = new Journal(0, "Journal A", 5.6, false);
journals[1] = new Journal(0, "Journal B", 2.6, false);
journals[2] = new Journal(0, "Journal C", 3.2, false);
journals[3] = new Journal(0, "Journal D", 4.1, false);
journals[4] = new Journal(0, "Journal E", 1.6, false);
}
private static int fillJournalList(int count, Journal[] journals,
int LENGTH_OF_JOURNAL, ArrayList<Journal> list) {
for (int i = 0; i < LENGTH_OF_JOURNAL; i++) {
journalRank = new Integer(journals[i].getRank());
journalName = new String(journals[i].getJournal());
journalScore = new Double(journals[i].getScore());
journalReview = new Boolean(journals[i].getIsReviewed());
if (!journalReview) {
Journal value = new Journal(journalRank, journalName,
journalScore, journalReview);
list.add(value);
count++;
} else {
continue;
}
}
return count;
}
private static void GenerateRanking(Integer ranking, int count,
ArrayList<Journal> list, Object[] scoreList) {
Double scoreComparatorOne;
Double scoreComparatorTwo;
Comparator<Journal> scores = new SortScore();
Collections.sort(list, scores);
for (int i = 0; i < count; i++) {
scoreComparatorOne = (list.get(i)).getScore();
if (i == 0) {
scoreComparatorTwo = (list.get(i)).getScore();
} else {
scoreComparatorTwo = (list.get(i - 1)).getScore();
}
if (scoreComparatorOne.equals(scoreComparatorTwo)) {
if (ranking == 0) {
ranking += 1;
} else {
ranking = ranking;
}
} else {
ranking = i + 1;
}
(list.get(i)).setRank(ranking);
scoreList[i] = (list.get(i));
}
}
private static void displayJournal(int counter, Object[] scoreList) {
JournalOutput printer = new JournalOutput();
printer.display(count, scoreList);
System.exit(0);
}
public static void main(String[] args) throws IOException {
initData(journals);
count = fillJournalList(count, journals, LENGTH_OF_JOURNAL, list);
GenerateRanking(ranking, count, list, scoreList);
displayJournal(count, scoreList);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T15:08:05.450",
"Id": "30695",
"Score": "0",
"body": "possible duplicate of [Array sort-rank class](http://codereview.stackexchange.com/questions/19180/array-sort-rank-class)"
}
] |
[
{
"body": "<p>Your biggest problem is that you are using <code>static</code> for everything. Change all of the static variables to instance variables, and all of the static methods (apart from <code>main</code>) into instance methods. Then have your <code>main</code> method create an instance of <code>JournalAnalyzer</code> and call the (now instance) methods on that instance.</p>\n\n<p>That will make the code more testable. Another thing you need to do to improve testability is to make the methods you want to test <code>public</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T19:17:18.530",
"Id": "30707",
"Score": "0",
"body": "Thank you very much indeed Stephen, it helped me alot and I've written the test case for it as well."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T15:07:09.740",
"Id": "19190",
"ParentId": "19174",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "19190",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T00:00:24.073",
"Id": "19174",
"Score": "4",
"Tags": [
"java",
"array",
"unit-testing"
],
"Title": "Ranking and sorting on Array/List"
}
|
19174
|
<pre><code>var WorkflowDialogBuilder = _.once(function () {
'use strict';
var workflowDialog = $('#WorkflowDialog');
var workflowDialogContent = $('#WorkflowDialogContent');
var events = {
onApplyChangesSuccess: 'onApplyChangesSuccess',
onValidationFailed: 'onValidationFailed',
onDialogOpen: 'onDialogOpen'
};
var dialogConfig = {
autoOpen: false,
buttons: {
OK: function () {
var form = $(this).find('form');
if (form.valid()) {
var self = this;
$.ajax({
type: "POST",
url: 'Form/Save',
dataType: 'json',
data: form.serialize(),
success: function (data) {
$(self).dialog('close');
$(self).trigger(events.onApplyChangesSuccess, data);
},
error: function (error) {
console.error(error);
}
});
} else {
$(this).trigger(events.onValidationFailed);
}
},
Cancel: function () {
$(this).dialog('close');
}
},
open: function () {
$(this).trigger(events.onDialogOpen);
}
};
workflowDialog.dialog(dialogConfig);
return {
onApplyChangesSuccess: function (event) {
workflowDialog.on(events.onApplyChangesSuccess, event);
},
onDialogOpen: function (event) {
workflowDialog.on(events.onDialogOpen, event);
},
onValidationFailed: function (event) {
workflowDialog.on(events.onValidationFailed, event);
},
buildAddTaskDialog: function () {
workflowDialogContent.load('NewTaskDetails', function () {
//Load ViewModel client-side helpers and then when its ready, open the dialog.
$.getScript('../Scripts/Orders/NewTaskDetailsModel.js', function () {
workflowDialog.dialog('open');
});
});
},
buildAddOrderDialog: function () {
workflowDialogContent.load('NewOrderDetails', function () {
//Load ViewModel client-side helpers and then when its ready, open the dialog.
$.getScript('../Scripts/Orders/NewOrderDetailsModel.js', function () {
workflowDialog.dialog('open');
});
});
}
}
}
</code></pre>
<p>So, I've made the above builder. It is responsible for initializing a dialog element, opening it, and responding appropriately when the dialog closes.</p>
<p>Now, I was pretty happy with this implementation until I realized that, given the following scenario, events were subscribing and not unsubscribing.</p>
<pre><code>//User calls WorkflowDialogBuilder.buildAddTaskDialog();
//NewTaskDetailsModel.js is loaded.
//NewTaskDetailsModel.js calls the following:
WorkflowDialogBuilder.onValidationFailed(function () {
console.log("NewTaskDetailsMode.js onValidationFailed fired.");
});
//AddTaskDialog is closed by the user. NewTaskDetailsModel.js has already been loaded.
//AddTaskDialog continues to be subscribed to DialogBuilder's onValidationFailed.
//User calls WorkflowDialogBuilder.buildAddOrderDialog();
//User works with the dialog and clicks 'OK' to apply validation.
//AddTaskDialog's onValidationFailed event runs because WorkflowDialogBuilder triggers an event.
</code></pre>
<p>Now, I can think of one very simple solution to this. I could simply respond to the dialog's onClose event and, at that pont in time, unsubscribe all events.</p>
<p><strong>Question:</strong> Does that seem like a proper solution? Or, have I gone down a bad path from the getgo and should rethink my architecture? If so, advice on how to restructure?</p>
|
[] |
[
{
"body": "<p>I would refactor it into a plugin that takes the content as an option. Then you will have two instances of \"dialog controllers\" each with its own events.</p>\n\n<p>Have a look at the \"plugin with data\" example in the jQuery docs.</p>\n\n<p><a href=\"http://docs.jquery.com/Plugins/Authoring#Data\" rel=\"nofollow\">http://docs.jquery.com/Plugins/Authoring#Data</a></p>\n\n<p>You'd set it up like</p>\n\n<pre><code><div id=\"addTaskDialog\"></div>\n<div id=\"addOrderDialog\"></div>\n<script type=\"text/javascript\">\n//...\n$(\"#addTaskDialog\").workflowDialog({model:\"NewTaskDetailsModel.js\"});\n$(\"#addOrderDialog\").workflowDialog({model:\"NewOrderDetailsModel.js\"});\n// attach events to either\n</script>\n</code></pre>\n\n<p>Otherwise I'd switch to $.unbind followed by $.bind in the subscribe functions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T17:23:52.570",
"Id": "30700",
"Score": "0",
"body": "Why on earth would you switch to using $.unbind and $.bind? Those are deprecated and have been replaced with $.on. I do like the idea of handing a model to the dialog, but I think I can do it without creating multiple div elements. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T11:38:17.997",
"Id": "30731",
"Score": "0",
"body": "Hmm, my bad if they're depreciated. Use on and off then. :) I just think you're over complicating by cramming two different dialogs into one container. If that's your goal you should at least try to separate the inner logic of the plugin into two separate \"classes\" with their own events, possibly forwarding to the plugins events."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T12:30:52.640",
"Id": "19185",
"ParentId": "19175",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "19185",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T00:09:28.747",
"Id": "19175",
"Score": "0",
"Tags": [
"javascript",
"jquery"
],
"Title": "Created a DialogBuilder object, but having issues with subscribing/unsubscribing to dialog events"
}
|
19175
|
<p>I would dearly love some feedback on the model below. It's a basic commenting structure where users can comment on a variety of objects in the model. I have denormalised it to make querying simpler, but I'm not sure if I've over/under done it. The model tests fine, but it all feels a little clunky.</p>
<pre><code>#####################################################################
# Base ##############################################################
class Base():
def __init__(self, **kwargs):
self._ClassName = self.__class__.__name__
self._Created = datetime.now()
self.__dict__.update(kwargs)
def __repr__(self):
return '<%s>' % self.__class__.__name__
#####################################################################
# Comment ###########################################################
class Comment(Base):
def __init__(self, username, person, comment, parent, **kwargs):
self.Username = username
self.Person = person
self.Comment = comment
self.Parent = parent
self.__dict__.update(kwargs)
def _save(self):
#save to Comments
db.Comments.save(self.__dict__)
#save to parent collection
parent_obj = db.dereference(self.Parent)
query = {'_id':parent_obj['_id']}
update = {'$addToSet':{'Comments':self.__dict__}}
db[parent_obj['_Collection']].find_and_modify(query, update, safe=True)
#save to people collection
query = {'_id':self.Person.id}
db.People.find_and_modify(query, update, safe=True)
def _remove(self):
#remove from Comments
query = {'_id':self._id}
db.Comments.remove(query, safe=True)
#remove from parent collection
query = {'Comments._id':self._id}
update = {'$pull':{'Comments':self.__dict__}}
db[self.Parent.collection].find_and_modify(query, update, safe=True)
#remove from people collection
db.People.find_and_modify(query, update, safe=True)
def __str__(self):
return '%s - %s...' % (self.Username, self.Comment[:10])
person = {'Username':'foobarman'}
db.People.save(person, safe=True)
program = {'Title':'the foobar', '_Collection', 'Programs'}
db.Programs.save(program, safe=True)
comment = Comment(
person['Username'],
DBRef('People', person['_id']),
'this is a comment about the foobar program',
DBRef(program['_Collection'], program['_id']))
comment._save()
# find latest 10 comments
list(db.Comments.find().sort('_Created', -1).limit(10))
# find all comments for username
db.People.find_one({'Username':'foobarman'})['Comments']
# find all comments for program
db.Programs.find({'Title':'the foobar'})['Comments']
# find all comments for program by user
list(db.Comments.find({
'Parent':DBRef(program['_Collection'], program['_id']),
'Username':'foobarman'}))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-27T00:08:59.853",
"Id": "206599",
"Score": "0",
"body": "I cannot run this code as it is written, as I don't know what `db.*` is. So my question is whether this question is still relevant, and if so what is the `db.*` stuff? Or if it should be deleted due to no relevancy any more, or closed as broken code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-29T09:44:45.260",
"Id": "226118",
"Score": "1",
"body": "Please [edti your question](http://codereview.stackexchange.com/posts/19176/edit) and add your `import` lines (as mentioned by @holroy, we don't know what `db` is)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-29T23:56:27.193",
"Id": "226269",
"Score": "0",
"body": "Delete the question."
}
] |
[
{
"body": "<pre><code>#####################################################################\n# Comment ###########################################################\n</code></pre>\n\n<p>This sort of stuff is useless noise that adds a lot of maintenance.</p>\n\n<p>If your classes are getting hard to find, move them over to separate files. If you don't want to move them to separate files, consider making use of your IDE to find the class you're looking for, rather than relying on optical recognition via big blocks of screenfilling characters.</p>\n\n<p>The reasons for this are twofold:</p>\n\n<ul>\n<li>If you refactor the name of the class, the comment doesn't change and you spend time formatting a comment like this, when you could have been doing normal programming</li>\n<li>If you ever had a name that is longer or wanted to describe a class with a docstring you might break convention and might have to restyle all your classes or risk inconsistencies</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-29T08:34:15.633",
"Id": "121412",
"ParentId": "19176",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T03:09:24.860",
"Id": "19176",
"Score": "1",
"Tags": [
"python",
"database",
"mongodb"
],
"Title": "Basic commenting structure for commenting on objects"
}
|
19176
|
<p>By reading some tutorial i have written some peace of code to do crud operation . I just want to know how is this code is efficient or how can i make better ?</p>
<p>Here i am giving code of 3 class
1. EntityManagerProvider : get connection from DB and do crud operation
2. BaseDao : A generalised Dao which uses EntityManagerProvider<br>
3. TargetGroupsDao : A specific Dao </p>
<pre><code>import java.util.Collection;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import javax.persistence.RollbackException;
import javax.persistence.TransactionRequiredException;
public class EntityManagerProvider {
private static EntityManagerFactory emf;
private static boolean lock;
private static String persistentUnitName = "TMS_PU";
static {
EntityManagerProvider.emf = Persistence.createEntityManagerFactory(persistentUnitName);
}
private static final ThreadLocal<EntityManager> localEm = new ThreadLocal<EntityManager>() {
@Override
protected EntityManager initialValue() {
if (emf == null || !emf.isOpen()) {
emf = Persistence
.createEntityManagerFactory(persistentUnitName);
}
return emf.createEntityManager();
}
};
@Override
protected void finalize() throws Throwable {
EntityManager em = getEntityManager();
if (em != null && em.isOpen())
em.close();
super.finalize();
}
public EntityManagerProvider() {
}
public static EntityManager getEntityManager() {
EntityManager em = localEm.get();
if (em == null || !em.isOpen()) {
em = emf.createEntityManager();
localEm.set(em);
}
return em;
}
public static void beginTransaction() {
if (lock)
return;
EntityTransaction tx = getEntityManager().getTransaction();
if (!tx.isActive()) {
tx.begin();
}
}
public static void rollbackTransaction() {
EntityTransaction tx = getEntityManager().getTransaction();
if (tx != null && tx.isActive()) {
tx.setRollbackOnly();
}
}
public static void commitTransaction() {
if (lock)
return;
EntityTransaction tx = getEntityManager().getTransaction();
if (tx != null && tx.isActive()) {
try {
if (tx.getRollbackOnly())
tx.rollback();
else
tx.commit();
} catch (RollbackException e) {
} catch (Exception e) {
}
}
}
public void persist(Object object) throws Exception {
try {
if (object instanceof Collection) {
Collection<?> objects = (Collection<?>) object;
for (Object o : objects) {
getEntityManager().persist(o);
}
} else {
getEntityManager().persist(object);
}
} catch (EntityExistsException e) {
throw e;
} catch (IllegalStateException e) {
throw e;
} catch (IllegalArgumentException e) {
throw e;
} catch (TransactionRequiredException e) {
throw e;
} catch (Exception e) {
rollbackTransaction();
throw e;
} finally {
}
}
public Object merge(Object object) throws Exception {
Object result = null;
try {
if (object instanceof Collection) {
Collection<?> objects = (Collection<?>) object;
for (Object o : objects) {
getEntityManager().merge(o);
}
} else {
result = getEntityManager().merge(object);
}
} catch (IllegalStateException e) {
throw e;
} catch (IllegalArgumentException e) {
throw e;
} catch (TransactionRequiredException e) {
throw e;
} catch (Exception e) {
rollbackTransaction();
throw e;
} finally {
}
return result;
}
public void clear() throws Exception {
try {
getEntityManager().clear();
} catch (IllegalStateException e) {
throw e;
}
}
public void flush() throws Exception {
try {
getEntityManager().flush();
} catch (IllegalStateException e) {
throw e;
} catch (TransactionRequiredException e) {
throw e;
} catch (PersistenceException e) {
throw e;
} catch (Exception e) {
throw e;
}
}
public Object getById(final Class<?> persistentClass, Object id) {
return getEntityManager().find(persistentClass, id);
}
public Object getReferenceById(final Class<?> persistentClass, Object id) {
return getEntityManager().getReference(persistentClass, id);
}
public void remove(Object valueObject) throws Exception {
try {
EntityManager em = getEntityManager();
em.remove(valueObject);
em.flush();
} catch (IllegalStateException e) {
throw e;
} catch (IllegalArgumentException e) {
throw e;
} catch (TransactionRequiredException e) {
throw e;
} catch (Exception e) {
rollbackTransaction();
throw e;
} finally {
}
}
public Query createQuery(String jpql) {
return getEntityManager().createQuery(jpql);
}
public static void lock() {
lock = true;
}
public static void unlock() {
lock = false;
}
public static boolean getlock() {
return lock;
}
}
</code></pre>
<hr>
<pre><code>import java.util.List;
import java.util.Map;
import javax.persistence.Query;
public class BaseDao {
private EntityManagerProvider emp;
private Class<?> className;
public BaseDao(final Class<?> className) {
this.className = className;
emp = new EntityManagerProvider();
}
public BaseDao(final Class<?> className, String localMsg) {
this.className = className;
emp = new EntityManagerProvider();
}
public void create(Object object, EntityManagerProvider emp)
throws Exception {
try {
if (emp == null) {
EntityManagerProvider.beginTransaction();
this.emp.persist(object);
EntityManagerProvider.commitTransaction();
} else {
emp.persist(object);
}
} catch (Exception e) {
throw e;
}
}
public void update(Object object, EntityManagerProvider emp)
throws Exception {
try {
if (emp == null) {
EntityManagerProvider.beginTransaction();
this.emp.merge(object);
EntityManagerProvider.commitTransaction();
} else {
object = emp.merge(object);
}
} catch (Exception e) {
throw e;
}
}
public Object getById(Object primaryKey) throws Exception {
Object object = null;
try {
emp = new EntityManagerProvider();
// FLUSH
EntityManagerProvider.beginTransaction();
// emp.flush();
// emp.clear();
object = emp.getById(className, primaryKey);
EntityManagerProvider.commitTransaction();
} catch (Exception e) {
throw e;
}
return object;
}
public Object getReferenceById(Object primaryKey) throws Exception {
Object object = null;
try {
emp = new EntityManagerProvider();
object = emp.getReferenceById(className, primaryKey);
} catch (Exception e) {
throw e;
}
return object;
}
public List<?> getAll() throws Exception {
return getAll(null, null);
}
public List<?> getAll(Integer fromRowNo, Integer noOfRows) throws Exception {
List<?> list = null;
String sql = null;
Query query = null;
try {
emp = new EntityManagerProvider();
// CLEAR & FLUSH
EntityManagerProvider.beginTransaction();
emp.flush();
emp.clear();
EntityManagerProvider.commitTransaction();
sql = "SELECT p " + "FROM " + className.getCanonicalName() + " p";
query = emp.createQuery(sql);
if (fromRowNo != null)
query.setFirstResult(fromRowNo);
if (noOfRows != null)
query.setMaxResults(noOfRows);
list = query.getResultList();
} catch (Exception e) {
throw e;
}
return list;
}
public void delete(Object primaryKey, EntityManagerProvider emp)
throws Exception {
Object object = getById(primaryKey);
if (object == null) {
return;
}
try {
if (emp == null) {
EntityManagerProvider.beginTransaction();
this.emp.remove(object);
EntityManagerProvider.commitTransaction();
} else {
emp.remove(object);
}
} catch (Exception e) {
throw e;
}
}
public List<?> search(Map<String, Object> var, String opr) throws Exception {
return search(var, null, null, true, null, null, opr);
}
public List<?> search(Map<String, Object> var, Integer fromRowNo,
Integer noOfRows, String opr) throws Exception {
return search(var, null, null, true, fromRowNo, noOfRows, opr);
}
public List<?> search(Map<String, Object> var, Map<String, Boolean> flags,
String opr) throws Exception {
return search(var, flags, null, true, null, null, opr);
}
public List<?> search(Map<String, Object> var, Map<String, Boolean> flags,
Integer fromRowNo, Integer noOfRows, String opr) throws Exception {
return search(var, flags, null, true, fromRowNo, noOfRows, opr);
}
public List<?> search(Map<String, Object> var, Map<String, Boolean> flags,
Map<String, Boolean> orderBy, Boolean orderFlag, Integer fromRowNo,
Integer noOfRows, String opr) throws Exception {
List<?> list = null;
if (opr == null)
opr = "AND ";
try {
emp = new EntityManagerProvider();
String sql = "SELECT p FROM " + className.getCanonicalName()
+ " p ";
String sql2 = null;
String sql3 = null;
String str2 = null;
if (var != null) {
for (String str : var.keySet()) {
if (str.indexOf(".") > 0) // This solves only for one
// level
str2 = str
.substring(str.indexOf(".") + 1, str.length());
else
str2 = str;
if (sql2 != null) {
if (flags != null) {
if (!flags.get(str))
sql2 += opr + "p." + str + " != :" + str2 + " ";
else
sql2 += opr + "p." + str + " = :" + str2 + " ";
} else
sql2 += opr + "p." + str + " = :" + str2 + " ";
} else {
if (flags != null) {
if (!flags.get(str))
sql2 = "WHERE p." + str + " != :" + str2 + " ";
else
sql2 = "WHERE p." + str + " = :" + str2 + " ";
} else
sql2 = "WHERE p." + str + " = :" + str2 + " ";
}
}
}
if (orderBy != null) {
for (String str : orderBy.keySet()) {
if (sql3 != null) {
if (orderBy.get(str) != null && orderBy.get(str))
sql3 += ", p." + str + " ";
} else {
if (orderBy.get(str) != null && orderBy.get(str))
sql3 = " ORDER BY p." + str;
}
}
}
if (sql2 != null)
sql += sql2;
if (sql3 != null) {
if (orderFlag)
sql += sql3;
else
sql += sql3 + " DESC ";
}
Query query = emp.createQuery(sql);
for (String str : var.keySet()) {
if (str.indexOf(".") > 0) // This solves only for one level
str2 = str.substring(str.indexOf(".") + 1, str.length());
else
str2 = str;
query.setParameter(str2, var.get(str));
}
if (fromRowNo != null) {
query.setFirstResult(fromRowNo);
}
if (noOfRows != null) {
query.setMaxResults(noOfRows);
}
EntityManagerProvider.beginTransaction();
// emp.flush();
// emp.clear();
list = query.getResultList();
EntityManagerProvider.commitTransaction();
} catch (Exception e) {
throw e;
}
return list;
}
public Integer countRecords(Map<String, Object> var,
Map<String, Boolean> flags, String opr) throws Exception {
Long count = null;
if (opr == null)
opr = "AND ";
try {
emp = new EntityManagerProvider();
String sql = "SELECT COUNT(p) FROM " + className.getCanonicalName()
+ " p ";
String sql2 = null;
String str2 = null;
if (var != null) {
for (String str : var.keySet()) {
if (str.indexOf(".") > 0) // This solves only for one
// level
str2 = str
.substring(str.indexOf(".") + 1, str.length());
else
str2 = str;
if (sql2 != null) {
if (flags != null) {
if (!flags.get(str))
sql2 += opr + "p." + str + " != :" + str2 + " ";
else
sql2 += opr + "p." + str + " = :" + str2 + " ";
} else
sql2 += opr + "p." + str + " = :" + str2 + " ";
} else {
if (flags != null) {
if (!flags.get(str))
sql2 = "WHERE p." + str + " != :" + str2 + " ";
else
sql2 = "WHERE p." + str + " = :" + str2 + " ";
} else
sql2 = "WHERE p." + str + " = :" + str2 + " ";
}
}
}
if (sql2 != null)
sql += sql2;
Query query = emp.createQuery(sql);
for (String str : var.keySet()) {
if (str.indexOf(".") > 0) // This solves only for one level
str2 = str.substring(str.indexOf(".") + 1, str.length());
else
str2 = str;
query.setParameter(str2, var.get(str));
}
EntityManagerProvider.beginTransaction();
// emp.flush();
// emp.clear();
count = (Long) query.getSingleResult();
// System.out.println(count); //TODO: REMOVE ME
EntityManagerProvider.commitTransaction();
} catch (Exception e) {
throw e;
}
return count.intValue();
}
}
</code></pre>
<hr>
<pre><code>public class TargetGroupsDao {
private BaseDao baseDao;
public TargetGroupsDao() {
baseDao = new BaseDao(TargetGroupsDo.class, TargetGroupsDao.class.getName());
}
public void create(TargetGroupsDo targetGroupsDo, EntityManagerProvider emp) throws Exception {
baseDao.create(targetGroupsDo, emp);
}
public void update(TargetGroupsDo targetGroupsDo, EntityManagerProvider emp) throws Exception {
baseDao.update(targetGroupsDo, emp);
}
public TargetGroupsDo getById(String serialId) throws Exception {
return (TargetGroupsDo)baseDao.getById(serialId);
}
@SuppressWarnings("unchecked")
public List<TargetGroupsDo> getAll(Integer fromRowNo, Integer noOfRows) throws Exception {
return (List<TargetGroupsDo>)baseDao.getAll(fromRowNo, noOfRows);
}
public void delete(String serialId, EntityManagerProvider emp) throws Exception {
baseDao.delete(serialId, emp);
}
@SuppressWarnings("unchecked")
public List<TargetGroupsDo> search(TargetGroupsDto targetGroupsDto, Integer fromRowNo, Integer noOfRows, String opr) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
if( targetGroupsDto.getTgDesc()!= null && !targetGroupsDto.getTgDesc().trim().equals(""))
map.put("tgDesc", targetGroupsDto.getTgDesc());
if( targetGroupsDto.getTgId()!= null && !targetGroupsDto.getTgId().trim().equals(""))
map.put("tgId", targetGroupsDto.getTgId());
if( targetGroupsDto.getTgName()!= null && !targetGroupsDto.getTgName().trim().equals(""))
map.put("tgName", targetGroupsDto.getTgName());
if( targetGroupsDto.getOwnershipType()!= null && !targetGroupsDto.getOwnershipType().trim().equals(""))
map.put("ownershipType", targetGroupsDto.getOwnershipType());
if( targetGroupsDto.getNoOfMembers()!= null)
map.put("noOfMembers", targetGroupsDto.getNoOfMembers());
return (List<TargetGroupsDo>)baseDao.search(map, fromRowNo, noOfRows, opr);
}
public TargetGroupsDo getReferenceById(String tgId) throws Exception {
return (TargetGroupsDo)baseDao.getReferenceById(tgId);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>1.This sample is really ugly :) You can extract method <code>isEmptyTrim()</code> at least.</p>\n\n<pre><code>if( targetGroupsDto.getTgDesc()!= null && !targetGroupsDto.getTgDesc().trim().equals(\"\"))\n map.put(\"tgDesc\", targetGroupsDto.getTgDesc());\nif( targetGroupsDto.getTgId()!= null && !targetGroupsDto.getTgId().trim().equals(\"\"))\n map.put(\"tgId\", targetGroupsDto.getTgId());\nif( targetGroupsDto.getTgName()!= null && !targetGroupsDto.getTgName().trim().equals(\"\"))\n map.put(\"tgName\", targetGroupsDto.getTgName());\nif( targetGroupsDto.getOwnershipType()!= null && !targetGroupsDto.getOwnershipType().trim().equals(\"\"))\n map.put(\"ownershipType\", targetGroupsDto.getOwnershipType());\nif( targetGroupsDto.getNoOfMembers()!= null)\n map.put(\"noOfMembers\", targetGroupsDto.getNoOfMembers());\n</code></pre>\n\n<p>2.Cycle over keyset is a bad practice. </p>\n\n<pre><code> for (String str : var.keySet()) {\n</code></pre>\n\n<p>You should use </p>\n\n<pre><code> for (Entry<String, Object> entry : var.entrySet()) {\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T06:08:05.317",
"Id": "30795",
"Score": "0",
"body": "Any Comment on Connection setting ? \nAnd The way BaseDao is used within TargetGroupsDao is correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T04:39:58.420",
"Id": "32043",
"Score": "0",
"body": "@codesparkle Why? If you need both key and value, then entrySet() should be used. The link that you posted says exactly the same, too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-01T16:34:20.190",
"Id": "32084",
"Score": "0",
"body": "Sorry, I wasn't precise enough: in one case, only the key is used; there, `keySet()` is the right choice. All others should indeed be `entrySet()`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T19:57:09.730",
"Id": "19195",
"ParentId": "19177",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T05:55:03.373",
"Id": "19177",
"Score": "4",
"Tags": [
"java",
"design-patterns",
"hibernate",
"jpa"
],
"Title": "JPA connection : is this code is efficient enough"
}
|
19177
|
<h2>Forward</h2>
<p>I would love any comments you have, any ideas, any flaws you can find, and any suggestions you might have regarding the code below.
If this is similar to other implementations, I would love to know about them, since this is something I came up with by myself, after not finding any solution 'out there', but I know there is nothing new here, just my way of doing things.</p>
<p>Also, this is my first time posting here, so <em>please</em> go easy on me if I did it wrong.</p>
<h2>Description</h2>
<p>Writing code for windows WinForms application, usually entails working asynchronously, and sometimes throwing some threads in the air, so that the UI will still be responsive, IO will happen in the background, data will stay fresh, and your users will love instead of hate you for the bugs you throw at them.</p>
<p>C# has the 'lock' keyword to help with creating Atomic operations, but what I find frustrating, is that most often then not, the data itself need to be guarded, but the sync syntax can be easily forgotten.</p>
<p>So I've created the following code for myself to manage object locking, via generics and extension methods, which allow me to easily wrap any data type I need to be kept safe, and use it only via the Synced context.</p>
<p>First the extension methods (or rather a single extension method with overloaded parameter signature to make it's use more natural) <code>DoLocked</code>.</p>
<p>DoLocked will perform a locked action, after verifying that the object is 'ready for work', with the option to 'wait' (or not) on the lock, will release the lock when the action has completed (or in case of an exception), and will let you know if the action was triggered or not.</p>
<p>So basically any object, for ex. <code>ComplexClass complexObject</code>, you want to performed an operation that is locked (with all the features mentioned above), the code will look something similar to:</p>
<pre><code>complexObject.DoLocked(syncObj,
() => { if( isReady ) return true; },
true,
obj => {
...
obj.Method();
...
obj.Property = value;
...
};
</code></pre>
<p>the getIsReady is a Func which tests readiness to enter the read (before even attempting to wait for the lock), when null, it is 'always ready'.</p>
<p>Next step is the Synced generic class, which will hold the syncObject along with the content (now locked) object.
The idea is not to abstract the internal object, but wrap it in a package that makes it clear how to use it right.</p>
<h2>The Code:</h2>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace IdleSharp.Sys.ThreadSafe
{
public static class SyncedDoExt
{
private static readonly Random random = new Random();
private static bool alwaysReady() { return true; }
// A note about the parameter order.
// Usually, it is preferred to have the most common param in the first (left most) postion.
// However, since the common argument is an action, which will likely be an in line lambda
// expression more often then not, I have decided to place the action always last.
// This is to make calls to DoLocked with multi-lines lambda inline methods more readable.
public static bool DoLocked<T>(
this T subject, object syncObj,
Func<bool> getIsReady, bool wait, Action<T> action
) where T : class
{
System.Diagnostics.Trace.Assert(
null != syncObj, "SyncObject must not be null!!!");
bool lockWasTaken = false;
try
{
Monitor.TryEnter(syncObj,
wait ? Timeout.Infinite : 0, ref lockWasTaken);
if (!lockWasTaken) return false;
getIsReady = getIsReady ?? alwaysReady;
// My original version
//while (lockWasTaken && wait && !getIsReady())
//{
// Monitor.Exit(syncObj);
// System.Threading.Thread.Sleep(random.Next(20, 70));
// lockWasTaken = false;
// Monitor.TryEnter(syncObj, Timeout.Infinite, ref lockWasTaken);
//}
//
// Code implementing Trevor Pilley's suggestion to use SpinWait instead
// After better understanding it with the help of:
// http://www.albahari.com/threading/part5.aspx#_SpinLock_and_SpinWait
if (!getIsReady()) System.Threading.SpinWait.SpinUntil(() =>
{
Monitor.Exit(syncObj);
lockWasTaken = false;
Monitor.TryEnter(syncObj, Timeout.Infinite, ref lockWasTaken);
return lockWasTaken && getIsReady();
});
// I now see that testing getIsReady here again is unnecessary, commenting it out.
// if (getIsReady())
// {
action(subject);
return true;
// }
return false;
}
finally
{
if (lockWasTaken) Monitor.Exit(syncObj);
}
}
// Alternative parameters overloading
public static bool DoLocked<T>(
this T subject, object syncObj, Func<bool> getIsReady, Action<T> action
) where T : class
{
return DoLocked(subject, syncObj, getIsReady, false, action);
}
public static bool DoLocked<T>(
this T subject, object syncObj, bool wait, Action<T> action
) where T : class
{
return DoLocked(subject, syncObj, (Func<bool>)null, wait, action);
}
public static bool DoLocked<T>(
this T subject, object syncObj, Action<T> action
) where T : class
{
return DoLocked(subject, syncObj, (Func<bool>)null, false, action);
}
// The method signatures below are the same as above, except that the subject object
// itself is also the lock object
public static bool DoLocked<T>(
this T subject, Func<bool> getIsReady, Action<T> action
) where T : class
{
return DoLocked(subject, subject, getIsReady, false, action);
}
public static bool DoLocked<T>(
this T subject, bool wait, Action<T> action
) where T : class
{
return DoLocked(subject, subject, (Func<bool>)null, wait, action);
}
public static bool DoLocked<T>(
this T subject, Action<T> action
) where T : class
{
return DoLocked(subject, subject,(Func<bool>)null, false, action);
}
}
// Easy container to hold lock objects with content objects, allowing a uniform
// access abstraction.
public class Synced<T> where T: class
{
public bool AutoWait { get; set; }
object _syncLock;
public T InnerObject { get; private set; }
public Synced(T source, object syncLock, bool autoWait)
{
AutoWait = AutoWait;
_syncLock = syncLock;
InnerObject = source;
}
public bool DoLocked(Action<T> action)
{
return InnerObject.DoLocked(_syncLock, null, AutoWait, action);
}
public bool DoLocked(bool wait, Action<T> action)
{
return InnerObject.DoLocked(_syncLock, null, wait, action);
}
public bool DoLocked(Func<bool> getIsReady, Action<T> action)
{
return InnerObject.DoLocked(_syncLock, getIsReady, AutoWait, action);
}
}
// Non-generic static class, for easy creation of Synced<T> objects.
public static class Synced
{
public static Synced<T> MakeSynched<T>(
T source, object syncLock, bool autoWait
) where T : class
{
return new Synced<T>(source, syncLock, autoWait);
}
public static Synced<T> MakeSynched<T>(
T source, object syncLock
) where T : class
{
return new Synced<T>(source, syncLock, false);
}
public static Synced<T> MakeSynched<T>(
T source, bool autoWait
) where T : class
{
return new Synced<T>(source, source, autoWait);
}
public static Synced<T> MakeSynched<T>(T source) where T : class
{
return new Synced<T>(source, source, false);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T09:43:04.087",
"Id": "30758",
"Score": "0",
"body": "Can you show a use case when `getIsReady` is actually used? Why would you try to acquire the lock when business logic is not ready for it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T10:58:05.473",
"Id": "30764",
"Score": "0",
"body": "@almaz, Perfectly valid question. When about to write to the object, I might want to check that the source data is ready before I take the lock for a 'long time', and so, of I'm not ready to write, I might as well not dwell on it. That's when I would provide different logic for 'read' and 'write'. It is still important that this test be done while the lock is in place. Does that makes sense?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T11:11:05.980",
"Id": "30765",
"Score": "0",
"body": "well... not really :)... the common pattern is: you prepare the data to write, acquire the lock, and write to shared resource as quickly as possible. Another common pattern is double-checked locking where you do prepare the data to be written while you are in lock, but that is done in order not to prepare the same data twice in different threads (often used in singletons)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T11:26:53.817",
"Id": "30767",
"Score": "0",
"body": "But what if the subject object itself has a 'readiness' state that needs to be verified. especially prior to writing, it still needs to be read while locked. I do agree, however, that getIsReady MUST be a very quick test, and not a complex/long operation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T11:40:40.993",
"Id": "30768",
"Score": "1",
"body": "Can you wait for subject object to be ready, capture its state if necessary, and only after that try to acquire the lock? Please provide example, as it still sounds like unnecessary complication."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T11:49:18.687",
"Id": "30769",
"Score": "0",
"body": "It seems you might be right, I wrote it in thinking about solving a situation, which later on did not present itself in the code after all. I'll think about it again, and most likely write it off my code. Thanks for taking the time."
}
] |
[
{
"body": "<p>While this may work in isolation, the problem here is that it only works if every caller uses your <code>Synced<T></code> class with the same <code>syncObj</code> as every other caller.</p>\n\n<p>Also, the <code>InnerObject</code> exposes the actual class outside the synchronization wrapper so there is nothing which prevents someone modifying the instance separately.</p>\n\n<p>A few other points around the actual \"code style\", you should alter your overloads for the <code>DoLocked</code> method, it's a good idea to add additional options after the common options. Since every method requires an action so that should be the first parameter, it helps keep the calling code consistent.</p>\n\n<pre><code> public bool DoLocked(Action<T> action)\n public bool DoLocked(Action<T> action, bool wait)\n public bool DoLocked(Action<T> action, Func<bool> getIsReady)\n</code></pre>\n\n<p>If you are using .NET 4/4.5 you should use the <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.spinwait.aspx\" rel=\"nofollow\">System.Threading.SpinWait</a> struct instead of the <code>Thread.Sleep</code> call, alternatively <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.thread.spinwait.aspx\" rel=\"nofollow\">Thread.SpinWait</a> is available in all versions of .NET.</p>\n\n<p>Your parameters should be camel cased and not named after keywords - <code>this T instance</code> instead of <code>this T This</code>. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T18:40:40.960",
"Id": "30739",
"Score": "0",
"body": "Thanks for pointing out the public InnerObject, I think that hiding it by making it private would resolve the issue though - would you agree?\n\nI'll change to the SpinWait.\n\nAs for the coding style, thanks for the suggestion, though I always feel that an action should be as far to the right as possible, since it is very likely to be a multi line entry, would it be better if it was always the last param?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T19:52:57.130",
"Id": "30741",
"Score": "0",
"body": "@Trever, thanks again, I've edited the code above to include your suggestions, I would appreciate a 2nd look by you if possible."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T09:13:44.710",
"Id": "19179",
"ParentId": "19178",
"Score": "3"
}
},
{
"body": "<p>Based on discussion in question comments it sounds like <code>getIsReady</code> might be unnecessary. Then, <code>wait</code> parameter can also be dropped in favor of 2 different methods. So, in case of <code>wait == true</code> it gets simplified to:</p>\n\n<pre><code>public static void DoLocked<T>(this T subject, object syncObj, Action<T> action)\n{\n //no need to check syncObject for null since lock will throw exception in this case anyway\n lock (syncLock)\n {\n action(subject);\n }\n}\n</code></pre>\n\n<p>or, put simply we just don't need this method at all.</p>\n\n<p>In case of <code>wait == false</code> we get the following code:</p>\n\n<pre><code>public static bool TryDoLocked<T>(this T subject, object syncObj, Action<T> action)\n{\n bool lockWasTaken = false;\n try\n {\n Monitor.TryEnter(syncObj, ref lockWasTaken);\n\n if (lockWasTaken) \n action(subject);\n\n return lockWasTaken;\n }\n finally\n {\n if (lockWasTaken)\n Monitor.Exit(syncObj);\n }\n}\n</code></pre>\n\n<p>This method can be useful, but I think situations where I would need to attempt non-blocking operation are quite rare, especially given .NET 4.5 asynchronous API. I think some of these cases can also be rewritten in a completely non-blocking fashion using atomic operations from <code>Interlocked</code> class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T18:51:56.493",
"Id": "30853",
"Score": "0",
"body": "These is not a bad idea, but it looses some of the abstraction I had in mind. I'll need to sleep on this. As before you might be right though. Simple is usually better, and maybe this is one of those examples where it is."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T19:02:52.180",
"Id": "30856",
"Score": "0",
"body": "Did you plan to pass `wait` as a variable and not explicit `true` or `false`? I can't imagine a case where you would need that. And if you do, your code will grow 10x bigger because each time you'll have to deal with \"what if my code in action didn't run?\". The simpler, the better :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T11:28:46.723",
"Id": "32341",
"Score": "0",
"body": "you are so right, I reviewed this code today again, given all the comments, and I agree with you completely. The simplest approach is usually the best, and that is exactly what you suggested. Thanks!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T12:28:33.517",
"Id": "19228",
"ParentId": "19178",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "19228",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T06:11:49.237",
"Id": "19178",
"Score": "7",
"Tags": [
"c#",
"thread-safety",
"locking",
"generics",
"extension-methods"
],
"Title": "Synced/Atomic access"
}
|
19178
|
<p>I had a task where I was supposed to write a solution to sort entries(Name, score - in an array/list) in order of score and generate ranking based on higher score to lower scores.</p>
<p>I tried doing that, code is working what it was supposed to do but it seems very ambiguous and tightly coupled, I can't even write a unit test for it.</p>
<p>Could someone have a look and suggest.</p>
<p>I have pasted main method class, If anyone wants me to paste other relevent classes as well so do ask me please.</p>
<p>Any suggestion(s)/workaround(s) would be much appreciated.</p>
<pre><code>public class JournalAnalyzer {
final static int LENGTH_OF_JOURNAL = 5; //Length Journal array
static int count = 0;
static Integer ranking = 1;
static Journal[] journals = new Journal[LENGTH_OF_JOURNAL];
static ArrayList<Journal> list = new ArrayList<Journal>();
static Object[] scoreList = new Object[LENGTH_OF_JOURNAL];
static String journalName;
static Double journalScore;
static Integer journalRank;
static Boolean journalReview;
private static void initData(Journal[] journals) {
journals[0] = new Journal(0, "Journal A", 5.6, false);
journals[1] = new Journal(0, "Journal B", 2.6, false);
journals[2] = new Journal(0, "Journal C", 3.2, false);
journals[3] = new Journal(0, "Journal D", 4.1, false);
journals[4] = new Journal(0, "Journal E", 1.6, false);
}
private static int fillJournalList(int count, Journal[] journals,
int LENGTH_OF_JOURNAL, ArrayList<Journal> list) {
for (int i = 0; i < LENGTH_OF_JOURNAL; i++) {
journalRank = new Integer(journals[i].getRank());
journalName = new String(journals[i].getJournal());
journalScore = new Double(journals[i].getScore());
journalReview = new Boolean(journals[i].getIsReviewed());
if (!journalReview) {
Journal value = new Journal(journalRank, journalName,
journalScore, journalReview);
list.add(value);
count++;
} else {
continue;
}
}
return count;
}
private static void GenerateRanking(Integer ranking, int count,
ArrayList<Journal> list, Object[] scoreList) {
Double scoreComparatorOne;
Double scoreComparatorTwo;
Comparator<Journal> scores = new SortScore();
Collections.sort(list, scores);
for (int i = 0; i < count; i++) {
scoreComparatorOne = (list.get(i)).getScore();
if (i == 0) {
scoreComparatorTwo = (list.get(i)).getScore();
} else {
scoreComparatorTwo = (list.get(i - 1)).getScore();
}
if (scoreComparatorOne.equals(scoreComparatorTwo)) {
if (ranking == 0) {
ranking += 1;
} else {
ranking = ranking;
}
} else {
ranking = i + 1;
}
(list.get(i)).setRank(ranking);
scoreList[i] = (list.get(i));
}
}
private static void displayJournal(int counter, Object[] scoreList) {
JournalOutput printer = new JournalOutput();
printer.display(count, scoreList);
System.exit(0);
}
public static void main(String[] args) throws IOException {
initData(journals);
count = fillJournalList(count, journals, LENGTH_OF_JOURNAL, list);
GenerateRanking(ranking, count, list, scoreList);
displayJournal(count, scoreList);
}
}
</code></pre>
<p>My question is how to minimize and simplify this code so that I can easily write a unit test for this class</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T23:45:35.493",
"Id": "30660",
"Score": "1",
"body": "What is your question?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T23:52:52.263",
"Id": "30661",
"Score": "0",
"body": "My question is how to minimize and simplify this code so that I can easily write a unit test for this class."
}
] |
[
{
"body": "<p>You could change this:</p>\n\n<pre><code>for (int i = 0; i < count; i++) {\n scoreComparatorOne = (list.get(i)).getScore();\n if (i == 0) {\n scoreComparatorTwo = (list.get(i)).getScore();\n } else {\n scoreComparatorTwo = (list.get(i - 1)).getScore();\n }\n if (scoreComparatorOne.equals(scoreComparatorTwo)) {\n if (ranking == 0) {\n ranking += 1;\n } else {\n ranking = ranking;\n }\n } else {\n ranking = i + 1;\n }\n (list.get(i)).setRank(ranking);\n scoreList[i] = (list.get(i));\n }\n</code></pre>\n\n<p>Theres no need to verify all the time this conditional:</p>\n\n<pre><code>if (i == 0) {\n scoreComparatorTwo = (list.get(i)).getScore();\n } else {\n scoreComparatorTwo = (list.get(i - 1)).getScore();\n }\n</code></pre>\n\n<p>inside the loop. Since <code>i</code> it will be equal to 0 only once.</p>\n\n<p>Modifying to:</p>\n\n<pre><code>...\nDouble scoreComparatorOne = (list.get(0)).getScore();\nDouble scoreComparatorTwo = (list.get(0)).getScore();\nranking = getRating(scoreComparatorOne,scoreComparatorTwo,ranking,0);\n(list.get(0)).setRank(ranking);\nscoreList[0] = (list.get(0));\n\nfor (int i = 1; i < count; i++){\n scoreComparatorOne = (list.get(i)).getScore();\n scoreComparatorTwo = (list.get(i - 1)).getScore();\n ranking = getRating(scoreComparatorOne,scoreComparatorTwo,ranking,i);\n (list.get(i)).setRank(ranking);\n scoreList[i] = (list.get(i));\n}\n</code></pre>\n\n<p>where <code>getRating</code> is:</p>\n\n<pre><code> public Integer getRating (Double sCOne, Double sCTwo, Integer ranking, int i)\n {\n if(sCOne.equals(sCTwo))\n return (ranking == 0) ? 1 : ranking;\n else return i + 1;\n }\n</code></pre>\n\n<p>also you can turn your <code>fillJournalList</code> into (but this is not a major problem):</p>\n\n<pre><code>private static int fillJournalList(Journal[] journals,\n int LENGTH_OF_JOURNAL, ArrayList<Journal> list) {\n\nfor (int i = 0; i < LENGTH_OF_JOURNAL; i++){\n\n if (!journals[i].getIsReviewed())\n list.add(new Journal(new Integer(journals[i].getRank(), \n new String(journals[i].getJournal(),\n new Double(journals[i].getScore(), \n false);\n\nreturn list.size();\n</code></pre>\n\n<p>}</p>\n\n<p>This way you only create the new Objects when you will insert them. Not in every for iteration. With the above modification there no need to this:</p>\n\n<pre><code>public class JournalAnalyzer {\n ...\n static String journalName;\n static Double journalScore;\n static Integer journalRank;\n static Boolean journalReview;\n</code></pre>\n\n<p>You can remove all four variables.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T09:52:52.040",
"Id": "30663",
"Score": "0",
"body": "Hi,\n\nI made changes to the code, now its throwing NullPointerException.\nDue to scoreList skipping to fill scorelist[0] element."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T12:13:50.310",
"Id": "30668",
"Score": "0",
"body": "@AliJay did you manage to solve?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T12:17:03.927",
"Id": "30669",
"Score": "0",
"body": "@@dreamcrash I have made changes like mentioned in my last comment, now its throwing NullPointerException. Due to scoreList skipping to fill scorelist[0] element. And it is due to GenerateRanking method where for loop starts from counter 1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T12:21:57.933",
"Id": "30670",
"Score": "0",
"body": "post your code here http://codepaste.net/ and post it back the link here so i can see it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T12:26:27.977",
"Id": "30671",
"Score": "0",
"body": "here you go <http://codepaste.net/87imtg>\nCheers"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T12:27:47.757",
"Id": "30672",
"Score": "0",
"body": "If you want me to paste other relevant classes, do let me know please.\nMany thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T12:28:49.050",
"Id": "30673",
"Score": "0",
"body": "ranking = getRating(scoreComparatorOne, scoreComparatorTwo, ranking, 0); put zero not i"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T12:33:12.143",
"Id": "30674",
"Score": "0",
"body": "another thing just put scoreComparatorOne = (list.get(i)).getScore(); inside the loop as well"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T12:39:44.817",
"Id": "30677",
"Score": "0",
"body": "Still the same, it's throwing NullException because of journals[0] is null, method starts filling in from [1] element.\nAny idea?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T12:43:36.247",
"Id": "30678",
"Score": "0",
"body": "put this out side (list.get(0)).setRank(ranking);\n scoreList[o] = (list.get(o)); right before the loop"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T13:03:12.310",
"Id": "30680",
"Score": "0",
"body": "Thanks, it works now but it not generating ranking as it should be, it generates 1st rank same if the scores are same, \nbut on 2nd rank it continues till 5.\nFor instance:\nScores [5.6,5.6,3.2,3.2,1.5]\nRanks [1,1,2,3,4,5]\nWhere it should been like this:\nScores [5.6,5.6,3.2,3.2,1.5]\nRanks [1,1,2,2,5]"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T13:09:01.680",
"Id": "30683",
"Score": "0",
"body": "Are you sure that in yours original code the rating were working? (I just edit my rating method but is not that different"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T14:10:37.687",
"Id": "30685",
"Score": "0",
"body": "Yes it's still working when I run my previous class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T14:21:13.593",
"Id": "30686",
"Score": "0",
"body": "Strange send me the code that works and the code that is not working codepaste.net"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T14:30:36.783",
"Id": "30687",
"Score": "0",
"body": "Working code before modification: http://codepaste.net/m31k46\nCode after modification: http://codepaste.net/n9ih9d"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T14:34:48.250",
"Id": "30688",
"Score": "0",
"body": "You have to add scoreComparatorOne = (list.get(i)).getScore(); inside the loop also, and it is scoreComparatorTwo = (list.get(i-1)).getScore();. Please see the method I had put here is different than you had put it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T14:37:12.610",
"Id": "30689",
"Score": "0",
"body": "Like this http://codepaste.net/a1tr45"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T14:48:51.353",
"Id": "30691",
"Score": "0",
"body": "Yes thanks, I figured it out before your last comment.\nBut a full heap thanks to you, I appreciate your help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T14:54:35.150",
"Id": "30693",
"Score": "0",
"body": "@AliJay You welcome, glap it helps you. I just don't know why I lots the points I earn on this question when it was on StackOverFlow, maybe it was due to the migration."
}
],
"meta_data": {
"CommentCount": "19",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T00:03:21.753",
"Id": "19181",
"ParentId": "19180",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "19181",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T23:44:43.793",
"Id": "19180",
"Score": "1",
"Tags": [
"java"
],
"Title": "Array sort-rank class"
}
|
19180
|
<p>I was trying to solve the Next Palindrome problem listed in SPOJ in Ruby language. Please find the problem statement <a href="http://www.spoj.pl/problems/PALIN/" rel="nofollow">here</a>. Though i came up with the below solution, i could not get the execution time below 1.4s even after tweaking this code numerous times. Where can this code be optimized in terms of memory and execution time or is there a better approach than the solution i came up with?</p>
<pre><code>def next_palindrome
number = gets.chomp
len = number.length
if len == 1
return "11\n" if number == "9"
return number.next!<<"\n"
end
if len.even?
f = len/2
return number[0..f-1]<<number[0..f-1].reverse<<"\n" if number[0..f-1]>number[f..-1]
number = number[0..f-1].next!
return number<<number[0..f-1].reverse<<"\n"
else
f = (len-1)/2-1
return number[0..f+1]<<number[0..f].reverse<<"\n" if number[0..f]>number[f+2..-1]
number = number[0..f+1].next!
return number<<number[0..f].reverse<<"\n"
end
end
def input
gets.chomp.to_i.times {print next_palindrome}
end
input
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T23:01:47.690",
"Id": "30664",
"Score": "0",
"body": "First thing I see that's obvious is that you get string ranges over and over and over again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-14T00:11:32.110",
"Id": "304613",
"Score": "0",
"body": "because we are looking at less than 1,000,000 - unless you really need to be super fast, why not consider ways of making the code more readable and perhaps more amenable to change (which will inevitably come)?"
}
] |
[
{
"body": "<p>Cache cache cache! :) All those substrings you take should be stored in variables, rather than using the expensive substring methods. Furthermore, comparing strings can also be expensive. When you store the substring in a variable, you could parse the integer and keep it for comparisons later.</p>\n\n<p>Advanced:</p>\n\n<p>Since you never need to look at the last half number (if it's a palindrome it must be the reverse of the first digits), you can just store two variables: big_half and small_half. for even-digit numbers, they will be equal, but for odd-digit numbers big_half will have the middle digit. This makes creating a that is adjacent to the number (either just smaller or just larger) as simple as <code>big_half + small_half.reverse</code>. If a test shows it's the smaller one, increment <code>big_half</code> and generate a new <code>small_half</code> from it, then add together as above.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T20:10:02.183",
"Id": "30742",
"Score": "1",
"body": "We do need to look at the second half of the number right? For example if we take 1783, the next palindrome is 1881. If we ignore the second half we might end up with 1771 which is lesser than our input. \nCaching did help in bringing down execution time, but not significantly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-08T11:07:14.677",
"Id": "31091",
"Score": "0",
"body": "sorry, what I meant was that we don't have to store the parsed second half of the number, since we'll never have to look at that \"part\". We still need the original, whole number for comparisons, of course. Just not the end slice by itself."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T00:41:49.080",
"Id": "19183",
"ParentId": "19182",
"Score": "2"
}
},
{
"body": "<p>I think you are over-complicating things here. I think there's two solutions to your problem.</p>\n\n<ul>\n<li>Comparing two halves of the string</li>\n<li>Recursively comparing chars[i] with chars[n-1-i], where n is the size</li>\n</ul>\n\n<p>Mark did explained our first option, so let me explain the second. We already know that if our number is a palindrome, the first char will equals the last one, the second with equals the one before the last, etc...</p>\n\n<p>As an example, let's start with a first number of 808.</p>\n\n<pre><code># our number\nk = \"808\"\n\n# let's continue until we break!\nwhile i = k.next! do\n\n # what is the size of our string?\n size = i.size\n\n # the next loop returns nil if two chars weren't equal\n # if it doesn't return nil, that means we have a palindrome! We can break\n break if (size / 2).ceil.times do |j|\n\n # Let's compare the first and the last chars.\n # If they aren't equal, we break (return nil).\n break unless i[j] == i[size - (j + 1)]\n end\nend\n\nputs i\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T20:12:33.733",
"Id": "30743",
"Score": "0",
"body": "Imagine running a loop with a million digit number. It is definitely going to cross the execution time limit they have set."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T03:12:10.913",
"Id": "19184",
"ParentId": "19182",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T22:44:50.180",
"Id": "19182",
"Score": "4",
"Tags": [
"optimization",
"algorithm",
"performance",
"ruby",
"palindrome"
],
"Title": "The Next Palindrome: Is my code efficient?"
}
|
19182
|
<p>Consider the following simple relationship.</p>
<p><img src="https://i.stack.imgur.com/fjdmm.png" alt="Class Diagram"></p>
<p><strong>Code</strong></p>
<pre><code>[DataContract(Name = "Wheel")]
public class Wheel { }
[DataContract(Name = "OffRoadWheel")]
public class OffRoadWheel : Wheel { }
[DataContract(Name = "RoadVehicle")]
public class RoadVehicle
{
public Collection<Wheel> Wheels { get; private set; }
public RoadVehicle()
{
Wheels = new Collection<Wheel>();
}
}
[DataContract(Name = "Truck")]
public class Truck : RoadVehicle
{
public Collection<OffRoadWheel> OffRoadWheels { get; private set; }
public Truck()
{
OffRoadWheels = new Collection<OffRoadWheel>();
}
}
</code></pre>
<p>The Collections are configured as Read-Only and initiated in the class constructor as per FXCop recommendation CAS2227. <a href="http://msdn.microsoft.com/en-us/library/ms182327(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms182327(VS.80).aspx</a></p>
<p>Now I know all the rules about Covariance & Contravariance, and the varying capabilities of using Collections vs. Lists vs. Enumerables (vs. their Interface Equivalents). However the above object model creates a number of competing difficulties.</p>
<p>If you create a truck with 4 Off-Road Wheels, down cast it to a RoadVehicle, and then iterate the Wheels collection... it's empty.</p>
<p>One way around this would be to create a <code>public new Collection<Wheel> Wheels</code> property on the <code>Truck</code> class which on-the-fly casts the contents of the <code>OffRoadWheel</code> collection, but this breaks behaviour if you go to add or remove on that collection.</p>
<p>Another problem is serialization, you can alter the above to store and duplicate the inner <code>Wheels</code> and <code>OffRoadWheels</code> properties, but then you'd end up complete serializing both if you wanted to serialize <code>Truck</code></p>
<p>Any other suggestions on how to make this more Developer Friendly object model where things happen as you'd expect them to?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T17:15:33.627",
"Id": "30699",
"Score": "1",
"body": "I'm a little concerned about having classes to represent off road wheels and wheels. Other than attributes (tread pattern, size, width, max speed, etc.) are there any differences between the two? I think the design is flawed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T17:47:31.333",
"Id": "30702",
"Score": "0",
"body": "it's a hacked together example to represent a real-world solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T17:47:51.457",
"Id": "30703",
"Score": "0",
"body": "or do you think that kind of \"Square Relationship\" is inherently flawed in any system."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T18:05:45.640",
"Id": "30704",
"Score": "0",
"body": "I think you could have just a Wheel class that has an attribute type (Off-Road, Touring, Racing, Slick, ...) in it. This will save you a bunch of extra classes, and the type could be an enum."
}
] |
[
{
"body": "<p>Create constructors that take appropriate wheel collections. then <code>RoadVehicle</code> constructor looks like this <code>public RoadVehicle(Collection<OffRoadWheel> hotWheels) : base(hotWheels) {}</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T14:42:19.530",
"Id": "30690",
"Score": "1",
"body": "That creates bi-directional coupling. The base types shouldn't know about the child types. e.g. what if the child types were defined in a seperate assembly, you'd end up with a cyclic reference to achieve what you're trying."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T14:39:21.283",
"Id": "19189",
"ParentId": "19188",
"Score": "-1"
}
},
{
"body": "<p>I think the model here is broken. If you have a <code>RoadVehicle</code> that's actually <code>Truck</code>, the interface lets you to add a normal <code>Wheel</code> to it, which is wrong.</p>\n\n<p>One way to make it work is to make the collection immutable (e.g. <code>IEnumerable<T></code>). This can be a reasonable solution if you're okay with setting the wheels only in the constructor.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T22:30:58.617",
"Id": "30712",
"Score": "0",
"body": "Alternatively rather than via the constructor you could have an AddWheel(Wheel wheel) method and the Truck could be responsible for knowing what wheels it supports? I guess this then could potentially lead to a builder pattern? i.e. AddWheel().AddDoors() ...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T12:20:57.497",
"Id": "30733",
"Score": "0",
"body": "@dreza I think that still breaks LSP. If you have a method `AddWheel(Wheel)`, then it shouldn't accept only a specific type of wheel."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T18:12:40.880",
"Id": "30736",
"Score": "0",
"body": "Wouldn't constructors get a bit crowded if this were the case. What would be another alternative to constructor injection?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T21:36:14.937",
"Id": "19197",
"ParentId": "19188",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "19197",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T14:12:00.263",
"Id": "19188",
"Score": "3",
"Tags": [
"c#",
"collections",
"generics",
"inheritance"
],
"Title": "How would you improve this object model design to get around Covariance Issues with ObjectModel.Collection<T>?"
}
|
19188
|
<p>I have the below code which is still under development - but I'm trying to get myself to find the ideal way to move forward.</p>
<pre><code>public interface IMemberSubscriptionService
{
void SelectSubscription(IMember member, IMemberSubscriptionTypePrice subscription, IOrder linkedOrderPaidWith);
IMemberSubscriptionRenewal GetCurrentApplicableRenewal(IMember member);
}
public class MemberSubscriptionService : IMemberSubscriptionService
{
private readonly IMemberSubscriptionRenewalService memberSubscriptionRenewalService;
public MemberSubscriptionService(IMemberSubscriptionRenewalService memberSubscriptionRenewalService)
{
this.memberSubscriptionRenewalService = memberSubscriptionRenewalService;
}
public void SelectSubscription(IMember member, IMemberSubscriptionTypePrice subscription, IOrder linkedOrderPaidWith)
{
var renewal = GetCurrentApplicableRenewal(member);
if (renewal == null || !object.Equals(renewal.Subscription, subscription))
{//if they are different
if (renewal != null)
{
updateRenewalDateToEndAsOfYesterday(renewal);
}
var newRenewal = createFirstSubscriptionRenewal(member, subscription, linkedOrderPaidWith);
memberSubscriptionRenewalService.Renew(newRenewal);
}
}
private IMemberSubscriptionRenewal createFirstSubscriptionRenewal(IMember member, IMemberSubscriptionTypePrice subscription, IOrder linkedOrder)
{
IMemberSubscriptionRenewal renewal = member.SubscriptionRenewals.CreateNewItem();
renewal.StartDate = CS.General_v3.Util.Date.Now.Date;
renewal.EndDate = CS.General_v3.Util.Date.GetEndOfDay(PayMammoth.Connector.Util.GeneralUtil.GetDateTimeAfterIncrementingBillingPeriod(renewal.StartDate,
subscription.DurationIntervalType,subscription.DurationInDays).AddDays(-1));
renewal.LinkedOrder = linkedOrder;
renewal.Save();
return renewal;
}
private void updateRenewalDateToEndAsOfYesterday(IMemberSubscriptionRenewal renewal)
{
renewal.EndDate = CS.General_v3.Util.Date.Now.AddDays(-1);
}
#region IMemberSubscriptionService Members
public IMemberSubscriptionRenewal GetCurrentApplicableRenewal(IMember member)
{
throw new NotImplementedException();
}
#endregion
}
</code></pre>
<p>What this code should do is 'select a subscription' (<code>SelectSubscription</code>) for a particular member. A member has a list of <code>SubscriptionRenewals</code> which basically contain information for each period of a subscription, e.g taking a monthly subscription would have a <code>SubscriptionRenewal</code> for Jan 2012, another for Feb 2012, etc.</p>
<p>The <code>SelectSubscription</code> should get the current subscription, and if the subscription is to be changed, the existing renewal is updated to end as of yesterday, and the new subscription starts from today, for the total period (e.g changing from monthly to yearly). If you have a <code>SubscriptionRenewal</code> from 1 - 29 Feb 2012, and today is 15 Feb and you call 'SelectSubscription' with a yearly interval, this should change the existing <code>SubscriptionRenewal</code> to end on 14Feb 2012, and create a new one from 15 Feb 2012 till 14 Feb 2013 for this particular case.</p>
<p>This is just to give you an idea of the functionality. I need to create the respective unit tests for such a functionality, and came out with several scenarios, as per below:</p>
<ul>
<li>if subscription is the same as the current, do nothing. </li>
<li>if a current subscription renewal exists, it is updated to end as of yesterday </li>
<li>test that SelectSubscription creates new renewal is created, based on today and the subscription</li>
</ul>
<p>My main issue is on how to structure the code for unit-testing. Should you create the <code>GetCurrentApplicableRenewal</code> as part of the same service? This way, I cannot simply mock that functionality, when I am testing out a portion of the <code>SelectSubscription</code>. Does it make sense to take that functionality out into a different interface/class, so that it can be mocked? </p>
|
[] |
[
{
"body": "<p>I see two options:</p>\n\n<ol>\n<li>Test/implement <code>GetCurrentApplicableRenewal</code> first.</li>\n<li>Implement the code you need (which will likely go into <code>GetCurrentApplicableRenewal</code>) in your <code>SelectSubscription</code> method now, imeplement/test <code>GetCurrentApplicableRenewal</code> next, and refactor it to use the <code>GetCurrentApplicableRenewal</code> method later.</li>\n</ol>\n\n<p>The latter allows you to implement and define tests for both methods in isolation from one another, only refactoring when you have a full set of tests. With these tests, you can safely validate whether refactoring <code>SelectSubscription</code> can safely switch to using <code>GetCurrentApplicableRenewal</code> or not.</p>\n\n<p>The former way will save you some time, and as long as you don't skip any tests for <code>SelectSubscription</code>, you will probably be OK. The downside is that you have to context-switch to <code>GetCurrentApplicableRenewal</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T11:55:32.503",
"Id": "30800",
"Score": "0",
"body": "So you would leave it in the same service? Another problem I find this way is that in order to test `SelectSubscription`, I must also create the data in such a way that is correct also for `GetCurrentApplicableRenewal`. If I could mock that functionality, I could just make it return whatever renewal I want as `SelectSubscription` is based on what renewal is returned, so I can more easily test out certain functionality."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T18:46:48.980",
"Id": "19193",
"ParentId": "19191",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T15:11:38.850",
"Id": "19191",
"Score": "3",
"Tags": [
"c#",
"unit-testing"
],
"Title": "Test Driven Development, Mocking & Unit-testing"
}
|
19191
|
<p>Heres the link to the original question . <a href="https://www.interviewstreet.com/challenges/dashboard/#problem/4f2c2e3780aeb" rel="nofollow">Billboards Link</a></p>
<p>I initially declared n*k array which led to a <code>Out Of Memory Exception</code>. </p>
<p>Then I resorted to using just 2 * k matrix and alternating between 0 and 1 during each iteration. Now the issue is time limit. As of now 8/10 cases are solved using this approach. </p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Billboards
{
class Program
{
static void Main(string[] args)
{
long n, k;
string line;
string[] parts = new string[2];
line = Console.ReadLine();
parts = line.Split(new char[] { ' ' });
n = long.Parse(parts[0]);
k = long.Parse(parts[1]);
long i, j;
long[] c = new long[n];
for (i = 0; i < n; i++)
{
c[i] = long.Parse(Console.ReadLine());
}
long[][] dp = new long[2][];
long max = 0;
int var1, var2, temp;
var1 = 0;
var2 = 1;
for(i=0;i<=1;i++){
dp[i] = new long[k + 1];
}
for (i = 1; i <= n; i++)
{
dp[var2][0] = max;
max = 0;
for (j = 1; j <= k; j++)
{
dp[var2][j] = Math.Max(dp[var1][j - 1] + c[i-1], dp[var1][j]);
if(dp[var2][j] > max)
max = dp[var2][j];
}
temp = var1;
var1 = var2;
var2 = temp;
}
max = Max(dp[var1]);
Console.WriteLine(max);
}
static long Max(long[] arr)
{
long max = 0;
for (long i = 0; i < arr.Length; i++)
{
if (arr[i] > max)
{
max = arr[i];
}
}
return max;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Since we are on a code review forum I would suggest you to give more meaningful names to variables, avoid redundant assignments (e.g. initial array assigned to <code>parts</code> variable is not used), and split the logic into smaller methods that perform distinct functionality. Also you can use <code>Max(IEnumerable<long>)</code> extension method instead of writing your own.</p>\n\n<p>But I guess that's not what you want to hear, so in terms of algorithms I suggest you to apply the <a href=\"http://en.wikipedia.org/wiki/A%2a_search_algorithm\" rel=\"nofollow\">A* algorithm</a> to this problem instead of full search. If you find it difficult to understand and implement, I would recommend you to pass the <a href=\"https://www.coursera.org/course/ml\" rel=\"nofollow\">Machine Learning course</a> from Coursera or <a href=\"http://www.udacity.com/overview/Course/cs271/CourseRev/1\" rel=\"nofollow\">Introduction to Artificial Intelligence</a> from Udacity</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T07:58:42.100",
"Id": "30726",
"Score": "0",
"body": "Thanks for the suggestions. But I am sure there is a DP solution to this problem. Will try that approach too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T09:13:28.417",
"Id": "30729",
"Score": "0",
"body": "According to constraints N<=10^5, K<=N. So in worst case you have a nested loop with 10^10 iterations, and that is the reason why your solution timed out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T13:13:05.470",
"Id": "30734",
"Score": "0",
"body": "Yep ..Need to get a better algorithm.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T13:44:35.467",
"Id": "30735",
"Score": "0",
"body": "A* explores most promising paths first, so you can find a solution with just slightly more than N iterations"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T04:23:36.010",
"Id": "19201",
"ParentId": "19194",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "19201",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T19:10:59.450",
"Id": "19194",
"Score": "2",
"Tags": [
"c#",
"optimization",
"algorithm"
],
"Title": "Billboards InterviewStreet - Code Optimization"
}
|
19194
|
<p>Obviously there are better ways of obtaining Pi, but for educational purposes, how is the code below?</p>
<pre><code>(defn leibniz-numerator [x] (* (- (rem x 4) 2) -4.0))
(defn calc-pi-leibniz
"Calculate pi with Leibniz formula
4/1 - 4/3 + 4/5 - 4/7 + 4/9 etc
Very slow convergence"
[terms]
(reduce + (map #(/ (leibniz-numerator %) %) (range 1 terms 2))))
(print (calc-pi-leibniz 10000000))
</code></pre>
|
[] |
[
{
"body": "<p>I'd say your solution is pretty good! Since you probably won't re-use your <code>leibniz-numerator</code> function, you might want to make it private by declaring it with <code>defn-</code>, or you could declare it within the body of your main function using <code>let</code> or <code>letfn</code>.</p>\n\n<p>Also, you might notice that your function actually computes pi with half the number of terms given has parameters (might not be of importance).</p>\n\n<p>I can share some alternatives I came up with.</p>\n\n<p>We could start by generating the sequence <code>(4 -4 4 -4...)</code>. To do that, we can use the method <code>iterate</code>:</p>\n\n<pre><code>(take 4 (iterate - 4))\n;;=> (4 -4 4 -4)\n</code></pre>\n\n<p>Then we want the sequence <code>(1 3 5 7)</code>. You already found method <code>range</code>for that:</p>\n\n<pre><code>(take 4 (range 1 10 2))\n;;=> (1 3 5 7)\n</code></pre>\n\n<p>If you divide those to element wise, you will get <code>(4 -4/3 4/5 -4/7...)</code>. You can do that with <code>map</code></p>\n\n<pre><code>(take 4 (map / (iterate - 4) (range 1 10 2)))\n;;=> (4 -4/3 4/5 -4/7)\n</code></pre>\n\n<p>In our final computation, this can get really slow because we're using decimals. Let's use floats instead, and put everything together:</p>\n\n<pre><code>(defn calc-pi-leibniz [terms]\n (reduce + (map / (iterate - 4.0) (range 1.0 terms 2.0))))\n</code></pre>\n\n<p>But for some reason, this is 5 times slower than your solution. If someone could tell me why, I'd be grateful. I suspect that is because map has to go through two lists instead of one, but since they are both lazy this should not matter?</p>\n\n<p>For a faster solution (but less elegant), we can see that there are two subsequences in the leibniz formula. One that is <code>(4 4/5 4/9)</code> and one that is <code>(-4/3 -4/7 -4/11)</code>. With that in mind, you can get the following:</p>\n\n<pre><code>(defn calc-pi-leibniz [terms]\n (* 4 (- (reduce + (map / (range 1.0 terms 4.0)))\n (reduce + (map / (range 3.0 terms 4.0))))))\n</code></pre>\n\n<p>Which runs as fast as your solution.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-26T15:57:48.303",
"Id": "19942",
"ParentId": "19198",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T23:34:54.507",
"Id": "19198",
"Score": "4",
"Tags": [
"beginner",
"clojure",
"floating-point"
],
"Title": "Calculating Pi in Clojure"
}
|
19198
|
<p>I retrieved 200 tweets using the Jersey API. I want to find two tweets which have the longest common substring.</p>
<p><code>tweetList</code> is an <code>ArrayList</code> of <code>Tweet</code> objects. The <code>comapreTweets</code> method compares <code>tweet</code> objects for longest substring.</p>
<pre><code>Tweet t1=new Tweet();Tweet t2=new Tweet();
int longestString=0;
for(int i=0;i<tweetList.size();i++)
{int store=0;Tweet comparer=null;
for(int j=i+1;j<tweetList.size();j++)
{
if(j!=i){
int result=tweetList.get(i).compareTweets(tweetList.get(j));
if(result>store){
store=result;
comparer=tweetList.get(j);
}}
}
if(longestString<store)
{
longestString=store;
t1=tweetList.get(i); t2=comparer;
}
}
</code></pre>
<p>If I retrieve 200 tweets then this will loop approx. 40000 times. I require a more efficient way.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T04:08:12.250",
"Id": "30714",
"Score": "0",
"body": "I don't know what's going on inside of the loop, but do strings need to be compared to each other twice? For example, i=5, j=3 and i=5, j=3 will compare tweets 5 and 3 twice. This would be a fairly minor improvement, but if it can be done (and it probably can be), it only takes about 10 characters of changes. (Also, `size` shouldn't be called over and over again)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T04:25:54.467",
"Id": "30715",
"Score": "0",
"body": "@Corbin but I did include `if(j!=i)` to ensure that. Can you point where will this repetition occur in my code"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T04:32:48.307",
"Id": "30716",
"Score": "0",
"body": "You've made sure not to compare a tweet to itself, but the comparison is two sided. Assume you have tweetList = {a, b, c, d}. This means i and j will both run from 0 to 3. Imagine when i = 1 and j = 3. Simple enough situation: compare(b, d). Now imagine when i = 3 and j = 1: compare(d, b). It's the same comparison, just inverted order."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T04:49:08.770",
"Id": "30717",
"Score": "0",
"body": "@Corbin do you know any way to prevent it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T05:12:06.620",
"Id": "30719",
"Score": "1",
"body": "Simple: `for (i = 0; i < n; ++i) { for (j = i + 1; j < n; ++j) {} }` (Note that this is still quadratic. It will just loop (n^2)/2 + n/2 times instead of n^2. So for 200 tweets, it would run 20100 times versus 40000.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T05:32:28.187",
"Id": "30722",
"Score": "0",
"body": "No problem. I suspect that other improvements are probably possible, but I'm not familiar with any of the longest common substring algorithms :)."
}
] |
[
{
"body": "<p>The classic solution to this well-known problem is using a <a href=\"http://en.wikipedia.org/wiki/Suffix_array\" rel=\"nofollow\">Suffix array</a> (see also <a href=\"http://en.wikipedia.org/wiki/Suffix_tree\" rel=\"nofollow\">Suffix tree</a> and <a href=\"http://en.wikipedia.org/wiki/Generalized_suffix_tree\" rel=\"nofollow\">Generalized Suffix tree</a> which is a more general data structure for these kinds of problems.). Basically, a Suffix array is a sorted set in which every suffix of every tweet is inserted. By using the prefixes of those sorted suffixes, you can find the longest common substring by iterating through every pair of substrings from different tweets in the Suffix array.</p>\n\n<p>Construction of all suffixes can be performed in <code>O(140 k)</code> time, where <code>k</code> is the the amount of tweets, and 140 is the length of a tweet. These can then be sorted in <code>O(k * log(k))</code> time. Finally allowing you to find the longest common substring in <code>O(k 140)</code> time. Which results in roughly <code>57 800</code> operations.</p>\n\n<p>The algorithm proposed in your orignal post loops through every tweet twice, and has to, worst case, compare all the characters. This leaves a total complexity of <code>O(k^2 * 140)</code> which is <code>5 600 000</code> operations.</p>\n\n<h2>Example</h2>\n\n<p>Imagine you have three strings:</p>\n\n<ol>\n<li>ababa</li>\n<li>bataba</li>\n<li>dafjkl</li>\n</ol>\n\n<p>We generate all suffixes of every string. Every suffix of the first string is:</p>\n\n<ul>\n<li>ababa</li>\n<li>baba</li>\n<li>aba</li>\n<li>ba</li>\n<li>a</li>\n</ul>\n\n<p>For the second we have:</p>\n\n<ul>\n<li>batabak</li>\n<li>atabak</li>\n<li>tabak</li>\n<li>abak</li>\n<li>bak</li>\n<li>ak</li>\n<li>a</li>\n</ul>\n\n<p>And finally for the third:</p>\n\n<ul>\n<li>dafjkl</li>\n<li>afjkl</li>\n<li>fjkl</li>\n<li>jkl</li>\n<li>kl</li>\n<li>l</li>\n</ul>\n\n<p>If we sort all suffixes for all strings, we get the following sorted set:</p>\n\n<ul>\n<li>a</li>\n<li>a</li>\n<li>aba</li>\n<li>ababa</li>\n<li>abak</li>\n<li>afjkl</li>\n<li>ak</li>\n<li>atabak</li>\n<li>ba</li>\n<li>baba</li>\n<li>bak</li>\n<li>batabak</li>\n<li>dafjkl</li>\n<li>fjkl</li>\n<li>jkl</li>\n<li>kl</li>\n<li>l</li>\n<li>tabak</li>\n</ul>\n\n<p>Thus we iterate through every pair of suffixes for different strings, to find the longest common prefix in suffixes from two different strings. This is equal to the longest common substring.</p>\n\n<p>First encounter is <code>a</code> (origining from the 1st string) and <code>a</code> (2nd string), thus our longest common substring (LCS) is of length 1 and equal to <code>a</code>.</p>\n\n<p>We go to the next pair from different strings, which is <code>aba</code>/<code>ababa</code> and <code>abak</code>, both of length 3. This is set as the LCS so far. If you keep going through the set using this algorithm, you will find that this is the LCS for these three strings.</p>\n\n<p>I do not know Java, however, I just created <a href=\"https://github.com/Sirupsen/informatics/blob/master/UVA/760-DNA-Sequencing/760-dna-sequencing.cpp\" rel=\"nofollow\">a C++ solution</a> to a <a href=\"http://uva.onlinejudge.org/external/7/760.html\" rel=\"nofollow\">very similar problem</a>. The solution for your problem is essentially the same, you just have to generate substrings for <code>k</code> strings rather than two.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T20:58:15.773",
"Id": "75500",
"Score": "0",
"body": "You said \"Imagine you have four strings:\" but don't you mean 3? If not, what is the fourth?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T20:08:45.703",
"Id": "19213",
"ParentId": "19200",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "19213",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T03:37:04.850",
"Id": "19200",
"Score": "6",
"Tags": [
"java",
"algorithm",
"strings",
"twitter",
"jersey"
],
"Title": "Finding the longest common substring between two tweets"
}
|
19200
|
<p>Here's my first effort at reformation: a business letter I wrote for a friend. I would appreciate a review. (Yes, I know this is a trivial example and it would be much more beneficial to have something reviewed that is more complicated. But I want to nip bad practices in the bud now, before they become embedded in me.)</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
.bodyBody {
margin: 10px;
font-size: 1.50em;
}
.divHeader {
text-align: right;
border: 1px solid;
}
.divReturnAddress {
text-align: left;
float: right;
}
.divSubject {
clear: both;
font-weight: bold;
padding-top: 80px;
}
.divAdios {
float: right;
padding-top: 50px;
}
</style>
</head>
<body class="bodyBody">
<div class="divReturnAddress">
Lopes de Almeido, Evanildo<br/>
Bl&auml;siring 161 <br/>
4057 Basel <br/>
<br/>
01 Dezember, 2012
</div>
<div class="divSubject">
Betreff: Vertretung waehrend Reise
</div>
<div class="divContents">
<p>
Sehr geehrte Frau Graf,
</p>
<p>
Ich fliege nach Brasilien am 29. Dezember 2012 f&uuml;r 6 Wochen.
Meine Nichte kann mich vertreten. Sie arbeitet sehr gesissenhaft.
Sie heisst Yasmin. Ihre Nummer ist xxx.
</p>
</div>
<div class="divAdios">
Freundliche Gr&uuml;sse <br/>
<!-- Space for signature. -->
<br/>
<br/>
<br/>
Evanildo Lopes do Almeida <br/>
Hauswart Binningerstrasse 19/23 <br/>
</div>
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-06T09:40:30.067",
"Id": "31006",
"Score": "0",
"body": "Useful: http://www.w3.org/TR/css3-selectors/#selectors"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T21:53:13.603",
"Id": "179589",
"Score": "0",
"body": "Consider using microformats, such as [hCard](http://microformats.org/wiki/hcard), for appropriate data. This may make it more searchable."
}
] |
[
{
"body": "<p>First of all, use external css file. Create style.css, put there all your css code and then link it in html file inside head tags:</p>\n\n<pre><code><link rel=\"stylesheet\" href=\"style.css\">\n</code></pre>\n\n<p>There is no need to prefix class with selectors name. It's not semantic and you're limiting yourself to use it only on that specific selector. Not literally but semantically.</p>\n\n<p>If you have two words in class name, don't write it like this: myCustomClass, use dash instead: my-custom-class.</p>\n\n<p>Read this guide for css, it's very good: <a href=\"https://github.com/necolas/idiomatic-css\" rel=\"nofollow\">https://github.com/necolas/idiomatic-css</a>\nand this guide for html: <a href=\"https://github.com/necolas/idiomatic-html\" rel=\"nofollow\">https://github.com/necolas/idiomatic-html</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T13:05:34.997",
"Id": "19206",
"ParentId": "19204",
"Score": "1"
}
},
{
"body": "<p>First of all, since you use HTML to write a business letter I assume you want to send an HTML e-mail? Since e-mail clients are <a href=\"http://www.email-standards.org/\" rel=\"nofollow\">far away from adopting web standards</a> and require <a href=\"http://www.sitepoint.com/code-html-email-newsletters/\" rel=\"nofollow\">special tactics</a>, this might not be the best area to practise writing HTML. For example, you should separate your CSS from the HTML (as Ben suggests) but aren't able to do this in HTML E-Mail.</p>\n\n<p>Now, focusing on your code, I can mainly echo what Ben writes (especially using <code>div.name</code> instead of <code>divName</code>, using the body-tag <code>body</code> instead of the selector <code>.bodyBody</code>).</p>\n\n<p>Additionally, I would suggest you use utf-8 encoding, so you can type your German umlauts (ä,ö,ü) instead of <code>&auml;</code>. Do this by inserting this line right after your head (and actually saving in UTF-8 in your text editor!)</p>\n\n<pre><code><head> \n <meta charset=\"utf-8\"> \n</code></pre>\n\n<p>Also, use <code><br /></code> only when you actually want to have a line break. It is commonly abused as a 'quick and dirty' spacer, the better way would be, to use a <code><p></code> tag for your <em>Freundliche Grüße</em> and give it a margin, like so:</p>\n\n<pre><code>div.adios p {\n margin-bottom: 30px;\n}\n</code></pre>\n\n<p>If you have several <code><p></code> you can select only the first child like this:</p>\n\n<pre><code>div.adios p:first-child {\n</code></pre>\n\n<p>Finally, I think I would wrap <em>.subject</em> into <em>.contents</em>, but that is just personal preference. Maybe, semantically, it would even make sense to just use the <em>h1</em> tag instead of <em>.subject</em> like so:</p>\n\n<pre><code><div class=\"contents\">\n <h1>Betreff: Vertretung während Reise</h1>\n <p>Sehr geehrte Frau Graf,</p>\n <p>Ich fliege am 29. Dezember 2012 für 6 Wochen nach Brasilien...</p>\n</div>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T16:04:11.180",
"Id": "19207",
"ParentId": "19204",
"Score": "2"
}
},
{
"body": "\n\n<h2>CSS</h2>\n\n<p>Since this is a single document, not a webpage of a website, it's fine to use internal CSS in the <code>style</code> element instead of linking to an external stylesheet. However, if you plan to write more letters in the future, you should create a stylesheet that includes all the shared styles that are typical for a letter and link to it from each letter (<code><link rel=\"stylesheet\" href=\"letter.css\" /></code>).</p>\n\n<p>You could name your classes more meaningful, but this is only a good practice, not a requirement. </p>\n\n<p>You could omit the class on <code>body</code>.</p>\n\n<h2>Encoding/Charset</h2>\n\n<p>You should add the encoding to the document. If you want to use UTF-8 (recommended), add <code><meta charset=\"utf-8\" /></code> as the first child of the <code>head</code> element.</p>\n\n<h2><code>title</code> element</h2>\n\n<p>You are missing the <code>title</code> element, which is required. Add it as child of <code>head</code>: <code><title>Vertretung während Reise – 1. Dezember 2012</title></code></p>\n\n<h2>Return address</h2>\n\n<p>The use of <code><br/></code> is correct here. However, the date is not part of the address, and therefor it shouldn't be separated by <code>br</code>. Put the date in its own element instead. HTML5 offers the <a href=\"http://www.w3.org/TR/html5/the-time-element.html#the-time-element\"><code>time</code> element</a>.</p>\n\n<p>Because this is your address (and not the recipient address), you should enclose it in the <code>address</code> element.</p>\n\n<p>You could enclose the return address and the date in the <a href=\"http://www.w3.org/TR/html5/the-header-element.html#the-header-element\"><code>header</code> element</a>. It might also be possible to enclose the return address in a <a href=\"http://www.w3.org/TR/html5/the-footer-element.html#the-footer-element\"><code>footer</code> element</a> and the <code>time</code> in a <code>header</code> (probably together with the <code>h1</code>), but this could be overkill ;)</p>\n\n<h2>Subject line / Betreff</h2>\n\n<p>Instead of using a meaningless <code>div</code> for the subject, you should use <code>h1</code> here, as it is the heading of the whole document.</p>\n\n<h2>Salution / Anrede</h2>\n\n<p>It's arguably if the salution is a paragraph on its own, or if it is part of the first paragraph. I think when followed by a comma, it should be part of the following paragraph. But this is not undisputed (I have no detailed knowledge about the semantics of a letter).</p>\n\n<h2>Greets</h2>\n\n<p>The use of the <code>br</code> element to separate the greeting from your anme is correct here. But don't use <em>several</em> <code>br</code> elements just because you want to add more spacing. Use only one and apply a class to it, so that you can give it a higher vertical <code>margin</code> (CSS).</p>\n\n<p>Also, include this in a <code>p</code> instead of a <code>div</code>.</p>\n\n<hr>\n\n<h2>Example</h2>\n\n<p>So your letter could look like:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><!DOCTYPE html>\n\n<html>\n\n <head>\n <meta charset=\"utf-8\" /> <!-- first element so that the encoding is applied to the title etc. -->\n <title>Vertretung während Reise – 1. Dezember 2012</title>\n <link rel=\"stylesheet\" href=\"letter.css\" />\n </head>\n\n <body>\n\n <header> \n <address class=\"return-address\">\n Lopes de Almeido, Evanildo<br/>\n Bläsiring 161 <br/>\n 4057 Basel <br/> \n </address>\n\n <time datetime=\"2012-12-01\">01 Dezember, 2012</time>\n </header>\n\n <h1>\n Betreff: Vertretung waehrend Reise\n </h1>\n\n <div class=\"content\"> <!-- use this div only if it is required for styling -->\n <p>\n Sehr geehrte Frau Graf,\n <br class=\"salution\" />\n\n Ich fliege nach Brasilien am 29. Dezember 2012 für 6 Wochen.\n Meine Nichte kann mich vertreten. Sie arbeitet sehr gesissenhaft.\n Sie heisst Yasmin. Ihre Nummer ist xxx.\n </p>\n <p>\n …\n </p>\n </div>\n\n <p class=\"adios\">\n Freundliche Grüsse \n <br class=\"greets\" />\n Evanildo Lopes do Almeida <br/>\n Hauswart Binningerstrasse 19/23\n </p>\n\n </body>\n\n</html>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T09:59:16.760",
"Id": "30761",
"Score": "0",
"body": "Would the higher vertical margin for the `<br>` element be done like this `br.greets { margin: 100px; }` where 100px would be adjusted for the space I wanted?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T14:33:20.067",
"Id": "30770",
"Score": "0",
"body": "@John: Yes. You could also use `.greets` as selector, so this style can be used even if you decide to use `p` instead of `br` in the future. And instead of `px` you could use the unit `em`, which always is in relation to the font-size of parents (so if you have a higher font-size, the margin gets higher, too)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-06T09:39:01.627",
"Id": "31005",
"Score": "0",
"body": "For the `detailed semantics of a letter`, a good forum to consult might be http://english.stackexchange.com/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-06T12:54:46.570",
"Id": "31011",
"Score": "0",
"body": "@ANeves: Or http://german.stackexchange.com in this case. I guess letter \"conventions\" differ by language (or more so, country)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-26T01:19:38.573",
"Id": "179595",
"Score": "0",
"body": "I think using the time element for the date is a bit excessive. Possibly could use U+00DF in Binningerstrasse if using umlauts in Bläsiring ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-26T12:28:27.757",
"Id": "179659",
"Score": "0",
"body": "@mckenzm: Why would that be \"excessive\"? It’s a date and HTML5 provides the `time` element for dates. // Regarding *Straße*: I ignored the actual content of the letter, as reviewing it would be off-topic here (but as a side note, in Swiss German both forms seem to be correct, *Straße* and *Strasse*)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-26T23:44:24.150",
"Id": "179775",
"Score": "0",
"body": "Because it is always historical and cannot be used for future appointments. Compare the verbosity. Also for legal purposes you really want dates in business letters to appear as you write them, not as a reader/browser renders them."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T04:51:47.113",
"Id": "19222",
"ParentId": "19204",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T11:59:58.913",
"Id": "19204",
"Score": "7",
"Tags": [
"html",
"css"
],
"Title": "Business Letter in HTML"
}
|
19204
|
<p>I created jQuery code to automatically insert new <code>input</code> field when the previous field is focused. The code works well but seems rather lengthy to me.</p>
<p>What I'm currently doing is cloning an element and then modifying the clone's attributes. As I add new a element into a DOM, I also need to modify this element and increase its <code>value</code> attribute by 1:</p>
<pre><code><input type="hidden" id="id_cat-TOTAL_FORMS" value="1" name="cat-TOTAL_FORMS">
</code></pre>
<p>How could this be improved?</p>
<p><strong>jQuery:</strong></p>
<pre><code>var slist = {
'init': function () {
$('form#cat-form').on('focus', 'p:last input[type="text"]', slist.addCategoryForm);
},
'addCategoryForm': function() {
slist.totalcatforms = parseInt($('form#cat-form input[id$=TOTAL_FORMS]').attr('value'));
console.log(slist.totalcatforms);
$('form#cat-form input[id$=TOTAL_FORMS]').attr('value', slist.totalcatforms + 1);
console.log('TOTAL_FORMS = ' + parseInt($('form#cat-form input[id$=TOTAL_FORMS]').attr('value')));
$('form#cat-form p:first').clone().insertBefore('form#cat-form input[type="submit"]');
$('form#cat-form p:last label').attr('for', 'id_cat-' + slist.totalcatforms + '-name');
$('form#cat-form p:last input[type="text"]').val('').attr({
id: 'id_cat-' + slist.totalcatforms + '-name',
name: 'cat-' + slist.totalcatforms + '-name'
});
$('form#cat-form p:last input[type="hidden"]').attr({
id: 'id_cat-' + slist.totalcatforms + '-id',
name: 'cat-' + slist.totalcatforms + '-id'
});
}
}
$(document).ready(slist.init);
</code></pre>
<p><strong>HTML:</strong></p>
<pre><code><form id="cat-form" method="post" action="/" name="cat-form">
<div style="display:none">
<input type="hidden" value="hjYpU5a6AD7VxhZpSSQv3s3efJ7uh2Z8" name=
"csrfmiddlewaretoken">
</div>
<input type="hidden" id="id_cat-TOTAL_FORMS" value="1" name=
"cat-TOTAL_FORMS">
<input type="hidden" id="id_cat-INITIAL_FORMS" value="0" name=
"cat-INITIAL_FORMS">
<input type="hidden" id="id_cat-MAX_NUM_FORMS" name=
"cat-MAX_NUM_FORMS">
<p>
<label for="id_cat-0-name">Name:</label>
<input type="text" maxlength="30" name=
"cat-0-name" id="id_cat-0-name">
<input type="hidden" id="id_cat-0-id" name=
"cat-0-id">
</p>
<input type="submit" value="Save" name="catForm">
</form>
</code></pre>
|
[] |
[
{
"body": "<p>Here's a quick review of your JavaScript code:</p>\n\n<ol>\n<li><p><em>Please</em> remember to <strong>always</strong> cache your selectors.</p></li>\n<li><p>To get the <code>value</code> of an <code>input</code> element, use <code>.val()</code> instead of <code>.attr('value')</code>.</p></li>\n<li><p>There's no need to use two separate steps to first get the value, then set it. Instead, pass a function to <code>val</code>, and return the new value you want.</p></li>\n<li><p>To convert a string to a number, just prefix it with the plus sign (e.g. <code>+'32'</code> will return the number <code>32</code>). It's safer, and more concise, than <code>parseInt</code>.</p></li>\n<li><p>When using CSS selectors, you should always strive to use the native CSS3 selectors, since they're much faster than jQuery's own custom selectors. <code>:first</code> and <code>:last</code> are not CSS3 selectors. In your case, you should use <code>:first-of-type</code> and <code>:last-of-type</code>, since they're native CSS3 selectors.</p></li>\n<li><p>Since IDs are unique per page, there's no reason to qualify an ID selector with the tag name (as you've done with <code>form#cat-form</code>). Just use the ID on its own. Again, better performance.</p></li>\n</ol>\n\n<hr>\n\n<p>With all that in mind, here's some sample code for you:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var slist = {\n cache: {},\n init: function () {\n slist.cache.form = $('#cat-form');\n slist.cache.totalsInput = slist.cache.form.find('input[id$=TOTAL_FORMS]');\n slist.cache.toClone = slist.cache.form.find('p:first-of-type');\n\n slist.cache.form.on('focus', 'p:last-of-type input[type=\"text\"]', slist.addCategoryForm);\n },\n addCategoryForm: function() {\n\n var totalCount;\n slist.cache.totalsInput.val(function (i, v) {\n totalCount = +v;\n return totalCount++;\n });\n\n slist.cache.toClone.clone()\n\n .find('label')\n .prop('for', 'id_cat-' + totalCount + '-name')\n\n .end().find('input[type=\"text\"]')\n .val('').prop({\n id: 'id_cat-' + totalCount + '-name',\n name: 'cat-' + totalCount + '-name'\n })\n\n .end().find('input[type=\"hidden\"]')\n .prop({\n id: 'id_cat-' + totalCount + '-id',\n name: 'cat-' + totalCount + '-id'\n })\n\n .end().insertAfter( $(this).closest('p') );\n }\n}\n\n$(slist.init);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T06:17:50.223",
"Id": "19223",
"ParentId": "19212",
"Score": "1"
}
},
{
"body": "<p><a href=\"http://jsfiddle.net/FsY7y/6/\" rel=\"nofollow\">Here's a short demo</a>, and the code is commented to reflect my take on improvements</p>\n\n<p>HTML</p>\n\n<pre><code><form id=\"cat-form\" method=\"post\" action=\"/\" name=\"cat-form\">\n <!--\n our template\n this is fetched as a string, and converted into HTML by jQuery later on\n this does not execute since the type \"text/template\" is unknown to the browser\n -->\n <script type=\"text/template\" id=\"nameTemplate\">\n <li>\n <input type=\"hidden\" id=\"id_cat-{name}-id\" name=\"cat-{name}-id\">\n <label for=\"id_cat-{name}-name\">Name:</label>\n <input type=\"text\" id=\"id_cat-{name}-name\" name=\"cat-{name}-name\" maxlength=\"30\">\n </li>\n </script>\n <div style=\"display:none\">\n <input type=\"hidden\" value=\"hjYpU5a6AD7VxhZpSSQv3s3efJ7uh2Z8\" name=\"csrfmiddlewaretoken\">\n </div>\n <!-- \n i would use IDs rarely, only when elements are unique.\n for form elements, i would stick to names instead\n -->\n <input type=\"hidden\" name=\"cat-TOTAL_FORMS\" value=\"0\">\n <input type=\"hidden\" name=\"cat-INITIAL_FORMS\" value=\"0\">\n <input type=\"hidden\" name=\"cat-MAX_NUM_FORMS\">\n <!--\n create a container for all the names\n since they are somewhat related to eachother, we use a list\n we also avoid using insertBefore(submitButton)\n -->\n <ul class=\"id_cat-names\"></ul>\n <input type=\"submit\" value=\"Save\" name=\"catForm\">\n</form>\n</code></pre>\n\n<p>JS</p>\n\n<pre><code>$(function() {\n\n //IDs are unique. No need to be so specific on the selector.\n //we take form as our \"base\" to find the other elements. \n var form = $('#cat-form'),\n //look for the name list in context of the form\n //this totally works like form.find('.id_cat-names'), only shorter\n nameList = $('.id_cat-names',form),\n //cache the total forms element, finding it using the same method\n totalForms = $('input[name=\"cat-TOTAL_FORMS\"]', form), \n //we get the template text\n //this is very useful for creating multiple elements of the same internals\n template = $('#nameTemplate', form).html(), \n //track latest count, initially based on totalForms value\n latestCount = totalForms.val();\n\n function addCategoryForm(){\n //we then take the template text\n //replace the numbers with an incremented count\n //turn it into HTML using jQuery\n //append it to nameList\n $(template.replace(/\\{name\\}/g,++latestCount)).appendTo(nameList);\n //update latest count\n totalForms.val(latestCount);\n }\n\n //focus event handler for the last name field\n //quotes are optional on single word element types\n nameList.on('focus', 'li:last input[type=text]', function(){\n addCategoryForm();\n });\n\n addCategoryForm();\n\n}); \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T19:08:33.283",
"Id": "30771",
"Score": "0",
"body": "Very interesting! A lot of new things for me in your approach. Thanks, I really appreciate your feedback! I think I won't be able to use it \"as is\" because I can't modify the HTML output that much. A lot of it is generated by the framework (Django). For example Django relies on element ids when processing forms, so they must stay. In any case, your response is fantastic for learning purposes. Thanks again."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T13:33:47.410",
"Id": "19230",
"ParentId": "19212",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T19:51:16.017",
"Id": "19212",
"Score": "0",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "Form field handling"
}
|
19212
|
<p>Here is the code I am using to apply DCT on 8x8 blocks, which I'm not sure is correct. I have tried to follow <a href="http://en.wikipedia.org/wiki/Discrete_cosine_transform" rel="nofollow">Wikipedia's discrete cosine transformation (DCT) formula</a> as closely as possible. Please let me know if there are any changes to be made.</p>
<pre><code>//round up a float type and show two decimal places
double rndup(double n)
{
double t;
double temp;
t=n-floor(n);
if (t>=0.5)
{
n*=100.0;//where n is the multi-decimal float
n=ceil(n);
temp = floor(n);
temp = n - temp;
n-=temp;
n/=100.0;
}
else
{
n*=100.0;//where n is the multi-decimal float
n=floor(n);
temp = floor(n);
temp = n - temp;
n-=temp;
n/=100.0;
}
return n;
}
//two functions that work together to apply DCT to a 8x8 block
void a_check(int u,int v, double *Cu, double *Cv)
{
if (u == 0) *Cu = sqrt(1.0 / 8.0); else *Cu = sqrt(2.0 / 8.0);
if (v == 0) *Cv = sqrt(1.0 / 8.0); else *Cv = sqrt(2.0 / 8.0);
}
void applyDCT(double *DCTMatrix, double *Matrix,int x, int y) //arguments: DCTMatrix = matrix where DCT values go, Matrix = input Matrix which needs to be processed
{
double Cu=0,Cv=0,cos_x=0,cos_y=0, DCT_value = 0;
for(int u=0;u<8;u++)
{
for(int v=0;v<8;v++)
{
a_check(u,v,&Cu,&Cv);
cos_x = cos( (3.14/8) * (double)u * ( (double) ( (x+u) + (1.0/2.0))));
cos_y = cos( (3.14/8) * (double)v * ( (double) ( (y+v) +(1.0/2.0))));
DCT_value = Cu * Cv * Matrix[u*8 + v] * cos_x * cos_y;
DCT_value = rndup(DCT_value);
DCTMatrix[u*8 + v] = DCT_value;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T23:02:58.153",
"Id": "30744",
"Score": "1",
"body": "It will be easier to answer your question if you include a link to the Wikipedia article you mentioned, and describe which formula from the article you are trying to implement"
}
] |
[
{
"body": "<p>I'll comment on readability as it could use some serious improvements.</p>\n\n<ul>\n<li><p>Your indentation is very inconsistent. Sometimes you indent two spaces, four spaces, eight spaces, or no spaces. Choose a style and keep it consistent throughout the program.</p>\n\n<p>Two common styles (using four spaces):</p>\n\n<pre><code>void func()\n{\n if (isTrue)\n {\n // ...\n }\n}\n</code></pre>\n\n<p></p>\n\n<pre><code>void func() {\n if (isTrue) {\n // ...\n }\n}\n</code></pre></li>\n<li><p>Your use of whitespace is also inconsistent. It'd be more readable to separate all operators and operands with one space <em>and</em> keep those consistent throughout the program.</p>\n\n<p>Don't do this:</p>\n\n<pre><code>int number=1+2+3;\n</code></pre>\n\n<p>Do this:</p>\n\n<pre><code>int number = 1 + 2 + 3;\n</code></pre></li>\n<li><p>This comment:</p>\n\n<pre><code>//where n is the multi-decimal float\n</code></pre>\n\n<p>can just be placed above the function. There's no need to put it in multiple places.</p></li>\n<li><p>The comment next to <code>applyDCT()</code> should probably be placed on top of the function instead. A comment that long should either be relocated or broken up into separate-lined comments.</p></li>\n<li><p>These:</p>\n\n<pre><code>if (u == 0) *Cu = sqrt(1.0 / 8.0); else *Cu = sqrt(2.0 / 8.0); \nif (v == 0) *Cv = sqrt(1.0 / 8.0); else *Cv = sqrt(2.0 / 8.0);\n</code></pre>\n\n<p>are not very readable nor maintainable. Prefer to apply curly braces, especially if you'll need to add to any of the conditions:</p>\n\n<pre><code>if (u == 0)\n{\n *Cu = sqrt(1.0 / 8.0);\n}\nelse\n{\n *Cu = sqrt(2.0 / 8.0);\n}\n\n// the same applies to the second aforementioned line\n</code></pre></li>\n<li><p>Do not declare/initialize variables on the same line:</p>\n\n<pre><code>double Cu=0,Cv=0,cos_x=0,cos_y=0, DCT_value = 0;\n</code></pre>\n\n<p>This is also not very readable nor maintainable, especially if you'll ever need to add comments or modify individual variables.</p>\n\n<p>Instead, have them on their own line:</p>\n\n<pre><code>double Cu = 0;\ndouble Cv = 0;\ndouble cos_x = 0;\ndouble cos_y = 0;\ndouble DCT_value = 0;\n</code></pre>\n\n<p>Moreover, in C++, you should try to use variables as close in scope as possible (next to where they will first be used). This will reduce the need for long lists of variables like above.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T07:49:24.107",
"Id": "41138",
"ParentId": "19216",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T21:26:09.770",
"Id": "19216",
"Score": "3",
"Tags": [
"c++",
"algorithm",
"image",
"compression"
],
"Title": "JPEG compression and DCT algorithm verification"
}
|
19216
|
<p>I often have static classes which uses the <code>DataContext</code> somehow, and they all make a new <code>DataContext</code>, but often I already have one instantiated elsewhere, so why not use that?</p>
<pre><code>public static bool SignIn(string email, string password, DataContext db = null)
{
bool disposeDb = false;
if (db == null)
{
disposeDb = true;
db = new DataContext();
}
//Sign In stuff, or any other stuff...
if (disposeDb) db.Dispose();
}
</code></pre>
<p>But is there a cool trick to do this, or am I just coding it wrong? Or is it ok? </p>
<p><strong>Update</strong></p>
<p>The <code>DataContext</code> is not expensive to instantiate. I guess I just leave it be.</p>
<p>But here is another example:</p>
<pre><code>public static User GetUser(DataContext db = null)
{
if (HttpContext.Current.Request.Cookies["Id"] == null)
{
return null;
}
else
{
bool disposeDb = false;
if (db == null)
{
disposeDb = true;
db = new DataContext();
}
int id = Convert.ToInt32(HttpContext.Current.Request.Cookies["Id"].Value);
string cookieKey = HttpContext.Current.Request.Cookies["CookieKey"].Value;
User user = db.Users.FirstOrDefault(x => x.Id == id && x.CookieKey == cookieKey);
if (disposeDb) db.Dispose();
return user;
}
}
</code></pre>
<p>This is again nice because if I already have a context, I can provide it, and then I won't have to attach the entity (User) to another context if I want to modify it:</p>
<pre><code>User user = MyClass.GetUser(db);
user.Email = "asdsasd";
db.SaveChanges();
</code></pre>
<p>How can I improve it? Or is it okay?</p>
<p><strong>Update 2</strong></p>
<p>The <code>DataContext</code> should only be instantiated once per page request. And <a href="https://stackoverflow.com/a/10153406/973485">here</a> is a neat way to do it, that actually allows me to access it even from static methods.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T00:01:37.270",
"Id": "30745",
"Score": "0",
"body": "I believe that ... since `db` is not passed in be reference, it should be disposed automatically as it falls out of scope when the function exists. Why do you sometimes pass in an instantiated `DataContext`, and why do you want it to auto-dispose. Is it good or bad? Well, it depends. What are you trying to do?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T00:11:26.470",
"Id": "30746",
"Score": "0",
"body": "Not sure if i follow, Well if there is a DataContext paramater is provided, it is because it is instansiated elsewhere, and will be disposed wlsewhere, but if you dont have one, and only need the result of that method, please dispose after use."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T00:26:36.733",
"Id": "30747",
"Score": "2",
"body": "How expensive is it to create a new `DataContext`? If it is expensive, then perhaps you create t once and hold on to it. Does the library provide the connection pooling for you? I do not like your original code (nothing personal), but I cannot tell you exactly how to make it better because I do not see examples of how you are using it. It is weird to me that the `DataContext` may or may not be already created. What control that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T00:32:39.967",
"Id": "30748",
"Score": "1",
"body": "\"I Often have static classes\" ??? I would look into why you often have these. Too many static classes IMHO can sometimes hints at design problems. Perhaps these are causing you to write code that you are not that keen about?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T00:54:39.667",
"Id": "30750",
"Score": "0",
"body": "@Leonid Not that expensise. so i'll just instasiate those inside. dreza Okay, i don't have that many static classes!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T06:11:39.073",
"Id": "30755",
"Score": "0",
"body": "You want us to kill you? That won't be very productive... who's going to accept our answers?"
}
] |
[
{
"body": "<p>At the very least, you should place the second <code>if</code> statement in a <code>finally</code> block. As things stand, the code is not generally correct from a purely mechanical perspective. I would also phrase it as:</p>\n\n<pre><code>bool dbDispose = db == null;\ndb = db ?? new DataContext();\n</code></pre>\n\n<p>From a design point of view: yes, I'd say this violates the single responsibility principle. You have a method that not only does certain calculations, but also creates a <code>DataContext</code> if necessary. If creation has to be modified at any point, then you'll have many places to change that. (Unlikely if it's default-constructed like this, but I doubt it's that simple in practice.)</p>\n\n<p>It looks to me like <code>SignIn</code> should actually be a member function of <code>DataContext</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T00:53:16.813",
"Id": "30749",
"Score": "0",
"body": "Wow, to make SignIn a part of DataContext would be just wrong... just.. or would it? I can't imagen thats how people make theese kind of functions.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T09:46:32.463",
"Id": "30759",
"Score": "0",
"body": "Making it directly part of a DataContext could be wrong, if that gives `DataContext` too much responsibility. On the other hand, having a class with a member `DataContext` and a `SignIn` method could definitely make sense."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T00:19:21.483",
"Id": "19218",
"ParentId": "19217",
"Score": "5"
}
},
{
"body": "<p>So, default argument values are nice, but in this case I favor the old-school (multiple methods with the same name) approach</p>\n\n<pre><code>public static bool SignIn(string email, string password)\n{\n using (var db = new DataContext())\n {\n return SignIn(email, password, db);\n }\n}\n\npublic static bool SignIn(string email, string password, DataContext db)\n{\n Require.IsNotNull(db, \"nice error message here\"); // Or whatever the syntax is ...\n //Sign In stuff, or any other stuff...\n}\n\n... and so on ...\n</code></pre>\n\n<p>I like static methods, Rich Hickey likes static methods. Static methods are one honking good idea! Let's have more of these. The static methods hatas will keep on hating.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T09:49:27.420",
"Id": "30760",
"Score": "1",
"body": "whole `MakeDataContextIfNeeded` method can be rewritten as `db ?? new DataContext()`, there is no need is this method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T10:36:14.217",
"Id": "30762",
"Score": "0",
"body": "Do you have any sources that the cleanup you expect is likely to happen?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T05:26:44.173",
"Id": "30794",
"Score": "0",
"body": "@Anton Golov, I talked out of my ass. It is generally a bad idea to let an `IDisposable` fall out of scope, so much so that there is a rule specifically for it. http://msdn.microsoft.com/en-us/library/ms182289(v=vs.100).aspx Apparently when compiling C++ to .Net, you can rely on the fact that a finalizer will run which will also call Dispose. When using C#, this will not happen for some time. So, an open file will be locked until the GC decides to run. It smells like an undefined behavior and you can code a Schroedingers cat logic around the fact that you do not know whether the file is locked"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T04:18:01.973",
"Id": "19220",
"ParentId": "19217",
"Score": "0"
}
},
{
"body": "<p>I see 2 issues with <code>SignIn</code> method:</p>\n\n<ul>\n<li>it is static. It means that you can't unit-test business logic that uses <code>SignIn</code> functionality in isolation, you'll have to hit the database in your tests.</li>\n<li><code>DataContext</code> in web applications should usually be instantiated once per web request because in most cases web request represents a unit-of-work, and as such should be covered by a single transaction. If you're using ASP.NET MVC you can move all the logic that deals with <code>DataConext</code> instantiation and calling <code>SaveChanges</code>/<code>Dispose</code> into base controller class, and expose instance of DataContext as a property. That way you business logic will be cleaned from DataContext management, and most likely you won't actually need a separate class with methods like <code>SignIn</code> since the functionality can go right into Controller class.</li>\n</ul>\n\n<p>About <code>GetUser</code> method - if this a method is in Controller class, and taking previous bullets into consideration, the code would look like that:</p>\n\n<pre><code>//MyBaseController exposes DataContext property\npublic class UserController : MyBaseController\n{\n public User GetUser()\n {\n HttpCookie idCookie = Request.Cookies[\"Id\"];\n HttpCookie keyCookie = Request.Cookies[\"CookieKey\"];\n\n int id;\n if (idCookie == null || keyCookie == null || !int.TryParse(idCookie.Value, out id))\n return null;\n\n return DataContext.Users.FirstOrDefault(x => x.Id == id && x.CookieKey == keyCookie.Value);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T08:43:19.407",
"Id": "19224",
"ParentId": "19217",
"Score": "3"
}
},
{
"body": "<p>Instead of init <code>DataContext</code> inside static methods you can use <strong>Singleton</strong> pattern or <strong>Factory</strong> pattern depending on what kind of life cycle of the object DataContext. That patterns allows to encapsulate logic of <code>DataContext</code> initialization and provide more control over the life cycle of an instance(including implementation caching politics).</p>\n\n<p>As for me correct variant <code>GetUser</code> method should look similar on that:</p>\n\n<pre><code>public static class UserService{\n\npublic static User GetUser(HttpContext context, DataContext db)\n{\n if (db==null)\n throw new ApplicationException(\"Data Context is null\");\n if (context==null)\n throw new ApplicationException(\"Http Context is null\");\n\n if (context.Request.Cookies[\"Id\"] == null)\n {\n return null;\n }\n else\n {\n int id = Convert.ToInt32(context.Request.Cookies[\"Id\"].Value);\n string cookieKey = context.Request.Cookies[\"CookieKey\"].Value;\n\n User user = db.Users.FirstOrDefault(x => x.Id == id && x.CookieKey == cookieKey);\n\n return user;\n }\n\n}\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T11:20:39.147",
"Id": "19226",
"ParentId": "19217",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "19224",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T23:56:44.403",
"Id": "19217",
"Score": "4",
"Tags": [
"c#",
"entity-framework",
"asp.net-mvc-4",
"null"
],
"Title": "Instantiating if null"
}
|
19217
|
<p>I want to direct all requests that haven't got a valid controller action to my custom page controller. </p>
<p>I.e. I want <code>/pages/new</code> & <code>/users/login</code> etc to work correctly, but a request for <code>/foo</code> or <code>/foo/bar</code> should be directed to <code>/pages/display/$path</code>.</p>
<p>The following code works, but I'm pretty certain I'm not doing something the right way(tm).</p>
<pre><code>// In app/Config/routes.php
Router::connect('/', array('controller' => 'pages', 'action' => 'displayHome'));
$controllerList = App::objects('controller');
foreach ($controllerList as $controller) {
$contstr = substr($controller, 0, strlen($controller)-10);
$contstr = Inflector::tableize($contstr);
if($contstr != 'app') {
Router::connect('/'. $contstr, array('controller'=>$contstr));
Router::connect('/'. $contstr .'/:action', array('controller'=>$contstr));
Router::connect('/'. $contstr .'/:action/*', array('controller'=>$contstr));
// FIXME: Check if admin routing is set
Router::connect('/admin/'. $contstr, array('controller'=>$contstr, 'admin'=>true));
Router::connect('/admin/'. $contstr .'/:action', array('controller'=>$contstr, 'admin'=>true));
Router::connect('/admin/'. $contstr .'/:action/*', array('controller'=>$contstr, 'admin'=>true));
}
}
Router::connect('/**', array('controller'=>'pages', 'action'=>'display'));
</code></pre>
<p>Would someone please be able to review this and tell me if this is okay/horribly wrong?</p>
|
[] |
[
{
"body": "<h2>Use a pattern</h2>\n<p>The general principle is fine, though it won't handle plugin routes (which I assume isn't a problem)</p>\n<p>However instead of a loop (and therefore defining 6 routes per controller) a parameter for the controller name can be used which will be more concise and likely overall more performant. The code could be rewritten like this:</p>\n<pre><code>// Define a home route\nRouter::connect('/', array('controller' => 'pages', 'action' => 'displayHome'));\n\n// Generate a regex-like controller name pattern (e.g. "posts|comments|users")\n$controllerList = App::objects('controller');\n$controllerList = array_map(function($c) {\n return Inflector::underscore(substr($c, 0, strlen($c)-10);\n}, $controllerList));\n$controllerList = array_filter($controllerList, function ($c) {\n return $c !== 'app'\n});\n$controller = implode('|', $controllerList);\n\n// Define normal routes\n$params = array('controller' => $controller);\nRouter::connect('/:controller', $params);\nRouter::connect('/:controller/:action', $params);\nRouter::connect('/:controller/:action/*', $params);\n\n// Define admin routes\n$params += array('admin' => true, 'prefix' => 'admin');\nRouter::connect('/admin/:controller', $params);\nRouter::connect('/admin/:controller/:action', $params);\nRouter::connect('/admin/:controller/:action/*', $params);\n\n// Define catchall\nRouter::connect('/**', array('controller'=>'pages', 'action'=>'display'));\n</code></pre>\n<p>In this way there are 8 routes in total, no matter how many controllers there are in the application.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-07T08:52:20.957",
"Id": "32369",
"ParentId": "19219",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "32369",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T04:15:25.097",
"Id": "19219",
"Score": "5",
"Tags": [
"php",
"cakephp"
],
"Title": "CakePHP 2.x Custom PagesController & Routing"
}
|
19219
|
<p>I'm starting with OOP for php, i get the idea, but don't have someone physical near me to fallback on so I'm hoping i can do that here.</p>
<p>The following works but i would like to know if it's good practice, that is something that weights a lot for me.</p>
<p>Concept is that you can create an object, the data for this object is gotten trough different soap calls. I have (at this point) a class to create the details and a class to connect soap and get the details.</p>
<p>Here it is: <a href="http://pastebin.com/9bgKzATv" rel="nofollow">http://pastebin.com/9bgKzATv</a></p>
<p>So again, just hoping someone is willing and has the time to give it a quick look and just shoot at it so i can learn.</p>
<p>I know i actually should use a dependency in the create, to the soap, but the way it's set up now does make the code cleaner and easyer...</p>
<h2>EDIT: i see the code must be included and not a link:</h2>
<pre><code>###
# INDEX
###
<?php
function __autoload( $class )
{
if( !defined( 'ROOT_DIR_CLASSES' ) )
{
define( 'ROOT_DIR_CLASSES', realpath( __DIR__ . DIRECTORY_SEPARATOR . 'classes' ) );
}
$directory = str_replace( '\\', DIRECTORY_SEPARATOR , $class );
$file = ROOT_DIR_CLASSES . DIRECTORY_SEPARATOR . $directory . '.class.php';
if( file_exists( $file ) )
{
include( $file );
}
}
$objectId = 0123;
$soapUser = 'User';
$soapPassword = 'Pass';
use Vendor\Object\Details\Create as Yacht;
try
{
$yacht = new Yacht( $objectId, $soapUser, $soapPassword );
print '<pre>';
print_r( $yacht->objectSpecs() );
}
catch( Exception $e )
{
var_dump( $e );
}
?>
##
# CREATE DETAILS
##
<?php
namespace Vendor\Object\Details;
class Create
{
public $objectId;
private $_soapUser;
private $_soapPassword;
private $_soapCall;
//construct our object
public function __construct( $objectId, $_soapUser, $_soapPassword )
{
$this->objectId = (string) $objectId;
$this->_soapUser = $_soapUser;
$this->_soapPassword = $_soapPassword;
$this->_soapCall = new \Vendor\Soap\Call\SoapGet( $this->_soapUser, $this->_soapPassword );
}
//make the details array
public function objectSpecs()
{
try
{
$soapObjectDetails = $this->_soapCall->GetDetails( $this->objectId );
}
catch( Exception $e )
{
throw $e;
}
if( is_array( $soapObjectDetails ) )
{
return $soapObjectDetails;
}
throw new \Exception('Requested object has no specs');
}
}
?>
##
# SOAP CALLS
##
<?php
namespace Vendor\Soap\Call;
class SoapGet
{
private $_soapUser;
private $_soapPassword;
public $soapCall;
public $soapParams;
public $objectId;
function __construct( $_soapUser, $_soapPassword )
{
$this->_soapUser = $_soapUser;
$this->_soapPassword = $_soapPassword;
if( !isset( $this->_soapUser ) OR empty( $this->_soapUser ) )
{
throw new \Exception('No SOAP user given');
}
if( !isset( $this->_soapPassword ) OR empty( $this->_soapPassword ) )
{
throw new \Exception('No SOAP password given for user ' . $this->_soapUser);
}
$this->soapParams = array(
'user' => $this->_soapUser,
'password' => $this->_soapPassword,
);
$this->soapCall = new \SoapClient(
null,
array(
'location' => 'http://localhost/webservice/webservice.php',
'uri' => 'http://localhost/webservice.php',
'trace' => 1,
)
);
}
function getDetails( $objectId )
{
if( !isset( $this->soapParams ) OR empty( $this->soapParams ) )
{
throw new \Exception('soapParams are empty');
}
$this->soapParams['yachtId'] = $objectId;
//Soap expects a string encoded objectid
$object = $this->soapCall->__soapCall( 'getDetails', $this->soapParams );
$object = base64_decode( $object );
$object = unserialize( $object );
return $object;
}
}
?>
</code></pre>
|
[] |
[
{
"body": "<h2>Code base</h2>\n\n<p>I have removed the namespaces for cleaner view of the situation.</p>\n\n<pre><code>class SoapCredentials {\n private $_soapUser;\n private $_soapPassword;\n\n function __construct( $_soapUser, $_soapPassword ) {\n if(empty( $this->_soapUser ) ) {\n throw new \\Exception('No SOAP user given');\n }\n\n if(empty( $this->_soapPassword ) ) {\n throw new \\Exception('No SOAP password given for user ' . $this->_soapUser);\n }\n\n $this->_soapUser = $_soapUser;\n $this->_soapPassword = $_soapPassword;\n }\n\n public function UserName() {\n return $this->_soapUser;\n }\n\n public function Password() {\n return $_this->_soapPassword;\n }\n}\n\nclass SoapGet { \n private $_credentials;\n private $_soapCall;\n\n function __construct(\\SoapClient $client, SoapCredentials $credentials) {\n $this->_credentials = array(\n 'user' => $credentials->UserName(),\n 'password' => $credentials->Password(),\n );\n\n $this->_soapCall = $client;\n }\n\n public function Execute($funcName, array $params = array(), $callback = NULL) {\n //TODO: check keys in $params for match one of the credentials key!!!\n\n $requestParams = array_merge($params, $this->_credentials);\n\n $result = $this->_soapCall->__soapCall( 'getDetails', $this->soapParams );\n\n if (\\is_callable($callback)) {\n return call_user_func_array($callback, array($result));\n }\n\n return $result;\n }\n}\n\nclass ShipYard {\n private $_soapGet;\n\n public function __construct(\\Vendor\\Soap\\Call\\SoapGet $soapGet) {\n $this->_soapGet = $soapGet;\n }\n\n public function GetYachSpecs($objectId) {\n $soapObjectDetails = $this->_soapGet->Execute('getDetails', array('yachtId' => $objectId), function ($object) {\n return unserialize( base64_decode( $object ) );\n });\n\n if( !is_array( $soapObjectDetails ) ) {\n //return an empty array instead it that's okay\n throw new \\Exception('Requested object has no specs');\n }\n\n //create a Ship object and return that not an associative array (on fail, return null)\n return $soapObjectDetails;\n }\n}\n</code></pre>\n\n<h2>Usage</h2>\n\n<pre><code>$objectId = 0123;\n$soapUser = 'User';\n$soapPassword = 'Pass';\n\n\n$soapCall = new SoapClient(\n null,\n array(\n 'location' => 'http://localhost/webservice/webservice.php',\n 'uri' => 'http://localhost/webservice.php',\n 'trace' => 1,\n )\n );\n\n$credentials = new SoapCredentials($soapUser, $soapPassword);\n\n$get = new SoapGet($soapCall, $credentials);\n\n$context = new ShipYard($get);\n\n$context->GetYachSpecs($objectId);\n</code></pre>\n\n<h2>Your code</h2>\n\n<p>In your code you are hard coding things when you are using the new operator in your classes, to avoid this use dependency injection as i did. Your SoapGet class has 3 responsibilities: checking credentials, connecting and executing calls, do this is separate classes: one class for validating the credentials, injecting the SoapClient instance and then SoapGet can execute the requests.</p>\n\n<h2>Hard coding</h2>\n\n<p>Never fix parameters like connection data, parameter names in \"generic\" classes!</p>\n\n<h2>Exception handling</h2>\n\n<pre><code>try {\n //anything\n}\ncatch(Exception $e) {\n throw $e;\n}\n</code></pre>\n\n<p>This is bad it makes the code dirty. Do not write these kind of try-catch block, they are unnecessary and this one especially bad becouse it will not work at all. When you are not in the global namespace in your catch block must reference to the base Exception type with the namespace qualifier (\\Exception) if you want to catch all exception (if you got an Exception class in your custum namespace then it will work but please rename it a custom one).</p>\n\n<p>(My code may contain typo-s.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T19:26:41.843",
"Id": "30772",
"Score": "0",
"body": "Thanks for this, going to give it a good look right away!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T20:52:56.607",
"Id": "30774",
"Score": "0",
"body": "Everything looks great, this is helping. I'm just thinking about the soapGet. The idea initially was that i wanted to create a soapGet class, and then define the options. For example the getDetails, but i could imagine a getOverview aswell."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T21:18:05.150",
"Id": "30775",
"Score": "0",
"body": "If you want other query methods put them in the ShipYard class as i did with the getDetails (GetYachtSpecs) the SoapGet is just gateway, a connection with authentication."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T19:33:11.903",
"Id": "30861",
"Score": "0",
"body": "I'm looking trough this but GetYachtSpecs $soapObjectDetails and the soapdetails execute lost me a bit. Could you maybe illitarte a bit more what you did in there. I think i get the concept, but i'm not sure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T20:05:05.697",
"Id": "30863",
"Score": "0",
"body": "There is some more issues that i am facing. For example the soap execute, returns a call_user_func_array() but the $result is still serialized and encoded, a string, but call_user_func_array expects an array. When i unserialize and decode the $result, it returns as an array and therefor can be returned with call_user_func_array. I'm still not getting why the is_callable is there, when returning the $result will return me the same value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T20:24:31.843",
"Id": "30865",
"Score": "0",
"body": "Ok i think you ment call_user_func() ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T20:27:59.170",
"Id": "30867",
"Score": "0",
"body": "Fixed the call_user_func_array thing. The unserialize and decode will happen a in a callback function becouse i'm not sure that every data cames in that way, so you can execute dufferent functions on the returned result."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T20:52:25.767",
"Id": "30869",
"Score": "0",
"body": "I'm just starting on stackexchange so not sure if im supposed to comment this much in stead of editing. But let's say you would want to change the structure of the result array, would you do that in the GetYachtSpecs?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T20:57:27.070",
"Id": "30870",
"Score": "0",
"body": "If it's specific for the yacht's specs then yes i would do it int the GetYachtSpecs() method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T21:28:56.483",
"Id": "30871",
"Score": "0",
"body": "I have added some options, $soapOptions. I wanted to add it to the SoapGet, but the problem is the soap server expects a order of $funcName, array(user,pass), array(yachtid, array( (array)options) ). So i had to place it in the GetYachtSpecs to keep that specific order"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T17:40:07.173",
"Id": "19236",
"ParentId": "19225",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "19236",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T09:39:40.137",
"Id": "19225",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"soap"
],
"Title": "OO PHP, requesting a look if good practice"
}
|
19225
|
<p>This is my work to generate an infinite <a href="http://en.wikipedia.org/wiki/Shepard_tone">Shepard Tone</a>. It is written in Clojure and works by generating repeating streams of incrementing frequencies, converting those to values on a sine wave and then adjusting the amplitude to fade in and fade our the audio.</p>
<p>Multiple concurrent streams gives the illusion of an ever increasing pitch.</p>
<ul>
<li><code>line-data</code> holds configuration values. </li>
<li><code>freq-freq-lazy-seq</code> is the infinite stream of looping frequencies</li>
<li><code>freq-to-sine</code> creates a function that converts a frequency to a value on a sine wave.</li>
<li><code>peak-volume</code> creates a function that adjusts the amplitude of a point on the wave.</li>
</ul>
<p><code>freq-to-sine</code> and <code>peak-volume</code> are not pure, they each hold internal state.
<code>peak-volume</code> doesn't have to, and could be replaced by another stream.
<code>freq-to-sine</code> perhaps does, as it's internal state is adjusted based on the argument passed in.</p>
<p>I'm not yet well versed in Clojure so I'm posting this here to gain criticism from experienced Clojure developers, particularly with regard to how close it is to the idiomatic style, whether I committed any language faux pas and comments and insights on how I perhaps could have written it differently. </p>
<p>I had to severely drop the sample rate to prevent buffer underruns on my machine so suggestions on performance improvement are welcome. I haven't investigated profiling in Clojure yet so I don't know whether the underruns are caused by something being slow, or just because it's doing a lot.</p>
<p>I'm especially keen to hear verdict on the impure <code>freq-to-sine</code> function and about any alternative pure way to achieve the same.</p>
<p>The code is available on github along with a README. Please run the code and enjoy it, Shepard Tones are pretty awesome. <a href="https://github.com/danmidwood/flox">https://github.com/danmidwood/flox</a></p>
<pre><code>(ns flox.rad
(:require clojure.algo.generic.math-functions)
(:require clojure.math.numeric-tower))
(import '(javax.sound.sampled AudioSystem DataLine$Info
SourceDataLine
AudioFormat AudioFormat$Encoding))
(def line-data
{:sample-rate (/ 44100 10)
:audio-format (AudioFormat. (/ 44100 10) 16 1 true false)
:write-size (/ 44100 10)
:12th-root (clojure.math.numeric-tower/expt 2 (/ 1 12))})
(defn- frequency
"Calculate the frequency of a note offset from a base frequency."
([offset base]
(* base (clojure.math.numeric-tower/expt (:12th-root line-data) offset))))
(defn- freq-freq-lazy-seq
"Create a lazy sequence of incrementing looping frequencies at one note per second."
([base] (freq-freq-lazy-seq base base (frequency 12 base)))
([base min max]
(lazy-seq
(cons base
(if (>= base max)
(freq-freq-lazy-seq min min max)
(freq-freq-lazy-seq (frequency (/ 1 (:sample-rate line-data)) base) min max))))))
(defn- freq-to-sine
"Create a function for values on a sine wave from frequencies.
The produced fn contains internal state to track the distance traveled along the sine so it is not suitable for concurrant use."
[]
(let [angle (atom 0.0)]
(fn
[frequency]
(let [increment (* 2 (. Math PI) (/ frequency (:sample-rate line-data)))
this-sine (clojure.algo.generic.math-functions/sin @angle)]
(do
;; The increment is divided by four to correct the pitch. Why though?
(swap! angle + (/ increment 4))
this-sine)))))
(defn- peak-volume
"Create a function that will accept a sine value and adjust it by a magnitude depending on how far through the cycle we are. This means that notes are loudest around the median and quiet at the end ranges.
The produced fn contains internal state to track how far into the cycle it is so it is not suitable for concurrant use."
[frames offset]
(let [middle (/ frames 2)
distance (atom offset)]
(fn
[sine]
(let [distance-traveled (mod @distance frames)
distance-from-middle (/ (clojure.math.numeric-tower/abs (- middle distance-traveled)) frames)
volume (- 1 (* 2 distance-from-middle))]
(do
(swap! distance inc)
(* sine (clojure.math.numeric-tower/expt volume 3)))))))
(defn- byte-my-sine
"Transforms a floating point sine value (-1..1) into a signed byte (-128..127)"
([sine]
(byte (* (. Byte MAX_VALUE) sine))))
(defn- create-line
[]
(let [line (. AudioSystem getSourceDataLine (:audio-format line-data))]
(doto line
(.open (:audio-format line-data))
(.start))))
(defn- merge-values
[& values]
(/ (apply + values) (count values)))
(defn- write-audio
[line data]
(.write ^SourceDataLine line (byte-array data) 0 (:write-size line-data)))
(defn- emit-audio
[line data]
(do
(write-audio line (take (:write-size line-data) data)))
(recur line (drop (:write-size line-data) data)))
(defn- freqs-to-sines
"Accepts a list of n lists of frequencies and returns a list of n lists of sine values"
[& freqs]
(apply map
#(map (freq-to-sine) %)
freqs))
(defn start
[base height threads]
(emit-audio
(create-line)
(map byte-my-sine
(apply map merge-values
(map
#(map
(peak-volume
(* height (:sample-rate line-data))
(* (/ 1 threads) % (* height (:sample-rate line-data))))
(map
(freq-to-sine)
(freq-freq-lazy-seq
(frequency (* (/ 1 threads) % height) base)
base
(frequency height base))))
(range threads))))))
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T13:01:42.777",
"Id": "19229",
"Score": "18",
"Tags": [
"clojure",
"audio"
],
"Title": "Shepard Tone stream generation in Clojure"
}
|
19229
|
<p>I have written a small JavaScript class that makes use of <code>setInterval</code> to create a delayed loop for iterating an array. I've used this technique in the past but never utilised a library to do so (and as a result it produced quite messy spaghetti code), and so I wrote up this:</p>
<pre><code>var DelayedLoop = function() { };
DelayedLoop.forEach = function(collection, delay, callback, completedCallback) {
var index = 0;
var timerObject;
var executor = function() {
// Stop the delayed loop.
clearInterval(timerObject);
// Executes the callback, and gets the returned value to indicate what the next delay will be.
var newInterval = callback(collection[index++]);
// If they returned false, quit looping.
if(typeof(newInterval) == "boolean" && newInterval == false) {
return;
}
// If nothing / non-number is provided, re-use initial delay.
if(typeof(newInterval) != "number") {
newInterval = delay;
} else if(newInterval < 0) { // If a negative number is returned, quit looping.
return;
}
// If there are more elements to iterate, re-set delayed loop. Otherwise, call the "completed" callback.
if(index < collection.length) {
timerObject = setInterval(executor, newInterval);
} else {
completedCallback();
}
};
// Initial loop setup.
timerObject = setInterval(function() {
executor();
}, delay);
};
</code></pre>
<p>An example usage can be seen here:</p>
<pre><code>$(document).ready(function() {
var myArray = [ "aaa", "bbb", "ccc" ];
DelayedLoop.forEach(myArray, 1000, function(arrayElement) {
console.log(arrayElement);
}, function() {
console.log("Finished all!");
});
});
</code></pre>
<p>How does it look? Are there any browser compatibility issues? Is there any potential flaw I'm not seeing?</p>
|
[] |
[
{
"body": "<p>My experience with Javascript isn't quite as developed as it is for other languages, but here's what I have to say about the code.</p>\n\n<p>Why use <code>setInterval()</code> and <code>clearInterval()</code>? You'd use those methods if you wanted to call a function repeatedly. Since all you do is set it and immediately clear it, there's no point in really using it. Better to use <code>setTimeout()</code> instead.</p>\n\n<p>I'd consider rearranging your parameters so the <code>delay</code> was last. That way you can make the delay optional, possibly provide a default delay instead. Also consider making <code>complatedCallback</code> optional too. It could be possible that you don't need the callback so you're forcing yourself to have to provide one.</p>\n\n<p>I don't think you'd want to put a delay of the first invocation on the first item. So probably should remove that initial timeout and just call the <code>executor()</code> directly.</p>\n\n<pre><code>DelayedLoop.forEach = function(collection, callback, completedCallback, delay) {\n var index = 0;\n\n var executor = function() {\n // Executes the callback, and gets the returned value to indicate what the next delay will be.\n var newInterval = callback(collection[index++]);\n\n // If they returned false, quit looping.\n if (typeof(newInterval) == \"boolean\" && newInterval == false) {\n return;\n }\n\n // If nothing / non-number is provided, re-use initial delay.\n if (typeof(newInterval) != \"number\") {\n newInterval = delay;\n } else if (newInterval < 0) { // If a negative number is returned, quit looping.\n return;\n }\n\n // If there are more elements to iterate, re-set delayed loop. Otherwise, call the \"completed\" callback.\n if (index < collection.length) {\n setTimeout(executor, newInterval);\n } else if (typeof(completedCallback) == \"function\") {\n completedCallback();\n }\n };\n\n // Initial loop setup.\n executor();\n};\n</code></pre>\n\n<p>Otherwise I don't see anything glaringly wrong with the code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T18:55:17.793",
"Id": "19237",
"ParentId": "19235",
"Score": "3"
}
},
{
"body": "<p>Jeff Mercado touched on many important things, so here are some other things to consider.</p>\n\n<p>1: There's no need to define <code>DelayedLoop</code> as a function; you're not using it as one. Instead you can just do a simple object literal:</p>\n\n<pre><code>var DelayedLoop = { ... };\n</code></pre>\n\n<p>or simply have a function called <code>delayedForEach</code>. If <code>forEach</code>is the only function in <code>DelayedLoop</code>, there's not much need for the <code>DelayedLoop</code> namespace.</p>\n\n<p>2: You could consider copying the <code>collection</code> array right away. Otherwise the array your <code>forEach</code> function is using can be changed elsewhere, outside the loop. This shouldn't cause any errors with your code, but could lead to confusion.</p>\n\n<p>3: Maybe do some type-checking and throw a TypeError if, for instance, <code>collection</code> isn't an array instance, or <code>callback</code> isn't a function.</p>\n\n<p>4: No need to both check <code>newInterval</code>'s type <em>and</em> value when checking if it's false; just use a strict comparison operator: <code>newInterval === false</code>. I'd also encourage you to use <em>only</em> false as your \"stop looping\" value; if a callback returns a negative number, just ignore it. This is more in line with how e.g. event handlers or jQuery <code>each</code> callbacks work; they can return anything they want, but boolean false - and <em>only</em> boolean false - is treated as \"stop\".</p>\n\n<p>5: No need to wrap the timed call to <code>executor</code> in a function; just write <code>executor</code> (as Jeff Mercado shows). I'd probably name it \"iterator\" as that's a bit more descriptive.</p>\n\n<p>6: Minor syntax thing: <code>typeof</code> is an operator - not a function - so there's no need to write <code>typeof(variable)</code>. In fact the more common way is to write <code>typeof variable</code></p>\n\n<p>7: Another minor syntax thing: You don't have to declare the <code>executor</code> as an expression. A straight-up <code>function executor() { ... }</code> syntax would work just as well. Of course, since both work it's mostly a matter of personal preference.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T22:32:21.767",
"Id": "30776",
"Score": "0",
"body": "I was also considering making the same change with using the strict comparison but since the return value could have been of differing types, I like seeing specific wording that indicates the type in all the different cases. If it was expected to be of a single type, then yes definitely."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T01:41:19.230",
"Id": "30779",
"Score": "0",
"body": "@JeffMercado The code's identical, though. The wording is just as specific, since the strict comparison literally means \"it must be a boolean and it must be false\". To be honest, I find the original code less clear, because it's a two-step comparison rather than just saying \"if it's _exactly_ false, then...\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T18:52:36.927",
"Id": "30854",
"Score": "0",
"body": "Also might be useful pass current `index` into callback: `index++; var newInterval = callback(collection[index], index);`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T21:12:56.207",
"Id": "19239",
"ParentId": "19235",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "19239",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T17:38:52.520",
"Id": "19235",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Review my \"delayed for-loop\" in JavaScript"
}
|
19235
|
<p>This is function, that works correctly, but it seems to be too ugly.
<code>panel</code> argument is never used for anything but pushing into <code>refreshGamePanel</code>,
and it seems to be too much case statements. How can I cleanup this?</p>
<pre><code>runGameLoop :: Game -> Panel -> Curses GameResult
runGameLoop game panel
= if victory game then return Victory else
refreshGamePanel game panel >> render >> getPanelWindow panel >>=
flip getEvent (Just 1)
>>=
\ event' ->
case event' of
Nothing -> runGameLoop game panel
Just event -> case event of
EventSpecialKey (KeyFunction 2) -> return Restart
EventSpecialKey (KeyFunction 10) -> return Quit
EventSpecialKey key' -> case keyToDirection key' of
Nothing -> runGameLoop game panel
Just dir -> runGameLoop (makeMove game dir) panel
_ -> runGameLoop game panel
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T08:31:04.377",
"Id": "30797",
"Score": "0",
"body": "Did you try to use `do` notation? Further, look for more idiomatic ways to deal with `Maybe` (how about `fromMaybe` ?)."
}
] |
[
{
"body": "<p>There is a nice language extension in GHC called <a href=\"http://www.haskell.org/ghc/docs/7.2.1/html/users_guide/syntax-extns.html#view-patterns\" rel=\"nofollow\">ViewPatterns</a>. Together with <a href=\"http://www.reddit.com/r/haskell/comments/wp70x/lambdacase_and_multiway_if_added_to_ghc_head_for/\" rel=\"nofollow\">LambdaCase</a> that fature allows you to shorten your code, I think. And <code>do</code> notation will be much more readable for imperative part.</p>\n\n<pre><code>runGameLoop game panel | victory game = return Victory\n | otherwise = continue\n where\n anyEvent = gatPanelWindow panel >>= flip getEvent (Just 1)\n isRestart = (EventSpecialKey (KeyFunction 2) ==)\n isQuit = (EventSpecialKey (KeyFunction 10) ==)\n continue = do\n refreshGamePanel game panel\n render\n anyEvent >>= \\case\n Just (isRestart -> True) -> return Restart\n Just (isQuit -> True) -> return Quit\n Just (EventSpecialKey (keyToDirection -> Just dir)) ->\n runGameLoop (makeMove game dir) panel\n _ -> runGameLoop game panel\n</code></pre>\n\n<p>Another variant is to consider using of <code>Monad Maybe</code> instance</p>\n\n<pre><code>runGameLoop game panel = nextStep where\n anyEvent = gatPanelWindow panel >>= flip getEvent (Just 1)\n nextStep = if victory game then return Victory else do\n refreshGamePanel game panel\n render\n liftM react anyEvent >>= \\case\n Just continuation -> continuation\n Nothing -> runGameLoop game panel\n react event' = do\n event' >>= \\case\n EventSpecialKey (KeyFunction 2) -> return (return Restart)\n EventSpecialKey (KeyFunction 10) -> return (return Quit)\n EventSpecialKey key -> do\n dir <- keyToDirection key\n return (runGameLoop (makeMove game dir) panel)\n _ -> Nothing\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-12T20:40:45.153",
"Id": "19554",
"ParentId": "19238",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-12-02T19:13:29.543",
"Id": "19238",
"Score": "1",
"Tags": [
"haskell",
"event-handling"
],
"Title": "Haskell game loop with keyboard handler"
}
|
19238
|
<p>As per suggestion on SO, I am posting my code here to be reviewed. It was said I should not be saving and reading from disk so many times when a user selects and deselects a cell in my tableView. </p>
<pre><code>@property (nonatomic, strong) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSArray *list;
- (void)viewDidLoad
{
[super viewDidLoad];
self.list = [[NSArray alloc] initWithObjects:@"Alabama", @"Alaska", @"Arizona",
@"Arkansas", @"California", @"Colorado", @"Connecticut", @"Delaware", @"District of Columbia",
@"Florida", @"Georgia", @"Hawaii", @"Idaho", @"Illinois", @"Indiana", @"Iowa", @"Kansas",
@"Kentucky", @"Louisiana", @"Maine", @"Maryland", @"Massachusetts", @"Michigan", @"Minnesota",
@"Mississippi", @"Missouri", @"Montana", @"Nebraska", @"Nevada", @"New Hampshire",
@"New Jersey", @"New Mexico", @"New York", @"North Carolina", @"North Dakota", @"Ohio", @"Oklahoma",
@"Oregon", @"Pennsylvania", @"Rhode Island", @"South Carolina", @"South Dakota",
@"Tennessee", @"Texas", @"Utah", @"Vermont", @"Virginia", @"Washington", @"West Virginia",
@"Wisconsin", @"Wyoming", nil];
}
- (NSString *)SettingsPlist
{
NSString *paths = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *PlistPath = [paths stringByAppendingPathComponent:@"Settings.plist"];
return PlistPath;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return [[self list] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *contentForThisRow = [[self list] objectAtIndex:[indexPath row]];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
}
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:[self SettingsPlist]];
NSString *row = [NSString stringWithFormat:@"%d",indexPath.row];
if([[dict objectForKey:row]isEqualToString:@"0"])
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
else
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
[[cell textLabel] setText:contentForThisRow];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSMutableDictionary *plist = [NSMutableDictionary dictionaryWithContentsOfFile:[self SettingsPlist]];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString *row = [NSString stringWithFormat:@"%d",indexPath.row];
if(cell.accessoryType == UITableViewCellAccessoryNone)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
NSString *on = @"1";
[plist setObject:on forKey:row];
[plist writeToFile:[self SettingsPlist] atomically:YES];
}
else if(cell.accessoryType == UITableViewCellAccessoryCheckmark)
{
cell.accessoryType = UITableViewCellAccessoryNone;
NSString *off = @"0";
[plist setObject:off forKey:row];
[plist writeToFile:[self SettingsPlist] atomically:YES];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
</code></pre>
|
[] |
[
{
"body": "<p>you should read the settings plist once in <code>-viewDidLoad:</code> and save the contents as a dictionary to a property.</p>\n\n<p>As you are doing, it is a huge performance hit as the disk will be accessed every time a cell appears on screen during scrolling. </p>\n\n<p>In <code>-tableView:cellForRowAtIndexPath:</code> and <code>-tableView:didSelectRowAtIndexPath:</code> you then should only work on that dictionary.</p>\n\n<p>Further more you could introduce a singleton-like shared object, that holds the settings and can be accessed in any class.</p>\n\n<p>see my <a href=\"https://github.com/vikingosegundo/checkmark\" rel=\"nofollow\">example code</a> for how to do multiple selection and keeping track of the selected contents.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T03:51:27.140",
"Id": "30784",
"Score": "0",
"body": "Save in the `-viewWillDisappear:` method?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T03:52:39.230",
"Id": "30785",
"Score": "0",
"body": "yeah, that would be a good solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T03:53:42.990",
"Id": "30786",
"Score": "0",
"body": "So when the user selects and deselects a cell, do I need to keep track of that row with a boolean, and then write the boolean values to the plist?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T03:55:18.563",
"Id": "30787",
"Score": "0",
"body": "you can change the contents in the dictionary immediately. to populate the cell correctly with the checkmark, see http://stackoverflow.com/a/13676588/106435"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T03:59:29.733",
"Id": "30788",
"Score": "0",
"body": "So you're saying it's safe to write to disk when the user selects and/or deselects cells?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T04:03:23.513",
"Id": "30789",
"Score": "0",
"body": "dont write to disk. write to the dictionary. and write that back to disk when leaving the view."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T04:05:12.047",
"Id": "30790",
"Score": "0",
"body": "see https://github.com/vikingosegundo/checkmark . I altered for state selection . Though it doest have code to write to disk."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T04:42:20.113",
"Id": "30793",
"Score": "0",
"body": "I got my objects to write back to the plist successfully now."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T03:50:06.437",
"Id": "19245",
"ParentId": "19244",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "19245",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T03:45:27.367",
"Id": "19244",
"Score": "1",
"Tags": [
"objective-c",
"ios"
],
"Title": "iOS UITableView; saving cell checkmarks to disk"
}
|
19244
|
<p>According to this two questions: <a href="https://codereview.stackexchange.com/questions/18160/jquery-different-way-to-write-multiple-click-functions">[1]</a> and <a href="https://codereview.stackexchange.com/questions/17759/jquery-javascript-refactoring-multiple-on-events">[2]</a></p>
<p>I need a way to combine these two methods of handling the event attachment in jQuery.</p>
<pre><code>$('selector').on({
mouseenter: function() {},
mouseleave: function() {},
mousedown: function() {},
mouseup: function() {}
});
</code></pre>
<p>I prefer the previous method but need something like the following to work with "live"-events. (The problem is, that the next pattern kills the clarity if the code will be a bit larger and even if there're comments between the handlers, it breaks the code.):</p>
<pre><code>$(document).on('mouseenter', 'selector1', function(){})
.on('mouseleave', 'selector2', function(){})
// this comment breaks the chain
.on('mousedown', 'selector3', function(){})
.on('mouseup', 'selector4', function(){});
</code></pre>
<p>However, since there's no real world example to do it like this?:</p>
<pre><code>$(document).on({
mouseenter: 'selector1': function() {},
mouseleave: 'selector2': function() {},
mousedown: 'selector3': function() {},
mouseup: 'selector4': function() {}
});
</code></pre>
<p>...I've ended up with this simple <code>on</code>-wrapper function: <a href="https://gist.github.com/4191657" rel="nofollow noreferrer">https://gist.github.com/4191657</a></p>
<pre><code>;(function($) {
$.fn.act = function() {
var args = arguments;
return this.each(function() {
for (var i = args.length; i--;) {
$(this).on(args[i][0], args[i][1], args[i][2]);
}
});
};
})(jQuery);
</code></pre>
<p>Now the usage is quite simpler:</p>
<pre><code>$(document).act(
['mouseenter', 'selector1', function() {}],
['mouseleave', 'selector2', function() {}],
['mousedown', 'selector3', function() {}],
['mouseup', 'selector4', function() {}]
);
</code></pre>
<p>As @Joonas <a href="https://stackoverflow.com/questions/13604582/multiple-jquery-events-on-one-element-with-different-functions-and-target-select/13604628#comment18778266_13604628">said</a> that this funtion improves anything. I had the need to came up here with a new question.</p>
<p>So my question, have you any thoughts, suggestions or improvements to <a href="https://gist.github.com/4191657" rel="nofollow noreferrer">this</a> function? Or is there maybe a better solution to handle this problem?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T12:07:33.280",
"Id": "30801",
"Score": "1",
"body": "I don't agree that `$(document).on().on()` is any less clear than your last example. Also, comments between the handlers don't break the code, as you can see here: http://jsfiddle.net/xXQnC/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T12:38:38.613",
"Id": "30802",
"Score": "0",
"body": "I'm inclined to agree with Joonas and @AlexeyLebedev. The 2 questions you link to were about different handlers for different selectors, but the event type was always \"click\". Like a math equation, when one part of the equation is constant, you can make some shortcuts. But if you want to have different handlers for different selectors _and_ different event types, well, that's exactly what jQuery already gives you with `.on()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T14:08:39.673",
"Id": "30816",
"Score": "0",
"body": "@AlexeyLebedev Nice! I think there was another problem then... In view of that fact were my questions probably unnecessary :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T15:43:28.937",
"Id": "30892",
"Score": "0",
"body": "@yckart the comment *might* be breaking the chain because you're not `\"using strict\";` and the browser assumes a semicolon at the line before the comment."
}
] |
[
{
"body": "<ul>\n<li><p>Try placing the comments inside the callback instead to avoid breakage. I also do this on <code>if-else</code> statements as well so comments remain uniform.</p></li>\n<li><p>Event maps are better when appending multiple event handlers to the same selector.</p></li>\n<li><p>If you want a bit readability, move the handlers away from the attaching procedure. That way, they look clean</p></li>\n</ul>\n\n<p>So here it is in the end:</p>\n\n<pre><code>//handlers\n\nfunction selector1handler(){\n //comment here\n};\n\nfunction selector2handler(){\n //comment here\n};\n\nfunction selector3click(){\n //comment here\n};\n\nfunction selector3mouseover(){\n //comment here\n};\n\n//add handlers\n\n$(document)\n .on('mouseenter', 'selector1', selector1handler)\n .on({\n click : selector3click,\n mouseover : selector3mouseover\n },'selector3')\n .on('mouseleave', 'selector2', selector1handler)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T14:10:39.077",
"Id": "30817",
"Score": "0",
"body": "Yeah, that's already what i did ;) However see my [comment](http://codereview.stackexchange.com/questions/19250/multiple-jquery-events-on-one-element-with-different-functions-and-target-select/19251#comment30816_19250) to @AlexeyLebedev"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T12:33:37.097",
"Id": "19251",
"ParentId": "19250",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T11:13:09.643",
"Id": "19250",
"Score": "2",
"Tags": [
"jquery",
"array"
],
"Title": "Multiple jQuery events on one element with different functions and target selectors"
}
|
19250
|
<p>As the question reads, I am building a database with 3 tables. Now these tables are going to be used to store names.</p>
<ul>
<li>Table 1 will store First Names </li>
<li>Table 2 will store Last Names </li>
<li>Table 3 will be a one to one table linking the First names to the Last names</li>
</ul>
<p>Now all this data will be coming from a text file in the format of:</p>
<blockquote>
<p>Firstname MI Lastname</p>
</blockquote>
<p>I estimate that their will be over 100 million records. I also don't want to do a insert for every name it will be an update record on duplicate Key. So what is the most optimal way to enter this into my database. By the way it is a Innodb so the whole table gets locked so I can't do multiple insert updates at a time</p>
<p>Now this whole process will be done via C# using mysql connection and I have:</p>
<pre><code>sqlRequest += "START TRANSACTION ;" +
"UPDATE firstName SET LastUpdated = CURRENT_TIMESTAMP WHERE first= '" + countSplit[0] +"' ;" +
"INSERT INTO firstName(first, LastUpdated) SELECT '" + countSplit[0] + "' AS first, CURRENT_TIMESTAMP AS LastUpdated FROM dual WHERE NOT EXISTS ( SELECT * FROM firstName d WHERE d.first= '" + countSplit[0] + "') ;" +
"COMMIT ;";
sqlRequest += "START TRANSACTION ;" +
"UPDATE lastName SET LastUpdated = CURRENT_TIMESTAMP WHERE last = '" + countSplit[2] + "' ;" +
"INSERT INTO lastName (last, LastUpdated) SELECT '" + countSplit[2] + "' AS last, CURRENT_TIMESTAMP AS LastUpdated FROM dual WHERE NOT EXISTS ( SELECT * FROM lastName d WHERE d.last = '" + countSplit[2] + "') ;" +
"COMMIT ;";
sqlRequest += "START TRANSACTION ;" +
"INSERT INTO first_to_last " +
"(firstid,lastid,LastUpdated) VALUES "+
"((SELECT firstid FROM firstName WHERE first='" + countSplit[0] + "')," +
"(SELECT lastid FROM lastName WHERE last='" + countSplit[2] + "' )," +
"CURRENT_TIMESTAMP)"+
"ON DUPLICATE KEY UPDATE LastUpdated = CURRENT_TIMESTAMP;"+
"COMMIT ;";
</code></pre>
<p>So do you think that this is the best way? Or do you think there is something better?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T04:24:37.300",
"Id": "30806",
"Score": "1",
"body": "Any reason why you're implementing the database like this where all you need is one table with a Primary Key, First Name, Last Name columns?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T05:21:32.443",
"Id": "30807",
"Score": "0",
"body": "Building a application that requires this layout"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T05:29:09.153",
"Id": "30808",
"Score": "0",
"body": "Can you be more specific on your application? The database design shouldn't be affected by the application design as you can display the data in any way you like. This sounds like a relational database homework assignment to show the use of foreign keys."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T06:11:21.347",
"Id": "30809",
"Score": "0",
"body": "Well to be honest I am working on this to be plugged into a already existing system. This is only a small part, my employer suggested I ask here but not to reveal anything relating to the project. I have it working but it takes a long time to build. I am looking for suggestions on speed performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T06:35:20.257",
"Id": "30810",
"Score": "0",
"body": "Performance could be related to how the tables are defined, and you can expect a hit on every query since the system will require to select on three tables, possibly use Joins for sane results, etc. With this implementation. As for the queries themselves, you are basically scanning the entire table with every insert with your nested select. It's also an expensive select because you're not using an index. (At least that's what I figure from the partial information."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-09T10:07:58.837",
"Id": "175984",
"Score": "0",
"body": "Is there any concern for the fact that there will many people with the same first and last names -- or are we just looking at a way of looking at name popularity or other such comparisons?"
}
] |
[
{
"body": "<p>From the looks of this, you should be using a Stored Procedure, not entirely familiar with how that works in MySQL but I imagine it is similar to SQL Server Stored Procedures.</p>\n\n<p>Using a Stored Procedure would be the easiest way to do this.</p>\n\n<p>You create the stored procedure with the parameters that you need, then in the C# you call the stored procedure giving it the parameters in the specified manner. I haven't tried to do with with MySQL but I imagine it is much the same as with SQL Server ( I know I said that once already ) </p>\n\n<p>You are trying to do the Database's work with C#, keep them separate. </p>\n\n<p>Cleanse the input, create a command for the Stored Procedure, give it the parameters, execute the command.</p>\n\n<p>This way you can loop through a list of names in C# sending the names to the stored procedure, or create the stored procedure to accept a list of names.</p>\n\n<p>Creating the Stored Procedure will also allow you to use it other places in the C# application, and if you need to change the Query, it is easily maintainable, you change the query and don't have to recompile the application as long as the input stays the same.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T18:22:12.130",
"Id": "35443",
"ParentId": "19253",
"Score": "3"
}
},
{
"body": "<p>You don't show it here, but I guarantee you're splitting on whitespace. Which is wrong. Condsider the name <code>Jane MaryAnne Vander Werf</code>. You're going to cut off the second half of this person's last name. This is notoriously hard to do in reality. Names don't just fall into our sense of what \"good data\" looks like. Please see <a href=\"http://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/\" rel=\"nofollow\">Falsehoods Programmers Believe About Names</a>.</p>\n\n<p>What you really need to do is make sure your input makes sense. If it doesn't, you're eventually going to have problems. Your input needs to be in the form of fixed width columns so that you can do this manipulation based on the position of the character.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-04T14:04:58.670",
"Id": "168284",
"Score": "1",
"body": "Relevant: [\"Falsehoods Programmers Believe About Names\"](http://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-04T14:02:19.823",
"Id": "92656",
"ParentId": "19253",
"Score": "2"
}
},
{
"body": "<p>A few thoughts:</p>\n\n<ol>\n<li><p>Pre-process the file to remove duplicates. Assuming the data is formatted appropriately you could sort the file and then walk through it to pull out the first first/last pairing as it appears the middle initial is not considered.</p></li>\n<li><p>During pre-processing regularize the output into a file that can be loaded into a working table using LOAD DATA INFILE. Let the database get the data inside as fast as it can.</p></li>\n<li><p>With the data loaded into a working table create a procedure to split the data into the horrible design apparently necessary without the need to send records in using your programming language of choice.</p></li>\n<li><p>Truncate or drop the working table when you don't need it anymore.</p></li>\n</ol>\n\n<p>And, a short anecdote on finding good solutions. Assume someone else has demonstrated a system that is ten times faster than yours. Then, start asking yourself how in the world they were able to do so. This can often push you past your initial impressions -- especially if you have a competitive nature.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-09T10:17:06.177",
"Id": "96337",
"ParentId": "19253",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T04:18:34.887",
"Id": "19253",
"Score": "2",
"Tags": [
"c#",
"sql",
"mysql"
],
"Title": "Building database from file"
}
|
19253
|
<p>I was searching for a free implementation of a "bounded" priority queue. The algorithm has been discussed many times on <a href="https://stackoverflow.com/questions/5329312/free-implementation-of-bounded-priority-queue-in-c">Stack Overflow</a>. I took a shot and wrote a STL-like bounded_priority_queue class (which implements the most efficient algorithm using a priority_queue with a "flipped" compare as the underlying container).</p>
<p>I do have some questions:</p>
<ol>
<li><p>Any comments on my interface? I couldn't think of anything more fine-grained than <code>pop_all()</code>. I provided a constructor that takes in an iterator range, since <code>std::partial_sort</code> can only be called using random access iterators.</p></li>
<li><p>Any comments on my implementation? I tried to mimic the style of the STL that comes with MSVC. (It's not my natural style.)</p></li>
<li><p>Is <code>flipped_compare</code> part of the STL? It feels like it should be there somewhere.</p></li>
<li><p>Is there any way to more succinctly implement the dispatch for bidir & random_access iterators? I couldn't come up with any way without explicit defining partial specializations of <code>_pop_all()</code> for both iterator categories.</p></li>
<li><p>Any reason why <code>std::priority_queue</code> defines the <code>_Container</code> template parameter before the <code>_Pr</code> template parameter? As a user, I would probably want specialize <code>_Pr</code> more frequently than <code>_Container</code>. (I kept the same order, but I don't like it.)</p></li>
</ol>
<p>Here's the code (feel free to copy):</p>
<pre><code>#include <queue>
#include <iterator>
template < typename _Ty, typename _Pr = std::less<_Ty> >
struct flipped_compare {
flipped_compare() : comp() {}
explicit flipped_compare(const _Pr& _Pred) : comp(_Pred) {}
bool operator()(const _Ty& l, const _Ty& r) { return comp(r,l); }
_Pr comp;
};
template < typename _Ty, typename _Container = std::vector<_Ty>,
typename _Pr = std::less<_Ty> >
class bounded_priority_queue
{
public:
typedef _Ty value_type;
typedef typename _Container::size_type size_type;
explicit bounded_priority_queue(size_type _Max_size)
: max_sz(_Max_size) {}
bounded_priority_queue(size_type _Max_size, const _Pr& _Pred)
: c( flipped_compare<_Ty,_Pr>(_Pred) ), max_sz(_Max_size) {}
template <typename _InIt>
bounded_priority_queue(size_type _Max_size, _InIt _First, _InIt _Last)
: max_sz(_Max_size)
{
for (; _First != _Last; ++_First) push( *_First );
}
template <typename _InIt>
bounded_priority_queue(size_type _Max_size, _InIt _First,
_InIt _Last, _Pr _Pred)
: c( flipped_compare<_Ty,_Pr>(_Pred) ), max_sz(_Max_size)
{
for (; _First != _Last; ++_First) push( *_First );
}
size_type max_size() const { return max_sz; }
size_type size() const { return c.size(); }
void push(const value_type& _Val)
{
if ( size() < max_size() ) c.push(_Val);
else if ( comp(c.top(), _Val) ) { c.pop(); c.push(_Val); }
}
template <typename _OutIt>
void pop_all(_OutIt _Dest)
{
_pop_all( _Dest,
typename std::iterator_traits<_OutIt>::iterator_category() );
}
private:
template <typename _OutIt, typename _Tag>
void _pop_all(_OutIt _Dest, _Tag)
{
std::vector<_Ty> tmp( size() );
_pop_all2( tmp.begin() );
std::copy( tmp.begin(), tmp.end(), _Dest );
}
template <typename _OutIt>
void _pop_all(_OutIt _Dest, std::bidirectional_iterator_tag)
{
_pop_all2( _Dest );
}
template <typename _OutIt>
void _pop_all(_OutIt _Dest, std::random_access_iterator_tag)
{
_pop_all2( _Dest );
}
template <typename _BidIt>
void _pop_all2(_BidIt _Dest)
{
_BidIt _First = _Dest;
while ( !c.empty() ) {
*_Dest++ = c.top();
c.pop();
}
std::reverse( _First, _Dest );
}
std::priority_queue< _Ty, _Container, flipped_compare<_Ty, _Pr> > c;
_Pr comp;
size_type max_sz;
};
#include <list>
#include <iostream>
int main (int argc, char* argv[])
{
int K = 20, N = 500;
std::list<int> l;
std::generate_n( std::back_inserter(l), N, &std::rand );
bounded_priority_queue<int> q( K, l.begin(), l.end() );
q.pop_all( std::ostream_iterator<int>( std::cout, " " ) );
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T16:08:36.960",
"Id": "30812",
"Score": "0",
"body": "flipped_compare is actually called `std::more`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T16:30:35.030",
"Id": "30813",
"Score": "0",
"body": "@BarnabasSzabolcs: What is `std::more`? Do you have a reference because I can't find it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T18:32:02.673",
"Id": "30814",
"Score": "1",
"body": "@Blastfurnace: I think he is talking about [std::greater](http://en.cppreference.com/w/cpp/utility/functional/greater)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T03:48:16.953",
"Id": "30815",
"Score": "0",
"body": "oops, that's embarrassing. I was so sure because I happened to use it before, and I was so wrong telling std::more. :( It is std::greater. Sorry"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-16T09:51:49.553",
"Id": "170572",
"Score": "0",
"body": "why do you need flipped_compare, shouldn't it be just std::less for a priority queue , which has the maximum element as top() ? and\nis pop(),push() if the element to insert is smaller < top(), the most efficient way?, can that not be combined somehow?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-16T09:57:23.767",
"Id": "170573",
"Score": "0",
"body": "Why not add -> begin() and end() for the container, to be able to iterate over"
}
] |
[
{
"body": "<p>First of all: names starting with an underscore followed by a capital letter are reserved for the <strong>implementation</strong>. You <strong>may not use them</strong>. Ever.</p>\n\n<p>You might also want to specify whether you're interested in all advice, or only that relevant to C++03; I don't see much C++11 could do here, but it's generally an important distinction.</p>\n\n<p>Now, comments:</p>\n\n<ul>\n<li>Why not have <code>flipped_compare::operator()</code> be <code>const</code>? Not very significant, but looks like it'd work.</li>\n<li>I suggest using <code>std::less<typename _Container::value_type></code> as your default <code>_Pr</code>, as that's what <code>std::priority_queue</code> does.</li>\n<li>The constructors should probably be implemented in terms of <code>std::for_each</code> or somesuch.</li>\n<li>Your indentation is inconsistent.</li>\n<li>Swap is a fairly important omission, in my opinion.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T16:13:31.137",
"Id": "19262",
"ParentId": "19254",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "19262",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-01T15:56:23.460",
"Id": "19254",
"Score": "2",
"Tags": [
"c++",
"stl"
],
"Title": "Free implementation of “bounded priority queue” in C++"
}
|
19254
|
<p>I'm working on a site that has to do with movies. I am consuming the Rotten Tomatoes API to get my movie information and using EF5 with a code first approach to get that into the database. I'm using MVC4. I am struggling to come up with a design that makes sense and accomplishes what I need to in an efficient manner while still following the Single Responsibility Principle.</p>
<p><strong>A quick summary:</strong></p>
<p>Users can have a collection of movies, so every movie that is returned to the client needs to have information like whether the requesting user has that movie in their collection, the user rating, etc. When a user adds a movie to their collection in the database I also insert that movie (into the database). So I'm only inserting movies that users own, as opposed to every movie returned from Rotten Tomatoes. </p>
<p>I think it makes sense to walk you through the action of a user searching for a movie to best show you my problems/questions...</p>
<p>A user searches for a movie and makes a request to my controller. I've created a wrapper class for the Rotten Tomatoes API, so the controller instantiates my <code>RottenTomatoes</code> object then calls the <code>FindMovies()</code> method.</p>
<p><strong>Controller</strong></p>
<pre><code>[HttpGet]
public JsonResult GetMovieSearchResults(string name) {
if(!string.IsNullOrEmpty(name)) {
var tomatoes = new RottenTomatoes(ConfigurationManager.AppSettings["RottenTomatoesApiKey"]);
return Json(tomatoes.FindMovies(name), JsonRequestBehavior.AllowGet);
}
return Json(new { success = false }, JsonRequestBehavior.AllowGet);
}
</code></pre>
<p>The <code>FindMovies()</code> method calls <code>GetResponse()</code> which makes a call to the API endpoint, deserializes the returned json into <code>MoviesDataContract</code> and then returns that <code>DataContract</code> back to <code>FindMovies()</code>.</p>
<p><strong>RottenTomatoes wrapper class</strong></p>
<pre><code>public class RottenTomatoes {
private const string MOVIES_SEARCH_URL = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey={0}&q={1}&page_limit={2}";
private Guid _userId;
private MovieContext _db;
public string ApiKey { get; set; }
public RottenTomatoes(string apiKey, Guid userId, MovieContext movieContext) {
ApiKey = apiKey;
_userId = userId;
_db = movieContext;
}
public IEnumerable<Movie> FindMovies(string name, int pageLimit = 20) {
string url = string.Format(MOVIES_SEARCH_URL, ApiKey, name, pageLimit);
var movies = GetResponse(url).Movies.Select(m => (Movie)m);
// populate the UserMovies property for each movie
var userMovies = _db.UserMovies.Where(u => u.UserId == _userId);
foreach(var movie in movies) {
var userMovie = userMovies.FirstOrDefault(u => u.Movie.Id == movie.Id);
if(userMovie != null) {
movie.UserMovies.Add(new UserMovie {
IsWatched = userMovie.IsWatched,
Rating = userMovie.Rating
});
}
}
return movies;
}
private MoviesDataContract GetResponse(string url) {
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Http.Get;
request.ContentType = "application/json; charset=utf-8";
try {
using (var response = (HttpWebResponse)request.GetResponse()) {
var serializer = new DataContractJsonSerializer(typeof(MoviesDataContract));
return (MoviesDataContract)serializer.ReadObject(response.GetResponseStream());
}
} catch (Exception e) {
throw new Exception(e.Message);
}
}
}
</code></pre>
<p>I think up to this point, the design is smooth. I am struggling with it going forward.</p>
<p><code>FindMovies()</code> receives back <code>MoviesDataContract</code> from <code>GetResponse()</code> and has the responsibilty of converting the <code>IEnumerable<></code> of movies in <code>MoviesDataContract</code> to an <code>IEnumerable<></code> of my EF model <code>Movie</code>. <em>See questions 1 & 2</em> </p>
<p>I created an explicit conversion operator in my EF model <code>Movie</code> class that will except a movie from my <code>DataContract</code> and convert it to the EF model. Here's the EF Model <code>Movie</code> class.</p>
<pre><code>public class Movie {
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
[MaxLength(100)]
public string Title { get; set; }
public int? Year { get; set; }
public virtual ICollection<UserMovie> UserMovies { get; set; }
public Movie() {
UserMovies = new HashSet<UserMovie>();
}
public static explicit operator Movie(MoviesDataContract.Movie rawMovie) {
var movie = new Movie {
Id = rawMovie.Id,
Title = rawMovie.Title,
Year = rawMovie.Year
};
return movie;
}
}
public class UserMovie {
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int? Rating { get; set; }
public bool IsWatched { get; set; }
public Guid UserId { get; set; }
[ScriptIgnore]
public virtual Movie Movie { get; set; }
}
</code></pre>
<p>Once the movie has been converted to my EF Model <code>Movie</code> I now need to give each movie information about the current user. This is where I struggle the most. Should the <code>RottenTomatoes</code> class have the responsibility of populating this information, should the controller, or should I create a new wrapper class around <code>RottenTomatoes</code>, or perhaps a better solution all together? <em>See question 3</em></p>
<p>If <code>RottenTomatoes</code> has the responsibility, then I need to worry about passing in the <code>DataContext</code> to get user information about each movie, and the user id of the auhtenticated user. Fine, but it seems like too many dependencies and it seems that<code>RottenTomatoes</code> shouldn't need to know anything about a <code>DataContext</code> or user id.</p>
<p>Once user information is set the result set is returned back to the controller where it is serialized and sent back to the client.</p>
<p><strong>Questions</strong></p>
<ol>
<li>Should I convert all movies from my <code>DataContract</code> to my EF model right away as soon as they're returned from <code>RottenTomates</code>, like I'm doing currently, or only when a user is adding a movie to their collection? Is there a best practice for this sort of thing? </li>
<li>Should <code>FindMovies()</code> have the responsibility of converting the <code>DataContract</code> into <code>Movie</code>, my EF model? Really, should the <code>RottenTomatoes</code> class have that responsibility at all?</li>
<li>Should <code>RottenTomatoes</code> be responsible for adding user information about each movie before it returns the result set back to the controller? If not, is there a better design or perhaps a design pattern that could help me here?</li>
</ol>
|
[] |
[
{
"body": "<p>This looks really silly to me:</p>\n\n<pre><code> try {\n using (var response = (HttpWebResponse)request.GetResponse()) {\n var serializer = new DataContractJsonSerializer(typeof(MoviesDataContract));\n return (MoviesDataContract)serializer.ReadObject(response.GetResponseStream());\n }\n } catch (Exception e) {\n throw new Exception(e.Message);\n }\n</code></pre>\n\n<p>You create an exception that throws an exception. It just doesn't make sense to me. If you want the exception to bubble up, then you should just get rid of the <code>try</code> <code>catch</code> altogether.</p>\n\n<p>It would be different if you returned a \"bad response\" so that the calling object knew that it was bad for some reason, so that it could tell the user that something went wrong.</p>\n\n<p>You already have a Using Statement in there so that if there is an issue the response is still disposed, so you should just let the exception bubble up naturally.</p>\n\n<pre><code>using (var response = (HttpWebResponse)request.GetResponse()) {\n var serializer = new DataContractJsonSerializer(typeof(MoviesDataContract));\n return (MoviesDataContract)serializer.ReadObject(response.GetResponseStream());\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-29T15:45:40.767",
"Id": "58397",
"ParentId": "19255",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T17:27:28.670",
"Id": "19255",
"Score": "11",
"Tags": [
"c#",
"design-patterns",
"entity-framework",
"api"
],
"Title": "Wrapper class for the Rotten Tomatoes API"
}
|
19255
|
<p>I would like to improve my preg_replace regex.
This is to clean a features list.</p>
<p>I want allow for the begining of each line:</p>
<ul>
<li>alphanumeric characters</li>
<li>== and alphanumeric characters</li>
<li>-- alphanumeric characters</li>
<li>++ alphanumeric characters</li>
<li>** alphanumeric characters</li>
</ul>
<p>my regex:</p>
<pre><code>$features = "
== Category one
→ feature 1
++ feature 2
-- feature 3
==-
! feature 4
% feature 5";
preg_replace('/' .
'^[^[:alnum:]]{0,}(==-.*)$' . '|' . // ==-
'^[^[:alnum:]]{0,}([\+|\-|\*|\=]{2}.*)$' . '|' . // ==
'^[^[:alnum:]]{0,}(.*)$' . // abc
'/mu', '$1$2$3',
$features);
</code></pre>
<p>Dirty features:</p>
<ul>
<li>== Category one </li>
<li>→ feature 1</li>
<li>++ feature 2</li>
<li>-- feature 3</li>
<li>==- </li>
<li>! feature 4 </li>
<li>% feature 5</li>
</ul>
<p>Clean:</p>
<ul>
<li>== Category one</li>
<li>feature 1</li>
<li>++ feature 2</li>
<li>-- feature 3</li>
<li>==-</li>
<li>feature 4</li>
<li>feature 5</li>
</ul>
<p>It works, but i think there is a better way ...
Thanks</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T14:20:09.873",
"Id": "30818",
"Score": "0",
"body": "Is $features the entire string - or has it already been separated for each line? Based off what I see in your Regexp - it looks like the entire string is in there. You may be better off just exploding your string by line and then compare the first 2 to 3 characters using a switch statement which would be a little cheaper to process me thinks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T09:09:10.283",
"Id": "30949",
"Score": "0",
"body": "Thanks a lot !\nIt's really easier !\nI'm going to work on it, i would like it transform something like -line1 -- line2 to line1 -- line2\nrefuse +|-|=|* without whitespace after ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T14:47:53.343",
"Id": "434480",
"Score": "0",
"body": "Hi and welcome to the site. Unfortunately, this reads like a \"please help me write better code\" - which is off topic, rather then \"please explain what is wrong with this code so I can improve it\" - which would be on-topic."
}
] |
[
{
"body": "<p>Maybe this one : <code>#^[^-=+*\\w]{2}\\s*#um</code> (that is <a href=\"http://lumadis.be/regex/test_regex.php?id=1387\" rel=\"nofollow\">~500% faster</a> than yours):</p>\n\n<pre class=\"lang-php prettyprint-override\"><code><?php\n$list = '\n== Category one\n→ feature 1\n++ feature 2\n-- feature 3\n==-\n! feature 4\n% feature 5\n** feature 6\nfeature 7';\n\n$list = preg_replace('#^[^-=+*\\w]{2}\\s*#um', '', $list);\nprint_r($list);\n</code></pre>\n\n<p>Whose output is:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>== Category one\nfeature 1\n++ feature 2\n-- feature 3\n==-\nfeature 4\nfeature 5\n** feature 6\nfeature 7\n</code></pre>\n\n<h2>Subsidiary question</h2>\n\n<p>You can complete the regexp <code>#^[^-=+*\\w]{2}\\s*#um</code> by the regexp\n<code>#^([-=+*])(?!\\1|\\s)#um</code> to refuse <code>+|-|=|*</code> without whitespace after.</p>\n\n<p>It is possible to combine the two regexps but at the expense of performance.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code><?php\nfunction printResult($label, $list, $start, $end) {\n printf(\n \"%s: %F s\\n%s\\n\\n\",\n $label,\n $end - $start,\n print_r($list, true)\n );\n}\n\n$list = '== Category one\n→ feature 1\n++ feature 2\n-- feature 3\n==-\n! feature 4\n% feature 5\n** feature 6\nfeature 7\n-line1\n-- line2';\n\n// Case 1: regrouping the regexps\n$time_start = microtime(true);\n$list = preg_replace('#^[^-=+*\\w]{2}\\s*|^([-=+*])(?!\\1|\\s)#um', '', $list);\n$time_end = microtime(true);\nprintResult('With one regexp', $list, $time_start, $time_end);\n\n// Case 2: a faster way\n$time_start = microtime(true);\n$list = preg_replace('#^[^-=+*\\w]{2}\\s*#um', '', $list);\n$list = preg_replace('#^([-=+*])(?!\\1|\\s)#um', '', $list);\n$time_end = microtime(true);\nprintResult('In two pass, a faster way', $list, $time_start, $time_end);\n</code></pre>\n\n<p>Whose output is:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>With one regexp: 0.000151 s\n== Category one\nfeature 1\n++ feature 2\n-- feature 3\n==-\nfeature 4\nfeature 5\n** feature 6\nfeature 7\nline1\n-- line2\n\nIn two pass, a faster way: 0.000024 s\n== Category one\nfeature 1\n++ feature 2\n-- feature 3\n==-\nfeature 4\nfeature 5\n** feature 6\nfeature 7\nline1\n-- line2\n</code></pre>\n\n<hr>\n\n<p>Note: <code>preg_replace</code> replaces the overall catch, therefore it is useless to try to capture the full line.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T14:23:13.253",
"Id": "19257",
"ParentId": "19256",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T14:12:02.697",
"Id": "19256",
"Score": "1",
"Tags": [
"php",
"regex"
],
"Title": "Preg_replace improvement"
}
|
19256
|
<p>How can <a href="http://jsfiddle.net/ARTsinn/dxPdw/" rel="nofollow">this</a> be written a bit shorter?</p>
<pre><code>jQuery.konami = function(fn, code) {
// ↑ ↑ ↓ ↓ ← → ← → B A
code = code || [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];
var kkeys = '',
i = 0;
$(document).keydown(function(e) {
var char = String.fromCharCode(e.which).toLowerCase();
if (char === code[i++]) {
kkeys += char;
if (kkeys === code) {
fn();
kkeys = '';
i = 0;
}
} else if (e.which === code[kkeys++]) {
if (kkeys === code.length) {
fn();
kkeys = '';
i = 0;
}
} else {
kkeys = '';
i = 0;
}
});
};
</code></pre>
|
[] |
[
{
"body": "<p>This is almost like code golf; this could probably be shortened. You just need to keep track of <code>i</code> and when it's past the end of the array, you know all the keys were hit in the correct order.</p>\n\n<pre><code>jQuery.konami = function() {\n function KonamiCode(kFn, kCode) {\n var i = 0;\n\n $(document).keydown(function(e) {\n var char = typeof kCode === 'string' ? String.fromCharCode(e.which).toLowerCase() : e.which;\n i = char === kCode[i] ? i + 1 : 0;\n if (i === kCode.length) {\n kFn();\n i = 0;\n }\n });\n }\n return function(fn, code) {\n // ↑ ↑ ↓ ↓ ← → ← → B A\n kCode = code || [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];\n new KonamiCode(fn, kCode);\n };\n}();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T15:19:19.487",
"Id": "30821",
"Score": "0",
"body": "nice approach, but works not as expected..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T15:20:38.177",
"Id": "30822",
"Score": "0",
"body": "@yckart what's wrong with it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T15:22:36.483",
"Id": "30823",
"Score": "0",
"body": "yeah it just simply isn't working, :p http://jsfiddle.net/dxPdw/5/ I haven't investigated as to why though"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T15:22:53.977",
"Id": "30824",
"Score": "0",
"body": "@NickLarsen it breaks on multiple instantiations and even fails with strings (words)... http://jsfiddle.net/ARTsinn/dxPdw/6/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T15:25:31.620",
"Id": "30825",
"Score": "0",
"body": "Silly logic error, `i = char === code[i] ? 0 : i + 1;` needed to be `i = char === code[i] ? i + 1 : 0;`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T15:27:10.310",
"Id": "30826",
"Score": "0",
"body": "@NickLarsen your updated answer works with strings but breaks now with keycodes :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T15:27:39.810",
"Id": "30827",
"Score": "0",
"body": "This part is messing it up: `String.fromCharCode(e.which).toLowerCase();` for the default version"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T15:30:08.000",
"Id": "30828",
"Score": "0",
"body": "@KevinB any ideas how to fix that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T15:31:45.920",
"Id": "30829",
"Score": "0",
"body": "@yckart Yes, you would have to use an if statement like in your original. If the array is made up of strings, check the String.fromCharCode, else, compare against the e.which."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T15:33:18.513",
"Id": "30830",
"Score": "0",
"body": "@KevinB yeah, had the same idea. Try around a bit..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T15:35:34.410",
"Id": "30831",
"Score": "0",
"body": "Okay, git it... http://jsfiddle.net/ARTsinn/dxPdw/10/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T15:42:02.443",
"Id": "30832",
"Score": "0",
"body": "@yckart Yes, that's better than mine"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T15:52:05.603",
"Id": "30833",
"Score": "0",
"body": "hmm, can you explan a bit further what you mean with *resilient to multiple invocations*?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T15:53:30.937",
"Id": "30834",
"Score": "0",
"body": "The original version is using the same `i` for every code, so if you invoke it twice with different codes they fail because they are competing for the same counter. This change just makes it so every call gets it's own counter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T15:58:54.100",
"Id": "30835",
"Score": "0",
"body": "Okay, this is obvious... But the current approach without your \"plugin wrapper\" works even with multiple instantiations. See: http://jsfiddle.net/ARTsinn/dxPdw/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T16:03:24.100",
"Id": "30836",
"Score": "0",
"body": "So where are the differences, or rather the dis/advantages?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T16:03:37.890",
"Id": "30837",
"Score": "0",
"body": "Ahh ok, that makes sense actually, it's the keypress event handler that's holding the reference to a new local version if `i` each time. That jsfiddle is just as good."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T16:07:05.157",
"Id": "30838",
"Score": "0",
"body": "Okay, thanks alot for your help and time:-*"
}
],
"meta_data": {
"CommentCount": "18",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T15:17:47.990",
"Id": "19260",
"ParentId": "19259",
"Score": "1"
}
},
{
"body": "<p>Here's a slightly shortened version:</p>\n\n<pre><code>jQuery.konami = function(fn, code) {\n // ↑ ↑ ↓ ↓ ← → ← → B A\n code = code || [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];\n\n var i = 0;\n\n $(document).keydown(function(e) {\n var char = $.type(code[i]) === \"string\" ? String.fromCharCode(e.which).toLowerCase() : e.which;\n if (char === code[i]) {\n i++;\n if (i == code.length) {\n fn();\n i = 0;\n }\n } else {\n i = 0;\n }\n });\n};\n</code></pre>\n\n<p>the kkeys var wasn't needed, and you could move the if else into the retrieval of <code>char</code>, allowing you to reuse what was inside the if originally.</p>\n\n<p><a href=\"http://jsfiddle.net/dxPdw/12/\" rel=\"nofollow\">http://jsfiddle.net/dxPdw/12/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T15:42:13.563",
"Id": "30839",
"Score": "0",
"body": "Nice! However, got it already http://stackoverflow.com/questions/13647824/optimize-jquery-plugin-according-to-dry-principle/13647984#comment18725838_13647984 ;-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T15:40:46.963",
"Id": "19261",
"ParentId": "19259",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-30T15:08:26.927",
"Id": "19259",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"event-handling",
"plugin"
],
"Title": "jQuery plugin to detect Konami cheat code sequence"
}
|
19259
|
<p>Based on the answer to my <a href="https://stackoverflow.com/a/13629394/298754">question on StackOverflow</a>, I have ended up with the following code:</p>
<pre><code>public class ColumnDataBuilder<T>
{
public abstract class MyListViewColumnData
{
public string Name { get; protected set; }
public int Width { get; protected set; }
public ColumnType Type { get; protected set; }
public delegate TOUT FormatData<out TOUT>(T dataIn);
protected abstract dynamic GetData(T dataRow);
public string GetDataString(T dataRow)
{
dynamic data = GetData(dataRow);
switch (Type)
{
case ColumnType.String:
case ColumnType.Integer:
case ColumnType.Decimal:
return data.ToString();
case ColumnType.Date:
return data.ToShortDateString();
case ColumnType.Currency:
return data.ToString("c");
break;
case ColumnType.Boolean:
var b = (bool)data;
if (b) return "Y";
else return "N";
default:
throw new ArgumentOutOfRangeException();
}
}
}
public class MyListViewColumnData<TOUT> : MyListViewColumnData
{
public MyListViewColumnData(string name, int width, ColumnType type, FormatData<TOUT> dataFormater)
{
DataFormatter = x => dataFormater(x); // Per https://stackoverflow.com/a/1906850/298754
Type = type;
Width = width;
Name = name;
}
public Func<T, TOUT> DataFormatter { get; protected set; }
protected override dynamic GetData(T dataRow)
{
return DataFormatter(dataRow);
}
}
}
</code></pre>
<p>This is called from a factory method (in <code>ColumnDataBuilder</code>) as </p>
<pre><code>public MyListViewColumnData Create<TOUT>(string name, int width, ColumnType type, MyListViewColumnData.FormatData<TOUT> dataFormater)
{
return new MyListViewColumnData<TOUT>(name, width, type, dataFormater);
}
public MyListViewColumnData Create(string name, int width, MyListViewColumnData.FormatData<DateTime> dataFormater)
{
return new MyListViewColumnData<DateTime>(name, width, ColumnType.Date, dataFormater);
}
...
</code></pre>
<p>That, in turn, is called from my code as:</p>
<pre><code>builder.Create("Date", 40, x => x.createdDate);
</code></pre>
<p>and </p>
<pre><code>private ListViewItem CreateListViewItem<TDATA>(IEnumerable<ColumnDataBuilder<TDATA>.MyListViewColumnData> columns, TDATA rowData)
{
var item = new ListViewItem();
foreach (var col in columns)
{
item.SubItems.Add(col.GetDataString(rowData));
}
item.SubItems.RemoveAt(0); // We generate an extra SubItem for some reason.
return item;
}
</code></pre>
<p>How can I refactor this so that I'm <strong>not</strong> using <code>dynamic</code>, but still preserve the syntax as it currently exists in the code?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T16:52:01.930",
"Id": "30841",
"Score": "0",
"body": "Alternatively, if this is a proper use for `dynamic`, that'd be good to know too... but I'm pretty sure it isn't."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T17:19:06.790",
"Id": "30842",
"Score": "0",
"body": "Where does `T` come from?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T17:30:26.573",
"Id": "30844",
"Score": "0",
"body": "Your `public abstract class MyListViewColumnData` has no generic parameters while it has `delegate TOUT FormatData<out TOUT>(T dataIn)` declared. Please make sure you post a compilable code here"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T17:33:10.813",
"Id": "30846",
"Score": "0",
"body": "@JeffVanzella - Good catch. I missed copying the class declaration. Edited it in."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T17:37:03.703",
"Id": "30847",
"Score": "0",
"body": "@almaz - I think this will now compile. If it doesn't, I'll go back and post a larger block, but I am trying to keep it down to the relevant portions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T09:21:15.067",
"Id": "30926",
"Score": "0",
"body": "Have a look at Convert.ToString(object, IFormatProvider) and implementing your format provider. A bit more complex way, but for good separation is reasonable enough."
}
] |
[
{
"body": "<p>I don't think you need <code>MyListViewColumnData</code> class there, I would replace it with interface and move the <code>GetDataString</code> implementation to <code>MyListViewColumnData<TOut></code>. And you don't need <code>dynamic</code> here, just use <code>object</code> instead (yes, it will use boxing for most cases except strings, but it's more efficient than dynamics).</p>\n\n<pre><code>public class ColumnDataBuilder<T>\n{\n public interface IMyListViewColumnData\n {\n string Name { get; }\n int Width { get; }\n ColumnType Type { get; }\n string GetDataString(T dataRow);\n }\n\n public delegate TOut FormatData<out TOut>(T dataIn);\n\n public class MyListViewColumnData<TOut> : IMyListViewColumnData\n {\n public string Name { get; private set; }\n public int Width { get; private set; }\n public ColumnType Type { get; private set; }\n private readonly FormatData<TOut> _dataFormatter;\n\n public MyListViewColumnData(string name, int width, ColumnType type, FormatData<TOut> dataFormater)\n {\n _dataFormatter = dataFormater;\n Type = type;\n Width = width;\n Name = name;\n }\n public string GetDataString(T dataRow)\n {\n object data = _dataFormatter(dataRow);\n\n switch (Type)\n {\n case ColumnType.String:\n case ColumnType.Integer:\n case ColumnType.Decimal:\n return data.ToString();\n case ColumnType.Date:\n return ((DateTime)data).ToShortDateString();\n case ColumnType.Currency:\n return ((decimal)data).ToString(\"c\");\n case ColumnType.Boolean:\n return (bool)data ? \"Y\" : \"N\";\n default:\n throw new ArgumentOutOfRangeException();\n }\n }\n }\n\n public IMyListViewColumnData Create<TOut>(string name, int width, ColumnType type, FormatData<TOut> dataFormater)\n {\n return new MyListViewColumnData<TOut>(name, width, type, dataFormater);\n }\n\n public IMyListViewColumnData Create(string name, int width, FormatData<DateTime> dataFormater)\n {\n return new MyListViewColumnData<DateTime>(name, width, ColumnType.Date, dataFormater);\n }\n}\n\npublic enum ColumnType\n{\n String,\n Integer,\n Decimal,\n Date,\n Currency,\n Boolean\n}\n</code></pre>\n\n<p><strong>Update</strong>\nIn comments it was asked if you can extract interface for ColumnDataBuilder. Of course you can :), and the easiest way would be to use \"Extract interface\" refactoring from ReSharper :). If you still don't use it you'll have to do that manually (move the <code>IMyListViewColumnData</code> and <code>FormatData<TOut></code> declarations out of <code>ColumnDataBuilder<T></code> first):</p>\n\n<pre><code>public interface IColumnDataBuilder<Tin>\n{\n IMyListViewColumnData Create<TOut>(string name, int width, ColumnType type, FormatData<TOut> dataFormater);\n IMyListViewColumnData Create(string name, int width, FormatData<DateTime> dataFormater);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T18:33:34.277",
"Id": "30849",
"Score": "0",
"body": "I *knew* there had to be a better way. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T18:47:49.383",
"Id": "30850",
"Score": "0",
"body": "Just a followup: Is there any way to extract an interface of `ColumnDataBuilder<>`, so that I can store it without knowing the type? Or is that asking too much of the compiler?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T18:58:16.307",
"Id": "30855",
"Score": "0",
"body": "@Bobson see updated answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T19:03:15.437",
"Id": "30857",
"Score": "0",
"body": "I'm not sure that addresses the goal, though. I have another class (the `ListView` subclass which this is handling the data for), which could have any datatype for `Tin` there. And I can't make it generic for other reasons, or this would be a lot simpler. So what type do I make that property? Or could I leave off the `<Tin>` and get this scenario working?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T19:09:33.653",
"Id": "30858",
"Score": "0",
"body": "you should have told how you want it to work first :). If you want to write a general logic that doesn't know about specific types upfront in may be a good idea just to stop using generics... At what time ListView gets to know the type T? Where is the code that calls `ColumnDataBuilder<T>.Create` located? Does that code know about specific types? It's probably better to open a new question since we've moved quite far from original one..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T19:11:02.800",
"Id": "30859",
"Score": "0",
"body": "Fair enough - I hadn't thought that far ahead when I asked this question. While I was waiting for an answer, I realized I needed to separate column creation from attaching the data. I'll see if I can formulate a new question, and then I'll link it here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T19:42:37.460",
"Id": "30862",
"Score": "0",
"body": "[Posted](http://codereview.stackexchange.com/questions/19270/generic-data-for-listview)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T17:59:55.207",
"Id": "19265",
"ParentId": "19263",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "19265",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T16:43:28.373",
"Id": "19263",
"Score": "0",
"Tags": [
"c#"
],
"Title": "Refactoring to avoid the use of dynamic"
}
|
19263
|
<p>I wanted to get the boolean status from a function. Here is my sample code, wherein I used return in try and catch, to get the status of function.</p>
<pre><code>public static void main(String[] args) {
System.out.println(getState() ? "successful" : "failed");
}
public static boolean getState() {
SAXBuilder builder = new SAXBuilder();
File xmlFile = new File("tile.xml");
Set<String> set = new TreeSet<String>();
try {
Document document = (Document) builder.build(xmlFile);
Element rootNode = document.getRootElement();
System.out.println(rootNode);
return true;
} catch (IOException io) {
System.out.println(io.getMessage());
return false;
} catch (JDOMException jdomex) {
System.out.println(jdomex.getMessage());
return false;
}
}
</code></pre>
<p>Does it makes sense ? Can I improve it ?
Assuming, that there might be more than 10 catch blocks, then should I use 10 return statements, in each catch block. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T17:22:15.827",
"Id": "30843",
"Score": "1",
"body": "Which Java version are you using? With Java7 multicatch is available and ideal when you have identical catch blocks but don't want to widen your catch scope. See details at http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T04:58:57.350",
"Id": "30878",
"Score": "0",
"body": "Dan Nidwood : I'm using java 1.6"
}
] |
[
{
"body": "<p>For only 2 or 3 instances, I may use multiple return statements, but only in the case of if-else chains or switches. Returns within a try catch block can be done, but also can become complicated when you start mixing in finally with it. In the case of try-catch blocks or several possible 'return' paths, I use a variable and set it as necessary, and return it at the end. If you want an early return to bypass some code, I tend to take that code and wrap it up in a separate method, and use an if statement with my value to return to determine whether to execute that method.</p>\n\n<pre><code>public static void main(String[] args) {\n System.out.println(getState() ? \"successful\" : \"failed\");\n}\n\npublic static boolean getState() {\n boolean success = false;\n SAXBuilder builder = new SAXBuilder();\n File xmlFile = new File(\"tile.xml\");\n Set<String> set = new TreeSet<String>();\n try {\n Document document = (Document) builder.build(xmlFile);\n Element rootNode = document.getRootElement();\n System.out.println(rootNode);\n success = true;\n } catch (IOException io) {\n System.out.println(io.getMessage());\n } catch (JDOMException jdomex) {\n System.out.println(jdomex.getMessage());\n }\n\n return success;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T19:49:03.347",
"Id": "19272",
"ParentId": "19264",
"Score": "6"
}
},
{
"body": "<p>I agree, that you should avoid return in try/catch/finally blocks, mostly because it is not always for everyone clear what is happening there. This goes hand in hand with the pattern that exceptions should not be used as flow control statements.</p>\n\n<p>Depending on the use case, one different suggestion compared to Drake Clarris is to extract the try catch outside the normal logic. This makes the source code more readable and more clear.</p>\n\n<pre><code>public static void main(String[] args) {\n System.out.println(getState() ? \"successful\" : \"failed\");\n}\n\npublic static boolean getState() {\n final File xmlFile = new File(\"tile.xml\");\n final Element rootNode = getRoodNode(xmlFile);\n if (rootNode == null)\n return false;\n System.out.println(rootNode);\n return true\n}\n\nprivate static Element getRoodNode(final File xmlFile)\n{\n Element rootNode = null;\n try {\n final Document document = (Document) new SAXBuilder().build(xmlFile);\n rootNode = document.getRootElement();\n } catch (IOException io) {\n System.out.println(io.getMessage());\n } catch (JDOMException jdomex) {\n System.out.println(jdomex.getMessage());\n }\n return rootNode;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-06T16:03:17.343",
"Id": "19360",
"ParentId": "19264",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "19272",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T16:57:13.637",
"Id": "19264",
"Score": "4",
"Tags": [
"java"
],
"Title": "Is using return appropriate here?"
}
|
19264
|
<p>I need to divide an array in blocks of 6 items max, however I can't find a better way to store the last block.</p>
<p>This is my current code and it works. Is there a way to avoid using the <code>if</code> after the <code>.each</code> ? </p>
<pre><code> var tabsData = [], tabCtr = 1, lpcCtr = 1;
$.each(PAGE_DATA.tableData, function(i, item) {
tabsData.push(item);
if(lpcCtr==6){
// show block of 6 items
tabsData = [];
tabCtr++;
lpcCtr = 0;
}
lpcCtr++;
});
if(tabsData.length > 0){
// show last block
}
</code></pre>
|
[] |
[
{
"body": "<p>It's better to use <code>slice</code> function. It will also correctly process the last block</p>\n\n<pre><code>var size = PAGE_DATA.tableData.length;\nfor (var i = 0; i < size; i += 6){\n var t = PAGE_DATA.tableData.slice(i, i + 6);\n //show block of 6 items (or smaller in case of last block)\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T18:47:09.693",
"Id": "19267",
"ParentId": "19266",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "19267",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T18:33:19.253",
"Id": "19266",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "Dividing an array"
}
|
19266
|
<p>I have this code to create an inverted index from a directory of text files:</p>
<pre><code>(def p (re-pattern #"[^\p{L}&&[^\p{M}]]"))
(defn invert[file]
(let [f (.getName file)
tokens (.split p (lower-case (slurp file)))]
(into {} (mapcat #(hash-map % #{f}) tokens))))
(defn build-index[dirname]
(reduce #(merge-with union %1 %2) (map invert (.listFiles (java.io.File. dirname)))))
</code></pre>
<p>Can you improve it / make it more idiomatic? My concern is performance. I'm testing it with 10k files of 10k in size, and I can make it about 20-30% faster if I use transients like this:</p>
<pre><code>(defn add![idx file]
(let [f (.getName file)]
(loop [idx idx
tokens (.split p (lower-case (slurp file)))]
(if-not (seq tokens) idx
(recur (assoc! idx (first tokens) (union (idx (first tokens)) #{f})) (rest tokens))))))
(defn build-index[dirname]
(loop [files (.listFiles (java.io.File. dirname))
idx (transient {})]
(if-not (seq files) (persistent! idx)
(recur (rest files) (add! idx (first files))))))
</code></pre>
<p>Full code including test file generator here:</p>
<p><a href="https://github.com/dbasch/closearch" rel="nofollow">https://github.com/dbasch/closearch</a></p>
<p>Any feedback is welcome.</p>
|
[] |
[
{
"body": "<p>You should be able to use reducers to get a good speed boost as the consumption and building of your index can be parallelized.</p>\n\n<p>I have found the best docs for reducers to be the doc strings themselves:\n<a href=\"https://github.com/clojure/clojure/blob/master/src/clj/clojure/core/reducers.clj\" rel=\"nofollow\" title=\"Reducers - Github\">Reducers -- Github</a></p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(ns ...\n (:require [clojure.core.reducers :as r]\n [clojure.java.io :as io]\n [clojure.string :as str]))\n\n(defn invert [file]\n (let [f (.getName file)\n tokens (str/split (str/lower-case (slurp file)) p)]\n (->> tokens\n (r/mapcat #(hash-map % #{f}))\n (into {}))))\n\n(defn build-index \n [dirname]\n (->> dirname\n io/file\n (.listFiles)\n (r/map invert)\n (r/fold (r/monoid (partial merge-with union) hash-map))))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T14:04:57.703",
"Id": "45827",
"ParentId": "19268",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T18:59:37.427",
"Id": "19268",
"Score": "3",
"Tags": [
"performance",
"clojure"
],
"Title": "Inverted index in Clojure - performance vs. idiomatic code"
}
|
19268
|
<p>I'm in the midst of writing a custom <code>ListView</code> for our application. </p>
<p>In the process of getting <a href="https://codereview.stackexchange.com/questions/19263/refactoring-to-avoid-the-use-of-dynamic">this question</a> answered, I realized I needed to separate my column-generation logic from the data population. This led to the need to preserve the <code>ColumnDataBuilder<TDATA></code> builder object that I used to create the columns, so that I could keep track of the type of my data.</p>
<p>Ideally, usage will look something like this:</p>
<pre><code>builder = MyListView.ColumnsFor<ReceiptHeaderForShipping>();
mlvShippingList.createColumns(_builder.Create("Receipt", 60, x => x.receiptNumber),
_builder.Create("Cust", 100, x => x.customer.LastName + ", " + x.customer.FirstName),
_builder.Create("Total", 60, MyListView.ColumnType.Currency, x => x.subTotal)
);
</code></pre>
<p>And then later </p>
<pre><code>mlvShippingList.populateData(_builder, data);
</code></pre>
<p>In addition, the <code>MyListView</code> will have to know what type of data it was built with, in order to know what type of <code>ColumnDataBuilder</code> the <code>IMyColumnData</code> comes from, so that it can cast to it in order to sort.</p>
<hr>
<p>From <code>MyListView</code>:</p>
<pre><code>public partial class MyListView : ListView
{
public static ColumnDataBuilder<T> ColumnsFor<T>(IEnumerable<T> data)
{
return new ColumnDataBuilder<T>();
}
public void populateFromData<TDATA>(IEnumerable<TDATA> data, params ColumnDataBuilder<TDATA>.IMyListViewColumnData[] columns)
{
createColumns(columns);
populateData(data, columns);
}
public void createColumns<TDATA>(params ColumnDataBuilder<TDATA>.IMyListViewColumnData[] columns)
{
Columns.Clear();
foreach (var col in columns)
{
var ch = new ColumnHeader
{
Text = col.Name,
Width = col.Width,
Tag = col,
};
// Other formatting goes here
this.Columns.Add(ch);
}
}
private void populateData<TDATA>(IEnumerable<TDATA> data, params ColumnDataBuilder<TDATA>.IMyListViewColumnData[] columns)
{
Items.Clear();
var parsedData = data.Select(row => CreateListViewItem(columns, row));
this.Items.AddRange(parsedData.ToArray());
}
public class ColumnDataBuilder<T>
{
internal List<IMyListViewColumnData> columns = new List<IMyListViewColumnData>();
public interface IMyListViewColumnData
{
string Name { get; }
int Width { get; }
ColumnType Type { get; }
string GetDataString(T dataRow);
}
public delegate TOut FormatData<out TOut>(T dataIn);
public class MyListViewColumnData<TOut> : IMyListViewColumnData
{
public string Name { get; private set; }
public int Width { get; private set; }
public ColumnType Type { get; private set; }
private readonly FormatData<TOut> _dataFormatter;
public MyListViewColumnData(string name, int width, ColumnType type, FormatData<TOut> dataFormater)
{
_dataFormatter = dataFormater;
Type = type;
Width = width;
Name = name;
}
public string GetDataString(T dataRow)
{
object data = _dataFormatter(dataRow);
switch (Type)
{
case ColumnType.String:
case ColumnType.Integer:
case ColumnType.Decimal:
return data.ToString();
case ColumnType.Date:
return ((DateTime)data).ToShortDateString();
case ColumnType.Currency:
return ((decimal)data).ToString("c");
case ColumnType.Boolean:
return (bool)data ? "Y" : "N";
default:
throw new ArgumentOutOfRangeException();
}
}
}
#region Factory Methods
public IMyListViewColumnData Create<TOut>(string name, int width, ColumnType type, FormatData<TOut> dataFormater)
{
var col = new MyListViewColumnData<TOut>(name, width, type, dataFormater);
columns.Add(col);
return col;
}
public IMyListViewColumnData Create(string name, int width, FormatData<DateTime> dataFormater)
{
return Create(name, width, ColumnType.Date, dataFormater);
}
// More type-specific factories go here
#endregion
}
}
</code></pre>
<hr>
<p>Am I totally off base at this point? Is this a reasonable track to go down? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T10:13:20.743",
"Id": "59046",
"Score": "0",
"body": "The ListView control is capable of [binding to generic data](http://www.kettic.com/winforms_ui/csharp_guide/listview_data_binding.shtml) to display them through properties, DataSource, ShowMember and ValueMember."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T15:15:39.133",
"Id": "59074",
"Score": "0",
"body": "@Myron - That's a proprietary component. The standard .NET ListView doesn't have a `DataSource` property. It's also on a broken website that you can't actually purchase it from (or even download the trial)."
}
] |
[
{
"body": "<p>I've done something like this a few times (a lot even), but most times it was a complete waste of time. You will probably not earn the time you save by not doing WebForms markup, even if it's terribly boring. If you have like 100-200 entity types to display in similar lists, it might be a useful path, but if it's 10 - go with good old aspx/ascx markup. If you don't need a lot of business rules and/or scalability in some form, go for markup only with SqlDataSource and WYSIWYG listviews. If you need a fancy UI, go with Telerik.</p>\n\n<p>Given you actually have multiple customers with different list needs for the same entities in the same product, this might be \"the only\" way, though.</p>\n\n<p>With regards to your code, it seems slim and clean enough. But beware when going further with this - you might get a lot of conflicting requirements. As you say, it's a good thing to separate responsibilities, so keep doing that if you really want to make something \"re-usable\". (It won't be, but still..)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T14:28:24.253",
"Id": "30891",
"Score": "0",
"body": "It's a WinForm app, so markup isn't really an option."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T08:18:54.907",
"Id": "30922",
"Score": "0",
"body": "Hmm, I see - but wysiwyg is still an option, as long as you separate out the fetching logic, you can use databinding and design time layout of the grids."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T17:03:43.217",
"Id": "30959",
"Score": "0",
"body": "ListView doesn't support data binding, and the class I'd be binding to uses fields instead of properties for legacy reasons, so it can't be bound anyway. Highly frustrating. I wish I could just databind directly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-06T09:52:21.747",
"Id": "31007",
"Score": "0",
"body": "OK, sorry for my rusty winforms. Really a web guy. Still, make absolutely sure you're using the right controls for the right job. Do you really really need to use the ListView with the limitations it imposes on you? Are there third party alternatives?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-06T14:36:16.787",
"Id": "31015",
"Score": "0",
"body": "No worries. Unfortunately, because of the legacy reasons, ListView is the right control. There are a few third party alternatives, but all the ones I've found fall short in one way or another. Rolling my own seemed easiest."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-19T15:12:40.317",
"Id": "39122",
"Score": "0",
"body": "In the end, I'm accepting this one because `most times it was a complete waste of time` is a good description of what happened. I like almaz's answer better, but this is the one that actually reflects what happened."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T09:09:56.010",
"Id": "39498",
"Score": "0",
"body": "Aww, sorry it didn't work out. At least you're quite a few experiences richer. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T15:59:23.463",
"Id": "39526",
"Score": "0",
"body": "Indeed. Live and learn. I'm now trying to push a switch to WPF for new development. We'll see how that goes..."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T00:33:06.780",
"Id": "19276",
"ParentId": "19270",
"Score": "1"
}
},
{
"body": "<p>Not sure I would ever do smth like this for my own production, but here is the code that (IMHO) would clean things up...</p>\n\n<p>Implementation of MyListView:</p>\n\n<pre><code>public interface IListViewDefinition<TData>\n{\n IMyListViewColumn<TData>[] GetColumns(); //Just in case...\n IListViewDefinition<TData> AddColumn<TOut>(string name, int width, ColumnType type, Converter<TData, TOut> dataFormater);\n void PopulateData(IEnumerable<TData> data);\n}\n\npublic interface IMyListViewColumn<in TData>\n{\n string Name { get; }\n int Width { get; }\n ColumnType Type { get; }\n string GetDataString(TData dataRow);\n}\n\npublic static class ListViewBuilderExtensions\n{\n public static IListViewDefinition<TData> AddColumn<TData>(this IListViewDefinition<TData> instance, string name, int width, Converter<TData, DateTime> dataFormater)\n {\n return instance.AddColumn(name, width, ColumnType.Date, dataFormater);\n }\n}\n\npublic partial class MyListView : ListView\n{\n public IListViewDefinition<TData> SetupListViewFor<TData>()\n {\n return new ListViewDefinition<TData>(this);\n }\n\n private void CreateColumns<TData>(IEnumerable<IMyListViewColumn<TData>> columns)\n {\n Columns.Clear();\n foreach (var col in columns)\n {\n var ch = new ColumnHeader\n {\n Text = col.Name,\n Width = col.Width,\n Tag = col,\n };\n // Other formatting goes here\n this.Columns.Add(ch);\n }\n }\n\n private void PopulateData<TData>(IEnumerable<TData> data, IList<IMyListViewColumn<TData>> columns)\n {\n Items.Clear();\n var parsedData = data.Select(row => CreateListViewItem(columns, row));\n Items.AddRange(parsedData.ToArray());\n }\n\n private class MyListViewColumn<TData, TOut> : IMyListViewColumn<TData>\n {\n public string Name { get; private set; }\n public int Width { get; private set; }\n public ColumnType Type { get; private set; }\n private readonly Converter<TData, TOut> _dataFormatter;\n\n public MyListViewColumn(string name, int width, ColumnType type, Converter<TData, TOut> dataFormater)\n {\n //TODO: check compatibility of type and TOut\n _dataFormatter = dataFormater;\n Type = type;\n Width = width;\n Name = name;\n }\n\n public string GetDataString(TData dataRow)\n {\n object data = _dataFormatter(dataRow);\n\n switch (Type)\n {\n case ColumnType.String:\n case ColumnType.Integer:\n case ColumnType.Decimal:\n return data.ToString();\n case ColumnType.Date:\n return ((DateTime)data).ToShortDateString();\n case ColumnType.Currency:\n return ((decimal)data).ToString(\"c\");\n case ColumnType.Boolean:\n return (bool)data ? \"Y\" : \"N\";\n default:\n throw new ArgumentOutOfRangeException();\n }\n }\n }\n\n private class ListViewDefinition<TData> : IListViewDefinition<TData>\n {\n private readonly List<IMyListViewColumn<TData>> _columns = new List<IMyListViewColumn<TData>>();\n private readonly MyListView _myListView;\n\n public ListViewDefinition(MyListView myListView)\n {\n _myListView = myListView;\n }\n\n public IMyListViewColumn<TData>[] GetColumns()\n {\n return _columns.ToArray();\n }\n\n public IListViewDefinition<TData> AddColumn<TOut>(string name, int width, ColumnType type, Converter<TData, TOut> dataFormater)\n {\n _columns.Add(new MyListViewColumn<TData, TOut>(name, width, type, dataFormater));\n return this;\n }\n\n public void PopulateData(IEnumerable<TData> data)\n {\n _myListView.CreateColumns(_columns);\n _myListView.PopulateData(data, _columns);\n }\n }\n}\n</code></pre>\n\n<p>The usage is like following</p>\n\n<pre><code>var viewDefinition = new MyListView().SetupListViewFor<ReceiptHeaderForShipping>();\nviewDefinition.AddColumn(\"Receipt\", 60, x => x.receiptNumber)\n .AddColumn(\"Cust\", 100, x => x.customer.LastName + \", \" + x.customer.FirstName)\n .AddColumn(\"Total\", 60, MyListView.ColumnType.Currency, x => x.subTotal);\n\nviewDefinition.PopulateData(/*your collection of ReceiptHeaderForShipping*/);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T12:56:52.200",
"Id": "19288",
"ParentId": "19270",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "19276",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T19:42:25.650",
"Id": "19270",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Generic data for ListView"
}
|
19270
|
<p>I have a small validation code that needs to make sure that exactly one of two parameter is
set</p>
<p>I consider two options, the "Naive" that has some repetitions and might look "clumsy" but is very clear, and a second that is a bit more "DRY" but I'm not sure it's as readable / convincing in it's correctness.</p>
<p><strong>Option one</strong></p>
<pre><code>if(param1==null && param2==null){
throw new RuntimeException("Either param1 or param2 must be specified");
}
if(param1!=null && param2!=null){
throw new RuntimeException("Only one of param1 or param2 must be specified");
}
if(param1!=null){
//do something with param1
}
if(param2!=null){
//do something with param2
}
</code></pre>
<p><strong>Option two</strong></p>
<pre><code>if(param1!=null){
if(param2!=null){
//only runs if both are not null
throw new RuntimeException("Only one of param1 or param2 must be specified");
}
//do something with param1
} else if(param2!=null){
//do something with param2
} else{
//only runs if both are null
throw new RuntimeException("Either param1 or param2 must be specified");
}
</code></pre>
<p>Which one is more readable? which one would you keep? do you see any issue with Option 2?</p>
<p><strong>Edit:</strong></p>
<p>Based on feedback, I think there is a bit nicer option</p>
<p><strong>Option three</strong> </p>
<pre><code>boolean isParam1Valid = param1!=null;
boolean isParam2Valid = param2!=null;
if(isParam1Valid == isParam2Valid ){ //e.g. either both are null or both are not null
throw new RuntimeException("param1 or param2 must be specified exactly once");
}
if(isParam1Valid){
//do something with param1
}
if(isParam2Valid){
//do something with param2
}
</code></pre>
<p><strong>Option four</strong> shorter, but a bit less readable IMHO than option three (one needs to go up and read the code to understand why author is so sure that the else block means that param2 is valid</p>
<pre><code>boolean isParam1Valid = param1!=null;
boolean isParam2Valid = param2!=null;
if(isParam1Valid == isParam2Valid ){ //e.g. either both are null or both are not null
throw new RuntimeException("param1 or param2 must be specified exactly once");
}
if(isParam1Valid){
//do something with param1
}else{ //must be true, as isParam1Valid is false, and they are not equal
//do something with param2
}
</code></pre>
|
[] |
[
{
"body": "<p>I would put all validations first, and then extract to a method. Better, trying using a parsing framework like <a href=\"http://jcommander.org\" rel=\"nofollow\">JCommander</a> that might be able to handle that for you, so that your code is just business logic</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T20:24:27.973",
"Id": "19273",
"ParentId": "19271",
"Score": "3"
}
},
{
"body": "<p>Your option one is ok.<br>\nI would recommend to not use option two, this is complex and everyone has to think what is happening here and if everything is correct.</p>\n\n<p>Two possible ways:</p>\n\n<p>1) If used multiple times</p>\n\n<pre><code>boolean isParameter1Valid = ...;\nboolean isParameter2Valid = ...;\ncheckIfExactlyOneIsTrue(isParameter1Valid, isParameter2Valid, \"Exactly one parameter must be specified\");\nif (isParameter1Valid) {\n // do something with param1\n}\nif (isParameter2Valid) {\n // do something with param2\n}\n\n/**\n * throws an exception with given message if either both are true or both are false\n */\nprivate static void checkIfExactlyOneIsTrue(boolean b1, boolean b2, String message) {\n if ((b1 == true && b2 == true) || (b1 == false && b2 == false))\n throw new IllegalArgumentException(message);\n}\n</code></pre>\n\n<p>2) If used only once:</p>\n\n<pre><code>boolean isParameter1Valid = ...;\nboolean isParameter2Valid = ...;\nif (!(isParameter1Valid ^ isParameter2Valid)) { // ^ is xor, which is true if both arguments are different, otherwise false\n throw new IllegalArgumentException(\"Exactly one parameter must be specified\");\n}\nif (isParameter1Valid) {\n // do something with param1\n}\nif (isParameter2Valid) {\n // do something with param2\n}\n</code></pre>\n\n<p>You should not forget to add a comment for the xor, because it is probably not known that much by the typical java programmer.</p>\n\n<p>Edit: as Eran Medan suggested, the typical programmer without xor knowledge could live better with a <code>!=</code> or <code>==</code> approach, see his starting post.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-06T00:44:08.780",
"Id": "30997",
"Score": "0",
"body": "Thanks, isn't it better to use `!=` instead of XOR? see http://stackoverflow.com/questions/160697/is-it-good-practice-to-use-the-xor-operator-in-java-for-boolean-checks. e.g. the first condition of the 2nd option is logically equivalent to if(isParameter1Valid == isParameter2Valid), or am I missing something? (if both are invalid or both are valid, throw the exception, else, e.g. if exactly one is valid, continue)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-06T15:40:48.797",
"Id": "31018",
"Score": "0",
"body": "Good point. For me, xor would be the cleaner way, because xor does exactly what i want in the way i want. For the `==` I had to think if it is correct or wrong. But I am perhaps not the typical one. So It could be a better approach to assume no knowledge about xor, then `==` or `!=` is the better way, I agree. I have edited my post, too"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T23:14:56.167",
"Id": "19348",
"ParentId": "19271",
"Score": "2"
}
},
{
"body": "<p>as you have only two tested parameters :</p>\n\n<pre><code>if (isParameter1Valid) {\n // do something with param1\n} else {\n // do something with param2\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-06T14:54:23.107",
"Id": "31016",
"Score": "0",
"body": "Thanks, yes, obviously, you are right, updated option 3. However some might say that having two explicit ifs is more readable, as the code above relies on the fact that `isParam1Valid!=isParam2Valid`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-07T07:31:07.223",
"Id": "31049",
"Score": "0",
"body": "@EranMedan You do not have to take care of others reading in the coding phasis, the code have to do obvious, clean, light for an expert (I cannot make better). But, if you think that some people are more easy with two if, you have to add comments for them, not complicate (or penalize) your code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-06T10:20:03.217",
"Id": "19354",
"ParentId": "19271",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "19273",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T19:46:01.750",
"Id": "19271",
"Score": "3",
"Tags": [
"java"
],
"Title": "Which one is more readable for mutually exclusive but mandatory command line parameters validation?"
}
|
19271
|
<p>I'm currently clearing my console window with this piece of code:</p>
<pre><code>void clrScr()
{
COORD cMap =
{
0, 3
};
if(!FillConsoleOutputAttribute(hCon, 0, 2030, cMap, &count))
{
std::cout << "Error clearing the console screen." << std::endl;
std::cout << "Error code: " << GetLastError() << std::endl;
std::cin.get();
}
}
</code></pre>
<p>, which I call once in the main loop.<br>
But since my window is quite large (70x35), it's flickering quite a bit.</p>
<p>I was wondering if there are any faster methods of doing this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T07:33:28.407",
"Id": "30882",
"Score": "2",
"body": "Have a look at ncurses for a platform neutral techniques for clearing a console window."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T09:57:06.080",
"Id": "30889",
"Score": "0",
"body": "Not really looking for a new lib. Thanks anyways."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T21:27:29.077",
"Id": "30987",
"Score": "3",
"body": "You should be looking for a new lib. You are using standard IO for stuff which it wasn't meant to be used for."
}
] |
[
{
"body": "<p>How about </p>\n\n<pre><code>system(\"cls\");\n</code></pre>\n\n<p>This clears the entire console nicely</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T02:21:13.090",
"Id": "30877",
"Score": "6",
"body": "That is actually WAY slower than my method. Also, system calls are supposedly very bad coding practice."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T02:11:20.053",
"Id": "19277",
"ParentId": "19274",
"Score": "-2"
}
},
{
"body": "<p>Have a look at <a href=\"http://www.cplusplus.com/forum/articles/10515/\" rel=\"nofollow\">Clear the Screen</a>. It basically boils down to using what you did (since the Windows console doesn't accept standard ansi sequences), although you might try the <code>conio.h</code> route.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T23:09:33.437",
"Id": "30995",
"Score": "0",
"body": "I can't use clrscr() for some reason. Probably something to do with the fact that it's non-standard. And pretty much the only other way (without using external libs) would be the way I'm doing it.. It seems there are no better ways of doing this, so I won't accept an answer, at least for now. If there are no better answers after a while, I'll accept yours."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T21:44:55.407",
"Id": "19344",
"ParentId": "19274",
"Score": "1"
}
},
{
"body": "<p>I decided that the best way to clear the screen - at least for a text-based game in console - is to clear literally only the individual squares that need to be cleared, instead of the whole window.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-06T07:13:01.897",
"Id": "31003",
"Score": "1",
"body": "Which is indeed almost the right and proper way to handle it in a game - if only you'd told us that :) But you could try overprinting with the new contents rather than clearing first."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-06T05:09:31.520",
"Id": "19351",
"ParentId": "19274",
"Score": "0"
}
},
{
"body": "<p>Here is an idea; ANSI escape codes work on Windows, Linux and OSX:</p>\n\n<pre><code>cout << \"\\033c\";\n</code></pre>\n\n<p><em><code>\\033</code></em> - stands for octal <kbd>ESC</kbd>,\n<em>c</em> - resets the device (terminal is default) to the initial state ( clear the screen,clear the buffer also so it is not possible to scroll, reset the fonts and so on).</p>\n\n<p>In some cases it may be more useful than well known which simply adds some empty lines and puts the cursor in the upper left corner:</p>\n\n<pre><code>cout << \"\\033[2J\\033[1;1H\"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-09T10:43:52.773",
"Id": "198137",
"ParentId": "19274",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "19351",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-12-03T22:52:02.830",
"Id": "19274",
"Score": "3",
"Tags": [
"c++",
"performance",
"console",
"windows"
],
"Title": "Clearing the screen using FillConsoleOutputAttribute()"
}
|
19274
|
<p>Everyone knows you can't put a <code>Derived</code> in an <code>std::vector<Base></code>. I decided to implement a collection which does allow you to do this:</p>
<pre><code>#pragma once
#include <boost/iterator/indirect_iterator.hpp>
#include <type_traits>
#include <vector>
template<typename T, std::size_t BLOCK_SIZE, std::size_t ALIGNMENT=alignof(T)>
class DerivedVector {
struct Block;
public:
using value_type = T;
using reference = T&;
using const_reference = T const&;
using pointer = T*;
using const_pointer = T const*;
private:
struct TypeInfo {
using deleter_t = void(*)(void*);
deleter_t deleter;
using mover_t = void(*)(Block&, void*);
mover_t mover;
};
template<typename D>
struct TypeInfoImpl {
static_assert(std::is_destructible<D>::value, "Derived class not destructible");
static_assert(std::is_move_constructible<D>::value, "Derived class not move-constructible");
static_assert(std::is_base_of<T, D>::value, "Class is not derived");
static_assert(sizeof(D) <= BLOCK_SIZE, "Derived class too big");
static_assert(ALIGNMENT % alignof(D) == 0, "Derived class has incompatible alignment");
static void deleter(void* p) {
static_cast<D*>(p)->~D();
}
static void mover(Block& p, void* o) {
new (p.data()) D(std::move(*static_cast<D*>(o)));
}
static TypeInfo* get() {
static TypeInfo info{deleter, mover};
return &info;
}
};
struct Block {
using element_type = T;
TypeInfo* info = nullptr;
typename std::aligned_storage<BLOCK_SIZE, ALIGNMENT>::type storage;
Block() = default;
template<typename D, typename CONDITION = typename std::enable_if<std::is_base_of<T, typename std::remove_reference<D>::type>::value>::type>
Block(D&& d) {
construct(std::forward<D>(d));
}
Block(Block&& b) : info(b.info) {
if (info)
info->mover(*this, b.data());
}
Block& operator=(Block&& b) {
if (this == &b)
return *this;
destroy();
info = b.info;
info->mover(*this, b.data());
return *this;
}
Block(Block const& b) = delete;
void operator=(Block const&) = delete;
template<typename D>
void construct(D&& d) {
using D_Val = typename std::remove_reference<D>::type;
static_assert(!std::is_same<D_Val, D>::value || std::is_copy_constructible<D_Val>::value,
"Derived class must be copy-constructible for this usage");
new (data()) D_Val(std::forward<D>(d));
info = TypeInfoImpl<D_Val>::get();
}
~Block() {
destroy();
}
void destroy() {
if (!info)
return;
auto deleter = info->deleter;
info = nullptr;
deleter(data());
}
const_reference operator*() const {
return *data();
}
reference operator*() {
return *data();
}
const_pointer operator->() const {
return data();
}
pointer operator->() {
return data();
}
const_pointer data() const {
return reinterpret_cast<const_pointer>(&storage);
}
pointer data() {
return reinterpret_cast<pointer>(&storage);
}
};
using container_type = std::vector<Block>;
container_type elements;
public:
using size_type = typename container_type::size_type;
using difference_type = typename container_type::difference_type;
using iterator = boost::indirect_iterator<typename container_type::iterator>;
using const_iterator = boost::indirect_iterator<typename container_type::const_iterator>;
DerivedVector() = default;
DerivedVector(DerivedVector&&) = default;
DerivedVector& operator=(DerivedVector&&) = default;
DerivedVector(DerivedVector const&) = delete;
void operator=(DerivedVector const&) = delete;
bool empty() const {
return elements.empty();
}
size_type size() const {
return elements.size();
}
size_type max_size() const {
return elements.max_size();
}
reference operator[](size_type i) {
return *elements[i];
}
const_reference operator[](size_type i) const {
return *elements[i];
}
const_iterator begin() const {
return elements.begin();
}
iterator begin() {
return elements.begin();
}
const_iterator cbegin() const {
return elements.cbegin();
}
const_iterator end() const {
return elements.end();
}
iterator end() {
return elements.end();
}
const_iterator cend() const {
return elements.cend();
}
template<typename D>
void push_back(D&& d) {
elements.emplace_back(std::forward<D>(d));
}
void pop_back() {
elements.pop_back();
}
template<typename D>
void reconstruct(size_type i, D&& d) {
elements[i].destroy();
elements[i].construct(std::forward<D>(d));
}
};
</code></pre>
<p>I'm looking for all-round feedback and criticism, suggestions for features, and any correctness concerns that may be present. Suggestions for an automatic way of determining <code>BLOCK_SIZE</code> and <code>ALIGNMENT</code> are also welcome. I'm also curious about what extra assertions I could be making to make the code fail in clearer ways when used with unreasonable <code>T</code>s and <code>D</code>s.</p>
<p><strong>EDIT</strong>: I found some significant bugs, so the code has been updated.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-07T14:37:43.210",
"Id": "31061",
"Score": "1",
"body": "Without having looked at the code in detail, could you please describe what advantage this solution has over just composing over a `std::vector<std::unique_ptr<Base>>` and exposing a value access interface? That would at the very least drastically reduce the code complexity."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-08T19:16:32.957",
"Id": "31095",
"Score": "0",
"body": "@KonradRudolph: I did it for the fun of it, but perhaps this could help with cache locality? Just taking a wild guess there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-09T14:59:29.060",
"Id": "31107",
"Score": "0",
"body": "It doesn’t help with cache locality – the vector of unique pointers is about as cache local as it gets. There’s an unrelated use-case where it *does* prove inconvenient: when you are using the same custom deleter for every object. Because then the vector of `unique_ptr` stores the custom deleter redundantly for every item in the vector, which is obviously a huge waste. But that’s not a concern here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-09T16:38:48.483",
"Id": "31110",
"Score": "1",
"body": "@KonradRudolph: Uhm, the objects themselves are nearly contiguous, unlike the way they'd be in the `unique_ptr` case, or am I missing something?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-23T15:49:52.323",
"Id": "62769",
"Score": "0",
"body": "If your objective is to implement it for fun, just ignore the rest of this message.\nIf your objective is to implement something you have not found anywhere, you might want to take a look to boost pointer container: http://www.boost.org/doc/libs/1_52_0/libs/ptr_container/doc/ptr_container.html For vectors: http://www.boost.org/doc/libs/1_52_0/libs/ptr_container/doc/ptr_vector.html Maybe you will be able to find good ideas to complete your library, too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-23T19:40:36.993",
"Id": "62770",
"Score": "0",
"body": "I'm aware of pointer vector, but it has somewhat different semantics; there's one more indirection, and it is focused around working with pointers."
}
] |
[
{
"body": "<p>Interesting.</p>\n\n<p>You should add <code>template <typename D, typename... Args> emplace_back(Args&&...)</code>.</p>\n\n<p>In terms of automatically determining blocksize, you can add a helper function like:</p>\n\n<pre><code>template <typename... Args>\nstd::size_t get_max_size() {\n return std::max({ sizeof(Args)... });\n}\n</code></pre>\n\n<p>Users can then list the derived classes they want to use and use that to compute the block size.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T04:07:25.670",
"Id": "28859",
"ParentId": "19275",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T23:12:15.817",
"Id": "19275",
"Score": "8",
"Tags": [
"c++",
"c++11",
"vectors",
"assertions"
],
"Title": "Vector of derived classes"
}
|
19275
|
<p>I have verified that both of my following functions successfully find prime numbers. I was pretty sure the function called <code>is_prime_new</code> would be faster than <code>is_prime_old</code>; however, after benchmarking (mainly consisting of generating huge lists of primes), I found this to be significantly false and I'm wondering why this may be.</p>
<p>I had two main reasons for thinking that <code>is_prime_new</code> would be a better algorithm than its counterpart:</p>
<ul>
<li><p><code>is_prime_new</code> does more checks for non-primailty early, thus eliminating numbers before iteration</p></li>
<li><p>It iterates in steps of 6, whereas its counterpart iterates in steps of 2, both to the same value <code>sqrt(n)+1</code></p></li>
</ul>
<p>Could anyone explain to me why the newer function is less optimized, and possibly debunk my above assumptions? Thank you.</p>
<pre><code>def is_prime_new(n):
if n < 2: return False
if n == 2 or n == 3: return True
if n%2 == 0 or n%3 == 0: return False
sqr = math.sqrt(n)
if sqr == int(sqr): return False
i = 1
while i*6 < sqr+1:
if n % (i*6-1) == 0 or n % (i*6+1) == 0: return False
i += 1
return True
def is_prime_old(n):
if n < 2: return False
if n == 2: return True
if n%2 == 0: return False
for i in xrange(3, int(math.sqrt(n)+1), 2):
if not n%i: return False
return True
</code></pre>
|
[] |
[
{
"body": "<p>can you test the following (slightly optimized) version?</p>\n\n<pre><code>def is_prime_new(n):\n if n < 2: return False\n if n == 2 or n == 3: return True\n if n%2 == 0 or n%3 == 0: return False\n sqr = math.sqrt(n)\n if sqr == int(sqr): return False\n sqr = int(sqr) + 1\n\n i = 6\n while i < sqr:\n if n % (i-1) == 0 or n % (i+1) == 0: return False\n i += 6\n\n return True\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T19:15:11.310",
"Id": "30971",
"Score": "0",
"body": "@almaz, Thank you. These suggestions did speed up my new function, but the old one is still faster! And my question (in its two parts) was \"why is the old one faster?\", \"and are my 2 assumptions invalid?\" Do you have anything to say about either of these questions?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T19:27:25.943",
"Id": "30974",
"Score": "0",
"body": "Please post the test code you're running"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T21:32:44.107",
"Id": "30988",
"Score": "0",
"body": "You didn't post how you measure performance, so the first thing I assumed was that you introduced unnecessary calculations, so I suggested you the variant where these calculations were stripped"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T08:53:57.803",
"Id": "19280",
"ParentId": "19278",
"Score": "2"
}
},
{
"body": "<p>The statement 'does more checks for non-primailty early, thus eliminating numbers before iteration' bears looking at. You only eliminate numbers on your list early if they were on the list. So if you test set has range(1,100), the statement </p>\n\n<blockquote>\n <p>if n < 2: return False</p>\n</blockquote>\n\n<p>only saves time on two numbers and costs time on 98 of them. Similarly</p>\n\n<blockquote>\n <p>if n == 2 or n == 3: return True</p>\n</blockquote>\n\n<p>However </p>\n\n<blockquote>\n <p>if n%2 == 0 or n%3 == 0: return False</p>\n</blockquote>\n\n<p>saves time on 50 and 33 respectively - albeit at a cost for 50 and 67 respectively. But if you only test with odd numbers that aren't divisible by 3 (eg a list you already know are primes), then it saves you nothing.</p>\n\n<p>The performance test is dependent on your test input so be careful both in choosing the test input and in optimizing for that particular set of data (ie optimize to real world use, not a constrained set of test data).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T12:35:25.920",
"Id": "19284",
"ParentId": "19278",
"Score": "0"
}
},
{
"body": "<p>Duncan's explanation is incorrect. This isn't my best piece of writing - bear with me.</p>\n\n<hr>\n\n<p>First lets deal with <code>n < 2</code> and <code>n == 2 or n == 3</code>:</p>\n\n<p>It is true that they let a lot more input go past them than they stop. But they don't account for the difference in time.</p>\n\n<ol>\n<li>Even the <code>old</code> definition has <code>n < 2</code> and <code>n == 2</code>.</li>\n<li>The time spent on this part of the function is very insignificant compared to that spent in the rest of the function.</li>\n</ol>\n\n<hr>\n\n<p>Next <code>n%2 == 0 or n%3 == 0</code>:</p>\n\n<ol>\n<li>Again <code>n%2 == 0</code> is in the <code>old</code> definition also.</li>\n<li><code>n%3 == 0</code> is the first check in <code>old</code>'s for loop</li>\n<li>The time spent on this part of the function is also insignificant compared to that spent in the rest of the function.</li>\n</ol>\n\n<p>I could've clubbed this with the previous section but didn't for the following reason:</p>\n\n<p>These checks work on 4 out of every 6 input numbers. And 4 > 6-4. But is that the way to look at it? If say they'd worked on 3/6 [As in the case of <code>old</code>] are these checks useless? If say they'd worked on 2/6 should they be avoided? No.</p>\n\n<p>By doing one(or two) comparison(s) on 6 inputs, they stop 2 from reaching the <em>work horse</em> of the code - the loop - that does most of the work. That's not to be avoided!</p>\n\n<p>Also, by imposing additional constraints on the input that reaches the loop, the loop itself has been made faster! Knowing that no multiple of 3 enters the loop, you don't test divisibility of n by any other multiple of 3. Don't forget your main idea behind moving from <code>old</code> to <code>new</code>!</p>\n\n<p>Faster loop + lesser numbers reaching loop should make <code>new</code> faster than <code>old</code>.</p>\n\n<hr>\n\n<p>How much faster exactly?</p>\n\n<ol>\n<li><p>I mentioned \"lesser numbers reaching loop\" being good only as a general guideline. It doesn't help much here because : In <code>old</code> 3,5,7,9... enter the loop, and in <code>new</code> 5,7,11,13... enter the loop. But in <code>old</code> 3,9... get stopped at the first check of the for loop. So only <em>faster loop</em> is important.</p></li>\n<li><p><code>new</code>'s loop jumps in steps of 6 but <code>old</code>'s jumps in steps of 2. So is <code>new</code> 3 times faster than old? No. At every step <code>new</code> does 3 comparisons - one for the <code>while</code> loop condition and two inside the loop. <code>old</code> does 2 - one at <code>for</code> loop condition and one inside the loop. So, <code>new</code> is (6/3) * (2/2) = 2 times faster than <code>old</code>.</p></li>\n</ol>\n\n<hr>\n\n<p>So far I've only been explaining why <code>new</code> should be faster. Finally I'll address your question of why this isn't observed:</p>\n\n<p><code>for</code> loops are much faster than <code>while</code> loops. python doesn't know how <code>i</code> is going to change inside <code>while</code>. So the <code>while</code> loop's condition check is like any other comparison. On the other hand <code>for</code> loop's condition check is highly optimised. Henceforth lets assume that <code>for</code> loop's condition check doesn't count as a comparison.</p>\n\n<p>Then <code>old</code>'s time/<code>new</code>'s time will be</p>\n\n<ol>\n<li>6/3 * 2/2 = 2 if both use <code>while</code></li>\n<li>6/2 * 1/2 = 1.5 if both use <code>for</code></li>\n<li>6/2 * 2/2 = 3 if <code>old</code> used <code>while</code> and <code>new</code> used for</li>\n<li>6/3 * 1/2 = 1 if <code>old</code> used <code>for</code> and <code>new</code> used while</li>\n</ol>\n\n<hr>\n\n<p>That still means that <code>old</code> and <code>new</code> should be (at least approximately) equally fast. This is where I was stumped. I had to resort to experimenting to figure this out. The reasons for this not occurring, as it turns out, are</p>\n\n<ol>\n<li>All the unnecessary arithmetic (*6) in the while loop</li>\n<li><code>while i*6 < sqr+1:</code> Here sqrt is a floating point number. As it turns out float comparison is costlier than int comparison. <code>while i*6 < int(sqr+1)</code> isn't good either. You should use <code>sqrp1 = int(sqr+1); while i*6 < sqrp1</code></li>\n</ol>\n\n<hr>\n\n<p>Note that the ratios provided are from rough calculations and far from being accurate - there are so many more things to consider. One major assumption is that time spent in the loops is much larger than time spent at base case checks - not true if all your input are multiples of 2.</p>\n\n<hr>\n\n<p>To summarise, the reasons for <code>new</code> being slower, despite being expected to be faster, are:</p>\n\n<ol>\n<li>Usage of <code>while</code> instead of <code>for</code> (this is not as important as the other two)</li>\n<li>Unnecessary arithmetic inside <code>while</code></li>\n<li>Usage of float comparison instead of int comparison in <code>while</code> condition check.</li>\n</ol>\n\n<p>The code given below illustrates some of the points made here.</p>\n\n<pre><code>import math, timeit\n\ndef is_prime_new_slowest(n):\n if n < 2: return False\n if n == 2 or n == 3: return True\n if n%2 == 0 or n%3 == 0: return False\n sqr = math.sqrt(n) #This is insignificant as it is outside the loop\n if sqr == int(sqr): return False\n sqrtp1 = sqr + 1 #Note that sqrtp1 is a float\n i = 1\n while i*6 < sqrtp1: # Comparison of floats adds some time\n if n % (i*6-1) == 0 or n % (i*6+1) == 0: return False #Unnecessary arithmetic\n i += 1\n return True\n\ndef is_prime_new_slow(n):\n if n < 2: return False\n if n == 2 or n == 3: return True\n if n%2 == 0 or n%3 == 0: return False\n sqrtp1 = int(math.sqrt(n) + 1)\n i = 6\n while i < sqrtp1:\n if n % (i-1) == 0 or n % (i+1) == 0: return False\n i += 6\n return True\n\ndef is_prime_new_fast(n):\n if n < 2: return False\n if n == 2 or n == 3: return True\n if n%2 == 0 or n%3 == 0: return False\n sqrtp1 = int(math.sqrt(n)+1)\n for i in xrange(6, sqrtp1, 6):\n if n % (i-1) == 0 or n % (i+1) == 0: return False\n return True\n\ndef is_prime_old_slow(n):\n if n < 2: return False\n if n == 2: return True\n if n%2 == 0: return False\n sqrtp1 = int(math.sqrt(n) + 1)\n i = 3\n while i < sqrtp1:\n if not n%i: return False\n i += 2\n return True\n\ndef is_prime_old_fast(n):\n if n < 2: return False\n if n == 2: return True\n if n%2 == 0: return False\n sqrtp1 = int(math.sqrt(n)+1)\n for i in xrange(3, sqrtp1, 2):\n if not n%i: return False\n return True\n\ndef sundaram3(max_n):\n numbers = range(3, max_n+1, 2)\n half = (max_n)//2\n initial = 4\n for step in xrange(3, max_n+1, 2):\n for i in xrange(initial, half, step):\n numbers[i-1] = 0\n initial += 2*(step+1)\n if initial > half:\n return [2] + filter(None, numbers)\n\ni = sundaram3(10**6)[-1]\n\nprint \"Input: largest prime less than 10^6, No. of runs: 25000\"\nprint \"new slowest:\", timeit.timeit('is_prime_new_slowest(i)', setup=\"from __main__ import is_prime_new_slowest, i; import math\", number=25000)\nprint \"new slow:\", timeit.timeit('is_prime_new_slow(i)', setup=\"from __main__ import is_prime_new_slow, i; import math\", number=25000)\nprint \"new fast:\", timeit.timeit('is_prime_new_fast(i)', setup=\"from __main__ import is_prime_new_fast, i; import math\", number=25000)\nprint \"old slow:\", timeit.timeit('is_prime_old_slow(i)', setup=\"from __main__ import is_prime_old_slow, i; import math\", number=25000)\nprint \"old fast:\", timeit.timeit('is_prime_old_fast(i)', setup=\"from __main__ import is_prime_old_fast, i; import math\", number=25000)\n\nprint \"\\nInput: range(1000000), No. of runs = 1\"\nprint \"new slowest:\", timeit.timeit('for i in xrange(1000000): is_prime_new_slowest(i)', setup=\"from __main__ import is_prime_new_slowest; import math\", number=1)\nprint \"new slow:\", timeit.timeit('for i in xrange(1000000): is_prime_new_slow(i)', setup=\"from __main__ import is_prime_new_slow; import math\", number=1)\nprint \"new fast:\", timeit.timeit('for i in xrange(1000000): is_prime_new_fast(i)', setup=\"from __main__ import is_prime_new_fast; import math\", number=1)\nprint \"old slow:\", timeit.timeit('for i in xrange(1000000): is_prime_old_slow(i)', setup=\"from __main__ import is_prime_old_slow; import math\", number=1)\nprint \"old fast:\", timeit.timeit('for i in xrange(1000000): is_prime_old_fast(i)', setup=\"from __main__ import is_prime_old_fast; import math\", number=1)\n</code></pre>\n\n<p>Output on my machine:</p>\n\n<pre><code>Input: largest prime less than 10^6, No. of runs = 25000\nnew slowest: 7.37190294266\nnew slow: 4.19636297226\nnew fast: 3.49502682686\nold slow: 6.08556985855\nold fast: 4.03657603264\n\nInput: range(1000000), No. of runs = 1\nnew slowest: 21.5607540607\nnew slow: 13.8396618366\nnew fast: 12.3734707832\nold slow: 20.0376861095\nold fast: 14.1358599663\n</code></pre>\n\n<hr>\n\n<p>Note that <code>for</code> - <code>while</code> deterioration becomes less important as the number of comparisons inside the loop reduces [<code>old</code> - one comparison - time goes from 14 to 20, <code>new</code> - two comparisons - 12.3 to 13.83]. This is expected because 1 comparison becoming 2 has a greater effect on final time than 10 comparisons becoming 11. This is why <code>while</code>-<code>for</code> performance difference generally doesn't matter in real life.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-12T21:12:50.497",
"Id": "19557",
"ParentId": "19278",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "19557",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T05:23:42.470",
"Id": "19278",
"Score": "3",
"Tags": [
"python",
"optimization",
"algorithm",
"primes"
],
"Title": "Naive prime finder, unexpected behavior in Python"
}
|
19278
|
<p>I am wondering am I doing the right "Drupal" way in getting formatted value of node's body field. Here is my code:</p>
<pre><code>$field = field_get_items('node', $node, 'body');
$body = '';
if (isset($field[0]['value'])) {
$body = check_markup($field[0]['value'], $field[0]['format']);
}
</code></pre>
|
[] |
[
{
"body": "<p>The API has the <a href=\"http://api.drupal.org/api/drupal/modules!field!field.module/function/field_view_value/7\" rel=\"nofollow\"><code>field_view_value()</code></a> function which essentially does the same thing as your code, except it applies all of the field/instance settings to the value so you won't need to make changes to your code if you change a field setting.</p>\n\n<p>You can use it like this:</p>\n\n<pre><code>$field = field_get_items('node', $node, 'body');\n\n$body = '';\nif (isset($field[0]['value'])) {\n $body = field_view_value('node', $node, 'body', $field[0]);\n}\n</code></pre>\n\n<p>Just in case you want the default HTML wrappers included with the field output, you can use <a href=\"http://api.drupal.org/api/drupal/modules%21field%21field.module/function/field_view_field/7\" rel=\"nofollow\"><code>field_view_field()</code></a> instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T00:43:12.490",
"Id": "19317",
"ParentId": "19282",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "19317",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T09:55:59.903",
"Id": "19282",
"Score": "2",
"Tags": [
"php",
"drupal"
],
"Title": "The right way to get formatted node's body field in Drupal 7"
}
|
19282
|
<p>I have the following in the header.php file which is included in all of my views:</p>
<pre><code>$dh = opendir(Vs.get_class($this).'/js') ;
while($script = readdir($dh)) {
if(!is_dir($script))
{
echo '<script type="text/javascript" src="js/'.$script.'"></script>' ;
}
}
$dh = opendir(Vs.get_class($this).'/css') ;
while($css = readdir($dh)) {
if(!is_dir($css))
{
echo '<link type="text/css" href="css/'.$css.'" rel="stylesheet"/>' ;
}
}
</code></pre>
<p>It's purpose is to autoload all the CSS and JS files for a particular view (which has the same name as the controller, hence <code>get_class</code>).</p>
<p>Should all this be a part of the associated controller or is how I have done it fine?</p>
|
[] |
[
{
"body": "<ol>\n<li><p>The way you are scanning the directory is going to get all files. If this is intentional thats cool, but if you are really just looking\nfor js & css files, use glob and scan for them directly. This will be much better in performance, and you can avoid the directory check.</p></li>\n<li><p>It seems like its a brittle idea to have the paths mapped to a specific class name. There has to be an easier way to associate views\nand view resources rather than referencing $this.</p></li>\n<li><p>This does not belong in the controller unless you are assigning the view data there. In frameworks like Zend, there are action helpers\nwhich take care of this for you. If you don't have access to that, create a base controller class and do a magic helper method to keep the\nfunctionality the same across all pages. This will allow you to maintain this functionality closer, and you can still use the <code>$this</code> if needed.</p></li>\n<li><p>Is this really a good idea to just scan a directory and include all files? What happens if a new developer comes along and dumps a <code>js</code> file\nthey were testing something in, in the directory and it got included by accident? If there are very few includes, try to just manually put them in;\neither through a layout or just hardcoding them in there. If you really have that much <code>js</code> and <code>css</code> being included in.... maybe there is a more\nfundamental problem.</p></li>\n</ol>\n\n<p>Better Scandir w/ Glob:</p>\n\n<pre><code>$jsGlob = Vs.get_class($this).'/js/*.js';\nforeach (glob($jsGlob) as $js)\n{\n echo '<script type=\"text/javascript\" src=\"$js\"></script>' ;\n}\n\n$cssGlob = Vs.get_class($this).'/css/*.css';\nforeach (glob($cssGlob) as $css)\n{\n echo '<link type=\"text/css\" href=\"$css\" rel=\"stylesheet\"/>' ;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T17:38:58.460",
"Id": "19302",
"ParentId": "19283",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T11:42:36.583",
"Id": "19283",
"Score": "2",
"Tags": [
"php",
"object-oriented",
"mvc"
],
"Title": "File loop and logic in controller of view header"
}
|
19283
|
<p>I have an <code>IWorkflow</code> interface defined as follows:</p>
<pre><code>public interface IWorkflow
{
Task ConfigureAsync();
Task StartAsync();
Task StopAsync();
}
</code></pre>
<p>And I have an <code>Engine</code> class:</p>
<pre><code>public sealed class Engine : IEngine
{
private readonly List<IWorkflow> workflows = new List<IWorkflow>();
public Engine(IEnumerable<IWorkflow> workflows)
{
this.workflows.AddRange(workflows);
}
public void Start()
{
var configureTasks = this.workflows.Select(w => w.ConfigureAsync()).ToArray();
Task.WaitAll(configureTasks);
var startTasks = this.workflows.Select(w => w.StartAsync()).ToArray();
Task.WaitAll(startTasks);
}
public void Stop()
{
var stopTasks = this.workflows.Select(w => w.StopAsync()).ToArray();
Task.WaitAll(stopTasks);
}
}
</code></pre>
<p>Is this the correct way for the <code>Engine</code> to invoke in parallel the configure method on all workflows and then once all are completed, invoke in parallel the start method on all workflows?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T20:06:12.693",
"Id": "30908",
"Score": "0",
"body": "Is there any reason why `Engine` isn't also asynchronous?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T08:53:13.800",
"Id": "30923",
"Score": "0",
"body": "I don't see a need for it to be as there is only one `Engine` and it starts on the app thread. I'm updating an old .NET 2.0 app so I'm just getting to grips with Tasks and async/await & wanted to confirm I was using it in the correct way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T08:55:42.573",
"Id": "30924",
"Score": "0",
"body": "If you mean it's a GUI app, then I think not locking up the GUI while the engine starts or stops is a good reason for that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T09:06:09.380",
"Id": "30925",
"Score": "0",
"body": "It's a console app running in TopShelf"
}
] |
[
{
"body": "<p>Your code is absolutely correct in case when you want to start workflows only when all of them are configured.</p>\n\n<p>But if you want to start each workflow once it's configured (independently from other workflows) then it might be a good idea to use continuations... In .NET 4.5 it would look like this:</p>\n\n<pre><code>public sealed class Engine : IEngine\n{\n private readonly List<IWorkflow> _workflows;\n\n public Engine(IEnumerable<IWorkflow> workflows)\n {\n _workflows = new List<IWorkflow>(workflows);\n }\n\n private async Task RunWorkflow(IWorkflow workflow)\n {\n await workflow.ConfigureAsync();\n await workflow.StartAsync();\n }\n\n public void Start()\n {\n var startTasks = this._workflows.Select(RunWorkflow).ToArray();\n Task.WaitAll(startTasks);\n }\n\n public void Stop()\n {\n var stopTasks = _workflows.Select(w => w.StopAsync()).ToArray();\n Task.WaitAll(stopTasks);\n }\n}\n</code></pre>\n\n<p>Also I would suggest to use <a href=\"http://msdn.microsoft.com/en-us/library/dd997364.aspx\" rel=\"noreferrer\">CancellationToken</a> to stop asynchronous processing.</p>\n\n<p><strong>UPDATE</strong> Based on comments it is really needed to wait for all workflows to be configured before starting them. So cancellable implementation can look like this:</p>\n\n<pre><code>public interface IWorkflow\n{\n Task ConfigureAsync(CancellationToken token);\n Task StartAsync(CancellationToken token);\n}\n\npublic sealed class Engine : IEngine\n{\n private readonly List<IWorkflow> _workflows;\n private readonly CancellationTokenSource _cancellationTokenSource;\n private Task _mainTask;\n\n public Engine(IEnumerable<IWorkflow> workflows)\n {\n _workflows = new List<IWorkflow>(workflows);\n _cancellationTokenSource = new CancellationTokenSource();\n }\n\n private async Task RunWorkflows()\n {\n await Task.WhenAll(_workflows.Select(w => w.ConfigureAsync(_cancellationTokenSource.Token)));\n if (_cancellationTokenSource.IsCancellationRequested)\n return;\n await Task.WhenAll(_workflows.Select(w => w.StartAsync(_cancellationTokenSource.Token)));\n }\n\n public void Start()\n {\n _mainTask = RunWorkflows();\n _mainTask.Wait();\n }\n\n public void Stop()\n {\n _cancellationTokenSource.Cancel();\n var mainTask = _mainTask;\n if (mainTask != null)\n mainTask.Wait();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T16:00:17.663",
"Id": "30893",
"Score": "0",
"body": "The idea as it stands is to start quickly but only if all workflows configure successfully."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T16:22:53.173",
"Id": "30898",
"Score": "0",
"body": "Then your solution is correct. Take into account that Engine.Start method will finish only all workflows are configured and started."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T20:09:28.517",
"Id": "30909",
"Score": "0",
"body": "I think your suggestion to use `CancellationToken` is not right. Cancellation is something exceptional (and `await`ing a canceled `Task` throws an exception). Stopping some long-running process is not exceptional."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T20:47:13.453",
"Id": "30911",
"Score": "0",
"body": "@svick CancellationToken is a recommended way to stop asynchronous processing, it **does not** throw exceptions and is not something exceptional. You probably confuse it with `Thread.Abort`, `CancellationToken.ThrowIfCancellationRequested` or `Task.Wait(CancellationToken)` which do throw exceptions. See the link I've included in my post for example of usage."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T22:55:43.507",
"Id": "30913",
"Score": "1",
"body": "But `ThrowIfCancellationRequested()` is the recommended way of using `CancellationToken`, AFAIK. Also, `Task` has a special status `Canceled` and when you `Wait()` or `await` such `Task`, it will throw an exception."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T10:39:46.293",
"Id": "30927",
"Score": "0",
"body": "@svick If you _can_ throw exception doesn't mean you _should_ :). `OperationCanceledException` should be thrown if you want to notify the `await`'er that operation didn't complete, e.g. if order was not posted. But if logically it's ok to stop processing (e.g. you're calculating PI and once you detect that cancellation was requested you just return current approximation of PI with precision) then you don't need to throw exception, you just finish the task, and status would be `RanToCompletion`. See [Task Cancellation](http://msdn.microsoft.com/en-us/library/dd997396.aspx) for more details"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T14:29:53.537",
"Id": "30947",
"Score": "0",
"body": "I don't think the cancellation would actually work in your example as the `Start` method is blocking so you can't actually stop it and cancel until it's all started which unless I'm missing something means there isn't a task to actually cancel."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T15:44:47.560",
"Id": "30951",
"Score": "0",
"body": "Implementation corresponds to your logic (`Engine.Start` method is also blocking in your code). `_mainTask` will get a Task object assigned as soon as all workflows return their tasks via `IWorkflow.ConfigureAsync`, that is very early. Once the `Stop` method is called we notify everyone that operation should be cancelled, and also waits on `_mainTask` as it will signal when all workflows noticed the cancellation. One thing we can actually add to protect us from incorrectly written workflows is not to call `StartAsync` if cancellation is already requested"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T15:59:04.787",
"Id": "30954",
"Score": "0",
"body": "What I mean, is because your `Start` method doesn't return until `_mainTask` has completed at which point all configuration and start tasks will also be completed. So it's not possible to call the Stop method and therefore request cancellation while any tasks are actually still running."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T16:06:57.103",
"Id": "30955",
"Score": "0",
"body": "How do you call `Stop` in your sample where `Start` method also blocks until all configuration and start tasks completed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T16:25:07.600",
"Id": "30956",
"Score": "0",
"body": "I don't the `Engine` runs as a windows service which is hosted in `TopShelf`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T17:08:06.787",
"Id": "30961",
"Score": "0",
"body": "So the same would be with my example: `Start` blocks until all workflows are configured and started, if someone calls `Stop` all workflows that are asynchronously running in `ConfigureAsync` or `StartAsync` will be notified (they should periodically observe the `CancellationToken` status or use other options like `CancellationToken.Register` to be notified) and thus should stop their work. Please read the manual on cancelling tasks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T17:39:03.080",
"Id": "30965",
"Score": "0",
"body": "You're missing the point, the tasks which are used in `Configure` and `Start` are run to completion however long that takes because the `Start` method doesn't return until the tasks have all completed. This means that they cannot be cancelled by the `Stop` method as the `Stop` method cannot be called until the tasks have all completed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-05T18:30:11.527",
"Id": "30968",
"Score": "0",
"body": "I'm afraid you're missing the point :). the `_mainTask` represents all the required work of configuring, starting tasks and waiting for their completion. It is initialized immediately without any waiting. `CancellationTokenSource` is also available immediately. Whoever calls `Stop` will be able to notify everyone to stop the processing. If your code runs in a single thread and thus can't call `Stop` because it's waiting for `Start` to finish - the same issue stands in original code. It can be easily avoided but you didn't specify this as an issue in your question"
}
],
"meta_data": {
"CommentCount": "14",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T13:07:49.593",
"Id": "19289",
"ParentId": "19285",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "19289",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T12:50:12.883",
"Id": "19285",
"Score": "10",
"Tags": [
"c#",
"multithreading",
"asynchronous",
"task-parallel-library"
],
"Title": "Correct approach to wait for multiple async methods to complete"
}
|
19285
|
The Task Parallel Library is part of .NET 4 and .NET 4.5. It is a set of APIs to enable developers to program asynchronous applications.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-04T12:50:44.553",
"Id": "19287",
"Score": "0",
"Tags": null,
"Title": null
}
|
19287
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.