body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I want to create pair, where <code>new UnorderedPair(ObjA, ObjB) == UnorderedPair(ObjB, ObjA)</code> returns <code>true</code>. I also want to avoid any (un)boxing.</p>
<p>Have I gone about this in the correct way?</p>
<pre><code>public struct UnorderedPair<T> : IEquatable<UnorderedPair<T>>
{
public T A;
public T B;
public UnorderedPair(T a, T b)
{
A = a;
B = b;
}
public override int GetHashCode()
{
return A.GetHashCode() ^ B.GetHashCode();
}
public bool Equals(UnorderedPair<T> other)
{
return (other.A.Equals(A) && other.B.Equals(B)) ||
(other.A.Equals(B) && other.B.Equals(A));
}
public override bool Equals(object obj)
{
return Equals((UnorderedPair<T>)obj);
}
public static bool operator ==(UnorderedPair<T> a, UnorderedPair<T> b)
{
return a.Equals(b);
}
public static bool operator !=(UnorderedPair<T> a, UnorderedPair<T> b)
{
return !(a == b);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>One thing: I would make the <code>struct</code> <a href=\"https://stackoverflow.com/questions/3751911/why-are-c-sharp-structs-immutable/3753640#3753640\">immutable</a> since mutable <code>struct</code>s <a href=\"https://stackoverflow.com/questions/441309/why-are-mutable-structs-evil\">have</a> <a href=\"https://docs.microsoft.com/en-us/archive/blogs/ericlippert/\" rel=\"nofollow noreferrer\">really</a> <a href=\"https://docs.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-one-kinds-of-immutability\" rel=\"nofollow noreferrer\">bad</a> <a href=\"https://social.msdn.microsoft.com/Forums/en-US/ab026c2a-21cd-4c30-b7b1-88b07493172d/immutable-structs?forum=csharplanguage\" rel=\"nofollow noreferrer\">unintended</a> <a href=\"http://geekswithblogs.net/blomqvist/archive/2009/06/15/struct-vs-class-and-immutability.aspx\" rel=\"nofollow noreferrer\">effects</a>. Otherwise, this is a good, solid implementation.</p>\n<pre><code>public struct UnorderedPair<T> : IEquatable<UnorderedPair<T>>\n{\n private readonly T a;\n\n private readonly T b;\n\n public UnorderedPair(T a, T b)\n {\n this.a = a;\n this.b = b;\n }\n\n public T A\n {\n get\n {\n return this.a;\n }\n }\n\n public T B\n {\n get\n {\n return this.b;\n }\n }\n\n public override int GetHashCode()\n {\n return this.a.GetHashCode() ^ this.b.GetHashCode();\n }\n\n public bool Equals(UnorderedPair<T> other)\n {\n return (other.A.Equals(this.a) && other.B.Equals(this.b)) ||\n (other.A.Equals(this.b) && other.B.Equals(this.a));\n }\n\n public override bool Equals(object obj)\n {\n return this.Equals((UnorderedPair<T>)obj);\n }\n\n public static bool operator ==(UnorderedPair<T> a, UnorderedPair<T> b)\n {\n return a.Equals(b);\n }\n\n public static bool operator !=(UnorderedPair<T> a, UnorderedPair<T> b)\n {\n return !(a == b);\n }\n}\n</code></pre>\n<p>and because time marches on, here's a more compact and performant C# 7.2 version:</p>\n<pre><code>public readonly struct UnorderedPair<T> : IEquatable<UnorderedPair<T>>\n{\n public UnorderedPair(in T a, in T b) => (this.A, this.B) = (a, b);\n\n public T A { get; }\n\n public T B { get; }\n\n public override int GetHashCode() => this.A.GetHashCode() ^ this.B.GetHashCode();\n\n public bool Equals(UnorderedPair<T> other) => (other.A.Equals(this.A) && other.B.Equals(this.B))\n || (other.A.Equals(this.B) && other.B.Equals(this.A));\n\n public override bool Equals(object obj) => this.Equals((UnorderedPair<T>)obj);\n\n public static bool operator ==(in UnorderedPair<T> a, in UnorderedPair<T> b) => a.Equals(b);\n\n public static bool operator !=(in UnorderedPair<T> a, in UnorderedPair<T> b) => !(a == b);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T23:18:27.370",
"Id": "13720",
"Score": "0",
"body": "Just a question. Is there any reason you would use a readonly private variable a and b over just having a private set accessor on the public A and B objects?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T23:22:27.300",
"Id": "13721",
"Score": "1",
"body": "`readonly` does not allow any other methods or properties to modify those variables. a `private set` accessor would allow other methods/properties in the class to modify them. I prefer `readonly` to signify intent - once they're set in the constructor, they're off-limits to anything else."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T00:10:28.703",
"Id": "13722",
"Score": "0",
"body": "Thanks for explaining that. Guess I hadn't thought it all the way through."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-02-02T14:45:54.853",
"Id": "8588",
"ParentId": "8587",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "8588",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-02T14:24:36.280",
"Id": "8587",
"Score": "3",
"Tags": [
"c#"
],
"Title": "Is this an ok implementation of an UnorderedPair?"
}
|
8587
|
<p>I often need to parse tab-separated text (usually from a huge file) into records. I wrote a generator to do that for me; is there anything that could be improved in it, in terms of performance, extensibility or generality? </p>
<pre><code>def table_parser(in_stream, types = None, sep = '\t', endl = '\n', comment = None):
header = next(in_stream).rstrip(endl).split(sep)
for lineno, line in enumerate(in_stream):
if line == endl:
continue # ignore blank lines
if line[0] == comment:
continue # ignore comments
fields = line.rstrip(endl).split(sep)
try:
# could have done this outside the loop instead:
# if types is None: types = {c : (lambda x : x) for c in headers}
# but it nearly doubles the run-time if types actually is None
if types is None:
record = {col : fields[no] for no, col in enumerate(header)}
else:
record = {col : types[col](fields[no]) for no, col in enumerate(header)}
except IndexError:
print('Insufficient columns in line #{}:\n{}'.format(lineno, line))
raise
yield record
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-02T09:56:42.030",
"Id": "13425",
"Score": "0",
"body": "@RikPoggi: I asked moderator to move it there. Thank you"
}
] |
[
{
"body": "<p>One thing you could try to reduce the amount of code in the loop is to make a function expression for these.</p>\n\n<pre><code> if types is None:\n record = {col : fields[no] for no, col in enumerate(header)}\n else:\n record = {col : types[col](fields[no]) for no, col in enumerate(header)}\n</code></pre>\n\n<p>something like this: <em>not tested but you should get the idea</em></p>\n\n<pre><code>def table_parser(in_stream, types = None, sep = '\\t', endl = '\\n', comment = None):\n header = next(in_stream).rstrip(endl).split(sep)\n enumheader=enumerate(header) #### No need to do this every time\n if types is None:\n def recorder(col,fields): \n return {col : fields[no] for no, col in enumheader}\n else:\n def recorder(col,fields): \n return {col : types[col](fields[no]) for no, col in enumheader}\n\n for lineno, line in enumerate(in_stream):\n if line == endl:\n continue # ignore blank lines\n if line[0] == comment:\n continue # ignore comments\n fields = line.rstrip(endl).split(sep)\n try:\n record = recorder(col,fields)\n except IndexError:\n print('Insufficient columns in line #{}:\\n{}'.format(lineno, line))\n raise\n yield record\n</code></pre>\n\n<p>EDIT: from my first version (read comments)</p>\n\n<pre><code>Tiny thing:\n\n if types is None:\n\nI suggest\n\n if not types:\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-02T09:48:43.397",
"Id": "13426",
"Score": "0",
"body": "In many cases I think `if types is None` would be preferable. I think I see why you disagree in this case, but I'm curious... could you say more?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-02T09:57:12.773",
"Id": "13427",
"Score": "0",
"body": "Generally do not test types if it's not clear that it's required. (duck type). In this case I can't come up with a specific benefit, some other type evaluated to false in a boolean context?\nAlso `is` is testing the identity and would be false even if the other None type was identical to None. Completely academic, yes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-02T10:03:06.797",
"Id": "13428",
"Score": "2",
"body": "Well, [PEP 8](http://www.python.org/dev/peps/pep-0008/) says \"Comparisons to singletons like None should always be done with 'is' or 'is not', never the equality operators.\" In this particular case, using `is` makes it possible to distinguish between cases where `[]` was passed and cases where no variable was passed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-02T10:08:51.010",
"Id": "13429",
"Score": "0",
"body": "All right that makes sense. From your link: A Foolish Consistency is the Hobgoblin of Little Minds"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-02T09:44:19.277",
"Id": "8590",
"ParentId": "8589",
"Score": "1"
}
},
{
"body": "<p>You also may use csv module to iterate over your file. Your code would be faster because of C implementation and cleaner without <code>line.rstrip(endl).split(sep)</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-02T19:06:04.593",
"Id": "8605",
"ParentId": "8589",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "8590",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-02T09:40:15.453",
"Id": "8589",
"Score": "3",
"Tags": [
"python",
"performance",
"parsing",
"generator"
],
"Title": "Text parser implemented as a generator"
}
|
8589
|
<p>I wrote a C++ program for review and got feedback that I had not used any kind of extensibility of object orientation.</p>
<p>I am wondering if this is a clearly defined concept or one that is more in the eye of the beholder? How would you define using extensibility of object orientation?</p>
<p>My sample program took text and parsed it into words to produce an index of how many times each word was repeated in the text as well as the locations of each word as a sentence number. It then printed out the index. Abbreviations were to be included in the index, but other punctuation omitted (e.g. commas and colons). Upper and lower case versions of words were treated as the same word. I saw no need for virtual functions in solving this nor for class inheritance. For example, this paragraph would result in:</p>
<pre><code> a 1:1
abbreviations 1:3
an 1:1
and 3:1,3,4
as 4:1,1,1,4
be 1:3
but 1:3
case 1:4
class 1:5
colons 1:3
commas 1:3
e.g. 1:3
each 2:1,1
example 1:6
for 3:5,5,6
functions 1:5
how 1:1
i 1:5
in 4:1,3,5,6
included 1:3
index 3:1,2,3
inheritance 1:5
into 1:1
it 2:1,2
locations 1:1
lower 1:4
many 1:1
my 1:1
need 1:5
no 1:5
nor 1:5
number 1:1
of 3:1,1,4
omitted 1:3
other 1:3
out 1:2
paragraph 1:6
parsed 1:1
printed 1:2
produce 1:1
program 1:1
punctuation 1:3
repeated 1:1
result 1:6
same 1:4
sample 1:1
saw 1:5
sentence 1:1
solving 1:5
text 2:1,1
the 5:1,1,2,3,4
then 1:2
this 2:5,6
times 1:1
to 2:1,3
took 1:1
treated 1:4
upper 1:4
versions 1:4
virtual 1:5
was 1:1
well 1:1
were 2:3,4
word 3:1,1,4
words 2:1,4
would 1:6
</code></pre>
<p>Please critique just my header file and how it could have been better written as object oriented to solve this problem.</p>
<p>My header file looked like the following:</p>
<pre><code>class Indexer {
private:
class Entry {
private:
typedef vector<unsigned> Occurrences;
public:
Entry(const unsigned sentence);
Entry &operator+=(const unsigned sentence);
void print(ostream &out) const;
private:
unsigned getCount() const;
private:
Occurrences _occurrences;
friend ostream &operator<<(ostream &out, const Entry &rhs);
};
class Abbreviations {
public:
Abbreviations();
bool isAbbreviation(const string &word) const;
private:
unordered_set<string> _abbreviations;
};
class Token {
private:
enum punctuationKind {
none,
sentenceEnd,
doubleQuotes,
otherPunctuation
};
public:
Token(const string &token);
const string &word() const;
bool empty() const;
bool isSentenceEnd() const;
private:
void noteSentenceEnd(bool isEnd =true);
void dropTrailingPunctuation();
bool isAbbreviation();
punctuationKind trailingPunctuationKind() const;
void stripTrailingPunctuation();
void stripLeadingPunctuation();
void lowerCase();
private:
string _word;
bool _isSentenceEnd;
bool _sentenceIsDetermined;
private:
static Abbreviations _abbreviations;
};
typedef unordered_map<string, Entry> wordMap;
private:
Indexer();
Indexer &operator+=(const string &word);
Indexer &operator+=(Token &token);
void print(ostream &out) const;
public:
static void processInput(istream &in =cin, ostream &out =cout);
private:
wordMap _entries;
unsigned _currentSentence;
friend ostream &operator<<(ostream &out, const Indexer &rhs);
friend ostream &operator<<(ostream &out, const Entry &rhs);
};
</code></pre>
<p>Let me know if you think the implementation is necessary to answer this question and I will add it.</p>
<hr>
<p>Some of the requested implementation:</p>
<p>The Operator +=:</p>
<pre><code>Indexer::Entry::Entry &
Indexer::Entry::operator+=(const unsigned sentence)
{
_occurrences.push_back(sentence);
return *this;
}
Indexer::Indexer&
Indexer::operator+=(const string &word)
{
string strippedWord = word;
wordMap::iterator itr = _entries.find(word);
if (itr == _entries.end()) {
_entries.insert(wordMap::value_type(word, Entry(_currentSentence)));
} else {
Entry &curValue = itr->second;
curValue += _currentSentence;
}
return *this;
}
</code></pre>
<p>The Token class:</p>
<pre><code>void
Indexer::Token::lowerCase()
{
const unsigned size = _word.size();
if (size) {
static const string uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const bool isOnlyFirstLetterUppercase
= (size == 1 || string::npos == _word.find_first_of(uppercaseLetters, 1));
char &firstChar = _word[0];
if (isupper(firstChar) && isOnlyFirstLetterUppercase) {
firstChar = tolower(firstChar);
}
}
}
Indexer::Token::Token(const string &token)
: _word(token),
_isSentenceEnd(false),
_sentenceIsDetermined(false)
{
stripTrailingPunctuation();
stripLeadingPunctuation();
lowerCase();
}
const string &
Indexer::Token::word() const
{
return _word;
}
bool
Indexer::Token::empty() const
{
return _word.empty();
}
bool
Indexer::Token::isSentenceEnd() const
{
return _isSentenceEnd;
}
void // private
Indexer::Token::noteSentenceEnd(bool isEnd /* =true */)
{
if (!_sentenceIsDetermined) {
_isSentenceEnd = isEnd;
_sentenceIsDetermined = true;
}
}
void // private
Indexer::Token::dropTrailingPunctuation()
{
_word.erase(_word.size() - 1);
}
bool // private
Indexer::Token::isAbbreviation()
{
return _abbreviations.isAbbreviation(_word);
}
Indexer::Token::punctuationKind
Indexer::Token::trailingPunctuationKind() const
{
const unsigned wordLen = _word.size();
if (0 == wordLen) {
return none;
}
const unsigned lastIndex = wordLen - 1;
const char lastChar = _word[lastIndex];
switch (lastChar) {
case '.':
case '?':
case '!': {
return sentenceEnd;
}
case '"': {
return doubleQuotes;
}
case ')':
case ']':
case '`':
case '\'':
case ',':
case ';':
case ':': {
return otherPunctuation;
}
}
return none;
}
/// Strips all trailing punctuation from a token except for the periods of an
/// abbreviation which are considered part of the word and retained.
void
Indexer::Token::stripTrailingPunctuation()
{
const punctuationKind punctuation = trailingPunctuationKind();
const bool havePunctuation = none != punctuation;
if (havePunctuation && !isAbbreviation()) {
if (punctuation == sentenceEnd) {
noteSentenceEnd(true);
} else if (punctuation == otherPunctuation) {
noteSentenceEnd(false);
} else {
// The punctuation is doubleQuotes so keep looking for sentence end when
// we recurse.
}
dropTrailingPunctuation();
stripTrailingPunctuation(); // Recurse to find more trailing punctuation.
return;
}
}
/// Strips all leading punctuation from a token.
void
Indexer::Token::stripLeadingPunctuation()
{
static const string leadingPunctuation = "([`\\\"";
string::size_type firstNonPunctuation
= _word.find_first_not_of(leadingPunctuation);
// Erase all leading characters that are not punction marks.
_word.erase(0, firstNonPunctuation);
}
</code></pre>
<p>Additional user of Token:</p>
<pre><code>void // static
Indexer::processInput(istream &in /* =cin */, ostream &out /* =cout */)
{
Indexer indexer;
string token;
while (in >> token) {
Token currentToken(token);
indexer += currentToken;
}
out << indexer << endl;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-02T16:12:36.423",
"Id": "13434",
"Score": "0",
"body": "I think seeing how the `Token` members are used and seeing the `Indexer::operator+=` methods might help a lot."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-02T16:21:54.397",
"Id": "13446",
"Score": "0",
"body": "@Paul Martel I've added more code per your request."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-02T20:54:13.967",
"Id": "13461",
"Score": "0",
"body": "Here is a facet to help you ignore punctuation automatically: \nhttp://stackoverflow.com/questions/6154204/how-to-tokenzie-words-classifying-punctuation-as-space/6154217#6154217"
}
] |
[
{
"body": "<p>The code shown implements only <code>operator+=(word)</code> but calls only <code>operator+=(token)</code>. Is one defined trivially in terms of the other?</p>\n\n<p>Unless you could reasonably expect some requirement for <code>indexer += token;</code> to do something different from <code>indexer += token.word()</code>, OR if you expected to have to replicate all that extra finger typing in MANY calls, go with the latter more explicit code -- it's clearer. On the other hand, it may be more OOPish for Token to have its own operator>> overload so that Indexer is not exposed to how a Token gets read. This change would dumb down the Token constructor to a minimal default constructor (called once) and move the current constructor actions into the <code>operator>></code> implementation.</p>\n\n<p>As for class hierarchy and virtuals, the one place I could picture it being applied to the current code is as a substitute for punctuationKind. Each of your enum values could be a different class derived from <code>PunctuationKind</code> and its effects on the Token could be encoded in a virtual function called like so:</p>\n\n<pre><code>void\nIndexer::Token::stripTrailingPunctuation()\n{\n // get the correct singleton.\n const PunctuationKind& punctuation = trailingPunctuationKind();\n if (punctuation.setSentenceState(*this)) { // false for PunctuationNone or abbrev.?\n dropTrailingPunctuation();\n stripTrailingPunctuation(); // Recurse to find more trailing punctuation.\n }\n}\n</code></pre>\n\n<p>Overkill? Possibly. Maybe not if you reasonably expect to have to build additional handling for other punctuation with new and different behavior.</p>\n\n<p>BTW, does your code properly handle abbreviations that have extra trailing punctuation?</p>\n\n<p>That leaves only OOP for the sake of future code. The question to ask is what new requirements could be reasonably expected and how could the existing code be set up so that it would still meet the requirements. </p>\n\n<p>So, factor out a base class where there is a reasonable expectation that <strong>some</strong> specific members or methods of a class will be useful under some generalized set of requirements while the <strong>other</strong> specific members or methods of that class will not be useful.</p>\n\n<p>Make a function virtual wherever you reasonably expect that expanded requirements will call for different instances of a class to implement it differently <em>when driven by the same calling code</em> <strong>and</strong> <em>when the choice of behavior can and should be decided when the instance is constructed</em>. </p>\n\n<p>Other kinds of requirement changes are better anticipated by generic programming techniques (templates), or by other kinds of refactoring (into referenced components). </p>\n\n<p>All of these things have their place in OOP.</p>\n\n<p>If you don't have a sense for how the requirements are likely to change, so that you have a clear idea of why you are applying any of these techniques, then you are better off keeping things simple -- fewer lines written means fewer lines to rewrite.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T15:59:55.927",
"Id": "13481",
"Score": "0",
"body": "I do not hear anything in your review to correlate with my failing review. Bottom line, in your opinion, why would the above preclude me from further consideration for an OOP lead position due to failure to use any extensibility of object oriented software? I wish to address this particular deficiency in my solution."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-02T22:26:41.323",
"Id": "8608",
"ParentId": "8591",
"Score": "3"
}
},
{
"body": "<p>First of all, code seams to be overly bloated. You do not need such a huge amount of classes for your simple task. Most of your methods may be written as (static) functions or even inlined into places of their use.</p>\n\n<p>Next, there may be possible an object orientation. </p>\n\n<pre><code> class Index;\n class Entry; // some virtual methods here\n class Abbreviation: public Entry;\n class Word: public Entry;\n\n Entry* get_entry( ...... );\n</code></pre>\n\n<p>Your get_entry function shall analyze an input stream and return either <code>new Abbreviation(....)</code> or <code>new Entry(....)</code>; use Index constructor instead of processInput, and print result using <code>Index::print(ostream&)</code> method or <code>operator<<(Index&)</code> -- that is, separate index creation and printing.</p>\n\n<p>A choice of taste -- do not use inner classes here. A better way is to place all your classes into Indexer namespace.</p>\n\n<p>These 4 classes ( + std::map + std::string + std::vector ) is enough.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T00:24:22.930",
"Id": "13757",
"Score": "0",
"body": "The suggested inheritance serves no apparent purpose, and ties together 3 classes with very different functions to give an impression that they are interchangeable in some hypothetical caller that might call '// some virtual methods'. No."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T14:07:10.077",
"Id": "13785",
"Score": "0",
"body": "@PaulMartel [Sorry for incorrect message that I've deleted]. OOP means extensibility for the future. Future client of Index class may iterate over Index elements; client may need to treat Abbreviation and Word differently. Say, client may need to print index entries for words only and skip abbreviations completely. So, client may quckly call a virtual method to distinguish between words and abbreviations; may be visitor is better solution. Sometimes such a simple solution as map<string> instead of Index class is permittable; note my wording \"**may be possible** an object orientation\"."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T01:33:23.047",
"Id": "8726",
"ParentId": "8591",
"Score": "2"
}
},
{
"body": "<p>I want to see data structures and logic separated from parsing and string representation.</p>\n\n<p>As such you would be able to use a different method of laying out the data and only have to modify your token parsing or printing logic, not the classes themselves that hold the data structures.</p>\n\n<p>The class should exist whilst allowing more than one string representation / layout.</p>\n\n<p>Work on the grounds of data structure and algorithms and then write external parsers and printers that can parse/populate your structure or read/print them.</p>\n\n<p>This is where I see your design lacking extensibility.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T01:36:34.887",
"Id": "13760",
"Score": "0",
"body": "Good point. I agree in principle, but how would this be worked here in practice? `Token` already seems to be doing a pretty good job of encapsulating the parsing and spoon-feeding entries to Indexer, except maybe for the mysterious updating of `_currentSentence` -- a little glitch that I missed in my review. For output, we can tell from the lack of something like iterator accessors on Indexer (even just private ones) that the `operator<<` is directly accessing the representation. Do you think that would provide enough separation or is a more radical change in order?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T17:56:28.050",
"Id": "8753",
"ParentId": "8591",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "8608",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-02T15:00:10.847",
"Id": "8591",
"Score": "6",
"Tags": [
"c++",
"object-oriented"
],
"Title": "How could this object oriented design class be improved for future extensibility?"
}
|
8591
|
<p>Simple static class that will write out a message that is passed in. The SpriteSheet is 256x256 and the A-Z starts at line 240 and the 0-9 starts at 248. Each character is 8x8. I hate the <code>if (ix >= 32)</code> and wondered if there is a tidier way of doing this? I'm pleased it's only one <code>Draw</code> call, but it looks ugly.</p>
<pre><code>public static class Font
{
private static String chars = "" + //
"ABCDEFGHIJKLMNOPQRSTUVWXYZ " + //
"0123456789.,!?'\"-+=/\\%()<>:; " + //
"";
public static void Draw(string msg, SpriteSheet sprites, SpriteBatch spriteBatch, int x, int y, Color color)
{
msg = msg.ToUpper();
for (int i = 0; i < msg.Length; i++)
{
int ix = chars.IndexOf(msg[i]);
int w = 0, h = 240;
if (ix >= 0)
{
if (ix >= 32)
{
w = 32;
h = 248;
}
spriteBatch.Draw(sprites.Sheet, new Rectangle(x + i * 8, y, 8, 8), new Rectangle((ix - w) * 8, h, 8, 8), color);
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T18:11:40.570",
"Id": "13486",
"Score": "0",
"body": "Do the sprites (`SpriteSheet`) ever change?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T08:50:30.817",
"Id": "13514",
"Score": "0",
"body": "No - they spritesheet stays the same."
}
] |
[
{
"body": "<p>It is hard to suggest improvements because the variable names are not very meaningful and, thus, it is hard to understand what they are for and which is the intention behind the code.<br>\nLesson to learn: <strong>using meaningful variable names is important</strong>.</p>\n\n<p>Here is an attempt.<br>\n\"Opening brackets not taking a new line\" is a matter of style, disregard it.</p>\n\n<p>Could you address the code comments I left?</p>\n\n<pre><code>public static class Font\n{\n private const string chars =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ \" + // I assume the spaces are padding to 32 chars.\n \"0123456789.,!?'\\\"-+=/\\\\%()<>:; \" // 35chars?!? What is the use of the 5 spaces?\n ;\n // Since the sprites never change, you can have them as a static property.\n private static SpriteSheet _Sprites = ...;\n\n public static void Draw(string msg, SpriteBatch spriteBatch, int xOffset, int yOffset, Color color) {\n msg = msg.ToUpper();\n for (int x = 0; x < msg.Length; x++) {\n int spriteX = chars.IndexOf(msg[x]);\n if (spriteX < 0) {\n continue; // Skipping char.\n }\n int spriteY = 240;\n if (spriteX >= 32) {\n // I really do not understand the justification of this...\n // Drawing a 1 is supposed to get a B, right? Strange.\n spriteX -= 32;\n spriteY = 248;\n }\n Rectangle charMask = new Rectangle(xOffset + x * 8, yOffset, 8, 8);\n Rectangle spriteMask = new Rectangle(spriteX * 8, spriteY, 8, 8);\n // XNA method: http://msdn.microsoft.com/en-us/library/ff433987.aspx\n spriteBatch.Draw(Sprites.Sheet, charMask, spriteMask, color);\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T18:08:47.377",
"Id": "8630",
"ParentId": "8600",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "8630",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-02T17:07:31.470",
"Id": "8600",
"Score": "2",
"Tags": [
"c#",
"optimization"
],
"Title": "Help tidying up a Draw call"
}
|
8600
|
<p>I wrote this class today, but I am trying to figure out how to make it more accurate. I pass in seconds and multiply by 1000 to make it milliseconds, and the time does not line up. I need the ability to have multiple timers, so using <code>timer_gettime()</code>, which limits one clock per process, is not an option. Also note I borrowed my idea from free glut.</p>
<p>Please feel free to leave general comments on style, but please focus more on how to improve the accuracy of the timer.</p>
<pre><code>#include "TimerManager.h"
#include <iostream>
void func1(int id)
{
std::cout << "I was called with " << std::endl;
}
void func2(int id)
{
std::cout << "I was called too ))))))))))))))))))))))))))))))))))))))))))))))))))))))))))" << std::endl;
}
int main(int argc, char *argv[])
{
TimerManager t;
t.addTimer(6, func1);
t.addTimer(2, func2);
while(true) {
t.start();
}
return 0;
}
</code></pre>
<hr />
<pre><code>#ifndef TIMERMANAGER_H_
#define TIMERMANAGER_H_
#include <stdlib.h>
#include <iostream>
#include <pthread.h>
#include <list>
extern "C" {
void *create_pthread(void *data);
}
class TimerManager {
public:
TimerManager();
~TimerManager();
void start();
void stop();
void addTimer(long usec, void (*callback)(int id));
private:
class Timer
{
public:
Timer(long usec, void (*callback)(int)) :
duration(usec),
callback(callback),
start(0)
{
}
bool operator ==(Timer other)
{
if ((this->callback == other.callback) && (this->duration == other.duration)) {
return true;
}
return false;
}
long duration;
void (*callback)(int);
long start;
};
std::list<Timer> m_timers;
pthread_t m_timer_thread;
Timer setUpTimer(long usec, void (*callback)(int id));
friend void *create_pthread(void *data);
void run();
bool go;
};
#endif
</code></pre>
<hr />
<pre><code>#include <algorithm>
#include <iterator>
#include <sys/time.h>
#include "TimerManager.h"
extern "C" void *create_pthread(void *data)
{
TimerManager *thread_timer_manager = static_cast<TimerManager *>(data);
thread_timer_manager->run();
return data;
}
TimerManager::TimerManager() :
go(false)
{
int thread_creation = pthread_create(&m_timer_thread, NULL, create_pthread, this);
if(thread_creation != 0) {
std::cerr << "Failed to create thread" << std::endl;
return;
} else {
std::cout << "The status flag is " << thread_creation << std::endl;
}
}
TimerManager::~TimerManager()
{
}
void TimerManager::run()
{
struct timeval l_tv;
while(true) {
if (go) {
typedef std::list<Timer>::iterator li;
li begin = m_timers.begin();
li end = m_timers.end();
int item = 0;
for(;begin != end; ++begin) {
gettimeofday(&l_tv, NULL);
long elapsed_time = (l_tv.tv_usec - begin->start);
sleep(1);
if (elapsed_time >= begin->duration) {
//std::cout << "Status of timer " << item << " is " << elapsed_time << " > " << begin->duration << std::endl;
begin->callback(item);
gettimeofday(&l_tv, NULL);
begin->start = l_tv.tv_usec;
} else {
//std::cout << "Status of timer " << item << " is " << elapsed_time << " < " << begin->duration << std::endl;
}
item++;
}
}
}
}
void TimerManager::start()
{
go = true;
}
oid TimerManager::stop()
{
go = false;
}
TimerManager::Timer TimerManager::setUpTimer(long usec, void (*callback)(int id))
{
struct timeval l_tv;
gettimeofday(&l_tv, NULL);
Timer l_t(usec * 100, callback);
l_t.start = l_tv.tv_usec;
std::cout << "Timer created with a values of START: " << l_t.start << " CALLBACK: " << &l_t.callback << " DURATION: " << l_t.duration << std::endl;
return l_t;
}
void TimerManager::addTimer(long usec, void (*callback)(int id))
{
Timer insert = setUpTimer(usec, callback);
typedef std::list<Timer>::iterator li;
li begin = m_timers.begin();
li end = m_timers.end();
for(;begin != end; ++begin) {
if (*begin == *end) {
return;
}
}
m_timers.push_back(insert);
}
</code></pre>
<hr />
<h1><em>Update</em>: Changes after reading answers.</h1>
<p>Here is the updated code,</p>
<pre><code>#include "TimerManager.h"
#include <iostream>
#include <fstream>
#include <sys/time.h>
extern "C"
void func1(int id)
{
struct timeval l_tv;
gettimeofday(&l_tv, NULL);
std::cout << "I was called (1) @ " << l_tv.tv_usec << std::endl;
}
extern "C"
void func2(int id)
{
struct timeval l_tv;
gettimeofday(&l_tv, NULL);
std::cout << "I was called (2) @ " << l_tv.tv_usec << std::endl;
}
int main(int, char *[])
{
TimerManager t;
t.addTimer(1000000 / 2, func1);
t.addTimer(1000000 * 4, func2);
t.start();
while(true) {
sleep(1);
}
return 0;
}
</code></pre>
<hr />
<pre><code>#ifndef TIMERMANAGER_H_
#define TIMERMANAGER_H_
#include <stdlib.h>
#include <iostream>
#include <pthread.h>
#include <list>
extern "C" {
void *create_pthread(void *data);
}
class TimerManager {
public:
TimerManager();
~TimerManager();
void start();
void stop();
void addTimer(long usec, void (*callback)(int id));
private:
class Timer
{
public:
Timer(long usec, void (*callback)(int)) :
duration(usec),
callback(callback),
start(0)
{
}
bool operator ==(Timer other)
{
if ((this->callback == other.callback) && (this->duration == other.duration)) {
return true;
}
return false;
}
void operator =(Timer other)
{
duration = other.duration;
callback = other.callback;
start = other.start;
}
suseconds_t duration;
void (*callback)(int);
suseconds_t start;
};
Timer setUpTimer(long micro_duration, void (*callback)(int id));
friend void *create_pthread(void *data);
void run();
bool m_bRunning;
bool m_bGo;
long m_lMinSleep;
std::list<Timer> m_cTimers;
pthread_t m_tTimerThread;
pthread_cond_t m_tGoLockCondition;
pthread_mutex_t m_tGoLock;
};
#endif
</code></pre>
<hr />
<pre><code>#include <algorithm>
#include <iterator>
#include <sys/time.h>
#include "TimerManager.h"
extern "C" void *create_pthread(void *data)
{
TimerManager *thread_timer_manager = static_cast<TimerManager *>(data);
thread_timer_manager->run();
return data;
}
TimerManager::TimerManager() :
m_bRunning(false),
m_bGo(false),
m_lMinSleep(0)
{
int mutex_creation = pthread_mutex_init(&m_tGoLock, NULL);
if(mutex_creation != 0) {
std::cerr << "Failed to create mutex" << std::endl; // Use RAII if resource acquisition fails
return;
}
int mutex_cond_creation = pthread_cond_init(&m_tGoLockCondition, NULL);
if(mutex_cond_creation != 0) {
std::cerr << "Failed to create condition mutex" << std::endl; // Use RAII if resource acquisition fails
return;
}
int thread_creation = pthread_create(&m_tTimerThread, NULL, create_pthread, this); // On success call create_pthread to start tiemr loop
if(thread_creation != 0) {
std::cerr << "Failed to create thread" << std::endl; // Use RAII if resource acquisition fails
return;
}
m_bRunning = true;
}
TimerManager::~TimerManager()
{
pthread_mutex_lock(&m_tGoLock); // m_bRunning access on other thread
m_bRunning = false;
pthread_mutex_unlock(&m_tGoLock);
void *result;
pthread_join(m_tTimerThread, &result); // Do not let calling thread exit before deleting
pthread_mutex_destroy(&m_tGoLock); // Now destroy the mutex (release resources)
pthread_cond_destroy(&m_tGoLockCondition);
}
void TimerManager::run()
{
pthread_mutex_lock(&m_tGoLock); // Timers run on seperate thread
while(m_bRunning) { // While timer manager exists
while (!m_bGo) { // While timer manager told to run
pthread_cond_wait(&m_tGoLockCondition, &m_tGoLock); // Set in the start() member function
}
pthread_mutex_unlock(&m_tGoLock); // Once timer unlocked and mutex released
if (!m_bRunning) { // Make sure timer manager not out of scope
break;
}
struct timeval l_tv;
usleep(std::max(0l, m_lMinSleep));
gettimeofday(&l_tv, NULL); // System call to get time of day
m_lMinSleep = 0; // Used to sleep if no timer to go off soon
long l_lMin = 0; // Used if timer goes off to get actual Min sleep
for(std::list<Timer>::iterator it = m_cTimers.begin(); it != m_cTimers.end(); ++it) { // Iterate over timers to see which one is going off
TimerManager::Timer l_oTimer = *it; // Obtain a copy of the timer
long elapsed_time = ((l_tv.tv_sec * 1000000 + l_tv.tv_usec) - (l_oTimer.start)); // Calcuate the elapsed time from the start of timer X
l_lMin = elapsed_time - l_oTimer.duration; // Minimum time you can sleep in loop
if (elapsed_time >= l_oTimer.duration) { // If time passed is greater than or equal to duration: THEN
l_lMin = l_oTimer.duration; // The minimum you can wait is possibly the entire duration of that timer
l_oTimer.callback(0); // Call the call back
gettimeofday(&l_tv, NULL); // After callback called...
it->start = (l_tv.tv_sec * 1000000) + l_tv.tv_usec; // Start the timer over again
}
m_lMinSleep = std::min(m_lMinSleep, l_lMin); // Find the actual minumum time you can sleep to not lock
}
}
}
void TimerManager::start()
{
pthread_mutex_lock(&m_tGoLock); // Go flag accessed from another thread
m_bGo = true;
pthread_cond_signal(&m_tGoLockCondition);
pthread_mutex_unlock(&m_tGoLock);
}
void TimerManager::stop()
{
pthread_mutex_lock(&m_tGoLock); // Go flag accessed from another thread
m_bGo = false;
pthread_mutex_unlock(&m_tGoLock);
}
TimerManager::Timer TimerManager::setUpTimer(long micro_duration, void (*callback)(int id))
{
struct timeval l_tv;
gettimeofday(&l_tv, NULL); // System call to get the ms and sec since Epoch0
Timer l_oTimer(micro_duration, callback); // Create a timer
l_oTimer.start = (l_tv.tv_sec * 1000000) + l_tv.tv_usec; // Tell the timer when to start
return l_oTimer; // Return a copy to addTimer
}
void TimerManager::addTimer(long usec, void (*callback)(int id))
{
pthread_mutex_lock(&m_tGoLock); // Tell object to wait till timer inserted
Timer insert = setUpTimer(usec, callback);
for (std::list<Timer>::iterator it = m_cTimers.begin(); it != m_cTimers.end(); ++it) {
if (*it == insert) { // Return if timer callback and duration the same
return;
}
}
m_cTimers.push_back(insert); // If no duplicate timers found then insert into list
pthread_mutex_unlock(&m_tGoLock); // Tell object it is okay to proceed
}
</code></pre>
|
[] |
[
{
"body": "<h1>Timer Accuracy:</h1>\n\n<p>I would say you currently have a bug in your code as you sleep 1 sec between checking each Timer object. After a sleep you should check all the Timer objects once this is complete then go back to sleep.</p>\n\n<h2>Timer Granularity</h2>\n\n<p>sleep() is very course grained (1 second resolution).</p>\n\n<p>MS has a higher resolution timer (but it is not portable).</p>\n\n<p>I have seen people use select() as a cross platform solution for a higher resolution timer (personally not tried it but it looks like it works). Technically it is to detect activity on streams (ie your web server uses it to wait for input from 1000s of browsers). But if you specify no streams (I think you will need to test) and a timeout of appropriate seconds and micro seconds then you should get your delay.</p>\n\n<pre><code>timeval timeout = {10 /* seconds */, 23 /* and microseconds */};\nif (select(0, NULL, NULL, NULL, &timeout) != 0)\n{\n // Need to deal with errors like EINTR\n}\n</code></pre>\n\n<h1>Comments on code:</h1>\n\n<h2>Variable Names</h2>\n\n<p>There are several variables that have really short names that are no descriptive to somebody reading your code. I would try and make these names more descriptive to their intent.</p>\n\n<h2>Bad use of start()</h2>\n\n<p>start() does not look like it needs to be called more than once.<br>\nOtherwise why have stop()?</p>\n\n<pre><code>while(true) {\n t.start();\n}\n</code></pre>\n\n<h2>thread_destruction</h2>\n\n<p>In the destructor I would wait for the thread to terminate.</p>\n\n<p>Otherwise the run() method may potentially be acting on invalid data.</p>\n\n<pre><code>TimerManager::~TimerManager() \n{\n running = false; // New member that the thread checks periodically to see\n // if it should continue running.\n // Alternative you can send a signal to the thread to kill it.\n // But I would avoid that as it results in objects not being\n // destroyed correctly.\n\n // Wait for the thread to check the flag and terminate.\n void* result;\n pthread_join(m_timer_thread, &result);\n}\n</code></pre>\n\n<p>Small Change to <code>run()</code> to use <code>running</code>:</p>\n\n<pre><code>void TimerManager::run() \n{\n struct timeval l_tv;\n while(running) /*previously this was true */{\n if (go) {\n</code></pre>\n\n<h2>Thread start-up and avoiding busy loops</h2>\n\n<p>In your thread <code>run()</code> phase you basically have a busy wait.<br>\nif <code>go</code> is false then the <code>while</code> loop repeats very quickly without releasing the processor for other threads. I bet this shoots your CPU utilization to 100% very quickly if you do anything before calling <code>start()</code> on the <code>TimerManager</code>. </p>\n\n<p>There are two solutions to this</p>\n\n<ul>\n<li>Put a sleep(1) in the else part\n<ul>\n<li>This forces the thread to give up its time slice to another thread.</li>\n</ul></li>\n<li>Use a conditional variable.\n<ul>\n<li>This will suspend the thread until you signal it to go (in start())</li>\n</ul></li>\n</ul>\n\n<h3>Simple <code>Sleep</code> Solution:</h3>\n\n<pre><code>void TimerManager::run() \n{\n struct timeval l_tv;\n while(running)\n {\n if (!go)\n {\n sleep(1);\n }\n else { // Code as before.\n</code></pre>\n\n<h3>Condition Variable</h3>\n\n<pre><code>void TimerManager::run() \n{\n struct timeval l_tv;\n while(running)\n {\n // Note: mutex and condition variable should be initialized in constructor\n // Must lock before testing go\n pthread_lock(goLock);\n while (!go)\n {\n // We use a while as the user\n // May potentially call start() stop() very quickly\n // So when the thread exits the condition variable we re-check the state.\n pthread_cond_wait(goCond, goLock);\n\n // The thread release the mutex when it is suspends and must re-acquire it\n // (internally) before it is release from the wait() call.\n\n }\n // Unlock now we have established go is true.\n // NOTE: This looks like a good place for RAII\n pthread_unlock(goLock);\n\n // Check to see if the running flag has been messed with.\n // It we are no longer running then break out of the running loop now.\n if (!running)\n { break;\n // Note: this mean put a signal in the destructor\n // just after setting running to false.\n }\n</code></pre>\n\n<p>We have to alter start and stop appropriately to go with the condition variable.</p>\n\n<pre><code>void TimerManager::start()\n{\n pthread_lock(goLock);\n go = true;\n pthread_cond_signal(goCond);\n pthread_unlock(goLock); // Another opportunity for RAII\n}\n\nvoid TimerManager::stop() \n{\n pthread_lock(goLock);\n go = false; // Modify go should really have a lock\n // to be consistent. \n pthread_unlock(goLock);\n}\n</code></pre>\n\n<h2>Bad Variables names:</h2>\n\n<pre><code> li begin = m_timers.begin();\n li end = m_timers.end();\n</code></pre>\n\n<p>begin is a bad name for the looping variable as you increment it and then it will not be the beginning anymore. There is no need to call end outside the loop. Most standard implementations this is so fast you will not notice it (if internally it is a problem then the implementers have already optimized the call the end() to cash the iterator so you are not saving anything by calling it outside the loop.</p>\n\n<pre><code> // In C++11 you can use auto for the type\n for(auto it = m_timers.begin(); it != m_timers.end(); ++it)\n\n // In C++03 you still need to use the correct type\n for(std::list<Timer>::iterator it = m_timers.begin(); it != m_timers.end(); ++it)\n</code></pre>\n\n<h2>Incorrect usage of microseconds</h2>\n\n<pre><code> long elapsed_time = (l_tv.tv_usec - begin->start);\n</code></pre>\n\n<p>This is not the elapsed time.<br>\nThe tv_usec loops every second so you need to this to tv_sec to get the actual time value.</p>\n\n<pre><code> long elapsed_time_in_MS = ((l_tv.tv_sec * 1000000 + l_tv.tv_usec) - (begin->start * 1000000);\n</code></pre>\n\n<h2>Bug in sleep calculations</h2>\n\n<p>You should probably move the calls to gettimeofday() and sleep() out of the loop body.</p>\n\n<pre><code> for(;begin != end; ++begin)\n {\n gettimeofday(&l_tv, NULL); \n long elapsed_time = (l_tv.tv_usec - begin->start);\n sleep(1);\n</code></pre>\n\n<p>I would get the time of day <code>then</code> Loop over all the timers to see if they had expired and call the associated function. Once all this has been done you can sleep() for the minimum time required until the next timeout (assuming that non of the functions take too long).</p>\n\n<pre><code> minSleep = 0; // First sleep is zero\n\n sleep(std::max(0, minSleep));\n gettimeofday(&l_tv, NULL);\n minSleep = 0; // Reset sleep (will be calculated in loop.\n for(;begin != end; ++begin)\n {\n\n long elapsed_time = getElapsedTime(l_tv, egin->start);\n\n // If this timer is not going to fire this time then we have to sleep a tin bit\n // tiny bit for this Timer.\n long myMin = elapsed_time - begin->duration;\n\n if (elapsed_time >= begin->duration)\n {\n // If the timer has expired then we need to sleep the whole duration.\n myMin = begin->duration;\n\n // Current Code\n }\n // The actual amount of time to sleep is the minimum of all myMin.\n minSleep = std::min(minSleep, myMin);\n }\n gettimeofday(&endOfCallbacks, NULL);\n timeSpentCallingCB = endOfCallbacks.\n</code></pre>\n\n<h2>Dead Code</h2>\n\n<p>This seems like dead code:</p>\n\n<pre><code> li begin = m_timers.begin();\n li end = m_timers.end();\n for(;begin != end; ++begin) {\n if (*begin == *end) {\n return;\n }\n }\n</code></pre>\n\n<h2>Centralize typedef</h2>\n\n<p>You have several of the same typdef:</p>\n\n<pre><code> typedef std::list<Timer>::iterator li;\n</code></pre>\n\n<p>If you put it inside the class definition then it will be in the scope of all methods of that class. If fact I would go one step further and typedef the container type.</p>\n\n<pre><code>class TimerManager\n{\n typedef std::list<Timer> Container;\n typedef Container::iterator iterator;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T17:50:31.573",
"Id": "13580",
"Score": "0",
"body": "Thanks for the great feedback yet again. I learned quite a bit about concurency and threads withing linux. I have made most of the changes, and was wondering if you could look them over."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T19:34:18.037",
"Id": "13585",
"Score": "0",
"body": "@MatthewHoggan: I see the version on SO http://stackoverflow.com/questions/9147027/pthreads-sighup-on-simple-linux-timer I think you will get good feedback there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T04:35:02.233",
"Id": "13603",
"Score": "0",
"body": "Thanks, I was trying to keep the code review seperate from the problems. Your help is greatly appreciated"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-17T10:01:00.627",
"Id": "52458",
"Score": "0",
"body": "Linux has [`nanosleep(2)`](http://linux.die.net/man/2/nanosleep)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T15:54:23.757",
"Id": "8623",
"ParentId": "8611",
"Score": "8"
}
},
{
"body": "<p>Review Based on Updated Answer:</p>\n\n<p>In the constructor of TimerManager</p>\n\n<pre><code>TimerManager::TimerManager() :\n</code></pre>\n\n<p>There are several places where a failed call to pthread_X results in you abandoning the initialization of the object and returning. The problem with this is that you now have an object that is not in a consistent state (people can still call start() stop() and addTimer()).</p>\n\n<p>If something fails during construction it is best to throw an exception (If an object is bad then you should not allow it to be used).</p>\n\n<p>Your problem here is that the objects you are initializing in the constructor are C type objects that have a separate destroy call that must be called (but an exception from the constructor will prevent the destructor being called). As a result you may find your self wrapping each of the C objects in their own class to make sure they are automatically destroyed correctly.</p>\n\n<p>The assignment operator for Timer:</p>\n\n<pre><code>void operator =(Timer other)\n{\n duration = other.duration;\n callback = other.callback;\n start = other.start;\n}\n</code></pre>\n\n<p>If you don't define it then the compiler will generate a version that does exactly the same (with the caveat that it will return a reference that allows assignment chaining). I have nothing against using void to stop the chaining but I though I should just point it out.</p>\n\n<p>Always try and make sue you symmetrically lock and unlock things like mutexes.</p>\n\n<pre><code> pthread_mutex_lock(&m_tGoLock); \n while(m_bRunning)\n { \n while (!m_bGo)\n { \n pthread_cond_wait(&m_tGoLockCondition, &m_tGoLock); \n }\n pthread_mutex_unlock(&m_tGoLock); \n // STUFF\n }\n</code></pre>\n\n<p>Notice that if m_bRunning is false at start-up then you may not unlock <code>m_tGoLock</code>. Also the second time around the loop you are call un-lock without calling lock. This case can be fixed by moving the first lock inside the first while loop. In general though this is a good case for the usage of RAII where things need to be done symmetrically even when exceptions are in play (In parallel to the advice about the constructor, it may be worth wrapping the pthread_X objects in some C++ classes).</p>\n\n<p>Though I comment you for commenting.<br>\nI prefer comments at a minimum and try not to write comments that tell you what the code is doing. We should be able to see that from reading the code. Comments should be there to explain the overall technique of what we are doing (ie <strong>what</strong> not <strong>how</strong>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T06:35:57.780",
"Id": "8692",
"ParentId": "8611",
"Score": "3"
}
},
{
"body": "<p>2 bugs:</p>\n\n<ol>\n<li><p>This value should be the other way around; thread never sleeps (always sleep a negative number):</p>\n\n<p>Original:</p>\n\n<pre><code>l_lMin = elapsed_time - l_oTimer.duration;\n</code></pre>\n\n<p>Fix:</p>\n\n<pre><code>l_lMin = l_oTimer.duration - elapsed_time;\n</code></pre></li>\n<li><p><code>m_lMinSleep = 0;</code> is wrong. In the minimum calculation, 0 or any other positive number, 0 is always the minimum. That is why you need to set it to max long value, or change the type to <code>unsigned</code> with -1 value.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-17T07:57:44.980",
"Id": "32800",
"ParentId": "8611",
"Score": "0"
}
},
{
"body": "<p><code>gettimeofday</code> should not be used to measure time. Use <code>clock_gettime(CLOCK_MONOTONIC)</code> instead - this clock is not affected by discontinuous jumps in the system time (e.g. if the system administrator manually changes the clock).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T13:48:57.373",
"Id": "38631",
"ParentId": "8611",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "8623",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T00:36:21.367",
"Id": "8611",
"Score": "3",
"Tags": [
"c++",
"linux",
"timer",
"pthreads"
],
"Title": "Linux C++ Timer Class: How can I improve the accuracy?"
}
|
8611
|
<p>This is a basic program I wrote that lets you select a band, and give a description about the band and publish what you wrote.</p>
<p>Are there ways I can apply concepts of OOP to improve this code? Any help and tips would be greatly appreciated!</p>
<p>(I tried to put this on JSFiddle, but it was rendering differently.)</p>
<pre><code><html>
<head>
<title>Foo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<form name="form1">
<input type="radio" name="band" value="Led Zeppelin" />Led Zeppelin <br />
<input type="radio" name="band" value="Red Hot Chili Peppers" />Red Hot Chili Peppers <br />
<input checked="checked" type="radio" name="band" value="The Beatles" />The Beatles <br />
<input type ="text" name="description" value="Enter something"/> <br />
</form>
<button onclick="addEntry()">Add row</button>
<hr id="start"/>
<div id="container"></div>
<hr id="end"/>
<button onclick="removeEntry()">Remove most recent entry</button>
<script>
function getRadioValue(){
for(i=0; i<document.form1.band.length; i++){
if(document.form1.band[i].checked){
return document.form1.band[i].value;
}
}
}
function getDescription(){
return document.form1.description.value;
}
function numOfEntries(){
return document.getElementById("container").childNodes.length + 1;
}
function addEntry(){
var band = getRadioValue();
var desc = getDescription();
var element = document.createElement("div");
var element_content = document.createTextNode(numOfEntries() + '. ' + getRadioValue() + ", " + getDescription());
element.appendChild(element_content);
var container = document.getElementById("container");
container.appendChild(element);
}
function removeEntry(){
var containerElm = document.getElementById("container");
if(containerElm.childNodes.length>0){
containerElm.removeChild(containerElm.lastChild);
}
}
</script>
</body>
</html>
</code></pre>
|
[] |
[
{
"body": "<p>I have several comments on both your HTML and your JS.</p>\n\n<p>We'll start with the HTML:</p>\n\n<ul>\n<li><p>You can keep it much cleaner by <a href=\"http://en.wikipedia.org/wiki/Unobtrusive_Javascript\" rel=\"nofollow\">separating Javascript from it completely</a>. For example, instead of doing this:</p>\n\n<pre><code><button onclick=\"addEntry()\">Add row</button>\n</code></pre>\n\n<p>you would do this:</p>\n\n<pre><code><button id=\"add-entry\">Add row</button>\n</code></pre>\n\n<p>and in your script:</p>\n\n<pre><code>$('#add-entry').on('click', addEntry); // binds addEntry() to the \n // click handler for that element\n</code></pre></li>\n<li>You don't need a <code>form</code> element as you aren't submitting anything. See my revised version below for how to access the checked radio option with jQuery.</li>\n<li>I would use <code>div</code> elements instead of <code>br</code> to create new lines, because it will be much easier to go in later and change the style (for example, if you wanted to add padding, or increase the spacing between the radio options).</li>\n<li>You can use an <code>ol</code> element to get a numbered list instead of manually inserting a number next to each new entry.</li>\n</ul>\n\n<p>JS:</p>\n\n<ul>\n<li>You included jQuery but you're not using it anywhere in your code (it makes it <em>very</em> easy to manipulate the DOM).</li>\n<li>You can put these statements inside a <a href=\"http://api.jquery.com/ready/\" rel=\"nofollow\"><code>$(document).ready()</code></a> block, which means they will get executed when the document is guaranteed to be ready for manipulation.</li>\n<li>In <code>addEntry()</code> you have a couple variables that you didn't use at all.</li>\n</ul>\n\n<p>To answer your question, I wouldn't use an OO paradigm for this at all. You aren't doing anything that OOP would improve or make easier. Here is my revision of your code with the changes I mentioned above (<a href=\"http://jsfiddle.net/wd5Bs/\" rel=\"nofollow\">demo on jsfiddle</a>):</p>\n\n<pre><code><html>\n <head>\n <title>Foo</title>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js\"></script>\n <script>\n $(document).ready(function() {\n $('#add-entry').on('click', addEntry);\n $('#remove-recent-entry').on('click', removeRecentEntry);\n });\n\n function addEntry() {\n var band = $('input[name=band]:checked').val();\n var desc = $('#description').val();\n $('#container').append('<li>' + band + ', ' + desc + '</li>');\n }\n\n function removeRecentEntry() {\n $('#container li').last().remove();\n }\n </script>\n </head>\n <body>\n <div><input type=\"radio\" name=\"band\" value=\"Led Zeppelin\">Led Zeppelin</input></div>\n <div><input type=\"radio\" name=\"band\" value=\"Red Hot Chili Peppers\">Red Hot Chili Peppers</input></div>\n <div><input checked=\"checked\" type=\"radio\" name=\"band\" value=\"The Beatles\">The Beatles</input></div>\n\n <div><input id=\"description\" type=\"text\" value=\"Enter something\"/></div>\n\n <button id=\"add-entry\">Add row</button> <button id=\"remove-recent-entry\">Remove most recent entry</button>\n <hr id=\"start\"/>\n <ol id=\"container\"></ol>\n <hr id=\"end\"/>\n </body>\n</html>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T05:50:55.390",
"Id": "13604",
"Score": "0",
"body": "You totally blew my mind away, I really liked the way you selected the checked band with `input[name=band]:checked`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T06:15:49.733",
"Id": "13606",
"Score": "1",
"body": "@LedZeppelin: yeah, jQuery is pretty awesome"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T12:52:04.080",
"Id": "13615",
"Score": "0",
"body": "I had another question, should you add a conditional statement in the remove function to make sure that there's at least one `<li>`? Or does jquery see if `'#container li'` exists before it removes the last one?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T14:28:23.907",
"Id": "13623",
"Score": "1",
"body": "@LedZeppelin: In that case it will return an empty list and the calls to `last()` and `remove()` will silently exit without doing anything. If you try it on the demo, you'll see it doesn't raise any JS errors."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T01:32:01.130",
"Id": "8675",
"ParentId": "8612",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "8675",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T00:57:16.227",
"Id": "8612",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Publishing a description about a selected band"
}
|
8612
|
<p>I've implemented Jon Bentley's bitmap sorting algorithm from Column 1 of his Programming Pearls book. This code supports user-defined integer range (works from <code>Integer.MIN_VALUE</code> to <code>Integer.MAX_VALUE</code>), but for now only works on a distinct set of integers.</p>
<p>In order to avoid overflow in the integer arithmetic, I use type-casting for intermediate results.</p>
<p>For anyone interested, I've also posted the full description of the algorithm and performance analysis <a href="http://letsalgorithm.blogspot.com/2012/02/bitmap-sort.html" rel="nofollow">here</a>.</p>
<pre><code>public int[] sortDistinctIntegers(int[] a, int min, int max){
int N = (int)(((long)max-min) / 8 + 1);
byte[] bitmap = new byte[N];
for(int i = 0; i < a.length; i++)
bitmap[(int)(((long)a[i]-min)/8)] |= 1 << (int)(((long)a[i]-min) % 8);
int k = 0;
for(int i = 0; i < N; i++){
for(int j = 0; j < 8; j++){
if((bitmap[i] & (1 << j)) > 0){
a[k] = i * 8 + j + min;
k++;
}
}
}
return a;
}
</code></pre>
<p>I was wondering if anyone has any comments or ideas on how to improve this code (in terms of prettification, readability and performance).</p>
|
[] |
[
{
"body": "<p>An idea: I'd try to implement the algorithm with bigger data types (<code>int</code>, <code>long</code>) instead of the <code>byte</code>.</p>\n\n<p>Some notes:</p>\n\n<ol>\n<li><p>I'd create a <code>BYTE_SIZE</code> constant for <code>8</code>, try to avoid magic numbers.</p>\n\n<pre><code>private static final int BYTE_SIZE = 8;\n</code></pre>\n\n<p>It would help a lot if you change from <code>byte</code> to another data type.</p></li>\n<li><p>The return type of <code>sortDistinctIntegers</code> is really confusing. It returns with the first argument. Users easily could believe that it returns another array despite the fact that it modifies the input array. Make it <code>void</code>.</p></li>\n<li><p>For easier readability I'd </p>\n\n<ul>\n<li>extract out some method for easier readability: <code>createBitmapArray</code>, <code>processBitmapByte</code>, <code>doSort</code>,</li>\n<li>use longer variable and parameter names (<code>outputIndex</code> instead of <code>k</code>, <code>bitmapSize</code> instead of <code>N</code>, <code>bitIndex</code> instead of <code>j</code>),</li>\n<li>create local variables for <code>1 << bitIndex</code> (<code>mask</code>), etc.</li>\n</ul></li>\n</ol>\n\n<p>Below is the code after a few refactoring steps. (I haven't checked that the algorithm is correct or not.)</p>\n\n<pre><code>private static final int BYTE_SIZE = 8;\n\npublic void sortDistinctIntegers(final int[] data, final int min, final int max) {\n final byte[] bitmap = createBitmapArray(data, min, max);\n\n doSort(data, min, bitmap);\n}\n\nprivate byte[] createBitmapArray(final int[] data, final int min, \n final int max) {\n final int bitmapSize = (int) (((long) max - min) / BYTE_SIZE + 1);\n final byte[] bitmap = new byte[bitmapSize];\n\n for (int i = 0; i < data.length; i++) {\n final long min2 = (long) data[i] - min; // TODO: need a better name\n final int mask = 1 << (int) (min2 % BYTE_SIZE);\n bitmap[(int) (min2 / BYTE_SIZE)] |= mask;\n }\n return bitmap;\n}\n\nprivate void doSort(final int[] data, final int min, final byte[] bitmap) {\n int outputIndex = 0;\n for (int bitmapArrayIndex = 0; bitmapArrayIndex < bitmap.length; \n bitmapArrayIndex++) {\n final byte currentBitmapByte = bitmap[bitmapArrayIndex];\n outputIndex = processBitmapByte(data, min, currentBitmapByte, \n outputIndex, bitmapArrayIndex);\n }\n}\n\nprivate int processBitmapByte(final int[] data, final int min, \n final byte currentBitmapByte, int outputIndex,\n final int bitmapArrayIndex) {\n for (int bitIndex = 0; bitIndex < BYTE_SIZE; bitIndex++) {\n final int mask = 1 << bitIndex;\n final boolean flagSet = (currentBitmapByte & mask) > 0;\n if (flagSet) {\n data[outputIndex] = bitmapArrayIndex * BYTE_SIZE + bitIndex + min;\n outputIndex++;\n }\n }\n return outputIndex;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T18:50:11.737",
"Id": "8632",
"ParentId": "8613",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "8632",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T02:21:35.197",
"Id": "8613",
"Score": "5",
"Tags": [
"java",
"algorithm",
"sorting",
"bit-twiddling"
],
"Title": "Jon Bentley's bitmap sort implementation"
}
|
8613
|
<p>I am making an app that allows the user to type chemical equations (H<sub>2</sub>O + NaCl) to the screen. The user taps, inside a tableviewcell, a custom textfield and types on a custom keyboard (both subclasses of uiviews). The vc doesn't have an actual instance of the keyboard, and the keyboard instead appears because it is the inputView property of the textfield. Also, the text field doesn't add text directly to itself, but instead places each compound inside a label, which is then added as its subview. Currently, the textfield stores the order of compounds internally, and the specific text is stored inside the labels. When the view controller needs the text, it creates a model class and takes the data from the textfield and stores it into the model. </p>
<p>According to MVC, the views shouldn't be handling their own data, something that my textfield and label seriously infringe. I need help determining what parts of my code to transfer into the view controller and model. Some specific questions I have are </p>
<ul>
<li>what class should implement the keyboard's protocol</li>
<li>whether the vc or the textfield should add labels as the textfield's subviews</li>
<li>how much data should be kept in the model, and how much (if any) can remain in the textfield/labels.
-- how the vc should exchange info between model and textfields</li>
</ul>
<p><img src="https://i.stack.imgur.com/BQG4w.png" alt="enter image description here"></p>
<p>Currently, the code is organized as follows:</p>
<p><strong>Keyboard</strong></p>
<p>It appears when textfield is tapped. When a key is pressed, it notifies its delegate, sometimes sending a key as a parameter.</p>
<pre><code>@protocol KeyInput <UITextInputTraits>
- (void) newCompound;
-(void) closeKeyboard;
- (void) addElement:(NSString*) currentElement;
- (void) changeCharge:(NSString*) chargeIncrease;
- (void) changeState:(NSString*) stateName;
- (void) deleteCharacter;
@end
@interface FormulaKeyboard : UIView {
id <KeyInput> delegate;
UIButton *element1;
}
@property (nonatomic, retain) id <KeyInput> delegate;
-(IBAction) addCompound:(id)sender; //calls [delegate newCompound]
-(IBAction) close:(id)sender;
- (IBAction) deletePressed:(id)sender;
-(IBAction) element1Pressed:(id)sender; // calls [delegate addElement:@"Na"]
-(IBAction) element2Pressed:(id)sender;
-(IBAction) element3Pressed:(id)sender;
-(IBAction) element4Pressed:(id)sender;
-(IBAction) openParenPressed:(id)sender; // rest are similar
-(IBAction) closedParenPressed:(id)sender;
-(IBAction) plusPressed:(id)sender;
-(IBAction) minusPressed:(id)sender;
-(IBAction) solidPressed:(id)sender;
-(IBAction) liquidPressed:(id)sender;
-(IBAction) gasPressed:(id)sender;
-(IBAction) aqueousPressed:(id)sender;
</code></pre>
<p><strong>Textfield</strong></p>
<p>It complies to the <code>KeyInput</code> protocol. When an element on the keyboard is pressed consecutively, the subscript increases (H + H + O would result in H<sub>2</sub>O); similarly pressing the '+' consecutively will increase the charge of ions. This process is handled in the protocol methods, and knowledge of the last keys pressed are stored inside the actual labels. Additionally, the element order, charge, and physical state are all stored as separate strings as properties of the label, and the textfield appends all the strings to create the complete formula.</p>
<pre><code>- (id)initWithCoder:(NSCoder *)coder {
self = [super initWithCoder:coder];
if (self) {
self.userInteractionEnabled = YES;
NSArray *bundle = [[NSBundle mainBundle] loadNibNamed:@"FormulaKeyboard" owner:self options:nil];
for (id object in bundle) {
if ([object isKindOfClass:[FormulaKeyboard class]])
keyboard = (FormulaKeyboard *)object;
}
self.inputView = keyboard;
keyboard.delegate = self;
consecutiveElementCount = 0;
chargeIndex = 4;
self.equationOrder = [[NSMutableArray alloc] init];
startingPoint = 5;
subscriptList = [[NSArray alloc] initWithObjects:@"", @"₂", @"₃", @"₄", @"₅", @"₆", @"₇", @"₈", @"₉", @"₁₀", @"₁₁", @"₁₂", nil];
}
return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self becomeFirstResponder];
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
#pragma mark -- KeyInput Protocol Methods
- (void)newCompound {
//add plus sign
if (self.currentLabel != nil) {
startingPoint = currentLabel.frame.origin.x + currentLabel.frame.size.width + 3;
UILabel *plus = [[UILabel alloc] initWithFrame:CGRectMake(startingPoint, 5, 10, 10)];
plus.text = @"+";
plus.font = [UIFont systemFontOfSize:13];
[plus sizeToFit];
[self addSubview:plus];
startingPoint = plus.frame.origin.x + plus.frame.size.width + 3;
}
self.currentLabel = [[FormulaLabel alloc] initWithFrame:CGRectMake(startingPoint, 2, 10, 22)];
self.currentLabel.elementFormula = [[NSMutableString stringWithString:@""] retain];
self.currentLabel.charge = [[NSString alloc] initWithString:@""];
self.currentLabel.state = [[NSString alloc] initWithString:@""];
[self addSubview:self.currentLabel];
[equationOrder addObject:self.currentLabel];
}
- (void)addElement:(NSString *)currentElement {
if (self.currentLabel != nil) {
if (![currentElement isEqualToString:self.currentLabel.lastElementPressed]) {
// when new element is pressed
[self.currentLabel.elementFormula appendString:currentElement];
self.currentLabel.lastElementPressed = currentElement;
consecutiveElementCount = 1;
subscriptLength = 0;
[self.currentLabel.elementOrder addObject:currentElement];
[self.currentLabel.subscriptOrder addObject:[subscriptList objectAtIndex:0]];
}
// don't increase subscript after 12 or of open parentheses
else if (consecutiveElementCount < 12 && (![currentElement isEqualToString:@"("])) { consecutiveElementCount++;
[self.currentLabel.subscriptOrder replaceObjectAtIndex:[self.currentLabel.subscriptOrder count] - 1 withObject:[subscriptList objectAtIndex:consecutiveElementCount - 1]];
}
NSRange range = NSMakeRange (([self.currentLabel.elementFormula length] - subscriptLength), subscriptLength);
[self.currentLabel.elementFormula deleteCharactersInRange:range];
NSString *tempSubscript = [subscriptList objectAtIndex:consecutiveElementCount - 1];
[self.currentLabel.elementFormula appendString:tempSubscript];
subscriptLength = [tempSubscript length];
[self synthesizeFormula];
}
}
- (void)changeCharge:(NSString *)chargeIncrease {
if (self.currentLabel != nil) {
NSArray *chargeList = [[[NSArray alloc] initWithObjects:@"⁴⁻", @"³⁻", @"²⁻", @"⁻", @"", @"⁺", @"²⁺", @"³⁺", @"⁴⁺", nil] autorelease];
if ([chargeIncrease isEqualToString:@"+"] && chargeIndex < ([chargeList count] - 1))
chargeIndex += 1;
if ([chargeIncrease isEqualToString:@"-"] && chargeIndex > 0)
chargeIndex -= 1;
self.currentLabel.charge = [chargeList objectAtIndex:chargeIndex];
[self synthesizeFormula];
}
}
- (void) changeState:(NSString *)stateName {
if (self.currentLabel.state != nil) {
self.currentLabel.state = stateName;
[self synthesizeFormula];
}
}
- (void)deleteCharacter {
if (![self.currentLabel.elementFormula isEqualToString:@""] && (self.currentLabel != nil)) {
NSString *lastElement = [self.currentLabel.elementOrder objectAtIndex:[self.currentLabel.elementOrder count] - 1];
NSString *lastSubscript = [self.currentLabel.subscriptOrder objectAtIndex:[self.currentLabel.subscriptOrder count] - 1];
int removeLength = [lastElement length] + [lastSubscript length];
NSRange range = NSMakeRange([self.currentLabel.elementFormula length]- removeLength, removeLength);
[self.currentLabel.elementFormula deleteCharactersInRange:range];
[self.currentLabel.elementOrder removeObjectAtIndex:[self.currentLabel.elementOrder count]-1];
[self.currentLabel.subscriptOrder removeObjectAtIndex:[self.currentLabel.subscriptOrder count]-1];
[self synthesizeFormula];
}
}
- (void)synthesizeFormula {
NSMutableString *synthesizedFormula = [[[NSMutableString alloc] initWithString:self.currentLabel.elementFormula] autorelease];
[synthesizedFormula appendString:self.currentLabel.charge];
[synthesizedFormula appendString:self.currentLabel.state];
self.currentLabel.text = synthesizedFormula;
[self.currentLabel sizeToFit];
}
- (void)closeKeyboard {
[self resignFirstResponder];
}
</code></pre>
<p><strong>Label</strong></p>
<p>Where the individual compounds are stored. </p>
<pre><code>@interface FormulaLabel : UILabel {
NSMutableString *elementFormula;
NSString *charge;
NSString *state;
NSString *lastElementPressed;
NSMutableArray *elementOrder;
NSMutableArray *subscriptOrder;
}
@property (nonatomic, retain) NSMutableString *elementFormula;
@property (nonatomic, retain) NSString *charge;
@property (nonatomic, retain) NSString *state;
@property (nonatomic, retain) NSString *lastElementPressed;
@property (nonatomic, retain) NSMutableArray *subscriptOrder;
@property (nonatomic, retain) NSMutableArray *elementOrder;
</code></pre>
|
[] |
[
{
"body": "<p>A UILabel is a view. Make your FormulaLabel class into just a Formula class that inherits from NSObject instead of UILabel.</p>\n\n<pre><code>@interface Formula : NSObject\n</code></pre>\n\n<p>Store data for one formula in the Formula class. The Formulas could be stored in the view controller via NSSet, NSArray, or NSDictionary. This doesn't violate MVC because the Model would be stored inside the controller and not the view. I generally use a \"container class\" that controls adding, removing, modifying, and setting a current data set. </p>\n\n<p>In your view, create just one label for each data field in a formula, only during initialization of the current view, and set the labels <strong>properties</strong> with an update method. If the properties such as font stays the same, you only need to do so during init, or just set in IB and it will get set in awakeFromNib.</p>\n\n<pre><code>- (void)updateLabelsForFormula:(Formula*)formula\n{\n NSString *label1Str;\n NSString *label2Str;\n\n if (formula == nil) {\n //passing nil will clear the labels\n NSString *blank = @\"\";\n label1Str = blank;\n label2Str = blank;\n } else {\n label1Str = [formula someStringForProperty];\n label2Str = [formula someStrongForOtherProperty];\n }\n // set label properties such as text, size, etc\n self.label1.text = label1Str;\n self.label2.text = label2Str;\n}\n</code></pre>\n\n<p>I would use an array to store the individual components, then build a string from the array.</p>\n\n<p>...</p>\n\n<pre><code>@property (nonatomic, strong) NSMutableArray *components;\n- (void)addComponent:(NSString*)component; // add to compnents array\n- (void)removeLastComponent; // remove last component in array;\n- (NSString*)stringFromComponents; // return a string built from components in array\n</code></pre>\n\n<p>...</p>\n\n<p>Much more to be said here, but this should get you started with separating model data from view properties.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-17T06:35:53.760",
"Id": "9080",
"ParentId": "8615",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "9080",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T06:28:01.227",
"Id": "8615",
"Score": "1",
"Tags": [
"design-patterns",
"objective-c",
"mvc"
],
"Title": "App for typing chemical equations to the screen"
}
|
8615
|
Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications that enables malicious attackers to inject client-side script into web pages viewed by other users. An exploited cross-site scripting vulnerability can be used by attackers to bypass access controls such as the same origin policy.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T07:27:04.757",
"Id": "8617",
"Score": "0",
"Tags": null,
"Title": null
}
|
8617
|
<p>I'm a C# programmer and I would like to start getting better at coding in C. I wrote a function which reads a space delimiters settings file (supports comments / and #).
The code works fine. But from the point of view of C coding style, I'd like to know if this code is well written.</p>
<p>example settings file:</p>
<pre><code>//Destination information
DestAddr 192.168.1.101
DestSSHPort 22
</code></pre>
<p>code:</p>
<pre><code>int ReadConfigFile(char * in_filename)
{
int t_buffSize = 612;
char t_key[t_buffSize];
char t_value[t_buffSize];
//if input filename is null
if(!in_filename ||
*in_filename == '\0' ||
in_filename == NULL)
{
return -1;
}
//open file
FILE *t_fd = NULL;
t_fd = fopen (in_filename,"r");
if (t_fd == NULL)
{
fprintf(stderr, "Error opening input file: %s\n",
in_filename);
return -1;
}
//read individual settings lines
char t_firstChar;
while( (t_firstChar = getc(t_fd)) != EOF )
{
//skip comment line
if(t_firstChar == '/' || t_firstChar == '#')
{
char t_comment[t_buffSize];
long t_currFP = getline(t_fd, t_comment, t_buffSize);
fseek(t_fd, t_currFP + 1, SEEK_SET);
}
else
{
long t_currFP = ftell (t_fd);
fseek(t_fd, t_currFP - 1, SEEK_SET);
if(fscanf (t_fd, "%s %s", t_key, t_value) != EOF)
{
printf("%s -- %s \n", t_key, t_value);
//just print the values for now
}
}
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>First of all, <code>getc</code> returns an <code>int</code>, not a <code>char</code> so change <code>char t_firstChar;</code> to <code>int t_firstChar;</code> (a <code>char</code> might not be able to hold <code>EOF</code>).</p>\n\n<hr>\n\n<p>In C it is conventional to put the pointer asterisk next to the variable name, so instead of:</p>\n\n<pre><code>char * in_filename\n</code></pre>\n\n<p>use</p>\n\n<pre><code>char *in_filename\n</code></pre>\n\n<hr>\n\n<p>Most often, function names in C don't use camel case but use underscores, like <code>read_config_file</code>. Follow your style guide or personal preference here. Underscores are more common here.</p>\n\n<hr>\n\n<p>I have seen more C code using curly brackets on the same line than code that has curly brackets on a new line.</p>\n\n<pre><code>if (...) {\n ...\n}\n</code></pre>\n\n<p>This is just a preference and many style guides use this, but just follow your style guide or your personal preference.</p>\n\n<hr>\n\n<p><code>!filename</code> and <code>filename == NULL</code> are the same thing.</p>\n\n<hr>\n\n<p>Your use of fscanf can result in buffer overflows.</p>\n\n<hr>\n\n<p><code>t_buffSize</code> should be a const or a macro. Variable size arrays are dangerous.</p>\n\n<hr>\n\n<p>Since you don't change <code>in_filename</code>, change its type to <code>const char *</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T00:21:37.143",
"Id": "13834",
"Score": "0",
"body": "Actually I prefer char* varname instead of char *varname. It shows clearly the intent of the code: varname's type is a pointer to char."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T16:13:53.023",
"Id": "8625",
"ParentId": "8620",
"Score": "4"
}
},
{
"body": "<p>You are testing for NULL twice</p>\n\n<pre><code>//if input filename is null\nif(!in_filename || // This is a test for NULL. !valid pointer is 0 !NULL is 1\n *in_filename == '\\0' || // Test for empty string\n\n\n in_filename == NULL) // Test for NULL again.\n</code></pre>\n\n<p>No Need to do the work twice.<br>\nWhen you declare the variable assign it at the same time:</p>\n\n<pre><code>//open file\nFILE *t_fd = NULL;\nt_fd = fopen (in_filename,\"r\");\n\n// Easyier to write and read:\n\n//open file\nFILE *t_fd = fopen (in_filename,\"r\");\n</code></pre>\n\n<p>Also not keen on the short non-descriptive file name.</p>\n\n<p>You are only allowing comments if the magic character is the first character in the line. That's a bit restrictive (most places allow for the first non white space character on a line to mark a comment).</p>\n\n<p>That's because scanf() easily allows you to ignore white space:</p>\n\n<pre><code>while( (t_firstChar = getc(t_fd)) != EOF )\n{\n //skip comment line\n if(t_firstChar == '/' || t_firstChar == '#')\n\n// Easier with:\n\nwhile(fscanf(t_fd, \" %c\", & nextChar) == 1)\n{\n // Skips empty lines.\n // Returns the first non white space character\n</code></pre>\n\n<p>You are skipping lines with getline() which reads off the end of line marker ('\\n'). The trouble is you are reading the line into a buffer of fixed size but not checking if you spill over that size. fscanf provides an alternative that allows you to read and discard the content.</p>\n\n<pre><code> long t_currFP = getline(t_fd, t_comment, t_buffSize);\n\n // Can be replaced with:\n fscanf(t_fd, \"%*[^\\n]\"); // Read up to the '\\n character \n // But not including it. The star '*' indicates to\n // discard the input \n fscanf(t_fd, \"\\n\"); // Read the '\\n' character\n\n // Note you have to do these two lines separately.\n // You can not use the string \"%*[^\\n]\\n\"\n // This is because if there is only a '\\n' character (not any comment) then\n // the first part fails and it would have failed leaving the '\\n' on the stream.\n</code></pre>\n\n<p>But you then doing a seek() to an absolute position. I am not sure how this is working in your code because the seek moves the read point to the absolute position identified by the length of the line just read. So unless the only comment is the first line then this will fail.</p>\n\n<pre><code>// this line should just be removed).\n// fseek(t_fd, t_currFP + 1, SEEK_SET);\n</code></pre>\n\n<p>Your move back one space in the input stream is support directly with a relative seek</p>\n\n<pre><code> long t_currFP = ftell (t_fd);\n fseek(t_fd, t_currFP - 1, SEEK_SET);\n\n // replace with:\n fseek(t_fd,-1, SEEK_CUR);\n</code></pre>\n\n<p>Then you do the real work:</p>\n\n<pre><code> if(fscanf (t_fd, \"%s %s\", t_key, t_value) != EOF)\n</code></pre>\n\n<ul>\n<li><p>This line will never return EOF as you have just made sure there is at least one character in the stream be rewinding one place. But it can still fail. You should test the result for the number of conversions it performed.</p></li>\n<li><p>Also if either your key or value exceed the size of the buffer things will horribly wrong. So you need to make sure your don't read past the end of the buffer:</p></li>\n<li><p>Finally you are not reading off the '\\n' character this will leave this on the line for (see above to find about reading the rest of the line).</p></li>\n</ul>\n\n<p>How to build the conversion string will depend.<br>\nYou are using the identifier <code>t_buffSize</code> as a buffer size. If this is a macro (which it usually is) then building the string is easy with some macros magic and string compile time concatenation:</p>\n\n<pre><code>#define DO_QUOTE(X) #X\n#define QUOTE(X) DO_QUOTE(X)\n\n#define CONVERSION_STRING_SIZE(SIZE) \"%\" QUOTE(SIZE) \"s\"\n\n#define ConvString CONVERSION_STRING_SIZE(t_buffSize) \" \" CONVERSION_STRING_SIZE(t_buffSize)\n\n// Assuming t_buffSize is 50 this should generate the string:\n// ConvString => \"%\" \"50\" \"s\" \" \" \"%\" \"50\" \"s\"\n// Consecutive string literals are concatenated at compile time to generate\n// \"%50s %50s\"\n</code></pre>\n\n<p>On the other hand if t_buffSize is a variable of type int the you will need to build the string dynamically using sprintf()</p>\n\n<pre><code>char ConvString[100]; // Big enough for two integer and 5 characters\nsprintf(ConvString, \"%%%ds %%%ds\", t_buffSize, t_buffSize);\n</code></pre>\n\n<p>Then you final read is:</p>\n\n<pre><code> if(fscanf (t_fd, ConvString, t_key, t_value) == 2)\n {\n // Do Stuff\n }\n // Ignore the rest of the line:\n fscanf(t_fd, \"%*[^\\n]\");\n fscanf(t_fd, \"\\n\");\n</code></pre>\n\n<h3>Summary</h3>\n\n<pre><code>#define BUFFER_SIZE 612\n#define DO_QUOTE(X) #X\n#define QUOTE(X) DO_QUOTE(X)\n#define ConvString \"%\" QUOTE(BUFFER_SIZE) \"s %\" QUOTE(BUFFER_SIZE) \"s\"\n\nint ReadConfigFile(char const *in_filename)\n{\n char t_key[BUFFER_SIZE];\n char t_value[BUFFER_SIZE];\n\n //if input filename is null\n if(!in_filename || *in_filename == '\\0')\n {\n fprintf(stderr, \"Invalid filename\\n\");\n return -1;\n }\n\n //open file\n FILE *t_fd = fopen (in_filename, \"r\");\n\n if (t_fd == NULL)\n {\n fprintf(stderr, \"Error opening input file: %s\\n\", in_filename);\n return -1;\n }\n\n //read individual settings lines\n char t_firstChar;\n while(fscanf(t_fd, \" %c\", &t_firstChar) == 1 )\n {\n if(t_firstChar != '/' && t_firstChar == '#')\n {\n // Not a comment so read the key value pair\n fseek(t_fd, -1, SEEK_CUR);\n\n if(fscanf (t_fd, ConvString, t_key, t_value) == 2)\n {\n printf(\"%s -- %s \\n\", t_key, t_value);\n }\n }\n\n // Ignore the rest of the line.\n fscanf(t_fd, \"%*[^\\n]\");\n // Don't need this line as the scanf() in the while will ignore '\\n' as white space.\n // But I have left it in for clarity.\n fscanf(t_fd, \"\\n\");\n }\n\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T19:53:14.853",
"Id": "13746",
"Score": "0",
"body": "Thank you Loki, you went out of your way to explain, cheers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T18:46:03.487",
"Id": "13803",
"Score": "0",
"body": "Quick question on the macros thought. is there a reason why you wrote `#define DO_QUOTE(X) #X\n #define QUOTE(X) DO_QUOTE(X)` and not just directory specifying QUOTE like so .... `#define QUOTE(X) #X`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T18:56:06.573",
"Id": "13804",
"Score": "0",
"body": "@ArmenB.: There are some corner case which I forget that will prevent that from working correctly in all situations. So by using the double indirect (as shown above) it always works."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T21:20:49.590",
"Id": "13811",
"Score": "1",
"body": "@ArmenB.: see: http://stackoverflow.com/q/5519680/14065 and http://stackoverflow.com/q/7387687/14065"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T00:43:02.477",
"Id": "8639",
"ParentId": "8620",
"Score": "14"
}
},
{
"body": "<p>It is a good idea in C to declare all the variables in the beginning of the scope, or you may have problems on some compilers (for example, Visual Studio).</p>\n\n<p>Also, <code>//</code> are C++ comments. In C, you should use <code>/* ... */</code> </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T00:22:07.673",
"Id": "13835",
"Score": "2",
"body": "That comment about comment's not true since C99."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T16:30:33.187",
"Id": "13976",
"Score": "2",
"body": "@kaoD: There is not universal support for C99 (yet) so it is a valid comment."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T11:54:44.580",
"Id": "8695",
"ParentId": "8620",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "8639",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T15:14:18.767",
"Id": "8620",
"Score": "9",
"Tags": [
"c",
"parsing"
],
"Title": "Read a space delimiters settings file in C"
}
|
8620
|
<p>I have taken a stab at creating my first jQuery script from scratch. I use this to post an update to a Django application that allows a user to "follow" another user. I am sure that there are better ways to do this and I appreciate any help that anyone can give.</p>
<pre><code><script type="text/javascript">
jQuery(function() {
jQuery('.follow').click(function(event) {
event.preventDefault();
var url = jQuery(this).attr("href");
var followtype = jQuery(this).text();
var user = jQuery(".follow").attr("href").match('/relationships/[a-z]+/([a-z]+)/following/')[1];
var postdata = {
'csrfmiddlewaretoken': '{{ csrf_token }}'
}
jQuery.post(url, postdata, function(json){
if(json.result == '1') {
if(followtype == 'Follow') {
jQuery('.follow').text('Unfollow');
jQuery('.follow').attr("href", '/relationships/remove/'+user+'/following/');
} else {
jQuery('.follow').text('Follow');
jQuery('.follow').attr("href", '/relationships/add/'+user+'/following/');
}
}
})
});
});
</script>
</code></pre>
|
[] |
[
{
"body": "<p>This is how I'd do it. There may be flaws because you haven't provided your HTML.</p>\n\n<p>I assume that within the <code>click</code> handler, you only want to interact with the current element being clicked. The reason I say that is because you had <code>$('.follow')</code> a number of times in there, which would affect <em>all</em> <code>.follow</code> elements.</p>\n\n<pre><code> // v--- makes the shortcut available inside the .ready() callback\njQuery(function($) {\n $('.follow').click(function(event) {\n event.preventDefault();\n\n // assuming it's a link, no need for jQuery here\n var url = this.href;\n\n // Looking at the code in your callback, I assume you only have text content\n var followtype = this.innerHTML;\n\n // I assume you actually want just the current \"follow\", not all\n var user = url.match('/relationships/[a-z]+/([a-z]+)/following/');\n\n // Make certain there was a match before accessing the Array.\n // If there was no match, just return the function\n if( user )\n user = user[1];\n else\n return;\n\n var postdata = {\n 'csrfmiddlewaretoken': '{{ csrf_token }}'\n };\n // Inside the $.post callback, are we still only working with the current\n // \"follow\" clicked? If so, cache it here, and use it in the callback\n var this_follow = this;\n\n $.post(url, postdata, function(json){\n if(json.result == '1') {\n if(followtype == 'Follow') {\n this_follow.innerHTML = 'Unfollow';\n this_follow.pathname = '/relationships/remove/'+user+'/following/';\n } else {\n this_follow.innerHTML = 'Follow';\n this_follow.pathname = '/relationships/add/'+user+'/following/';\n }\n }\n })\n });\n});\n</code></pre>\n\n<p>As you can see, I tend to eliminate jQuery when convenient.</p>\n\n<p>I should note that using <code>.innerHTML</code> in the way I have is cheating a bit. It's an HTML parser really, but it's convenient for changing small chunks of text quickly.</p>\n\n<p>To do it properly, you'd select the child text node of the element, and change its <code>nodeValue</code>.</p>\n\n<pre><code>this_follow.firstChild.nodeValue = 'Unfollow';\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T16:26:21.363",
"Id": "8627",
"ParentId": "8621",
"Score": "2"
}
},
{
"body": "<p>Two generic notes:</p>\n\n<ol>\n<li><p>I'd invert the condition:</p>\n\n<pre><code>jQuery.post(url, postdata, function(json){\n if(json.result != '1') {\n return;\n }\n if(followtype == 'Follow') {\n jQuery('.follow').text('Unfollow');\n jQuery('.follow').attr(\"href\", '/relationships/remove/'+user+'/following/');\n } else {\n jQuery('.follow').text('Follow');\n jQuery('.follow').attr(\"href\", '/relationships/add/'+user+'/following/');\n }\n}\n</code></pre>\n\n<p>It makes the code flatten and more readable.</p>\n\n<p>References: <em>Replace Nested Conditional with Guard Clauses</em> in <em>Refactoring: Improving the Design of Existing Code</em>; <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">Flattening Arrow Code</a></p></li>\n<li><p>Lots of duplication could be eliminated with local variables:</p>\n\n<pre><code> var text;\n var command;\n if (followtype == 'Follow') {\n text = 'Unfollow';\n command = 'remove';\n } else {\n text = 'Follow';\n command = 'add';\n }\n var follow = jQuery('.follow');\n follow.text(text);\n follow.attr(\"href\", '/relationships/' + command + '/' + user + '/following/');\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T16:45:11.270",
"Id": "8628",
"ParentId": "8621",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T15:14:22.013",
"Id": "8621",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "Application for allowing a user to \"follow\" another user"
}
|
8621
|
<p>I have a properties file I'm using for GIS software. You have a feature like a road, then properties under it, like so:</p>
<pre><code>{
"road": {
"colour": "rgb(0,0,0)"
},
"railway": {
"colour": "rgb(100,100,100)"
}
}
</code></pre>
<p>Now I need to group these into categories, for example, transportation. The first thing I thought of was:</p>
<pre><code>{
"transportation":
{
"road": {
"colour": "rgb(0,0,0)"
},
"railway": {
"colour": "rgb(100,100,100)"
}
}
}
</code></pre>
<p>This makes things awkward when I want to access <code>"road"</code> (for example), because now I need to know it is under <code>"transportation"</code> (mind you I could always write a helper function to eliminate this). Further, <code>"road"</code> could be under multiple groups, perhaps <code>"transportation"</code> and <code>"public works"</code>. Now I would need to duplicate the properties in both instances.</p>
<p>Would I be wiser to use the following format, or is there a better way to do this?</p>
<pre><code>{
"road": {
"colour": "rgb(0,0,0)",
"group": ["transportation"]
},
"railway": {
"colour": "rgb(100,100,100)",
"group": ["transportation"]
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T00:26:44.857",
"Id": "13550",
"Score": "0",
"body": "This has nothing at all to do with php."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T20:51:07.390",
"Id": "13748",
"Score": "0",
"body": "It has little to do with PHP. The PHP portion is stating what language I am using to work with the data. People often ask stuff like \"In what application are you trying to do this in?\" Part of that question is answered by having the php tag."
}
] |
[
{
"body": "<p>Assuming you're using JavaScript to manipulate the object, you could also split it up into 2 different structures, one for maintaining the hierarchy and another for easy access:</p>\n\n<pre><code>var hierarchy = {\n transportation: {\n road: {\n colour: \"rgb(0,0,0)\"\n },\n railway: {\n colour: \"rgb(100,100,100)\"\n }\n }\n};\n</code></pre>\n\n\n\n<pre><code>var features = {\n road: hierarchy.transportation.road,\n railway: hierarchy.transportation.railway\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T20:52:08.137",
"Id": "13749",
"Score": "0",
"body": "I am not using javascript here, but rather straight JSON in text files.\n\nStill, this is the way I ended up leaning to. I have my styles in one JSON file, while completely ignoring the hierarchy. Then another file states the nesting hierarchy of the features."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T17:40:44.397",
"Id": "8629",
"ParentId": "8622",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "8629",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T15:41:06.233",
"Id": "8622",
"Score": "0",
"Tags": [
"json"
],
"Title": "JSON formatting and processing hierarchies"
}
|
8622
|
<p>I've just started working with Workflow (WF4) and have been playing with an idea of using it in MVC3.0 controller actions to see if it improves the maintainability of complex actions; also potentially giving the ability to make multiple DB calls in parallel to populate the output model. Along with this I've been looking at Async controller actions but I'm not sure I've really got my head around those. I know you can load workflow into a WorkflowApplication and call BeginRun(...) to get that to run asynchronously but I'm thinking that's the wrong approach; from looking online I've come up with the following implementation which does run as expected but I'm wondering if there's anything wrong with the code below or it will cause other issues that I've not thought about.</p>
<pre><code> [HttpPost]
public void ConfigureAsync(ConfigureExportInputModel inputModel)
{
if (inputModel == null)
{
throw new ArgumentNullException("inputModel");
}
var arguments = new Dictionary<string, object> { { "ExportType", inputModel.ExportType } };
var wf = new ErrorHandledExportWorkflow();
AsyncManager.OutstandingOperations.Increment();
ThreadPool.QueueUserWorkItem(o =>
{
AsyncManager.Parameters["result"] = WorkflowInvoker.Invoke(wf, arguments)["MvcOutput"] as IDefineMvcOutput;
AsyncManager.OutstandingOperations.Decrement();
});
}
public ActionResult ConfigureCompleted(IDefineMvcOutput result)
{
return this.ActionResultFactory.Create(this, result);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T16:28:46.267",
"Id": "13690",
"Score": "2",
"body": "Just FYI - C# 4 introduced the Code Contracts library so you can do `Contract.Requires(inputModel != null)` which is more semantic and has interesting AOP possibilities. For example you can have all these checks fire in development and testing and disabled to boost performance in production. There is also a VS extension that will attempt to do some basic analysis on the code contracts *while your coding* and point out gaps in logic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T18:54:05.783",
"Id": "13700",
"Score": "0",
"body": "Thanks for the comment, I've seen code contracts and taken a quick look but not used them in any real code yet - they do sound really nice. I keep meaning to see if there's a way to unit test that a method implements a particular contract. I think you can put them on as attributes so it would be possible to do it that way; reflect over the method to confirm it has the expected contract(s) in place."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T19:24:59.183",
"Id": "13702",
"Score": "0",
"body": "I think code contracts are complementary to unit tests, they don't need to and shouldn't be included by them. From what I understand they are inspired by projects like Spec# so they aim to eventually be an extension of the type system. As far as using them goes though, it takes like 5 seconds to learn, I very much recommend it."
}
] |
[
{
"body": "<p>I cannot believe this went unanswered for 5 and a half years (I guess I can, it <em>is</em> a difficult question to answer) - I'm going to try to answer it from the respect of early 2012, and the respect of today (mid 2017).</p>\n\n<hr>\n\n<h1>2012</h1>\n\n<p>The biggest concern I see comes from this line:</p>\n\n<blockquote>\n<pre><code>AsyncManager.Parameters[\"result\"] = WorkflowInvoker.Invoke(wf, arguments)[\"MvcOutput\"] as IDefineMvcOutput;\n</code></pre>\n</blockquote>\n\n<p>I don't know how WorkflowInvoker works, but I assume that it has the capability of throwing an exception, which means that your <code>AsyncManager.OutstandingOperations.Decrement();</code> line would not be reached, and I wonder what other issues that might cause for your application. (Looking for operations that aren't there, for example.) I would consider a <code>try</code>/<code>finally</code> block, or decrement <em>before</em> your operation gets invoked. (You can probably consider \"In Progress\" as a non-outstanding operation.)</p>\n\n<p>The other issue I see with your Lambda method is regarding the idea of \"closures\", and captured variables. In .NET the <code>wf</code> and <code>arguments</code> variables are still part of the local method and are simply referring to the local copy, which means if you modify either variable after queuing up the worker, you could end up with a different result. This may not be an issue with your infrastructure, but I feel it's worth pointing out none-the-less.</p>\n\n<hr>\n\n<h1>2017</h1>\n\n<p>Let's fast-forward five years and six months (which is an agonizingly long time) and examine what <em>language</em> features might make this a different process. I'm just going to post the form that takes advantage of the new language features, then we'll discuss where <code>async</code>/<code>await</code> might help you.</p>\n\n<pre><code>[HttpPost]\npublic void ConfigureAsync(ConfigureExportInputModel inputModel)\n{\n if (inputModel == null)\n {\n throw new ArgumentNullException(\"inputModel\");\n }\n\n var arguments = new Dictionary<string, object> { [nameof(inputModel.ExportType)] = inputModel.ExportType };\n var wf = new ErrorHandledExportWorkflow();\n\n AsyncManager.OutstandingOperations.Increment();\n ThreadPool.QueueUserWorkItem(o =>\n {\n AsyncManager.Parameters[\"result\"] = WorkflowInvoker.Invoke(wf, arguments)[\"MvcOutput\"] as IDefineMvcOutput;\n AsyncManager.OutstandingOperations.Decrement();\n });\n}\n\npublic ActionResult ConfigureCompleted(IDefineMvcOutput result) =>\n this.ActionResultFactory.Create(this, result);\n</code></pre>\n\n<p>So it doesn't look much different, but you can see that it's just a bit shorter. The expression-bodied method syntax, the dictionary initializer, and the <code>nameof</code> operator. But what <em>really</em> makes a difference is the <code>async</code>/<code>await</code> of the TPL. This starts making our code come alive.</p>\n\n<p>With the <em>proper</em> implementation, you can leverage <code>async</code>/<code>await</code> to really bring a good flow to the asynchronous nature of your code. If properly implemented on the <code>WorkflowInvoker.Invoke</code> method, you might get away with something like:</p>\n\n<blockquote>\n<pre><code>[HttpPost]\npublic Task<ActionResult> RunAsync(ConfigureExportInputModel inputModel)\n{\n if (inputModel == null)\n {\n throw new ArgumentNullException(\"inputModel\");\n }\n\n var arguments = new Dictionary<string, object> { [nameof(inputModel.ExportType)] = inputModel.ExportType };\n var wf = new ErrorHandledExportWorkflow();\n\n var result = await WorkflowInvoker.InvokeAsync(wf, arguments);\n return this.ActionResultFactory.Create(this, result[\"MvcOutput\"] as IDefineMvcOutput);\n}\n</code></pre>\n</blockquote>\n\n<p>This would allow you to <code>await</code> the whole method, and return the thread to the pool until done. By leveraging what .NET built-in with C#5.0, you can write succinct asynchronous code that doesn't have to worry about the overhead of performing the async operations. The framework and language really take that burden away from you.</p>\n\n<p>Of course, this expects an <code>InvokeAsync</code> method on the <code>WorkflowInvoker</code>, which may or may not exist, and as such this is pseudo-/hypothetical code, but the idea should remain the same. You can <a href=\"https://msdn.microsoft.com/library/hh191443(vs.110).aspx\" rel=\"noreferrer\">read the MSDN article</a> for more explanation of what is possible with this design.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-17T18:55:42.843",
"Id": "328697",
"Score": "0",
"body": "Thank you for your detailed response (and yes, it is a blast from the past question!)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-17T19:02:13.487",
"Id": "328698",
"Score": "2",
"body": "@PaulHadfield I'm actually pleasantly surprised you're still around. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-18T04:29:47.790",
"Id": "328737",
"Score": "0",
"body": "Three thoughts: 1) Did you want to quote the first snippet which is OP code and not the second one which is yours? 2) Didn't you forget the `async` keyword on the method signature in your implementation? 3) Wouldn't we now return `BadRequest()` instead of throwing an `ArgumentNullException`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-18T13:28:26.583",
"Id": "328775",
"Score": "0",
"body": "@t3chb0t 1) No, the first block is my code, the second is *pseudo-C#* code, so I quoted it to mean it's **not** usable. 2) Yes, I forgot that `async` modifier - part of th reason for the quote. ;) 3) Yes, and again, part of the reason for *pseudo-* quote."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-17T14:41:44.320",
"Id": "173263",
"ParentId": "8624",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "173263",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T15:56:33.393",
"Id": "8624",
"Score": "6",
"Tags": [
"c#",
"asp.net-mvc-3",
"asynchronous"
],
"Title": "MVC Async Action Invoking Workflow"
}
|
8624
|
<p>I have been building my own carousel over the past few days. I am not a jQuery guru, just an enthusiast, and I think my code is a little sloppy, hence the post.</p>
<p>Basically what happens is:</p>
<ul>
<li>If someone hits the page with a # values in the URL it will show the appropriate slide and example would be www.hello.com#two, this would slide to slide two.</li>
<li>If someone clicks the numbers it will show the appropriate slide.</li>
<li>Next and prev also slide through the slides.</li>
</ul>
<p>Is there anything I could have written better, as I know there is a lot of duplicate code?</p>
<blockquote>
<pre><code>if ($slideNumber == 1) {
$('#prev').attr("class", "not_active")
$('#next').attr("class", "active")
}
else if ($slideNumber == divSum) {
$('#next').attr("class", "not_active");
$('#prev').attr("class", "active");
}
else {
$('#prev').attr("class", "active")
$('#next').attr("class", "active")
};
</code></pre>
</blockquote>
<p>I've made a <a href="http://jsfiddle.net/JHqBA/2/" rel="nofollow">jsFiddle</a> and included the complete code below:</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 () {
//////////////////////////// INITAL SET UP /////////////////////////////////////////////
//Get size of images, how many there are, then determin the size of the image reel.
var divWidth = $(".window").width();
var divSum = $(".slide").size();
var divReelWidth = divWidth * divSum;
//Adjust the image reel to its new size
$(".image_reel").css({ 'width': divReelWidth });
//set the initial not active state
$('#prev').attr("class", "not_active");
//////////////////////////// SLIDER /////////////////////////////////////////////
//Paging + Slider Function
rotate = function () {
var triggerID = $slideNumber - 1; //Get number of times to slide
var image_reelPosition = triggerID * divWidth; //Determines the distance the image reel needs to slide
//sets the active on the next and prev
if ($slideNumber == 1) {
$('#prev').attr("class", "not_active")
$('#next').attr("class", "active")
}
else if ($slideNumber == divSum) {
$('#next').attr("class", "not_active");
$('#prev').attr("class", "active");
}
else {
$('#prev').attr("class", "active")
$('#next').attr("class", "active")
};
//Slider Animation
$(".image_reel").animate({
left: -image_reelPosition
}, 500);
};
//////////////////////////// SLIDER CALLS /////////////////////////////////////////////
//click on numbers
$(".paging a").click(function () {
$active = $(this); //Activate the clicked paging
$slideNumber = $active.attr("rel");
rotate(); //Trigger rotation immediately
return false; //Prevent browser jump to link anchor
});
//click on next button
$('#next').click(function () {
if (!$(".image_reel").is(':animated')) { //prevent clicking if animating
var left_indent = parseInt($('.image_reel').css('left')) - divWidth;
var slideNumberOn = (left_indent / divWidth);
var slideNumber = ((slideNumberOn * -1) + 1);
$slideNumber = slideNumber;
if ($slideNumber <= divSum) { //do not animate if on last slide
rotate(); //Trigger rotation immediately
};
return false; //Prevent browser jump to link anchor
}
});
//click on prev button
$('#prev').click(function () {
if (!$(".image_reel").is(':animated')) { //prevent clicking if animating
var left_indent = parseInt($('.image_reel').css('left')) - divWidth;
var slideNumberOn = (left_indent / divWidth);
var slideNumber = ((slideNumberOn * -1) - 1);
$slideNumber = slideNumber;
if ($slideNumber >= 1) { //do not animate if on first slide
rotate(); //Trigger rotation immediately
};
}
return false; //Prevent browser jump to link anchor
});
//URL eg:www.hello.com#one
var hash = window.location.hash;
var map = {
one: 1,
two: 2,
three: 3,
four: 4
};
var hashValue = map[hash.substring(1)];
//animate if hashValue is not null
if (hashValue != null) {
$slideNumber = hashValue;
rotate(); //Trigger rotation immediately
return false; //Prevent browser jump to link anchor
};
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.window {
height:200px; width: 200px;
overflow: hidden; /*--Hides anything outside of the set width/height--*/
position: relative;
}
.image_reel {
position: absolute;
top: 0; left: 0;
}
.slide {float:left; width:200px; height:200px}
.one {background: #03C}
.two {background:#0F6}
.three {background: #39C}
.four {background:#FC3}
.hide {display:none}
.not_active {background:#F00}
.active {background:#0F0}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div class="window">
<div class="image_reel">
<div class="slide one">slide 1</div>
<div class="slide two">slide 2</div>
<div class="slide three">slide 3</div>
<div class="slide four">slide 4</div>
</div>
</div>
<div class="paging">
<a href="#" rel="1">one</a>
<a href="#" rel="2">two</a>
<a href="#" rel="3">three</a>
<a href="#" rel="4">for</a>
</div>
<div class="nav">
<a id="prev" class="active" href="#">prev</a>
<a id="next" class="active" href="#">next</a>
</div></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p><strong>1) Separation of Concerns</strong></p>\n\n<p>Start by refactorring your code in to more granular functions.\nYou can read more about SoF at <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Separation_of_concerns</a></p>\n\n<p>Update:\nE.g. Instead of having your reel resizing code inline, put it in it's own function, like this: </p>\n\n<pre><code>function setImageReelWidth () {\n //Get size of images, how many there are, then determin the size of the image reel.\n var divWidth = $(\".window\").width();\n var divSum = $(\".slide\").size();\n var divReelWidth = divWidth * divSum;\n\n //Adjust the image reel to its new size\n $(\".image_reel\").css({ 'width': divReelWidth }); \n}\n</code></pre>\n\n<p>This achieves 2 things:</p>\n\n<p>a. First, it groups a block of code that is logically cohesive, removing it from the main code which results in a much cleaner code habitat.\n b. It effectively gives a label to the code block via the function name that is descriptive of what it does, and therefore makes understanding of the code much simpler.</p>\n\n<p>Later, you can also encapsulate the whole thing in it's own \"class\" (function) and you can move it into it's own js file.</p>\n\n<p><strong>2) The jQuery \"on\" function</strong></p>\n\n<p>Use the \"on\" function to attach your click events, rather than the \"click\" function.\n<a href=\"http://api.jquery.com/on/\" rel=\"nofollow\">http://api.jquery.com/on/</a>\nThis has the added advantage of also binding it to future elements matching your selector, even though they do not exist yet.</p>\n\n<p><strong>3) The ready function</strong></p>\n\n<pre><code>// I like the more succinct:\n$(handler)\n// Instead of:\n$(document).ready(handler)\n</code></pre>\n\n<p>But you might like the more obvious syntax.</p>\n\n<p>Those are just a few things to start with.</p>\n\n<p>-- Update 1 --</p>\n\n<p>I think you should keep your original code block in your question, so that future readers can see where it started and how it systematically improved.</p>\n\n<blockquote>\n <p>I would like to know more about the create a new function, outside of\n the jQuery ready block as i cant get this working or quite understand\n how i can get it to work sorry</p>\n</blockquote>\n\n<p>I am not familiar with jsfiddle.net, but it looks cool and helpful, but might also be a bit confusing if you don't know what is going on. I am not sure I do :), but I think that script editor window results in a .js file that is automatically referenced by the html file.</p>\n\n<p>So here is an example of a function defined outside of the ready block, but referenced from within.</p>\n\n<pre><code>function testFunction () {\n alert ('it works');\n}\n$(document).ready(function () {\n testFunction();\n\n // ... other code\n});\n</code></pre>\n\n<p>This should pop up an alert box that says, \"it works\" when the page is loaded.\nYou can try it for yourself.\nThen, once you got that working, you can refactor other logically cohesive blocks of code into their own functions. Later you can wrap them all up into their own javascript 'class'. But we'll get to that.</p>\n\n<blockquote>\n <p>also is there a better way to write:</p>\n</blockquote>\n\n<pre><code>if ($slideNumber == 1) {\n $('#prev').attr(\"class\", \"not_active\")\n $('#next').attr(\"class\", \"active\")\n}\nelse if ($slideNumber == divSum) {\n $('#next').attr(\"class\", \"not_active\");\n $('#prev').attr(\"class\", \"active\");\n}\nelse {\n $('#prev').attr(\"class\", \"active\")\n $('#next').attr(\"class\", \"active\")\n};\n</code></pre>\n\n<p>One option is to write it like this:</p>\n\n<pre><code>$('#prev').attr(\"class\", \"not_active\")\n$('#next').attr(\"class\", \"not_active\")\nif ($slideNumber > 1)\n $('#prev').attr(\"class\", \"active\")\nif ($slideNumber < divSum )\n $('#next').attr(\"class\", \"active\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T20:13:14.953",
"Id": "8635",
"ParentId": "8634",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "8635",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T19:59:14.863",
"Id": "8634",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"animation"
],
"Title": "Carousel for website"
}
|
8634
|
<p>I wrote a framework and I want to hear the thoughts of other on the design patterns it uses. Every method contains three design patterns - adapters(strategy), intercepting filters, and observers.</p>
<p>A normal class/method in a class looks like this:</p>
<pre><code>class Run extends PVStaticObject{
public static function goForARun($miles) {
$return ='I ran '.$miles. ' miles today';
return $return;
}
}
</code></pre>
<p>With the design patterns the class/method looks like this:</p>
<pre><code>class Run extends PVStaticObject{
public static function goForARun($miles) {
if (self::_hasAdapter(get_class(), __FUNCTION__))
return self::_callAdapter(get_class(), __FUNCTION__, $miles);
$miles = self::_applyFilter(get_class(), __FUNCTION__, $miles, array('event' => 'args'));
$return ='I ran '.$miles. ' miles today';
self::_notify(get_class() . '::' . __FUNCTION__, $miles, $return);
$return = self::_applyFilter(get_class(), __FUNCTION__, $return, array('event' => 'return'));
return $return;
}
}
</code></pre>
<p>A brieft explanation, the adapter will completely change the method by calling another method in its place. Its a way of changing the functionality of a class without modifying the core functionality. </p>
<p>Filters modify variables in a method by passing them out to another class's method or anonymous function where they are modified and return. Normal execution of the method continues.</p>
<p>Observers do not have a return and are purely call another class or anonymous function. They are for event drivin programming. </p>
<p>Examples of adding adapters, filters and observers are below.</p>
<pre><code>Run::addObserver('Run::goForARun', 'run_observer', function($miles, $return){
echo PVHtml::div('Running '. $miles. ' has caused you to lose 2 pounds', array('style' => 'margin-top:10px;'));
}, array('type' => 'closure'));
Run::addAdapter('Run','goForARun', function($miles){
echo PVHtml::p('Because of the weather, you were not able to run '.$miles. ' today');
}, array('type' => 'closure'));
Run::addFilter('Run', 'goForARun', 'run_filter', function($data, $options) {
$data = PVHtml::strong($data);
$data = PVHtml::p($data);
return $data;
}, array('type'=> 'closure', 'event' => 'return'));
</code></pre>
<p>So what is thoughts and feedback on the design patterns? They are meant to faciliate aspect oriented and event driven design. They also to replace design patterns like dependency injection easily.</p>
<p>PS: More examples of AOP <a href="https://github.com/ProdigyView/ProdigyView/tree/master/examples/design" rel="nofollow">here</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T18:37:15.480",
"Id": "13582",
"Score": "0",
"body": "Do not approach this problem from the point of view of the common solution of using DI/IoC/Strategy. This is none of those and does NOT strive to be it. These design patterns are about method manipulation and aspect oriented programming. DI/IoC/Strategy is nice for classes with one or two methods but can be boilerplated and cumbersome as classes become larger. Why rewrite a whole class to alter one method? Also this approach does not require a dependency, dependency can be added as needed meaning they are loosely coupled and easily exchangeable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T15:18:35.767",
"Id": "13628",
"Score": "0",
"body": "We know that you are doing something different. We just don't think its better."
}
] |
[
{
"body": "<p>Firstly, that is a ridiculous of boilerplate to put into every function. That alone means I'd never have anything to do with that code.</p>\n\n<p>Secondly, I don't see how its a good idea. Basically, all of these constructs allow the modification of the behaviour of the object. My functions won't act like I expect them to because somebody's filtered the input, replaced the function with an adapter, and has dozens of observers hanging off of it. </p>\n\n<p>These techniques can be useful, but I think they generally harm code readability. Introducing a framework that encourages doing it everywhere strikes me a recipe for disaster.</p>\n\n<p>Let's consider the example of not running in the rain, comparing DI and your method:</p>\n\n<p>DI</p>\n\n<pre><code>class SunnyRunner\n{\n void run()\n {\n print \"Running\";\n }\n}\n\nclass RainyRunner\n{\n void run()\n {\n print \"Staying out of the rain\";\n }\n}\n\nif(weather.raining)\n runner = new RainyRunner();\nelse\n runner = new SunnyRunner();\n</code></pre>\n\n<p>AOP (yours)</p>\n\n<pre><code>class Runner\n{\n void run()\n {\n print \"Running\";\n }\n}\n\nif(weather.raining)\n{\n runner.adapt(\"run\", function() {\n print \"Staying out of the rain\";\n });\n}\n</code></pre>\n\n<p>They are somewhat similiar, but to my mind your method gives me a false impression of what the code does. The DI makes it clear that we split into two different versions of Runner depending. Your code gives me the impression there is only one runner, and then subverts that. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T23:04:30.590",
"Id": "13498",
"Score": "0",
"body": "Consider this when comparing DI to these adapters. 1) DI you are building an object with multiple objects. Here you are just replacing the default functionality of a single method. 2) For larger interfaces, DI maybe require a whole rewrite of an entire class. That can be a lot of code. Back to the answer one, you are just modifying one method. 3) DI requires classes. This can be done with anonymous functions. 4) DI requires dependencies to be marked as public. This can be used with protected and privated. For complex functions, these adapters are more flexible and easier to write than DI."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T23:39:33.937",
"Id": "13501",
"Score": "2",
"body": "@DevinDixon, I grant that you method is more flexible and in at least some cases easier then DI. My concern is that it also makes it harder to follow your code. Sometimes that'll be worth it, but IMO often not. I do use those technique when they are useful. But to build a framework based on the pervasively applying those techniques seems like a bad idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T20:45:29.487",
"Id": "24905",
"Score": "0",
"body": "@DevinDixon how does DI require dependencies to be marked as public?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T22:11:03.107",
"Id": "8638",
"ParentId": "8637",
"Score": "2"
}
},
{
"body": "<p>You should relearn design patterns. Until you do this, your framework is bound to be messed up and poorly architected, if only because of your flawed axioms.</p>\n\n<p>The Adapter Pattern is for taking <code>class A implements InterfaceA</code> and wrapping it inside a <code>class Adapter</code> so that you can use it with the same API as <code>class B implements InterfaceB</code>. It has <strong>nothing</strong> to do with executing different code or whatever inside another class.</p>\n\n<p>The Strategy Pattern is meant to reduce cyclomatic complexity (<em>basically</em>, lots of nested if statements). It works like this:</p>\n\n<pre><code>interface BasicLogicI {\n public function execute();\n}\n\nclass GreetingLogic implements BasicLogicI {\n public function execute() { echo \"Hi!\\n\"; }\n}\n\nclass DismissLogic implements BasicLogicI {\n public function execute() { echo \"Bye!\\n\"; }\n}\n\nclass Speaker {\n protected $strategy;\n\n public function __construct($strategy) {\n $this->changeContext($strategy);\n }\n public function changeContext($strategy) {\n unset($this->strategy);\n $this->strategy = $strategy;\n }\n public function speak() {\n $this->strategy->execute();\n }\n}\n\n$speaker = new Speaker(new GreetingLogic);\n$speaker->speak();\n$speaker->changeContext(new DismissLogic);\n$speaker->speak();\n// Output: Hi!\n// Bye!\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T23:04:18.553",
"Id": "13543",
"Score": "0",
"body": "Everyone goes after the adapter pattern. One thing I should say its not exactly an adapter but attempts to a mix between adapter and strategy but more flexible. Strategy has the same issues that DI. The pattern implemented above is not about rewriting an entire class and passing the object, interface or not, which can be more work than its worth. The adapter is about easily writing a single method of class and having it loosely coupled if needed. I also should state that another semi popular framework, Lithium, uses the adapter pattern in a similar way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T23:28:47.053",
"Id": "13546",
"Score": "0",
"body": "Also, the adapter pattern above only has +1 cylomatic complexity compared to strategy. Rather than seeing this as design patterns already known and written about, see this as a different approach to solving a problem. Also, proof of concept it does work: https://github.com/ProdigyView/Helium-MongoDB . Adapters work in there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T23:40:39.220",
"Id": "13547",
"Score": "0",
"body": "Just because you say something is an adapter doesn't make it so. That's my point."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T22:17:44.690",
"Id": "8671",
"ParentId": "8637",
"Score": "5"
}
},
{
"body": "<p>I'm not really sure that I agree that what you have presented is a solution for providing AOP in PHP. A true AOP solution would allow you to point-cut at any line of code, not just at the entrance and exit of a method call. Also, I would argue that the amount of boilerplate required is counter-productive to the goal of making code easier to read/maintain by separating cross-cutting concerns from business logic.</p>\n\n<p>In my opinion, what you have here is a generic decorator solution, not AOP. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-16T19:49:32.730",
"Id": "9057",
"ParentId": "8637",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T20:58:45.297",
"Id": "8637",
"Score": "5",
"Tags": [
"php",
"design-patterns",
"functional-programming"
],
"Title": "Design pattern for adapter"
}
|
8637
|
<p>Under sage from another CR post I'm crafting an OOP MySQL connection/query class. Nothing new, but a place to start plying OOP PHP. Here is the current design,what would aid speed and portability?</p>
<p><strong>conf/config.php</strong></p>
<pre><code><?php
//Inlcude the Data Access Layer: Db
require_once (dirname(dirname(__FILE__)) . '/inc/class/dbc.php');
//DB Constants...
define('DB_HOST','dbhost');
define('DB_USER','user');
define('DB_PASS','pass');
define('DB_NAME','dbname');
?>
</code></pre>
<p><strong>inc/class/dbc.php</strong></p>
<pre><code><?php
/**
*
*/
class Db
{
public $mysql;
function __construct()
{
$this->mysql = new mysqli (DB_HOST, DB_USER, DB_PASS, DB_NAME) OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );
//adding custom error checking:
}// End Constructor
}//End Class Definition
</code></pre>
<p><strong>index.php</strong></p>
<pre><code><div id="todo">
<?php
require_once(dirname(__FILE__) . '/conf/config.php');
$db = new Db();
$query = "SELECT * FROM todo ORDER BY id asc";
$results = $db->mysql->query($query);
if($results->num_rows) {
while($row = $results->fetch_object()) {
$title = $row->title;
$description = $row->description;
$id = $row->id;
?>
</div>
</code></pre>
|
[] |
[
{
"body": "<p>This code binds your Db object to the global constants. Its going to be difficult to connect to more than 1 database. Your DB class isn't doing anything for you.</p>\n\n<p>The solution to this is: <strong>injection</strong>. You should pass in the settings for the Db in the constructor. Below is the PDO class from my framework which I think is serving a similar role to what you are trying to achieve with your Db class. The injection is achieved by accepting parameters in the constructor ($setup).</p>\n\n<pre><code>/// PDO wrapper class to ensure DB implements the Evoke Core DB interface.\nclass PDO extends \\PDO implements \\Evoke\\Core\\Iface\\DB\n{\n public function __construct(Array $setup)\n {\n $setup += array(\n 'DSN' => NULL,\n 'Options' => array(\\PDO::ATTR_ERRMODE => \\PDO::ERRMODE_EXCEPTION),\n 'Password' => NULL,\n 'Username' => NULL);\n\n if (!isset($setup['DSN']))\n {\n throw new \\InvalidArgumentException(__METHOD__ . ' requires DSN');\n }\n\n if (!isset($setup['Password']))\n {\n throw new \\InvalidArgumentException(__METHOD__ . ' requires Password');\n }\n\n if (!isset($setup['Username']))\n {\n throw new \\InvalidArgumentException(__METHOD__ . ' requires Username');\n }\n\n parent::__construct($setup['DSN'],\n $setup['Username'],\n $setup['Password'],\n $setup['Options']);\n }\n}\n</code></pre>\n\n<p>There are a number of differences with this approach:</p>\n\n<ol>\n<li>The Db class is a Db type object (extends PDO).</li>\n<li>Common database type functions are ensured (implements Iface\\DB).</li>\n<li>Setup for the database is injected (with the setup parameter). This means that many databases could be connected to each with a different set of parameters injected.</li>\n<li>Validity of the setup is enforced.</li>\n</ol>\n\n<p>By creating an interface we can pass any type of object that implements the interface for use as our Db object. This means our code is decoupled from the specific type of database object (I could replace PDO with mysqli very easily if I wanted to).</p>\n\n<pre><code>function index($db)\n{\n if (!$db instanceof \\Iface\\DB)\n {\n throw new \\InvalidArgumentException(__METHOD__ . ' we need a Db object.');\n }\n}\n</code></pre>\n\n<p>Personally I have the small PDO wrapper you saw above and then a further abstraction for SQL statements. With everything all of the dependencies are injected (normally in the constructor). You can see <a href=\"https://github.com/Evoke-PHP/Evoke-PHP-Framework/tree/master/php/src/Evoke/Core/DB\" rel=\"nofollow\">more of my Db objects here</a>. Notice how the SQL class is injected with a Db (any sort of DB that implements the DB interface):</p>\n\n<pre><code>class SQL implements \\Evoke\\Core\\Iface\\DB\n{\n protected $inTransaction = false;\n\n protected $setup;\n\n /// Class constructor\n public function __construct($setup=array())\n {\n $this->setup = array_merge(array('DB' => NULL), $setup);\n\n if (!$this->setup['DB'] instanceof \\Evoke\\Core\\Iface\\DB)\n {\n throw new \\InvalidArgumentException(__METHOD__ . ' needs DB');\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T05:11:14.293",
"Id": "8644",
"ParentId": "8642",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T03:45:46.050",
"Id": "8642",
"Score": "2",
"Tags": [
"mysql",
"performance",
"object-oriented",
"php5"
],
"Title": "OOP MySQL connection class"
}
|
8642
|
<p>The factory should only have the responsibility of creating instances and <em>knowing what types</em> of instances to create, without having the added overhead of knowing about configurations. </p>
<p>With that in mind, here is how I would approach the problem: </p>
<pre><code>/// <summary>
/// Each class that can generate a problem should accept a problem configuration
/// </summary>
public class BinaryProblem : IProblem
{
public BinaryProblem (ProblemConfiguration configuration)
{
// sample code, this is where you generate your problem, based on the configuration of the problem
X = new Random().Next(configuration.MaxValue + configuration.MinValue) - configuration.MinValue;
Y = new Random().Next(configuration.MaxValue + configuration.MinValue) - configuration.MinValue;
Answer = X + Y;
}
public int X { get; private set; }
public int Y { get; private set; }
public int Answer { get; private set; }
}
</code></pre>
<p>For this we will need a problem configuration class </p>
<pre><code>/// <summary>
/// A problem configuration class
/// </summary>
public class ProblemConfiguration
{
public int MinValue { get; set; }
public int MaxValue { get; set; }
public Operator Operator { get; set; }
}
</code></pre>
<p>I would also a dedicated class for handling the configuration of levels and remove it from the factory class.</p>
<pre><code>/// <summary>
/// The abstract level configuration allows descendent classes to configure themselves
/// </summary>
public abstract class LevelConfiguration
{
protected Random Random = new Random();
private Dictionary<Level, ProblemConfiguration> _configurableLevels = new Dictionary<Level, ProblemConfiguration>();
/// <summary>
/// Adds a configurable level.
/// </summary>
/// <param name="level">The level to add.</param>
/// <param name="problemConfiguration">The problem configuration.</param>
protected void AddConfigurableLevel(Level level, ProblemConfiguration problemConfiguration)
{
_configurableLevels.Add(level, problemConfiguration);
}
/// <summary>
/// Removes a configurable level.
/// </summary>
/// <param name="level">The level to remove.</param>
protected void RemoveConfigurableLevel(Level level)
{
_configurableLevels.Remove(level);
}
/// <summary>
/// Returns all the configurable levels.
/// </summary>
public IEnumerable<Level> GetConfigurableLevels()
{
return _configurableLevels.Keys;
}
/// <summary>
/// Gets the problem configuration for the specified level
/// </summary>
/// <param name="level">The level.</param>
public ProblemConfiguration GetProblemConfiguration(Level level)
{
return _configurableLevels[level];
}
}
</code></pre>
<p>This would allow the Binary Configuration to look something like this: </p>
<pre><code>/// <summary>
/// Contains level configuration for Binary problems
/// </summary>
public class BinaryLevelConfiguration : LevelConfiguration
{
public BinaryLevelConfiguration()
{
AddConfigurableLevel(Level.Easy, GetEasyLevelConfiguration());
AddConfigurableLevel(Level.Medium, GetMediumLevelConfiguration());
AddConfigurableLevel(Level.Hard, GetHardLevelConfiguration());
}
/// <summary>
/// Gets the hard level configuration.
/// </summary>
/// <returns></returns>
private ProblemConfiguration GetHardLevelConfiguration()
{
return new ProblemConfiguration
{
MinValue = 100,
MaxValue = 1000,
Operator = Operator.Addition
};
}
/// <summary>
/// Gets the medium level configuration.
/// </summary>
/// <returns></returns>
private ProblemConfiguration GetMediumLevelConfiguration()
{
return new ProblemConfiguration
{
MinValue = 10,
MaxValue = 100,
Operator = Operator.Addition
};
}
/// <summary>
/// Gets the easy level configuration.
/// </summary>
/// <returns></returns>
private ProblemConfiguration GetEasyLevelConfiguration()
{
return new ProblemConfiguration
{
MinValue = 1,
MaxValue = 10,
Operator = Operator.Addition
};
}
}
</code></pre>
<p>Now the factory should <em>only</em> be responsible for <em>creating new instances</em> of problems and knowing what types of problems it can serve</p>
<pre><code>/// <summary>
/// The only responsibility of the factory is to create instances of Problems and know what kind of problems it can create,
/// it should not know about configuration
/// </summary>
public class ProblemFactory
{
private Dictionary<Type, Func<Level, IProblem>> _registeredProblemTypes; // this associates each type with a factory function
/// <summary>
/// Initializes a new instance of the <see cref="ProblemFactory"/> class.
/// </summary>
public ProblemFactory()
{
_registeredProblemTypes = new Dictionary<Type, Func<Level, IProblem>>();
}
/// <summary>
/// Registers a problem factory function to it's associated type
/// </summary>
/// <typeparam name="T">The Type of problem to register</typeparam>
/// <param name="factoryFunction">The factory function.</param>
public void RegisterProblem<T>(Func<Level, IProblem> factoryFunction)
{
_registeredProblemTypes.Add(typeof(T), factoryFunction);
}
/// <summary>
/// Generates the problem based on the type parameter and invokes the associated factory function by providing some problem configuration
/// </summary>
/// <typeparam name="T">The type of problem to generate</typeparam>
/// <param name="problemConfiguration">The problem configuration.</param>
/// <returns></returns>
public IProblem GenerateProblem<T>(Level level) where T: IProblem
{
// some extra safety checks can go here, but this should be the essense of a factory,
// the only responsibility is to create instances of Problems and know what kind of problems it can create
return _registeredProblemTypes[typeof(T)](level);
}
}
</code></pre>
<p>Then here is how you could use all this</p>
<pre><code>class Program
{
static void Main(string[] args)
{
ProblemFactory problemFactory = new ProblemFactory();
BinaryLevelConfiguration binaryLevelConfig = new BinaryLevelConfiguration();
// register your factory functions
problemFactory.RegisterProblem<BinaryProblem>((level) => new BinaryProblem(binaryLevelConfig.GetProblemConfiguration(level)));
// consume them
IProblem problem1 = problemFactory.GenerateProblem<BinaryProblem>(Level.Easy);
IProblem problem2 = problemFactory.GenerateProblem<BinaryProblem>(Level.Hard);
}
}
</code></pre>
<p>The problem is, in <code>BinaryProblemConfiguration</code> methods, I'd like to add more configurations in the methods, I mean, returns something like an <code>IEnumerable</code>, but I'm not sure how would I modify <code>ProblemFactory</code>.</p>
<p>I guess I need to create another class <code>ListProblemFactory</code>, and maintain the last configuration to show the next one.</p>
<p>I mean generate problems with the configs sequently.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T19:18:06.047",
"Id": "13537",
"Score": "3",
"body": "I've been following your ongoing quest for this for most of your posts. I may be out of line here, but I just have to say: Do you *REALLY* need this level of abstraction? I get the feeling that we're currently at the ProblemConfigurationProblemLevelConfigurationFactoryFactory level."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-27T04:34:28.197",
"Id": "21195",
"Score": "1",
"body": "\"BinaryProblemConfiguration\" doesn't exist in any of the code you posted. What exactly are you referring to there?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-20T09:57:20.587",
"Id": "25645",
"Score": "0",
"body": "@Brannon He's probably refering to `BinaryLevelConfiguration`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T02:36:38.327",
"Id": "35168",
"Score": "0",
"body": "I'm confused. Can you give example code of adding \"more configurations in the methods\"?"
}
] |
[
{
"body": "<p>Sure, you can do that, why not? Isn't it easy to pass a list of Levels instead of a Level in GenerateProblem? Without more details on what you really want to do with that list, it's hard to answer.</p>\n\n<p>Unfortunately, as Willem van Rumpt said in comments, we're currently at the ProblemConfigurationProblemLevelConfigurationFactoryFactory level and it doesn't make sense anymore. You need to learn when to stop abstracting things.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-20T10:00:20.163",
"Id": "15762",
"ParentId": "8647",
"Score": "2"
}
},
{
"body": "<p>The original question is too old, so adding my two cents for future comers :)</p>\n\n<p>It seem that OP is using a <a href=\"http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/\" rel=\"nofollow\">Service Locator pattern</a>. </p>\n\n<hr>\n\n<pre><code>/// <summary>\n/// Each class that can generate a problem should accept a problem configuration\n/// </summary>\npublic class BinaryProblem : IProblem\n{\n readonly ProblemConfiguration _configuration;\n public BinaryProblem(ProblemConfiguration configuration)\n {\n _configuration = configuration;\n }\n\n public void Generate() \n {\n // sample code, this is where you generate your problem, based on the configuration of the problem\n X = new Random().Next(_configuration.MaxValue + _configuration.MinValue) - _configuration.MinValue;\n Y = new Random().Next(_configuration.MaxValue + _configuration.MinValue) - _configuration.MinValue;\n Answer = X + Y;\n }\n\n public int X { get; private set; }\n public int Y { get; private set; }\n public int Answer { get; private set; }\n}\n</code></pre>\n\n<p><strong>improvement in the above code fragment:</strong></p>\n\n<ol>\n<li>extracted out a Generate method from constructor, conceptually\nspeeking, constructor is responsible for initialising an object and\nnothing more than that. It is a best practice, <em>can't say about the\nRandom class and testability</em></li>\n<li>As posted by the OP's code it seems that <em>LevelConfiguration</em> class\ndoesn't solve any purpose. Also, if it does it should be better\nrenamed to <strong>Level_ProblemConfigurationStore</strong> in my opinion as that\nis what it actually does.</li>\n</ol>\n\n<hr>\n\n<pre><code>/// <summary>\n/// Contains level configuration for Binary problems\n/// </summary>\npublic class BinaryLevelConfiguration\n{\n public ProblemConfiguration GetProblemConfiguration(Level level)\n {\n switch (level)\n {\n case Level.Easy:\n return GetEasyLevelConfiguration();\n case Level.Medium:\n return GetMediumLevelConfiguration();\n case Level.Hard:\n return GetHardLevelConfiguration();\n default: //throw not implemented here\n return null;\n }\n }\n /// <summary>\n /// Gets the hard level configuration.\n /// </summary>\n /// <returns></returns>\n private ProblemConfiguration GetHardLevelConfiguration()\n {\n return new ProblemConfiguration\n {\n MinValue = 100,\n MaxValue = 1000,\n Operator = Operator.Addition\n };\n }\n\n /// <summary>\n /// Gets the medium level configuration.\n /// </summary>\n /// <returns></returns>\n private ProblemConfiguration GetMediumLevelConfiguration()\n {\n return new ProblemConfiguration\n {\n MinValue = 10,\n MaxValue = 100,\n Operator = Operator.Addition\n };\n }\n\n /// <summary>\n /// Gets the easy level configuration.\n /// </summary>\n /// <returns></returns>\n private ProblemConfiguration GetEasyLevelConfiguration()\n {\n return new ProblemConfiguration\n {\n MinValue = 1,\n MaxValue = 10,\n Operator = Operator.Addition\n };\n }\n\n}\n</code></pre>\n\n<p><strong>Improvement:</strong> </p>\n\n<ol>\n<li><p>As per the OP's code and my previous comments, inheritance is not\nrequired, indeed this is a Factory class as You are creating/\nconfiguring something here.</p></li>\n<li><p>You are configuring the dictionary in Your constructor, consider\nextracting that part as shown in the above code if required. I\nbelieve You don't even require a dictionary here</p></li>\n</ol>\n\n<hr>\n\n<p>Finally the calling code looks like this:</p>\n\n<pre><code> static void Main(string[] args)\n {\n ProblemFactory problemFactory = new ProblemFactory();\n BinaryLevelConfiguration binaryLevelConfig = new BinaryLevelConfiguration();\n\n\n // register your factory functions\n problemFactory.RegisterProblem<BinaryProblem>((level) =>\n {\n var binProblem = new BinaryProblem(binaryLevelConfig.GetProblemConfiguration(level));\n binProblem.Generate();\n return binProblem;\n });\n\n // consume them\n IProblem problem1 = problemFactory.GenerateProblem<BinaryProblem>(Level.Easy);\n IProblem problem2 = problemFactory.GenerateProblem<BinaryProblem>(Level.Hard);\n\n }\n</code></pre>\n\n<p><strong>A word of Caution:</strong> You can easily forget to call Generate method of binary problem, You should be having appropriate tests to ensure that.</p>\n\n<p><strong>Note:</strong>\nSince the OP never clarified the question as per comments, I assume that he wishes to add new level of difficulties, You can easily do that by modifying the BinaryLevelConfiguration Class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-01T17:32:25.677",
"Id": "30623",
"ParentId": "8647",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T06:17:35.737",
"Id": "8647",
"Score": "3",
"Tags": [
"c#",
"design-patterns"
],
"Title": "How to add a new feature to this factory model?"
}
|
8647
|
<p>Please critique my word frequency generator. I am a beginner programmer so any criticism are welcome.</p>
<p>Original Code: <a href="http://pastebin.com/rSRfbnCt" rel="nofollow">http://pastebin.com/rSRfbnCt</a></p>
<p>Here is my revised code after the feedback:</p>
<pre><code>import string, time, webbrowser, collections, urllib2
def timefunc(function):
def wrapped(*args):
start = time.time()
data = function(*args)
end = time.time()
timetaken = end - start
print "Function: "+function.__name__+"\nTime taken:",timetaken
return data
return wrapped
@timefunc
def process_text(text_file):
words = text_file.read().lower().split()
words = [word.strip(string.punctuation+string.whitespace) for word in words]
words = [word for word in words if word]#skips ''(None) elements
return words
@timefunc
def create_freq_dict(wordlist):
freq_dict = collections.Counter(wordlist)
return freq_dict
@timefunc
def create_sorted_list(freqdict):
sorted_list = [(value,key) for key,value in list(freqdict.items())]#list() provides python 3 compatibility
sorted_list.sort(reverse=True)
return sorted_list
@timefunc
def write_results(sorted_list):
text_file = open('wordfreq.txt','w')
text_file.write('Word Frequency List\n\n')
rank = 0
for word in sorted_list:
rank += 1
write_str = "[{0}] {1:-<10}{2:->10}\n".format(rank, word[1],word[0])
text_file.write(write_str)
text_file.close()
## The Brothers Grimm
## This file can be obtained from Project Gutenberg:
## http://www.gutenberg.org/cache/epub/5314/pg5314.txt
web_file = urllib2.urlopen('http://www.gutenberg.org/cache/epub/5314/pg5314.txt')
wordlist = process_text(web_file)
freqdict = create_freq_dict(wordlist)
sorted_list = create_sorted_list(freqdict)
results = write_results(sorted_list)
webbrowser.open('wordfreq.txt')
print "END"
</code></pre>
|
[] |
[
{
"body": "<pre><code>import string, time, math, webbrowser\n\ndef timefunc(function, *args):\n start = time.time()\n data = function(*args)\n end = time.time()\n timetaken = end - start\n</code></pre>\n\n<p>I'd recommend calling this <code>time_taken</code> as its slightly easier to read.</p>\n\n<pre><code> print \"Function: \"+function.__name__+\"\\nTime taken:\",timetaken\n</code></pre>\n\n<p>Print already introduces newlines and combines different pieces. Take advantage of that.</p>\n\n<pre><code> print \"Function: \", function.__name__\n print \"Time Taken: \", time_taken\n</code></pre>\n\n<p>That's easier to follow</p>\n\n<pre><code> return data\n\ndef process_text(filename):\n</code></pre>\n\n<p>You never use filename in here, but you do use fin which is the same thing. typo?</p>\n\n<pre><code> t = []\n</code></pre>\n\n<p>Not a very descriptive name. I suggest coming up with something clearer</p>\n\n<pre><code> for line in fin:\n for i in line.split():\n</code></pre>\n\n<p><code>i</code> usually means <code>index</code> which its not here</p>\n\n<pre><code> word = i.lower()\n word = word.strip(string.punctuation)\n if word != '':\n t.append(word)\n return t\n</code></pre>\n\n<p>I'd do this as</p>\n\n<pre><code> words = fin.read().lower().split()\n words = [word.strip() for word in words]\n words = [word for word in words if word]\n return words\n</code></pre>\n\n<p>I think its easier to follow and probably more efficient</p>\n\n<pre><code>def create_freq_dict(wordlist):\n d = dict()\n</code></pre>\n\n<p><code>d</code> is not a very good name. Usually dicts are created with <code>{}</code> not <code>dict()</code>. No difference, but the first is generally preffered</p>\n\n<pre><code> for word in wordlist:\n if word not in d.keys():\n d[word] = 1\n else:\n d[word] += 1\n</code></pre>\n\n<p>Use <code>d = collections.defaultdict(int)</code> or <code>d = collections.Counter()</code>. Both will make it easier to count up like this. See the python documentation for collections. You should actually be able to write this function in one line</p>\n\n<pre><code> return d\n\ndef sort_dict(in_dict):\n t = []\n for key,value in in_dict.items():\n t.append((value, key))\n</code></pre>\n\n<p><code>in_dict.items()</code> is a list already, there is no reason to copy the elements into the list. (NOTE: in Python 3.x in_dict.items() is no longer a list). Even if it wasn't a list you could do:</p>\n\n<pre><code> t = list(in_dict.items())\n</code></pre>\n\n<p>Which would do the same thing your code does</p>\n\n<pre><code> t.sort(reverse=True)\n return t\n</code></pre>\n\n<p>I'd implement this function as</p>\n\n<pre><code>return sorted(in_dict.items())\n</code></pre>\n\n<p>The sorted function takes anything sufficiently list-like and produces a sorted list from it.</p>\n\n<pre><code>def write_results(sorted_list):\n</code></pre>\n\n<p>sorted_list isn't a great name. It would be better to give an indication of what's in the list.</p>\n\n<pre><code> fout = open('wordfreq.txt','w')\n fout.write('Word Frequency List\\n\\n')\n r = 0\n for i in sorted_list:\n r += 1\n</code></pre>\n\n<p>Use <code>for r, (key, value) in enumerate(sortedlist):</code> That way you don't need to manage <code>r</code> yourself, and you can refer the value as <code>value</code> rather then the harder to read <code>i[1]</code>.</p>\n\n<pre><code> fillamount = 20 - (len(i[1]) + len(str(r)))\n</code></pre>\n\n<p>Some of the those parens are unnecessary. </p>\n\n<pre><code> write_str = str(r)+': '+i[1]+' '+('-' * (fillamount-2))+' '+str(i[0])+'\\n'\n</code></pre>\n\n<p>Multiplication has precedence, you don't need the parens to make that happen. Also, python has a method ljust which does this for you</p>\n\n<pre><code> write_str = (str(r) + ': ' + i[1]).ljust('-', 20) + str(i[0]) + '\\n'\n</code></pre>\n\n<p>You may also want to consider using string formatting rather then adding strings</p>\n\n<pre><code> write_str = ('%d: %s' % (r, i[1])).just('-', 20) + '%d\\n' % i[0]\n</code></pre>\n\n<p>I think its easier to follow, although I'd probably split across several lines</p>\n\n<pre><code> fout.write(write_str)\n fout.close()\n\n\n## The Brothers Grimm\n## This file can be obtained from Project Gutenberg:\n## http://www.gutenberg.org/cache/epub/5314/pg5314.txt\nfin = open('c:\\Python27\\My Programs\\wx\\grimm.txt')\n</code></pre>\n\n<p>fin presumable stands for file in. Give a name that indicates what's actually in it ike <code>grim_text</code></p>\n\n<pre><code>wordlist = timefunc(process_text,fin)\nfreqdict = timefunc(create_freq_dict,wordlist)\nsorted_list = timefunc(sort_dict,freqdict)\nresults = timefunc(write_results,sorted_list)\n</code></pre>\n\n<p>Very nice</p>\n\n<pre><code>webbrowser.open('wordfreq.txt')\n</code></pre>\n\n<p>That's a slightly unusual use of a webbrowser</p>\n\n<pre><code>print \"END\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T02:42:22.163",
"Id": "13723",
"Score": "0",
"body": "Thanks for the great feedback. I have added my revised code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T05:21:32.453",
"Id": "13727",
"Score": "0",
"body": "@talloaktrees, nice work. Two things: 1. the `list` in `created_sorted_list` isn't necessary for Python 3 compatibility. The python 3 iterator and python 2 list are similar enough that both work in that situation. In `write_results`, use `for rank, word in enumerate(sorted_list):` then you can avoid having to keep track of rank yourself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T14:58:58.170",
"Id": "13738",
"Score": "0",
"body": "Yes I accidentally skipped over `enumerate(sorted_list)` when I was rewriting my code. Also, I forgot to mention that `webbrowser.open('wordfreq.txt')` was a quick way to open up a text file in the default text editor I found somewhere. I imagine it's a bit hackish."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T21:04:04.453",
"Id": "8670",
"ParentId": "8648",
"Score": "7"
}
},
{
"body": "<p>You could turn the <code>timefunc</code> function into a decorator, like this:</p>\n\n<pre><code>def timed(function):\n def wrapped(*args):\n start = time.time()\n data = function(*args)\n end = time.time()\n timetaken = end - start\n print \"Function: \"+function.__name__+\"\\nTime taken:\",timetaken\n return data\n return wrapped\n</code></pre>\n\n<p>And then:</p>\n\n<pre><code>@timed\ndef process_text(filename):\n ...\n\n@timed\ndef create_freq_dict(wordlist):\n ...\n</code></pre>\n\n<p>Etc., which would let you call your functions like this:</p>\n\n<pre><code>wordlist = process_text(fin)\nfreqdict = create_freq_dict(wordlist)\nsorted_list = sort_dict(freqdict)\nresults = write_results(sorted_list)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T12:05:23.373",
"Id": "8696",
"ParentId": "8648",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "8670",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T08:57:34.783",
"Id": "8648",
"Score": "6",
"Tags": [
"python",
"strings"
],
"Title": "Word frequency generator in Python"
}
|
8648
|
<p>I've created a website that displays weather and currency rates for London and New York. The following is an abstract from my <code>cityConfig.php</code> script. Is this a good approach for adding variables from each city into an array? </p>
<pre><code>// Define arrays //
$cities = array();
$currencyRateHeadings = array();
$currencySource = array();
$weatherSource = array();
// Feed URL's //
$yahooWeather = 'http://weather.yahooapis.com/forecastrss?p=';
$theMoneyConverter = 'http://themoneyconverter.com/rss-feed/';
// City 1 //
$city = 'London';
$currencyRateHeading = '1 British Pound Sterling';
$cityWeatherSourceCode = 'UKXX0085';
$cityWeatherSource = $yahooWeather . $cityWeatherSourceCode . '&u=c';
$currencyRateFeedCode = 'GBP';
$cityCurrencySource = $theMoneyConverter . $currencyRateFeedCode . '/rss.xml';
array_push($currencySource, $cityCurrencySource);
array_push($weatherSource, $cityWeatherSource);
array_push($cities, $city);
array_push($currencyRateHeadings, $currencyRateHeading);
// City 2 //
$city = 'New York';
$currencyRateHeading = '1 US Dollar';
$cityWeatherSourceCode = 'USNY0996';
$cityWeatherSource = $yahooWeather . $cityWeatherSourceCode . '&u=c';
$currencyRateFeedCode = 'USD';
$cityCurrencySource = $theMoneyConverter . $currencyRateFeedCode . '/rss.xml';
array_push($cities, $city);
array_push($currencyRateHeadings, $currencyRateHeading);
array_push($currencySource, $cityCurrencySource);
array_push($weatherSource, $cityWeatherSource);
</code></pre>
<p>Another alternative I considered was to create extra variables by adding either a 1 or a 2 to the end of the variable name (depending whether they are related to <code>city1</code> or <code>city2</code>) and push everything onto the array at the end.</p>
<pre><code>// Define arrays //
$cities = array();
$currencyRateHeadings = array();
$currencySource = array();
$weatherSource = array();
// Feed URL's //
$yahooWeather = 'http://weather.yahooapis.com/forecastrss?p=';
$theMoneyConverter = 'http://themoneyconverter.com/rss-feed/';
// City 1 //
$city1 = 'London';
$currencyRateHeading1 = '1 British Pound Sterling';
$cityWeatherSourceCode1 = 'UKXX0085';
$cityWeatherSource1 = $yahooWeather . $cityWeatherSourceCode . '&u=c';
$currencyRateFeedCode1 = 'GBP';
$cityCurrencySource1 = $theMoneyConverter . $currencyRateFeedCode . '/rss.xml';
// City 2 //
$city2 = 'New York';
$currencyRateHeading2 = '1 US Dollar';
$cityWeatherSourceCode2 = 'USNY0996';
$cityWeatherSource2 = $yahooWeather . $cityWeatherSourceCode . '&u=c';
$currencyRateFeedCode2 = 'USD';
$cityCurrencySource2 = $theMoneyConverter . $currencyRateFeedCode . '/rss.xml';
array_push($cities, $city1, $city2);
array_push($currencyRateHeadings, $currencyRateHeading1, $currencyRateHeading2);
array_push($currencySource, $cityCurrencySource1, $cityCurrencySource2);
array_push($weatherSource, $cityWeatherSource1, $cityWeatherSource2);
</code></pre>
<p>Can anyone provide an example of a better way of doing this? </p>
<p>The arrays and variables are called later in my <code>threeColumnContainer.php</code> script after passing through the <code>switch</code> statement to determine which page they have come from. I'm happy with what's happening below at the moment. It's just setting the array's that I'd like feedback for?</p>
<pre><code><li class="leftCol">
<p>
<?php
switch ($currentPage) {
case 'index.php':
echo displayCityContent($weatherSource[0], $columnSubheading);
break;
case 'currencyRate.php':
echo displayCurrencyRateContent($currencySource[0]);
break;
default:
content_unavailable();
break;
}
?>
</p>
</li>
<li class="rightCol">
<p>
<?php
switch ($currentPage) {
case 'index.php':
echo displayCityContent($weatherSource[1], $columnSubheading);
break;
case 'currencyRate.php':
echo displayCurrencyRateContent($currencySource[1]);
break;
default:
content_unavailable();
break;
}
?>
</p>
</li>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T12:03:36.943",
"Id": "13515",
"Score": "1",
"body": "*Another alternative I considered was to create extra variables by adding either a 1 or a 2 to the end of the variable name* - No, do not do this; it's naive (no offense). Can you store your data in a database (of some kind, not necessarily MySQL but that would work)? If it were an relational database like MySQL, you could simply query for the cities. Alternatively, you could create an array \"normally\" (`$cities = array(array('key'=>'first value'),array('key'=>'another value'));`) in an included file that setup your array's structure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T12:07:43.037",
"Id": "13516",
"Score": "1",
"body": "Anywhere where you're repeating code, though, should be optimized so you don't do it (practicality sometimes dictates that you will copy some code). The general rule is [Don't Repeat Yourself (DRY)](http://en.wikipedia.org/wiki/Don%27t_repeat_yourself)."
}
] |
[
{
"body": "<p>First of all, regarding your use of array_push(), I quote the <a href=\"http://se2.php.net/manual/en/function.array-push.php\" rel=\"nofollow\">documentation</a>: \"Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.\"</p>\n\n<p>With that out of the way, on to the code!</p>\n\n<p>With or without array_push, I find that the code is a bit to repetitive, this is just a personal preference, but I like this much better:</p>\n\n<pre><code>$yahooWeather = 'http://weather.yahooapis.com/forecastrss?p=';\n$theMoneyConverter = 'http://themoneyconverter.com/rss-feed/';\n\n$currencySource = array(\n 0 => $theMoneyConverter . 'GBP/rss.xml',\n 1 => $theMoneyConverter . 'USD/rss.xml',\n);\n\n$cities = array(\n 0 => 'London',\n 1 => 'New York',\n);\n\n$currencyRateHeadings = array(\n 0 => '1 British Pound Sterling',\n 1 => '1 US Dollar',\n); \n\n$weatherSource = array(\n 0 => $yahooWeather . 'UKXX0085&u=c',\n 1 => $yahooWeather . 'USNY0996&u=c',\n);\n</code></pre>\n\n<p>This however still repeats a few things, and will become worse if you add additional cities, so at the very least, I would then change it into this:</p>\n\n<pre><code>$yahooWeather = 'http://weather.yahooapis.com/forecastrss?p=';\n$theMoneyConverter = 'http://themoneyconverter.com/rss-feed/';\n\n$cities = array(\n 0 => 'London',\n 1 => 'New York',\n);\n\n$currencyRateHeadings = array(\n 0 => '1 British Pound Sterling',\n 1 => '1 US Dollar',\n); \n\n$weather_codes = array('UKXX0085', 'USNY0996');\n$currency_codes = array('GBP', 'USD');\n$weatherSource = array();\n$currenySource = array();\nforeach ($weather_codes as $weather_code) {\n $weatherSource[] = $yahooWeather . $weather_code . '&u=c';\n}\nforeach ($currency_codes as $currency_code) {\n $currencySource[] = $theMoneyConverter . $currency_code . '/rss.xml';\n}\n</code></pre>\n\n<p>This second example, makes it very easy to add new elements, especially the weather and currency codes, as all you need to do is attach a new element at the end of the two arrays that hold them.</p>\n\n<p>So far the structure of your arrays have been kept the same, to make sure that they still work with your current scripts. If I were you though, I would restructure it.</p>\n\n<p>If you really only need two cities, just do:</p>\n\n<pre><code>$city_data = array(\n 'London' => array('1 British Pound Sterling', $yahooWeather . 'UKXX0085' . '&u=c', $theMoneyConverter . 'GBP' . '/rss.xml'),\n 'New York' => array('1 US Dollar', $yahooWeather . 'USNY0996' . '&u=c', $theMoneyConverter . 'USD' . '/rss.xml'),\n);\n</code></pre>\n\n<p>If you want it to be extensible to more cities on the other hand:</p>\n\n<pre><code>$city_data = array(\n 'London' => array('1 British Pound Sterling', 'UKXX0085', 'GBP'),\n 'New York' => array('1 US Dollar', 'USNY0996', 'USD'),\n);\n\n$cities = array();\nforeach($city_names as $city) {\n $cities[$city] = city($city[0], $city[1], $city[2]);\n}\n\nfunction city($currency_heading = '', $weather_code, $currency_code) {\n $yahooWeather = 'http://weather.yahooapis.com/forecastrss?p=';\n $theMoneyConverter = 'http://themoneyconverter.com/rss-feed/';\n\n return array(\n 'currency_heading' => $currency_heading,\n 'weather' => $yahooWeather . $weather_code . '&u=c';\n 'currency' => $theMoneyConverter . $currency_code . '/rss.xml';\n );\n}\n</code></pre>\n\n<p>From there on, we could start doing really cool stuff with databases, closures, factories, dependency injection, and all kinds of other awesomeness. I disgress however, and will leave you to discover those subjects later. :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-14T20:00:44.120",
"Id": "8974",
"ParentId": "8649",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T11:46:38.813",
"Id": "8649",
"Score": "2",
"Tags": [
"php",
"array"
],
"Title": "Setting configuration arrays"
}
|
8649
|
<p>I am trying to create a stamp order / preview form for a site and have gotten fairly far on my own, with a little help from Google and of course you all. If you can suggest any other method of going about this, please guide me in the right direction. Also, I need to figure out how to put a border, the same colour as has been chosen in the dropdown selection, around the containing div.</p>
<pre><code> <SCRIPT LANGUAGE="JavaScript">
function setColor() {
var color = document.getElementById("color").value;
document.getElementById("myDiv").style.color = color;
}
function addContent(divName, content) {
document.getElementById(divName).innerHTML = content;
}
function fontSize(size) {
document.getElementById("lineOne").style.fontSize = size
}
function fontFamily(family) {
document.getElementById("lineOne").style.fontFamily = family
}
function fontStyle(style) {
document.getElementById("lineOne").style.fontStyle = style
}
function fontWeight(weight) {
document.getElementById("lineOne").style.fontWeight = weight
}
function align(align) {
document.getElementById("lineOne").style.textAlign = align;
}
function fontSize1(size1) {
document.getElementById("lineTwo").style.fontSize = size1
}
function fontFamily1(family1) {
document.getElementById("lineTwo").style.fontFamily = family1
}
function fontStyle1(style1) {
document.getElementById("lineTwo").style.fontStyle = style1
}
function fontWeight1(weight1) {
document.getElementById("lineTwo").style.fontWeight = weight1
}
function align1(align1) {
document.getElementById("lineTwo").style.textAlign = align1;
}
function fontSize2(size2) {
document.getElementById("lineThree").style.fontSize = size2
}
function fontFamily2(family2) {
document.getElementById("lineThree").style.fontFamily = family2
}
function fontStyle2(style2) {
document.getElementById("lineThree").style.fontStyle = style2
}
function fontWeight2(weight2) {
document.getElementById("lineThree").style.fontWeight = weight2
}
function align2(align2) {
document.getElementById("lineThree").style.textAlign = align2;
}
function fontSize3(size3) {
document.getElementById("lineFour").style.fontSize = size3
}
function fontFamily3(family3) {
document.getElementById("lineFour").style.fontFamily = family3
}
function fontStyle3(style3) {
document.getElementById("lineFour").style.fontStyle = style3
}
function fontWeight3(weight3) {
document.getElementById("lineFour").style.fontWeight = weight3
}
function align3(align3) {
document.getElementById("lineFour").style.textAlign = align3;
}
function border(border) {
document.getElementById("myDiv").style.border = border;
}
function boldText(checkBox,target) {
if(checkBox.checked) {
document.getElementById(target).style.fontWeight = "bold";
}
else {
document.getElementById(target).style.fontWeight = "normal";
}
}
function underlineText(checkBox,target) {
if(checkBox.checked) {
document.getElementById(target).style.textDecoration = "underline";
}
else {
document.getElementById(target).style.textDecoration = "none";
}
}
function italic(checkBox,target) {
if(checkBox.checked){
document.getElementById(target).style.fontStyle = "italic";
}
else {
document.getElementById(target).style.fontStyle = "normal";
}
}
</SCRIPT>
</head>
<body>
<div id="edit">
<h1>Edit text as needed</h1>
<form name="myForm" enctype="multipart/form-data">
<table border="0" width="100%" style="border-collapse: collapse">
<tr>
<td width="278">Text</td>
<td width="165">Font Family</td>
<td width="74">Size</td>
<td width="86">Align</td>
<td><b>B</b></td>
<td><u>U</u></td>
<td><i>I</i></td>
</tr>
<tr>
<td>
<input name="myContent"></input>
<input type="button" value="Add content" onClick="addContent('lineOne', document.myForm.myContent.value); setCookie('content', document.myForm.myContent.value, 7);">
</td>
<td width="165">
<select id="fontFamilyChanger" onchange="fontFamily(this.value)">
<option value="Arial">Arial</option>
<option value="Comic Sans MS">Comic Sans MS</option>
<option value="serif" selected="selected">Times New Roman</option>
<option value="Verdana">Verdana</option>
</select>
</td>
<td width="74">
<select name=fontSizeChanger onchange="fontSize(this.value)">
<option value="6">6</option>
<option value="8">8</option>
<option value="10">10</option>
<option value="12" selected="selected">12</option>
<option value="14">14</option>
<option value="16">16</option>
<option value="18">18</option>
<option value="20">20</option>
</select>
</td>
<td width="75">
<select id="textAlignChanger" onchange="align(this.value);">
<option value="left">left</option>
<option value="center" selected="selected">center</option>
<option value="right">right</option>
</select>
</td>
<td>
<input type="checkbox" onclick="boldText(this,'lineOne')">
</td>
<td>
<input type="checkbox" onclick="underlineText(this,'lineOne')">
</td>
<td>
<input type="checkbox" onclick="italic(this,'lineOne')">
</td>
</tr>
<tr>
<td>
<input name="myContent1"></input>
<input type="button" value="Add content" onClick="addContent('lineTwo', document.myForm.myContent1.value); setCookie('content', document.myForm.myContent1.value, 7);">
</td>
<td width="165">
<select id="fontFamilyChanger" onchange="fontFamily1(this.value)">
<option value="Arial">Arial</option>
<option value="Comic Sans MS">Comic Sans MS</option>
<option value="serif" selected="selected">Times New Roman</option>
<option value="Verdana">Verdana</option>
</select>
</td>
<td width="74">
<select name=fontSizeChanger onchange="fontSize1(this.value)">
<option value="6">6</option>
<option value="8">8</option>
<option value="10">10</option>
<option value="12" selected="selected">12</option>
<option value="14">14</option>
<option value="16">16</option>
<option value="18">18</option>
<option value="20">20</option>
</select>
</td>
<td width="75">
<select id="textAlignChanger" onchange="align1(this.value);">
<option value="left">left</option>
<option value="center" selected="selected">center</option>
<option value="right">right</option>
</select>
</td>
<td>
<input type="checkbox" onclick="boldText(this,'lineTwo')">
</td>
<td>
<input type="checkbox" onclick="underlineText(this,'lineTwo')">
</td>
<td>
<input type="checkbox" onclick="italic(this,'lineTwo')">
</td>
</tr>
<tr>
<td>
<input name="myContent2"></input>
<input type="button" value="Add content" onClick="addContent('lineThree', document.myForm.myContent2.value); setCookie('content', document.myForm.myContent2.value, 7);">
</td>
<td width="165">
<select id="fontFamilyChanger" onchange="fontFamily2(this.value)">
<option value="Arial">Arial</option>
<option value="Comic Sans MS">Comic Sans MS</option>
<option value="serif" selected="selected">Times New Roman</option>
<option value="Verdana">Verdana</option>
</select>
</td>
<td width="74">
<select name=fontSizeChanger onchange="fontSize2(this.value)">
<option value="6">6</option>
<option value="8">8</option>
<option value="10">10</option>
<option value="12" selected="selected">12</option>
<option value="14">14</option>
<option value="16">16</option>
<option value="18">18</option>
<option value="20">20</option>
</select>
</td>
<td width="75">
<select id="textAlignChanger" onchange="align2(this.value);">
<option value="left">left</option>
<option value="center" selected="selected">center</option>
<option value="right">right</option>
</select>
</td>
<td>
<input type="checkbox" onclick="boldText(this,'lineThree')">
</td>
<td>
<input type="checkbox" onclick="underlineText(this,'lineThree')">
</td>
<td>
<input type="checkbox" onclick="italic(this,'lineThree')">
</td>
</tr>
<tr>
<td>
<input name="myContent3"></input>
<input type="button" value="Add content" onClick="addContent('lineFour', document.myForm.myContent3.value); setCookie('content', document.myForm.myContent3.value, 7);">
</td>
<td width="165">
<select id="fontFamilyChanger" onchange="fontFamily3(this.value)">
<option value="Arial">Arial</option>
<option value="Comic Sans MS">Comic Sans MS</option>
<option value="serif" selected="selected">Times New Roman</option>
<option value="Verdana">Verdana</option>
</select>
</td>
<td width="74">
<select name=fontSizeChanger onchange="fontSize3(this.value)">
<option value="6">6</option>
<option value="8">8</option>
<option value="10">10</option>
<option value="12" selected="selected">12</option>
<option value="14">14</option>
<option value="16">16</option>
<option value="18">18</option>
<option value="20">20</option>
</select>
</td>
<td width="75">
<select id="textAlignChanger" onchange="align3(this.value);">
<option value="left">left</option>
<option value="center" selected="selected">center</option>
<option value="right">right</option>
</select>
</td>
<td>
<input type="checkbox" onclick="boldText(this,'lineFour')">
</td>
<td>
<input type="checkbox" onclick="underlineText(this,'lineFour')">
</td>
<td>
<input type="checkbox" onclick="italic(this,'lineFour')">
</td>
</tr>
</table>
</div>
<br>
Colour:
<select id="color" onclick="setColor();">
<option value="white">white</option>
<option value="black" selected="selected">black</option>
<option value="red">red</option>
<option value="lightblue">light blue</option>
<option value="darkblue">dark blue</option>
<option value="lightgreen">light green</option>
<option value="darkgreen">dark green</option>
<option value="yellow">yellow</option>
<option value="orange">orange</option>
<option value="pink">pink</option>
<option value="purple">purple</option>
<option value="gray">gray</option>
</select>
<select id="border" onchange="border(this.value);">
<option value="1px solid" selected="selected">1px</option>
<option value="2px solid">2px</option>
<option value="3px solid">3px</option>
<option value="4px solid">4px</option>
<option value="5px solid">5px</option>
</select>
</form>
<br>
<div id="myDiv">
<div id="lineOne"></div>
<div id="lineTwo"></div>
<div id="lineThree"></div>
<div id="lineFour"></div>
</div>
</code></pre>
<p><a href="http://jsfiddle.net/ShauniD/ELER2/" rel="nofollow">http://jsfiddle.net/ShauniD/ELER2/</a></p>
<p>Have a look and let me know!</p>
<p>I need coding advice with this code. Please go easy as this is my first code in JavaScript, and I need good criticism.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T12:29:22.803",
"Id": "13519",
"Score": "0",
"body": "I have included the code for you to see (As the FAQ says)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T12:41:56.953",
"Id": "13520",
"Score": "0",
"body": "For the font size to work in Chrome I had to append `+ 'pt'` in the `fontSize` function. On a side note, did you consider using a library like jQuery to make the code a bit shorter and less repeating? On the other hand, using a library might actually take away a bit of the language learning process. Just wanted to suggest this to help you avoid writing repeated parts of code for each row."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T12:46:20.520",
"Id": "13521",
"Score": "0",
"body": "I have not thought of using jquery, as you said, it will hinder the learning process. Once i get javascript down, i would assume jquery will be my next step. I need to find out if this script is how it should be done in javascript, if there is an easier way around writing code for each line (in javascript), and how to get the border to show around the containing div?"
}
] |
[
{
"body": "<p>It is my first code review, I hope I'll be clear enough to explain why I would have done things like that.</p>\n\n<p>Here is how I would have it done - I removed the setCookie part because it was not used in what you show to us - :</p>\n\n<pre><code><html>\n <head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">\n </head>\n\n <body>\n <div id=\"edit\">\n <h1>Edit text as needed</h1>\n <form name=\"myForm\" enctype=\"multipart/form-data\">\n\n <table border=\"0\" width=\"100%\" style=\"border-collapse: collapse\">\n <tr>\n <td width=\"278\">Text</td>\n <td width=\"165\">Font Family</td>\n <td width=\"74\">Size</td>\n <td width=\"86\">Align</td>\n <td><b>B</b></td>\n <td><u>U</u></td>\n <td><i>I</i></td>\n </tr>\n\n <tr>\n <td>\n <input name=\"myContent\"></input>\n <input type=\"button\" value=\"Set content\" onclick=\"DOMModifier.setContent('lineOne', document.myForm.myContent.value);\">\n </td>\n\n <td width=\"165\">\n <select id=\"fontFamilyChanger\" onchange=\"DOMModifier.setFontFamily('lineOne', this.value);\">\n <option value=\"Arial\">Arial</option>\n <option value=\"Comic Sans MS\">Comic Sans MS</option>\n <option value=\"serif\" selected=\"selected\">Times New Roman</option>\n <option value=\"Verdana\">Verdana</option>\n </select>\n </td>\n\n <td width=\"74\">\n <select name=\"fontSizeChanger\" onchange=\"DOMModifier.setFontSize('lineOne', this.value);\">\n <option value=\"6\">6</option>\n <option value=\"8\">8</option>\n <option value=\"10\">10</option>\n <option value=\"12\" selected=\"selected\">12</option>\n <option value=\"14\">14</option>\n <option value=\"16\">16</option>\n <option value=\"18\">18</option>\n <option value=\"20\">20</option>\n </select>\n </td>\n\n <td width=\"75\">\n <select id=\"textAlignChanger\" onchange=\"DOMModifier.setAlign('lineOne', this.value);\">\n <option value=\"left\">left</option>\n <option value=\"center\" selected=\"selected\">center</option>\n <option value=\"right\">right</option>\n </select>\n </td>\n\n <td>\n <input type=\"checkbox\" onclick=\"DOMModifier.toggleBold('lineOne', this);\">\n </td>\n\n <td>\n <input type=\"checkbox\" onclick=\"DOMModifier.toggleUnderline('lineOne', this);\">\n </td>\n\n <td>\n <input type=\"checkbox\" onclick=\"DOMModifier.toggleItalic('lineOne', this);\">\n </td>\n </tr>\n\n <tr>\n <td>\n <input name=\"myContent1\"></input>\n <input type=\"button\" value=\"Set content\" onclick=\"DOMModifier.setContent('lineTwo', document.myForm.myContent1.value);\">\n </td>\n\n <td width=\"165\">\n <select id=\"fontFamilyChanger\" onchange=\"DOMModifier.setFontFamily('lineTwo', this.value);\">\n <option value=\"Arial\">Arial</option>\n <option value=\"Comic Sans MS\">Comic Sans MS</option>\n <option value=\"serif\" selected=\"selected\">Times New Roman</option>\n <option value=\"Verdana\">Verdana</option>\n </select>\n </td>\n\n <td width=\"74\">\n <select name=\"fontSizeChanger\" onchange=\"DOMModifier.setFontSize('lineTwo', this.value);\">\n <option value=\"6\">6</option>\n <option value=\"8\">8</option>\n <option value=\"10\">10</option>\n <option value=\"12\" selected=\"selected\">12</option>\n <option value=\"14\">14</option>\n <option value=\"16\">16</option>\n <option value=\"18\">18</option>\n <option value=\"20\">20</option>\n </select>\n </td>\n\n <td width=\"75\">\n <select id=\"textAlignChanger\" onchange=\"DOMModifier.setAlign('lineTwo', this.value);\">\n <option value=\"left\">left</option>\n <option value=\"center\" selected=\"selected\">center</option>\n <option value=\"right\">right</option>\n </select>\n </td>\n\n <td>\n <input type=\"checkbox\" onclick=\"DOMModifier.toggleBold('lineTwo', this)\">\n </td>\n\n <td>\n <input type=\"checkbox\" onclick=\"DOMModifier.toggleUnderline('lineTwo', this)\">\n </td>\n\n <td>\n <input type=\"checkbox\" onclick=\"DOMModifier.toggleItalic('lineTwo', this)\">\n </td>\n </tr>\n\n <tr>\n <td>\n <input name=\"myContent2\"></input>\n <input type=\"button\" value=\"Set content\" onclick=\"DOMModifier.setContent('lineThree', document.myForm.myContent2.value);\">\n </td>\n\n <td width=\"165\">\n <select id=\"fontFamilyChanger\" onchange=\"DOMModifier.setFontFamily('lineThree', this.value);\">\n <option value=\"Arial\">Arial</option>\n <option value=\"Comic Sans MS\">Comic Sans MS</option>\n <option value=\"serif\" selected=\"selected\">Times New Roman</option>\n <option value=\"Verdana\">Verdana</option>\n </select>\n </td>\n\n <td width=\"74\">\n <select name=\"fontSizeChanger\" onchange=\"DOMModifier.setFontSize('lineThree', this.value);\">\n <option value=\"6\">6</option>\n <option value=\"8\">8</option>\n <option value=\"10\">10</option>\n <option value=\"12\" selected=\"selected\">12</option>\n <option value=\"14\">14</option>\n <option value=\"16\">16</option>\n <option value=\"18\">18</option>\n <option value=\"20\">20</option>\n </select>\n </td>\n\n <td width=\"75\">\n <select id=\"textAlignChanger\" onchange=\"DOMModifier.setAlign('lineThree', this.value);\">\n <option value=\"left\">left</option>\n <option value=\"center\" selected=\"selected\">center</option>\n <option value=\"right\">right</option>\n </select>\n </td>\n\n <td>\n <input type=\"checkbox\" onclick=\"DOMModifier.toggleBold('lineThree', this);\">\n </td>\n\n <td>\n <input type=\"checkbox\" onclick=\"DOMModifier.toggleUnderline('lineThree', this);\">\n </td>\n\n <td>\n <input type=\"checkbox\" onclick=\"DOMModifier.toggleItalic('lineThree', this);\">\n </td>\n </tr>\n\n <tr>\n <td>\n <input name=\"myContent3\"></input>\n <input type=\"button\" value=\"Set content\" onclick=\"DOMModifier.setContent('lineFour', document.myForm.myContent3.value);\">\n </td>\n\n <td width=\"165\">\n <select id=\"fontFamilyChanger\" onchange=\"DOMModifier.setFontFamily('lineFour', this.value);\">\n <option value=\"Arial\">Arial</option>\n <option value=\"Comic Sans MS\">Comic Sans MS</option>\n <option value=\"serif\" selected=\"selected\">Times New Roman</option>\n <option value=\"Verdana\">Verdana</option>\n </select>\n </td>\n\n <td width=\"74\">\n <select name=\"fontSizeChanger\" onchange=\"DOMModifier.setFontSize('lineFour', this.value);\">\n <option value=\"6\">6</option>\n <option value=\"8\">8</option>\n <option value=\"10\">10</option>\n <option value=\"12\" selected=\"selected\">12</option>\n <option value=\"14\">14</option>\n <option value=\"16\">16</option>\n <option value=\"18\">18</option>\n <option value=\"20\">20</option>\n </select>\n </td>\n\n <td width=\"75\">\n <select id=\"textAlignChanger\" onchange=\"DOMModifier.setAlign('lineFour', this.value);\">\n <option value=\"left\">left</option>\n <option value=\"center\" selected=\"selected\">center</option>\n <option value=\"right\">right</option>\n </select>\n </td>\n <td>\n <input type=\"checkbox\" onclick=\"DOMModifier.toggleBold('lineFour', this);\">\n </td>\n\n <td>\n <input type=\"checkbox\" onclick=\"DOMModifier.toggleUnderline('lineFour', this);\">\n </td>\n\n <td>\n <input type=\"checkbox\" onclick=\"DOMModifier.toggleItalic('lineFour', this);\">\n </td>\n </tr>\n </table>\n\n\n <br/>\n <span>Colour:</span>\n <select id=\"color\" onchange=\"DOMModifier.setColor('myDiv', this.value);\">\n <option value=\"white\">white</option>\n <option value=\"black\" selected=\"selected\">black</option>\n <option value=\"red\">red</option>\n <option value=\"lightblue\">light blue</option>\n <option value=\"darkblue\">dark blue</option>\n <option value=\"lightgreen\">light green</option>\n <option value=\"darkgreen\">dark green</option>\n <option value=\"yellow\">yellow</option>\n <option value=\"orange\">orange</option>\n <option value=\"pink\">pink</option>\n <option value=\"purple\">purple</option>\n <option value=\"gray\">gray</option>\n </select>\n\n <select id=\"border\" onchange=\"DOMModifier.setBorder('myDiv', this.value);\">\n <option value=\"1px solid\" selected=\"selected\">1px</option>\n <option value=\"2px solid\">2px</option>\n <option value=\"3px solid\">3px</option>\n <option value=\"4px solid\">4px</option>\n <option value=\"5px solid\">5px</option>\n </select>\n </form>\n </div>\n <br/>\n <div id=\"myDiv\">\n <div id=\"lineOne\"></div>\n <div id=\"lineTwo\"></div>\n <div id=\"lineThree\"></div>\n <div id=\"lineFour\"></div>\n </div>\n\n <script type=\"text/javascript\">\n\n var DOMModifier = {\n // method that get an element by is identifier - don't repeat document.getElementById hundred times in your code\n // the method cache elements already retrieven from the DOM\n // throw error if element does not exists\n getElement : (function() {\n var elements = {}; // private - element collection, allow to cache DOM acces to div\n return function(identifier) {\n // check if element was alredy retrieved\n if ( typeof elements[identifier] === 'undefined' || elements[identifier] === null) {\n // if not, store it\n elements[identifier] = document.getElementById(identifier);\n if ( elements[identifier] === null ) // throw an error if it do not exists\n throw new Error('Element ' + identifier + ' does not exists');\n }\n\n return elements[identifier];\n };\n }()),\n\n // set content\n setContent: function(targetIdentifier, content) {\n this.getElement(targetIdentifier).innerHTML = content; // innerHTML on some elements is readonly in IE !\n },\n\n // add content\n addContent: function(targetIdentifier, content) {\n this.getElement(targetIdentifier).innerHTML += content;\n },\n\n // set style\n setStyle: function(targetIdentifier, style, value) {\n this.getElement(targetIdentifier).style[style] = value;\n },\n\n //modifiers - could have used content of thoses functions directly in \"onchange\" proprerty\n //but using functions is more maintainable and evoluable\n // ie : add check functions before doing a setStyle\n setColor: function(target, value) {\n this.setStyle(target, 'color', value);\n },\n\n setBorder: function(target, value) {\n this.setStyle(target, 'border', value);\n },\n\n setFontSize: function(target, value) {\n this.setStyle(target, 'fontSize', value);\n },\n\n setFontFamily: function(target, value) {\n this.setStyle(target, 'fontFamily', value);\n },\n\n setFontStyle: function(target, value) {\n this.setStyle(target, 'fontStyle', value);\n },\n\n setFontWeight: function(target, value) {\n this.setStyle(target, 'fontWeight', value);\n },\n\n setAlign: function(target, value) {\n this.setStyle(target, 'textAlign', value);\n },\n\n setBold: function(target, value) {\n this.setStyle(target, 'fontWeight', value);\n },\n\n setUnderline: function(target, value) {\n this.setStyle(target, 'textDecoration', value);\n },\n\n setItalic: function(target, value) {\n this.setStyle(target, 'fontStyle', value);\n },\n\n toggleBold: function(target, element) {\n this.setBold(target, element.checked === true ? 'bold' : 'normal');\n },\n\n toggleUnderline: function(target, element) {\n this.setUnderline(target, element.checked === true ? 'underline' : 'none');\n },\n\n toggleItalic: function(target, element) {\n this.setItalic(target, element.checked === true ? 'italic' : 'normal');\n }\n };\n </script>\n </body>\n</html>\n</code></pre>\n\n<p>Just check at the more important thing, the JavaScript code:</p>\n\n<pre><code>var DOMModifier = {\n // Method that get an element by is identifier - don't repeat document.getElementById hundred times in your code.\n // The method cache elements already retrieved from the DOM.\n // It throws an error if an element does not exist.\n getElement : (function() {\n var elements = {}; // private - element collection, allow to cache DOM acces to div\n return function(identifier) {\n // check if element was alredy retrieved\n if ( typeof elements[identifier] === 'undefined' || elements[identifier] === null) {\n // if not, store it\n elements[identifier] = document.getElementById(identifier);\n if ( elements[identifier] === null ) // throw an error if requested element does not exists\n throw new Error('Element ' + identifier + ' does not exists');\n }\n\n return elements[identifier];\n };\n }()),\n\n // Set content\n setContent: function(targetIdentifier, content) {\n this.getElement(targetIdentifier).innerHTML = content; // innerHTML on some elements is read-only in Internet Explorer!\n },\n\n // Add content\n addContent: function(targetIdentifier, content) {\n this.getElement(targetIdentifier).innerHTML += content;\n },\n\n // Set style\n setStyle: function(targetIdentifier, style, value) {\n this.getElement(targetIdentifier).style[style] = value;\n },\n\n //Modifiers - could have used content of thoses functions directly in the \"onchange\" proprerty,\n //but using functions is more maintainable and evolvable.\n // ie: add check functions before doing a setStyle\n setColor: function(target, value) {\n this.setStyle(target, 'color', value);\n },\n\n setBorder: function(target, value) {\n this.setStyle(target, 'border', value);\n },\n\n setFontSize: function(target, value) {\n this.setStyle(target, 'fontSize', value);\n },\n\n setFontFamily: function(target, value) {\n this.setStyle(target, 'fontFamily', value);\n },\n\n setFontStyle: function(target, value) {\n this.setStyle(target, 'fontStyle', value);\n },\n\n setFontWeight: function(target, value) {\n this.setStyle(target, 'fontWeight', value);\n },\n\n setAlign: function(target, value) {\n this.setStyle(target, 'textAlign', value);\n },\n\n setBold: function(target, value) {\n this.setStyle(target, 'fontWeight', value);\n },\n\n setUnderline: function(target, value) {\n this.setStyle(target, 'textDecoration', value);\n },\n\n setItalic: function(target, value) {\n this.setStyle(target, 'fontStyle', value);\n },\n\n toggleBold: function(target, element) {\n this.setBold(target, element.checked === true ? 'bold' : 'normal');\n },\n\n toggleUnderline: function(target, element) {\n this.setUnderline(target, element.checked === true ? 'underline' : 'none');\n },\n\n toggleItalic: function(target, element) {\n this.setItalic(target, element.checked === true ? 'italic' : 'normal');\n }\n};\n</code></pre>\n\n<p>Let's talk about what differs from yours:</p>\n\n<ul>\n<li>I declared one global object (DOMModifier) containing all the functions. This, in order to <strong>not populate the Global scope with a lot of functions</strong>.</li>\n<li>I made the functions \"generics\" like you did with yours <code>boldText</code>, <code>italic</code> and <code>underlineText</code>. To do that, we just have to pass the target identifier to the function <strong>instead of creating one function by target</strong>.</li>\n<li>I created a generic function <code>getElement</code> which cache the DOM elements access. So, for one identifier, it will only call the DOM function \"getElementById\" the first time, and store the result (or throw an error if it does not exist). Every other call in order to retrieve this element will just return the cached one.</li>\n<li>I created a generic function <code>setStyle</code> that is used by all the others function which are made to change a style.</li>\n<li>I changed some function names:\n<ul>\n<li><code>addContent</code> become <code>setContent</code> because it was, in fact, setting content. I added an <code>addContent</code> that add content.</li>\n<li>I added the keyword \"set\" before a lot of function names to make the code \"speaking\" about what it is doing.</li>\n</ul></li>\n<li>I added three functions: <code>toggleBold</code>, <code>toggleUnderline</code> and <code>toggleItalic</code> and I used them on the checkbox click event, beacause those event don't just set a style, but <code>set</code> or <code>unset</code> -litterally speaking- according to the state of the checkbox.</li>\n<li>I putted the JavaScript part at the end of the HTML, just before the body close, to ensure that all DOM elements are loaded before adding JavaScript features.</li>\n</ul>\n\n<p>Now let's talk about the JavaScript part in the <code>onchange</code> and <code>onclick</code> properties:</p>\n\n<ul>\n<li>Now that I have a global object instead of global functions, I call every function on the object - that is, <code>DOMModifier.setFontFamily()</code> with required arguments (target, value, etc.)</li>\n</ul>\n\n<p>Now what I did can really be improved by:</p>\n\n<ul>\n<li>Adding JavaScript <strong>EventListeners</strong> to elements when the DOM is loaded instead of using the <code>onchange</code> and <code>onclick</code> properties. It will <strong>separate HTML and JavaScript code</strong>, be more flexible, avoid errors, add features only when the DOM is ready to handle them...</li>\n<li>Modify some functions to make it cross-browser (that is, innerHTML on some elements won't work in Internet Explorer)</li>\n<li>Test and modify it to add features, make some actions more generics, etc...</li>\n</ul>\n\n<p>Just remember:</p>\n\n<ul>\n<li>What I changed here is good (I hope) for what I wanted it to do, in an other context, maybe I would have make it different, more flexible, more generic, more intrusive for objects nature, etc...</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T17:49:00.013",
"Id": "13529",
"Score": "0",
"body": "Thank you for all the work you have put into helping me with learning. I reaally to appreciate it. I am taking each piece you modified and studying it in comparieson with my (not so good)code. Thank you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T18:00:35.187",
"Id": "13530",
"Score": "0",
"body": "If you have any question, i'll be happy to answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T18:08:47.620",
"Id": "13532",
"Score": "0",
"body": "Thank you for offering. I am going through the code and will definatlely ask if i am not sure of anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T20:05:39.487",
"Id": "13538",
"Score": "0",
"body": "I am still really baffled as to how to get the border to show up from a checkbox, but it must be the same colour as the selection made for the font colour. As this is a stamp, only one colour can be on it, and having a checkbox for border or no border seems simple enough, however i need it to take the colour of the text colour selection."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T20:27:02.257",
"Id": "13540",
"Score": "0",
"body": "You want to have the possibility to add a border on a line ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T08:06:49.067",
"Id": "13568",
"Score": "0",
"body": "No, to have the possibility to add a border around a div. the border must be the same colour as the text selection colour."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T17:35:10.537",
"Id": "8664",
"ParentId": "8650",
"Score": "6"
}
},
{
"body": "<p>Not in the JavaScript part, but the HTML is not <a href=\"http://en.wikipedia.org/wiki/Well-formed_element\" rel=\"nofollow\">well-formed</a>. Excerpt:</p>\n\n<pre><code><div id=\"edit\">\n\n <form name=\"myForm\" enctype=\"multipart/form-data\">\n\n</div>\n\n </form>\n</code></pre>\n\n<p>The elements <code>div</code> and <code>form</code> overlap.</p>\n\n<p>The intended structure is probably:</p>\n\n<pre><code><div id=\"edit\">\n\n <form name=\"myForm\" enctype=\"multipart/form-data\">\n\n </form>\n\n</div>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-12T05:32:01.783",
"Id": "475117",
"Score": "0",
"body": "(This is not a comment. I just don't know a useful way to contact a user, in this case, about two suggested \"hexadecimal\" edits of yours I visited for review. I myself am a bit lax on the \"substantial\" side, more so since nobody else \"needs\" to check them (on CR - I read about your SU 15 minutes). I was called to order on a code edit - my current take there: fix unsuccessful conversions to a code block, remove blank lines top and bottom - nothing else. (I voted on neither to leave that to reviewers wiser than me. Or more opinionated.))"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T12:06:47.803",
"Id": "8682",
"ParentId": "8650",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "8664",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T12:13:04.323",
"Id": "8650",
"Score": "9",
"Tags": [
"javascript",
"beginner"
],
"Title": "Stamp order / preview form for a site"
}
|
8650
|
<p>I create python dictionary based on the parsed data:</p>
<pre><code>user_details['city'] = None
if api_result.get('response')[1] and api_result.get('response')[1][0]:
api_result_response = api_result.get('response')[1][0] # city details
if api_result_response:
user_details['city'] = int(api_result_response.get('cid'))
city_name = api_result_response.get('name')
if user_details['city'] and city_name:
# do something
</code></pre>
<p>So, I do a lot of verifications if passed data exists, if <code>user_details['city']</code> assigned etc. Is there any way to simplify that?</p>
|
[] |
[
{
"body": "<p>You should just use <code>try</code>/<code>except</code> here:</p>\n\n<pre><code>try:\n response = api_result['response'][1][0]\n user_details['city'] = int(response['cid'])\n city_name = response['name']\nexcept KeyError, IndexError:\n pass\nelse:\n # do something\n</code></pre>\n\n<p>The <code>else</code> on a <code>try</code>/<code>except</code> block is only executed if the <code>try</code> block ended normally, i.e. no exception was raised.</p>\n\n<p>You may also want to catch 'ValueError' in case <code>int()</code> is passed an invalid value.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T17:42:47.440",
"Id": "13528",
"Score": "0",
"body": "+1, but I'd note that you should be careful with this. If you call a function inside that block, it may raise a IndexError due to a bug, which will be hidden by this code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T13:51:57.897",
"Id": "8653",
"ParentId": "8652",
"Score": "2"
}
},
{
"body": "<p>Another key feature to dictionaries is the <code>dict.get(key, default)</code> function which allows you to get a default value if the key doesn't exist. This allows you to make the code less cluttered with <code>if</code> statements and also <code>try/except</code>.</p>\n\n<p>The solution is often a balance between <code>if</code> and <code>try</code> statements and default values. If you are checking correctness of values, keep the <code>try/catch</code> statements as small as possible.</p>\n\n<pre><code> response = api_result.get('response', None)\n if response:\n city_name = response.get('name', '')\n try:\n user_details['city'] = int( reponse.get('cid', 0) )\n except ValueError, e:\n pass # report that the 'cid' value was bogus\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T17:40:31.077",
"Id": "13527",
"Score": "0",
"body": "I think your answer would be better to include the numerical indexes as well as the string ones."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T15:42:16.033",
"Id": "13579",
"Score": "0",
"body": "FWIW, PEP8 asks you to use `if response is not None:`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T04:22:25.820",
"Id": "13844",
"Score": "0",
"body": "@WielandH., this way you will get an `AttributeError` on the next line, if response will happen to be `0`/`[]`/`False`/`()`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T16:51:21.280",
"Id": "8660",
"ParentId": "8652",
"Score": "4"
}
},
{
"body": "<p>I'd write a class that let me do this:</p>\n\n<pre><code>data = DataExtractor(api_result)\ntry:\n city = data.fetch('response', 1, 0, 'cid', int)\n city_name = data.fetch('response', 1, 0, 'city_name', str)\nexcept DataExtractionError:\n print \"Couldn't get the data!\"\n</code></pre>\n\n<p>Then I'd just have to worry about checking the validity of incoming data in one place, DataExtractor. It will take care of verifying anything I throw at it, and will always throw the DataExtractionError if something doesn't line up. As Paul Martel points out, you should give the arguments of fetch to DataExtractionError so you can have a clear error message.</p>\n\n<p>Another option to consider is using a json schema validator. Most of them can be used with objects that aren't actually JSON. Here is a link to PyPi which lists a few of them.</p>\n\n<p><a href=\"http://pypi.python.org/pypi?%3Aaction=search&term=json+schema&submit=search\" rel=\"nofollow\">http://pypi.python.org/pypi?%3Aaction=search&term=json+schema&submit=search</a></p>\n\n<p>The basic idea is that you tell it the structure of the data, and it can determine whether or not it actually fits. This can simplify your code because you once you've validated the data you can assume that the data's structure is correct and you don't have to do as much testing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T03:47:46.773",
"Id": "13840",
"Score": "1",
"body": "+1, and `DataExtractionError` should contain the arguments passed to data.fetch and the exception condition (missing value or wrong type) so you can print what when wrong in the except block."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T03:51:39.353",
"Id": "13841",
"Score": "0",
"body": "@PaulMartel, excellent point!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T04:27:14.957",
"Id": "13846",
"Score": "0",
"body": "@WinstonEwert, omg, what are all those arguments? How about going 1 step further and hiding them under the argumentless `DataExtractor.get_city_id()` and `DataExtractor.get_city_name()`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T04:45:46.633",
"Id": "13849",
"Score": "0",
"body": "@MishaAkovantsev, the argument specifies where in the data structure the piece of information you are interested lies. The op accesses `api_result['response'][1][0]['cid']` and I'm suggesting that he should pass all those keys to a function which can handle the logic of safely extracting in one place."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T04:53:16.983",
"Id": "13850",
"Score": "0",
"body": "@MishaAkovantsev, the arguments tell it where the data lives. DataExtractor is not specific to a single extraction task, but can be reused for any data structure you find yourself with. So having a `get_city_id()` function doesn't make any sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T05:06:13.803",
"Id": "13852",
"Score": "0",
"body": "@WinstonEwert, I got that, I just didn't thought of `DataExtractor` being **that** generic."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T17:34:20.040",
"Id": "8663",
"ParentId": "8652",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T13:27:42.437",
"Id": "8652",
"Score": "4",
"Tags": [
"python"
],
"Title": "Python dictionary usage"
}
|
8652
|
<p>Bulls and cows is a variation of the popular game called 'Mastermind', On a sheet of paper, the players each write a 4-digit secret number. The digits must be all different. Then, in turn, the players try to guess their opponent's number who gives the number of matches. If the matching digits are on their right positions, they are "bulls", if on different positions, they are "cows"</p>
<p><a href="http://en.wikipedia.org/wiki/Bulls_and_cows" rel="nofollow">Wikipedia page</a></p>
<p>One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equivalent score to how the last guess was scored. The next guess can be any number from the pruned list.</p>
<p>Either the program guess correctly or run out of numbers to guess, which indicates a problem with the scoring. </p>
<p>This is the implementation for n digits in C++, hunters (the list of all possible numbers that could be the answer) is a <code>vector</code> of <code>string</code> and cows it he function that counts the cows from two numbers:</p>
<pre><code>for(int h=0; Hunters.size() > 1; h++){
askBullsCows(h);
string guess = Hunters.at(0);
for(int i=Hunters.size()-1; i >= 0; i--){
int pl = 0, fl = 0;
for (unsigned int ix = 0; ix < Hunters.size(); ix++){
if(Hunters[i].at(ix) == guess.at(ix)) pl++;
}
Cows(i, guess, fl);
if((pl != P.p) || (fl != P.f)){
Hunters.erase(cazadores.begin()+i);}
}
}
</code></pre>
<p>Now, hunters (the <code>vector</code>) have more than 150.000 <code>string</code>s and it's too expensive for erase one by one <code>string</code> that couldn't be the answer.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T04:23:04.590",
"Id": "13522",
"Score": "3",
"body": "Use a linked list instead of a vector, then erasure is much cheaper. Or copy just the eligible solutions to a brand new vector. Either one avoids the expense of copying elements down to fill in each erased space."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T04:51:03.200",
"Id": "13523",
"Score": "0",
"body": "After what I heard at Going Native, I would challenge this assertion and say test it first. Lists according to those exalted souls, are going to be slower due to cache and traversal issues."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T17:37:53.090",
"Id": "13526",
"Score": "2",
"body": "Erase does not need to be expensive. The version implemented by std::vector<> is because it has some extra constraints that you do not need. A cheap way to remove an element swap it with the last element and then re-size the vector to 1 smaller. Thus erasing is the cost of a single copy."
}
] |
[
{
"body": "<ol>\n<li><p>Use <code>char[n]</code> instead of string to store each individual solution.</p></li>\n<li><p>Copy just the eligible solutions to a brand new <code>vector</code> (as <em>Ben Voigt said</em>) instead of deletion.</p></li>\n</ol>\n\n<p>Assume <code>n<=10</code>. So, memory you need is less than 73Mb (i.e. twice 10*10!). Sequential memory access (#2) and avoiding pointer dereference (#1) means high performance on modern DDR memory.</p>\n\n<p>UPDATE: Some notes on random or even non-random, but non-sequentional DDR memory read. Say, four 8-byte reads at addresses 0x8000 0x8100 0x8200 0x8300 will be slower than four 8-byte reads at 0x9000 0x9008 0x9010 0x9018, because in the later case all the data for the last reads (i.e. 0x9008 0x9010 0x9018) are <strong>already</strong> in processor 32-byte cache line (also, there are 64-byte cache lines in some processors). Each memory read (say, 8-byte read) transfers the <strong>whole</strong> 32-byte cache line from memory to processor cache.</p>\n\n<p>Next, even the best possible optimizer can not decrease non-sequentional memory access latency (that is, the time between the memory address was calculated and the memory address contents was arrived into the processor)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T18:14:02.907",
"Id": "13533",
"Score": "0",
"body": "Arrays are non copyable. So this involves more work. The cost of copying a string is not that much more (n + 3 pointers) and if the optimizer spots it only actually requires copying three pointers. array memory is the same as pointer memory there is no difference to the machine in terms of de-referencing and using high performance instructions. Though you would potentially gain in code locality."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T20:32:02.300",
"Id": "13644",
"Score": "0",
"body": "@LokiAstari What does this mean: \"Arrays are non copyable\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T20:56:47.440",
"Id": "13645",
"Score": "0",
"body": "@Thomas I can not comment on your \"use a vector<bool>\" suggestion ( http://codereview.stackexchange.com/a/8658/10800 ). So I shall comment here. Do you suggest to re-generate each of solution \"on the fly\" while pruning? If so, this will be much slower than to sequentially read eligible solutions from the memory -- DDR3 **sequentional** memory read rate is around 16 GB/s, that is, around 2GT/s of 8-byte solutions. (So, the next optimization target is calculation of cows. For the memory read rates you may look at, say, http://zsmith.co/bandwidth.html )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T21:21:52.897",
"Id": "13648",
"Score": "0",
"body": "I made a mistake about array copying: http://stackoverflow.com/q/9167253/14065"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T05:11:19.800",
"Id": "8657",
"ParentId": "8656",
"Score": "4"
}
},
{
"body": "<p>Instead of using a <code>vector<string></code>, use a <code>vector<bool></code> of constant size, 10000 elements. Element 0 represents answer <code>0000</code>, and so on, up to <code>9999</code>. Set all to <code>true</code> initially, except those containing the same digit more than once, and simply flip the bits to <code>false</code> when you've eliminated a particular option.</p>\n\n<p>A <code>vector<bool></code> has a specialized implementation (the source of much complaint) that packs bits tightly, so it takes only 10000 bits, or approximately 1.2 kB. More importantly, \"deletions\" are done in constant time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T12:03:35.970",
"Id": "8658",
"ParentId": "8656",
"Score": "2"
}
},
{
"body": "<p>First comment your variable names are horrible which makes reading the code really hard.</p>\n\n<p>Where:</p>\n\n<pre><code>for(int h=0; Hunters.size() > 1; h++){\n</code></pre>\n\n<ul>\n<li>What is <code>h</code> supposed to represent?</li>\n<li>Why is <code>h</code> not part of the condition?<br>\nSince <code>h</code> is not part of the loop you should remove it from the loop construct, which turns this into a while.</li>\n</ul>\n\n<p>Do you really want to make a copy of the string here</p>\n\n<pre><code> string guess = Hunters.at(0);\n\n // make it a const reference\n // You are not altering the gurss and you don't need a copy.\n string const& guess = Hunters.at(0);\n</code></pre>\n\n<p>Curios why you decided to count down.<br>\nThere does not seem a need for it, counting up is more natural and easier to reason about so you should prefer it when you can.</p>\n\n<pre><code> for(int i=Hunters.size()-1; i >= 0; i--){\n</code></pre>\n\n<p>Please declare one variable to a line. </p>\n\n<pre><code> int pl = 0, fl = 0;\n</code></pre>\n\n<p>And give those variables meaningful names so we can see what is happening. I have no idea how these two related to bulls/cows/ position in hunters/size of other stuff. Without this context the code is nearly indecipherable. Something that should be obvious at a glance takes 5 minutes of head scratching to understand.</p>\n\n<p>There is something wrong here:</p>\n\n<pre><code> for (unsigned int ix = 0; ix < Hunters.size(); ix++){\n if(Hunters[i].at(ix) == guess.at(ix)) pl++;\n }\n</code></pre>\n\n<p>The variable <code>ix</code> is ranging over the size of the array. But is used as index into individual members of the attar (luckily you used at() to generate the appropriate exceptions). Maybe if you had given them reasonable names that would have been easier to spot.</p>\n\n<p>OK. Erasing from a vetor can be expensive. Especially one as large as you claim.</p>\n\n<pre><code>if((pl != P.p) || (fl != P.f)){\n Hunters.erase(cazadores.begin()+i);}\n</code></pre>\n\n<p>But you have not inherent ordering on the array so you can make this a lot less costly to do (but you would need to invert the above loop so it counts up rather than down).</p>\n\n<pre><code> if (testToKeep())\n {\n ++hunterIndex; // Move to the next element.\n // OK: That name is a bit long for a loop variable.\n // But its intent is clear. `huntIdx` would do.\n }\n else\n {\n hunters[hunterIndex].swap(hunters[hunters.size()-1]);\n hunters.resize(hunters.size()-1);\n\n // Note: We do not increment the loop here\n // This is because we have a new value to test\n // at the current location and the size of the array\n // has decreased thus effectively moving us one closer\n // to the end.\n }\n</code></pre>\n\n<p>I can forgive putting the '{' on the wrong line as about 30% of developers prefer that way (the other 30% prefer to line up open and close and the final 40% don't care (as long as you consistent)). </p>\n\n<pre><code>if((pl != P.p) || (fl != P.f)){\n Hunters.erase(cazadores.begin()+i);}\n</code></pre>\n\n<p>But please put the closing brace '}' underneath. There is absolutely no need for this insane attempt at saving space and making the code unreadable. Also this would make it consistent with the rest of your code (which is much more important).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T17:55:42.593",
"Id": "8665",
"ParentId": "8656",
"Score": "2"
}
},
{
"body": "<p>You are using Hunter.size() function at various places(that too inside a for loop).\nYou could at the begining store it in a variable(like below) and then use it.It will decrease the overhead of a function call in a loop.</p>\n\n<pre><code>var size = Hunter.size();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-25T07:45:25.340",
"Id": "12057",
"ParentId": "8656",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T04:19:17.117",
"Id": "8656",
"Score": "10",
"Tags": [
"c++",
"algorithm"
],
"Title": "\"Bulls and cows\" algorithm"
}
|
8656
|
<p>I have a function which is supposed to replace all instances of variables (represented as <code>NSStrings</code>) from an <code>NSDictionary</code> with their corresponding values before calling another procedure. I ended up doing this with a simple <code>for</code> loop, though I suspect that there is a better way. Do you have a suggestion how to do this differently?</p>
<pre><code>+ (double)runProgram:(id)program usingVariables:(NSDictionary *)variables {
NSMutableArray *stack;
if ([program isKindOfClass:[NSArray class]]) {
stack = [program mutableCopy];
for (int i=0; i<stack.count; i++) {
/* replace variable values with NSNumber values */
NSNumber *variableValue = [variables valueForKey:[stack objectAtIndex:i]];
if ([variableValue isKindOfClass:[NSNumber class]]) {
[stack replaceObjectAtIndex:i withObject:variableValue];
}
/* all variables should be replaced now */
}
}
return [self popOperandOffProgramStack:stack];
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>+ (double)runProgram:(id)program usingVariables:(NSDictionary *)variables { \n NSMutableArray *stack;\n if ([program isKindOfClass:[NSArray class]]) {\n</code></pre>\n\n<p>Checking the type of incoming parameters is a little suspicious. Do you really want to allow other parameters and just ignore them?</p>\n\n<pre><code> stack = [program mutableCopy];\n</code></pre>\n\n<p>This process would actually be easier if you didn't create a copy, but instead create an empty NSMutableArray and add the filtered objects to it.</p>\n\n<pre><code> for (int i=0; i<stack.count; i++) {\n</code></pre>\n\n<p>Presumably, you are using this because you need the indexes to replace the objects. If you stop making a copy, you should be able to replace this a foreach loop over the program.</p>\n\n<pre><code> /* replace variable values with NSNumber values */\n NSNumber *variableValue = [variables valueForKey:[stack objectAtIndex:i]];\n if ([variableValue isKindOfClass:[NSNumber class]]) {\n</code></pre>\n\n<p>Again why are you checking types? Are there other things besides numbers in your variables? If there are, do you just want to ignore them?</p>\n\n<pre><code> [stack replaceObjectAtIndex:i withObject:variableValue];\n }\n /* all variables should be replaced now */\n</code></pre>\n\n<p>This comment isn't true here, because its on the wrong side of the brace</p>\n\n<pre><code> }\n }\n return [self popOperandOffProgramStack:stack];\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T17:37:26.850",
"Id": "13525",
"Score": "0",
"body": "Also, if 'program' is not an NSArray then 'stack' is uninitialized in the return statement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T09:00:20.217",
"Id": "13569",
"Score": "0",
"body": "Thank you for your feedback. I agree on most points. In the case of the `NSNumber *variableValue` test, I imagine that there will be some objects which will not be found in the `variables` `NSDictionary`. Rather than testing if there is nothing in the dictionary for that key, I opted to test that the object returned was in fact a kind of `NSNumber` before doing anything. I don't want to replace anything if there is nothing in `variables` for that key."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T09:00:28.267",
"Id": "13570",
"Score": "0",
"body": "Do you think it's better to explicitly test for null instead?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T09:05:14.923",
"Id": "13571",
"Score": "0",
"body": "The technique of testing classes and ignoring input if it is not what you expect is something I learned from watching the iPhone dev videos from Stanford (http://www.stanford.edu/class/cs193p/cgi-bin/drupal), although I'm not sure if I'm doing it correctly... The `runProgram:usingVariables` is API so I can't be certain that the input is as I would expect. How would you handle erroneous values?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T09:18:16.437",
"Id": "13572",
"Score": "0",
"body": "By the way, I really liked your suggestion to create an empty `NSMutableArray` and add each step (replacing variables on the way) rather than replacing variables later. It's much easier to read - thank you!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T19:17:05.007",
"Id": "13583",
"Score": "0",
"body": "@jaresty, I think it is better to explicitly check for null. If you check for null, I can tell that you are checking whether the element was actually in the dictionary. It's not obvious from your code above that that is what you checking for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T19:22:14.847",
"Id": "13584",
"Score": "0",
"body": "@jaresty, there are different theories on how to handle invalid data. I don't like simply ignoring input because it makes so that when the invalid input happens, things just don't work without any explanation. Depending on the situation, I might not have a check, and trust that I'll get a selector not implemented error which make the problem obvious. Or I might put in an assertion, so that I only check the type during debugging. At the very least, I'd log the fact that invalid data is found."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T23:10:59.823",
"Id": "13598",
"Score": "0",
"body": "@WinstonEwert thanks - I agree. I added an explicit check for nil and NSLog if the value isn't as expected. Please let me know if you have any further suggestions!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T03:04:15.400",
"Id": "13601",
"Score": "0",
"body": "@jaresty, you are stilling ignoring in the case that program isn't an NSArray. (and I still think you simply shouldn't be checking the types. But you can ignore if you choose)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T06:11:48.103",
"Id": "13605",
"Score": "0",
"body": "Ok - I added an explicit else to catch non-NSArray program values. I'm still conflicted about the type-checking since I've heard a different argument from the Stanford lecture I'm listening to. I can see advantages and disadvantages to each, but as I'm working through that class right now I think I'll stick to this methodology for now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T15:03:25.053",
"Id": "13626",
"Score": "0",
"body": "@jaresty, fair enough. There are reasonable arguments on either side of the question of doing those type checks. Obviously, I come down on the one side, but I don't think its the only reasonable way."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T16:56:54.897",
"Id": "8661",
"ParentId": "8659",
"Score": "5"
}
},
{
"body": "<p>I'm going to handle this answer in two parts, as they're two distinct issues I want to address here:</p>\n\n<pre><code>+ (double)runProgram:(id)program usingVariables:(NSDictionary *)variables { \n NSMutableArray *stack;\n if ([program isKindOfClass:[NSArray class]]) {\n stack = [program mutableCopy];\n for (int i=0; i<stack.count; i++) {\n /* replace variable values with NSNumber values */\n NSNumber *variableValue = [variables valueForKey:[stack objectAtIndex:i]];\n if ([variableValue isKindOfClass:[NSNumber class]]) {\n [stack replaceObjectAtIndex:i withObject:variableValue];\n }\n /* all variables should be replaced now */\n }\n }\n return [self popOperandOffProgramStack:stack];\n}\n</code></pre>\n\n<p>First, let's change the method signature to something that makes a whole lot more sense:</p>\n\n<pre><code>+ (double)runProgram:(NSArray *)program usingVariables:(NSDictionary *)variables;\n</code></pre>\n\n<p>The method only makes sense if <code>program</code> is an array. If it's not an array, then what does the method body actually look like? It looks like this:</p>\n\n<pre><code>return [self popOperandOffProgramStack:nil];\n</code></pre>\n\n<p>So let's change the argument to <code>NSArray *</code> rather than <code>id</code>. Now our method is more explicitly clear to callers that we except an <code>NSArray</code>, and if you don't have an array to send, send <code>nil</code>, because that's how we're going to use any non-array argument anyway.</p>\n\n<p>Now that we've change the argument, we can get rid of the type check in the body.</p>\n\n<hr>\n\n<p>Now to the second point I want to address in the body. First, in Objective-C, <code>forin</code> loops are faster then the other available loops, so use them where you can.</p>\n\n<p>I think the method body works much better as such:</p>\n\n<pre><code>+ (double)runProgram:(NSArray *)program usingVariables:(NSDictionary *)variables { \n NSMutableArray *stack = [NSMutableArray array];\n for (id obj in program) {\n if ([variables[obj] isKindOfClass:[NSNumber class]]) {\n [stack addObject:variables[obj]];\n } else {\n [stack addObject:obj];\n }\n }\n return [self popOperandOffProgramStack:stack];\n}\n</code></pre>\n\n<p>As a note, the <code>else</code> block is in there simply in order to rewrite your existing code and produce identical results. If objects that are not <code>NSNumbers</code> should be added to the array, simply remove the <code>else</code> block.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-07T01:33:52.843",
"Id": "56306",
"ParentId": "8659",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "8661",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T15:57:27.907",
"Id": "8659",
"Score": "8",
"Tags": [
"objective-c"
],
"Title": "Replacing Items in an NSMutableArray"
}
|
8659
|
<p>I am trying to fetch information out of <a href="http://en.wikipedia.org/wiki/SHOUTcast">SHOUTcast</a> for mutiple users at the same time. Here is my current code:</p>
<pre><code><?php
header("Access-Control-Allow-Origin:*");
function failOut($http, $text) {
header('HTTP/1.x ' . $http);
die(htmlspecialchars($text));
}
$params = $_GET;
$user = 'root'; // Change this to username
$password = ''; // Put your password here. My home database doesn't have any password (is empty).
$con = mysql_connect('localhost',$user,$password) or die('Could Not Connect..');
$context = stream_context_create(
array(
'http' => array(
//Required To fool ShoutCast or it will flood with the stream instead
'user_agent' => "GET / HTTP/1.0\r\n"
."Host:117.200.149.48\r\n"
."User-Agent: Mozilla/5.0 (compatible; ShoutCastInfoClass/0.0.2; ".PHP_OS.")\r\n"
."\r\n",
),
)
);
if($params['act'] == 'st'){
mysql_select_db('radio',$con);
$count = mysql_query("select * from info where ID='".$params['id']."'")or die('Error In Query'.mysql_error());
$content = null;
$rows = mysql_num_rows($count);
if( $rows > 0 ){
$res = mysql_fetch_assoc($count);
if($res['TIMESTAMP'] + 30 < time()){
if($res['version'] == '1'){
$base = $res['IP'].'/admin.cgi?mode=viewxml&user=admin&pass='.$res['PASS'];
// Well i will change this crazy method with something non password secured pretty soon
}else{
$base = $res['IP'].'/stats?sid=1';
// As per shoutcast v2 APIs !! :D
}
$content = file_get_contents($base, false, $context)or die("Unable to Load resourse");
$dom = new DOMDocument();
$dom->loadXML($content);
$res['SERVERTITLE'] = htmlspecialchars($dom->getElementsByTagName('SERVERTITLE')->item(0)->textContent);
$res['SONGTITLE'] = htmlspecialchars( $dom->getElementsByTagName('SONGTITLE')->item(0)->textContent );
$res['BITRATE'] = $dom->getElementsByTagName('BITRATE')->item(0)->textContent;
$res['GENRE'] = $dom->getElementsByTagName('SERVERGENRE')->item(0)->textContent;
$res['CONTENT'] = $dom->getElementsByTagName('CONTENT')->item(0)->textContent;
if(strpos($res['CONTENT'],'mpeg')){
$res['CONTENT'] = 'MP3';
}else if(strpos($res['CONTENT'],'aac')){
$res['CONTENT']= 'AAC';
}else{
$res['CONTENT'] = 'OGG';
}
$query='update INFO SET SERVERTITLE="'.$res['SERVERTITLE'].
'", SONGTITLE="'.$res['SONGTITLE'].
'", BITRATE="'.$res['BITRATE'].
'", GENRE="'.$res['GENRE'].
'", CONTENT="'.$res['CONTENT'].
'" , TIMESTAMP='.time().' where ID=\''.$params['id']. '\';';
mysql_query($query,$con)or die(mysql_error());
mysql_close($con);
}
unset( $res['IP'] );
unset( $res['PASS'] );
echo json_encode($res);
}
}else if($_params['act']== 's'){
// To search for a specific keyword
$queryString = $params['q'];
}else if($_params['act'] == 'l'){
// To feed list to the applet
$cat = $params['c'];
// Categories are various lists depending on genre languages etc...
}
?>
</code></pre>
<p>I was wondering if making a phpSocket server would be better for this purpose as sockets will reduce the demand of required MySQL connections to be opened.</p>
<p>Or</p>
<p>Is my current method the best solution?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T11:41:19.883",
"Id": "13574",
"Score": "2",
"body": "Well first I'd suggest you ditch the mysql_* functions. :) Both PHP and MySQL have moved on a lot since the early days and the mysql_* set of functions really just don't cut it anymore. I'd strongly advise switching to mysqli or PDO."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T11:43:43.477",
"Id": "13575",
"Score": "0",
"body": "Also, your code is wide open to SQL injection because you do no filtering or validating of the user input (other than assigning $_GET to $params). mysqli and PDO both support a mechanism called prepared statements that allow automatic escaping of variables when they're injected into a SQL statement. (I would still implement some proper validation of user input as well before passing it to the DB though. You can never be too careful)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T13:27:09.063",
"Id": "13577",
"Score": "0",
"body": "@GordonM thanks for the heads up i will fix it as soon as possible :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T13:37:56.007",
"Id": "13578",
"Score": "0",
"body": "Its been ages since i have actually written something on PHP so it feels kind of confusing now , anyways still socket or Multi Script ? which is better ? also with sockets i can remove the MYSQL need totally by storing all the values into RAM ."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-16T02:47:34.843",
"Id": "18903",
"Score": "1",
"body": "Switch to PDO! I'd also recommend breaking up some code logically into functions. You have too many if statements and nested if statements and it makes it hard to follow the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T16:53:18.340",
"Id": "40403",
"Score": "0",
"body": "If you dont want to use PDO directly, there are many ORMs out there that will do the heavy lifting for you. I.e. Zend_Db, Doctrine2 etc."
}
] |
[
{
"body": "<ol>\n<li><p>If you want to use this function you should have buffering:</p>\n\n<blockquote>\n<pre><code>function failOut($http, $text) {\n header('HTTP/1.x ' . $http);\n die(htmlspecialchars($text));\n}\n</code></pre>\n</blockquote>\n\n<p>Otherwise it's possible that the script sends out some output (including error messages) and you can't send out any header later. (<a href=\"https://stackoverflow.com/q/3111179/843804\">How do headers work with output buffering in PHP?</a>) Anyway, I don't see any call to this function, so you might be able to remove it.</p></li>\n<li><blockquote>\n<pre><code>$con = mysql_connect('localhost',$user,$password) or die('Could Not Connect..');\n</code></pre>\n</blockquote>\n\n<p>As others already suggested you should use mysqli or PDO. Another note is that you might want to set the <a href=\"http://www.php.net/manual/en/function.http-response-code.php\" rel=\"nofollow noreferrer\">HTTP response code</a> to 503 here to save your search engine ranking when the database is down.</p></li>\n<li><blockquote>\n<pre><code>$params = $_GET; \n...\n$count = mysql_query(\"select * from info where ID='\".$params['id'].\"'\")or die('Error In Query'.mysql_error()); \n</code></pre>\n</blockquote>\n\n<p>As others already mentioned in comments it's not safe against <a href=\"https://en.wikipedia.org/wiki/SQL_injection\" rel=\"nofollow noreferrer\">SQL injections attacks</a>. <code>mysql_error()</code> should not be the output of the script. Show only a generic error message and log the details to a server-side log file, don't help attackers. It would also be more user-friendly, most of the users doesn't care nor understand MySQL errors (or at least can't fix them). (<a href=\"https://stackoverflow.com/q/3531703/843804\">How to log errors and warnings into a file?</a>)</p></li>\n<li><blockquote>\n<pre><code>$dom->getElementsByTagName('BITRATE')->item(0)->textContent\n</code></pre>\n</blockquote>\n\n<p>This is in the code at least five times (with different tagname). You could create a function (whose parameter is the tagname) to remove the duplication.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T18:16:21.637",
"Id": "44519",
"ParentId": "8666",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "44519",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T18:12:40.383",
"Id": "8666",
"Score": "7",
"Tags": [
"php",
"mysql",
"http"
],
"Title": "What is better for the code segment, sockets or multiple processes?"
}
|
8666
|
<p>Here's my C++ code:</p>
<pre><code>bool isPrime(double value) {
if (value == 2) // ensure 2 returns true
return true;
else if (value <= 1) // eliminate 1 and all negative numbers
return false;
else if (fmod(value, 2) == 0) // eliminate all even numbers
return false;
for (int i = 3; i < sqrt(value); i++) {
if (fmod(value, i) == 0) {
return false;
}
}
return true;
}
</code></pre>
<p>This function should return true if a number given by value is a prime, and false if a number given by value is a composite. First off, I just want to make sure it works correctly, is fairly efficient (it doesn't have to be the best, but I would like it to be decent for a naive approach), and that the code looks nice.</p>
<p>Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T17:55:13.840",
"Id": "13634",
"Score": "0",
"body": "I don't know how efficient the implementation is of `fmod()` on your system, but statements like `if ((value & 0x1) == 0)` is likely a faster way to detect even numbers. That's possibly the case with `fmod()` in your for loop as well. You could use `if ((value % i) == 0)` instead."
}
] |
[
{
"body": "<p>2 things:</p>\n\n<ol>\n<li><code>isPrime(9)</code> returns <code>true</code> because you're using <code><</code> in the loop's termination clause instead of <code><=</code>.</li>\n<li>You don't need to add a special case for eliminating even numbers, you can just change the loop's starting point to <code>2</code> instead of <code>3</code>.</li>\n</ol>\n\n\n\n<pre><code>for(int i = 2; i <= sqrt(value); i++) {\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T19:10:47.080",
"Id": "13534",
"Score": "0",
"body": "If I change the loops starting point to 2 instead of 3, and I fail to check for 2, with my current implementation, it says that 2 is composite."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T19:15:44.967",
"Id": "13536",
"Score": "0",
"body": "@Bob: No, I was talking about the even numbers only, not the first `if` statement where you check for `2`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T00:30:36.103",
"Id": "13553",
"Score": "0",
"body": "@seand - good catch on the isPrime(9)! adjusted my answer to include that."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T19:02:10.053",
"Id": "8668",
"ParentId": "8667",
"Score": "5"
}
},
{
"body": "<p>Is there such a thing as a prime real number?</p>\n\n<p>If not then the function signature should use integer (preferably unsigned as there are no negative primes).</p>\n\n<p>Then you should be able to use <code>%</code> rather than <code>fmod()</code> which I would suspect is a tad faster but, more importantly, easier to read.</p>\n\n<p>Since you have already checked for all even primes:</p>\n\n<pre><code>for (int i = 3; i < sqrt(value); i+=2) {\n // ^^^^ No need to increment by 1;\n // All evens already checked already so inc by 2\n // So just check 3/5/7/9 etc\n</code></pre>\n\n<p>Here is a link to cool but not obvious optimization (That allows you to avoid checking all multiples of <code>3</code> as well as <code>2</code>): <a href=\"https://codereview.stackexchange.com/a/7342/507\">https://codereview.stackexchange.com/a/7342/507</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T16:01:02.907",
"Id": "13631",
"Score": "0",
"body": "The optimization is interesting (and clever) but seems to complicate the flow beyond OP goal of a \"naive\" algorithm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T16:05:07.470",
"Id": "13632",
"Score": "0",
"body": "@codingoutloud: Your definition of complicated must be different from mine :-) `i+=2` => `i+=t, t=6-t`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T22:17:01.563",
"Id": "13650",
"Score": "0",
"body": "Hi @Loki Astari - IMHO even that simple change would elicit a WTF from many programmers. It is not obvious - not \"naive\" - what is going on. Your comment did not include all the changes; the loop initialization is also more complex (and, IMHO, also does not pass the initial WTF/naivity test). I am *not* saying that nobody can understand it, or that it isn't a good optimization, etc., simply that it doesn't seem to me consistent with the request for a \"naive primality test\" as specified in the OP."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T22:22:17.627",
"Id": "13651",
"Score": "1",
"body": "@codingoutloud: OK. I can agree with that :-)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T22:23:29.387",
"Id": "8672",
"ParentId": "8667",
"Score": "12"
}
},
{
"body": "<p>I would start by removing the <code>sqrt(value)</code> from the loop condition check. You do not want to compute the square root every time as this will not change for the whole of the computation.\nCompute the root once, round it up and cast it to an <code>int</code> value.</p>\n\n<p>As pointed by Seand, you need to check the equality to the square root, otherwise you might end up with a false positive with that value.</p>\n\n<p>You do not need to check for multiples of <code>2</code> and then start the loop at <code>3</code>. Remove the extra check and start the loop at <code>2</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T00:27:33.190",
"Id": "13551",
"Score": "0",
"body": "I want to say that modern compilers will cache the result of the `sqrt` call but I'm not sure about that. It's good that you mention it though because caching the value yourself is a good habit to get into for cases where the compiler can't optimize it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T00:53:58.337",
"Id": "13555",
"Score": "0",
"body": "I don't think you''ll find a compiler these days which can't figure out that optimization. But if you leave it in the loop, you will want to cast it since I believe otherwise the compiler will promote your int value to a double to do the comparison each time through the loop. So `i < int(sqrt(value))` could go in the loop and be better off from optimization point of view. As I did in my answer, I think that `i < int(floor(sqrt(value)))` is more intent revealing."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T23:27:01.467",
"Id": "8673",
"ParentId": "8667",
"Score": "2"
}
},
{
"body": "<p>I suggest the follow edits:</p>\n\n<ol>\n<li>Deal only with <code>int</code> (or could use <code>long</code>, but does not change basic algorithm). This allows use of regular modulo operator (<code>%</code>).</li>\n<li>Could take <code>sqrt(value)</code> out of the loop, but not needed for performance since the C++ compiler has plenty of information to optimize it for you. </li>\n<li>Instead of just a cast for <code>sqrt</code>, use <code>floor</code> (same effect, but more intent revealing)</li>\n<li>No explicit test is needed for <code>2</code> - it returns <code>true</code>.</li>\n<li>Skip by <code>2</code> in loop.</li>\n<li>Improved comments.</li>\n<li>Fixed logic flaw with <code>< sqrt</code> which should be <code><=</code></li>\n</ol>\n\n<p>With the resulting code:</p>\n\n<pre><code>bool isPrime(int value)\n{\n if (value < 2) // 2 is smallest prime number\n return false;\n\n // at least one factor guaranteed to appear before sqrt(x) if x is composite\n for (int i = 3; i <= int(floor(sqrt(value))); i += 2) \n {\n if (value % i == 0)\n return false;\n }\n\n return true;\n}\n</code></pre>\n\n<p>This is entirely a style thing, but could also tighten to the following, which looks less cluttered:</p>\n\n<pre><code>bool isPrime(int value)\n{\n // 2 is smallest prime number\n if (value < 2) return false;\n\n // at least one factor guaranteed to appear before sqrt(x) if x is composite\n for (int i = 3; i <= int(floor(sqrt(value))); i += 2) \n if (value % i == 0) return false;\n\n return true;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T00:29:29.430",
"Id": "13552",
"Score": "1",
"body": "It's C++ code, not Java."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T00:47:47.643",
"Id": "13554",
"Score": "1",
"body": "Thanks - I updated my syntax and comment - and thanks for the formatting edit to improve visibility of keywords."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T00:25:33.630",
"Id": "8674",
"ParentId": "8667",
"Score": "5"
}
},
{
"body": "<p>If you check for primes a lot, use memoisation to avoid checking values more than once. I would also pre-cache some results and make PrimeCheck class a singleton.</p>\n\n<pre><code>#include <cmath>\n#include <unordered_map>\n\ntypedef std::unordered_map<int, bool> IntBoolMap;\n\nclass PrimeCheck {\npublic:\n PrimeCheck();\n\n bool isPrimeCached(int value);\n\n static bool isPrime(int value);\n\nprivate:\n IntBoolMap checked_;\n};\n\nPrimeCheck::PrimeCheck() {\n checked_[1] = false;\n checked_[2] = true;\n checked_[3] = true;\n checked_[4] = false;\n //pre-populate a few results here\n}\n\nbool PrimeCheck::isPrimeCached(int value) {\n IntBoolMap::iterator it = checked_.find(value);\n if (it != checked_.end()) {\n //result found\n return it->second;\n }\n bool result = PrimeCheck::isPrime(value);\n checked_[value] = result;\n return result;\n}\n\nbool PrimeCheck::isPrime(int value) {\n if (value < 2) return false;\n\n int max = static_cast<int>(floor(sqrt(value)));\n for (int i = 3; i <= max; i += 2) {\n if (value % i == 0) return false;\n }\n\n return true;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T11:46:55.087",
"Id": "13576",
"Score": "0",
"body": "Couldn't you just cache all the primes and the greatest non-prime found? Assuming that knowing the primeness of `n` tells you the primeness of `n-1` for `n >= 3`, this could save space and you'd still know all primes. It would lead to lookups being O(lg(n)) instead of O(1), though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T17:48:17.583",
"Id": "13699",
"Score": "0",
"body": "To generate all the primes up to N, create an array up to N(-1)with factor[x]=x for all values. Then iterate x up to sqrt(N) (x*x < N ) with if( factor[x]==x ) // primes only; for( y = x; (factor[y]==y || factor[y]==x) && x*y < N ){ factor[x*y]=x; }\n\nYou end up with a table of the lowest prime factor of every number and a number is prime if its lowest prime factor is itself."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T03:16:03.890",
"Id": "8676",
"ParentId": "8667",
"Score": "3"
}
},
{
"body": "<p>One inefficiency I will eliminate for you is the test against the sqrt because you are calculating the square root every iteration.</p>\n\n<p>Calculcate it once. </p>\n\n<pre><code>for( int i = 3, const iMax = static_cast<int>(sqrt(value)); i<=iMax; i+=2 )\n{\n // check\n}\n</code></pre>\n\n<p>Of course fmod is potentially less efficient than converting your value to an int once then using % to check for mod.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T17:41:33.487",
"Id": "8752",
"ParentId": "8667",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T18:41:14.527",
"Id": "8667",
"Score": "18",
"Tags": [
"c++",
"primes"
],
"Title": "Is this C++ naive primality test done right?"
}
|
8667
|
<p>I've got a simple thing that I inherited from another developer and think it could be replaced with something a bit more elegant. What this is doing is comparing the length of a string to a set value, and setting the font size accordingly:</p>
<pre><code>if(maxLen<50){$('.fc-cards').css('font-size',40);}
if(maxLen<100){$('.fc-cards').css('font-size',25);}
if(maxLen<150){$('.fc-cards').css('font-size',22);}
if(maxLen<200){$('.fc-cards').css('font-size',20);}
</code></pre>
<p>If the min font size is 18, and the max 40, what a nice way to dynamically figure a font size with a range of <50 chars being 40px to >200 being 18px... it doesn't have to match the exact values mentioned above, a sliding scale would be perfect.</p>
|
[] |
[
{
"body": "<p>So, a linear mapping from 50-200 onto 40-20 is (40-20)/(200-50) = 0.1333 font size points per length. So we can can compute this as</p>\n\n<pre><code>$('.fc-cards').css('font-size', 20 + 0.1333 * (200 - maxLen));\n</code></pre>\n\n<p>for a sliding linear falloff in font size. If you want to clamp the sizes to change in exactly the same way, you could index them into an array of sizes, computed by the modulus of the length, i.e. something like...</p>\n\n<pre><code> $('.fc-cards').css('font-size', [40, 25, 22, 20][Math.floor(maxLen / 50)]);\n</code></pre>\n\n<p>But you'll need suitable checks on the length to ensure you remain in bounds.</p>\n\n<p>These solutions are debatably more elegant though. They take less code, but they're not as easy to read as definitely solving the same problem your original <code>if</code> tests did. I'd probably prefer a loop over a dictionary of range/size possibilities as the best solution:</p>\n\n<pre><code>sizes = [50, 100, 150, 200];\nfonts = [40, 25, 22, 20];\n\nfor (var i = 0; i < sizes.length; i++)\n{\n if (maxLen < sizes[i])\n {\n $('.fc-cards').css('font-size', fonts[i]);\n break;\n }\n}\n</code></pre>\n\n<p>Edit: Changed based on comment that for/in doesn't ensure enumeration order.</p>\n\n<p>I wouldn't rage against the original solution in a code review, either. Elegance is found in the clearest expression of the goal, in tension with the solution efficiency and maintainability (where, in my view, clear expression wins 99/100 times). Efficiency is not a worry here, and adding/removing sizes from the range in the original code is trivial. Hence, pick whatever your team finds easiest to read a solving the \"Change the font size based on length in these windows\" problem is.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T15:00:33.583",
"Id": "13562",
"Score": "0",
"body": "this is a nice one!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T15:01:24.790",
"Id": "13563",
"Score": "0",
"body": "Faster than me, i need those reputation points ;) Good job Adam"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T15:08:04.343",
"Id": "13564",
"Score": "2",
"body": "Your last solution probably shouldn't use `for-in` since the order of the enumeration isn't guaranteed. You'd need an Array to guarantee that `50` is tested first."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T15:09:05.830",
"Id": "13565",
"Score": "1",
"body": "@amnotiam Fair point"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T17:04:17.970",
"Id": "13566",
"Score": "0",
"body": "nice, on all points, especially the 'keep it readable' bit. I forget that sometimes..."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T14:58:17.407",
"Id": "8680",
"ParentId": "8679",
"Score": "7"
}
},
{
"body": "<p>I think this is called <a href=\"http://en.wikipedia.org/wiki/Proportionality_%28mathematics%29\" rel=\"nofollow\">proportion</a>. Given</p>\n\n<pre><code>minValue = 0\nmaxValue = 200\n\nminFont = 18\nmaxFont = 40\n</code></pre>\n\n<p>then</p>\n\n<pre><code>fontSize = minFont + ((value - minValue) / (maxValue - minValue)) * (maxFont - minFont)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T15:07:58.557",
"Id": "8681",
"ParentId": "8679",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "8680",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-03T14:53:35.127",
"Id": "8679",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "Algorithm to replace this duplicated code"
}
|
8679
|
<p>Any suggestions on better way to remove the last word from a string?</p>
<pre><code>$words = str_word_count($text, 1);
$lastWord = array_pop($words);
$textWithoutLastWord = implode(" ", $words);
</code></pre>
<p>or </p>
<pre><code>$lastSpacePosition = strrpos($text," ");
$textWithoutLastWord =substr($text,0,$lastSpacePosition);
</code></pre>
|
[] |
[
{
"body": "<p>Regular expressions are your friend, this should find the last word and remove it while keeping the final punctuation. This may not work with multiline strings, you'll have to fiddle with the regular expression.</p>\n\n<pre><code>$textWithoutLastWord = preg_replace('/\\W\\w+\\s*(\\W*)$/', '$1', $words);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-13T13:42:44.453",
"Id": "234315",
"Score": "0",
"body": "Regular expressions are a powerful and complex tool, that should be used when nothing else will do the job. This site is CodeReview. Imagine you're reviewing this code. Is it correct? Is what it does it obvious? Are there any hidden 'gotchas' or edge cases? Who can tell?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T15:10:05.450",
"Id": "8810",
"ParentId": "8683",
"Score": "3"
}
},
{
"body": "<p>My personal preference would be the second option:</p>\n\n<pre><code>$lastSpacePosition = strrpos($text, ' ');\n$textWithoutLastWord = substr($text, 0, $lastSpacePosition);\n</code></pre>\n\n<ol>\n<li>It's more obvious what's happening. The fact that str_word_count returns an array because you feed it a 1, is not obvious.</li>\n<li>The code is shorter, in this case I feel that makes it easier to read, rather than obfuscated.</li>\n<li>It is by far the fastest. In my text of 110 words copied from a wikipedia article, with 1e6 iterations\n<ol>\n<li>str_word_count version took 17.952 milliseconds.</li>\n<li>strrpos took 0.597 milliseconds.</li>\n<li>preg_replace (By Oscar M) took 71.189 milliseconds.</li>\n</ol></li>\n<li>In my test text the are letters outside of a-z. The str_word_count solution breaks these letters as if spaces. Whether this is, or is not, the intended behaviour of the function, I would stay away from such behaviour.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-17T16:25:35.350",
"Id": "14264",
"Score": "0",
"body": "The only downside that I could find with this is that it doesn't work properly with multi line strings."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-16T21:37:58.857",
"Id": "9064",
"ParentId": "8683",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "8810",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T14:43:17.643",
"Id": "8683",
"Score": "2",
"Tags": [
"php",
"strings"
],
"Title": "Remove last word from string"
}
|
8683
|
<p>I'm trying to make my function more versatile by removing hard coded data.</p>
<pre><code>function get_currency_rate($currencySource) {
if (isset($currencySource)) {
$feed = $currencySource;
} else {
echo 'Feed not found. Check URL';
}
if (!$feed) {
echo('Feed not found');
}
$xml = new SimpleXmlElement($feed);
$rate = get_rate($xml, 15); //EUR
if ($feed == 'http://themoneyconverter.com/rss-feed/USD/rss.xml') {
$rate = get_rate($xml, 16); //GBP
} else {
$rate = get_rate($xml, 56); //USD
}
}
</code></pre>
<p>I would prefer to pass in the values <code>15</code>, <code>16</code>, <code>56</code> and the URL <code>'http://themoneyconverter.com/rss-feed/USD/rss.xml'</code> rather than hard coding them into the function. </p>
<p>Below is the <code>get_rate</code> function. </p>
<pre><code>// Get and return currency rate
// Perform regular exp<b></b>ression to extrat numeric data
// Split title string to extract currency title
function get_rate(SimpleXMLElement $xml, $xmlTagPosition) {
$currency['rate'] = $xml->channel->item[$xmlTagPosition]->description;
preg_match('/([0-9]+\.[0-9]+)/', $currency['rate'], $matches);
$rate = $matches[0];
$title['rate'] = $xml->channel->item[$xmlTagPosition]->title;
$title = explode('/', $title['rate']);
$title = $title[0];
echo $rate . ' ' . $title . '<br />';
}
</code></pre>
<p>The feed URLs are set in my <code>cityConfig.php</code> script as below: </p>
<pre><code>// Feed URLs //
$theMoneyConverter = 'http://themoneyconverter.com/rss-feed/';
// Define arrays //
$cities = array('London', 'New York', 'Paris');
$currencyHeadings = array('London - 1 British Pound Sterling', 'New York - 1 US Dollar', 'Paris - 1 Euro');
$currencySource = array($theMoneyConverter . 'GBP/rss.xml', $theMoneyConverter . 'USD/rss.xml', $theMoneyConverter . 'EUR/rss.xml');
$currencyId = array(15, 16, 56);
?>
</code></pre>
<p>Notice the <code>$currencyId</code> array values are the same as those hard coded into the <code>get_currency_rate</code> function. I tried passing in a second parameter for the <code>$currencyId</code> to no avail. Any ideas where I'm going wrong? </p>
<p>I have tried the following:</p>
<p>Added an argument onto the end of the feed URL's e.g. </p>
<pre><code>?x=15 // for EURO feed
?x=16 // for GBP feed
?x=56 // for USD feed
</code></pre>
<p>These numbers correspond to the position of the XML tag as an array from the feed URL's. </p>
<pre><code>$currencySource = array($theMoneyConverter . 'GBP/rss.xml?x=15', $theMoneyConverter . 'USD/rss.xml?x=16', $theMoneyConverter . 'EUR/rss.xml?x=56');
</code></pre>
<p>I have edited the get_rate function to parse in the URL and the PHP query. </p>
<pre><code>// Get and return currency rate
// Perform regular expression to extrat numeric data
// Split title string to extract currency title
function get_rate(SimpleXMLElement $xml) {
$vars = parse_url($xml, PHP_URL_QUERY);
parse_str($vars);
echo "x = " . $x;
//$x = 15;
$currency['rate'] = $xml->channel->item[$x]->description;
preg_match('/([0-9]+\.[0-9]+)/', $currency['rate'], $matches);
$rate = $matches[0];
$title['rate'] = $xml->channel->item[$x]->title;
$title = explode('/', $title['rate']);
$title = $title[0];
echo $rate . ' ' . $title . '<br />';
}
</code></pre>
|
[] |
[
{
"body": "<p>Well the first thing I notice is that your <code>get_currency_rate()</code> function requires a <code>$currencySource</code> to be added as a parameter. Which makes the first if statement a little redundant. The other thing is that <code>get_currency_rate()</code> is setting the variable <code>$rate</code> from <code>get_rate()</code>, but <code>get_rate()</code> doen't return anything.</p>\n\n<p>I think you should ommit the <code>get_currency_rate()</code> function and change <code>get_rate()</code> to handle the XML feed request and return the information you want rather than using two separate functions.</p>\n\n<p>It would look like this.</p>\n\n<pre><code>function get_rate($feed_url, $xmlTagPosition) {\n $xml = new SimpleXmlElement($feed_url);\n $xml_item = $xml->channel->item[$xmlTagPosition];\n\n // make sure the $xmlTagPosition was valid\n if( empty($xml_item) )\n return false;\n\n $currency['rate'] = $xml_item->description;\n preg_match('/([0-9]+\\.[0-9]+)/', $currency['rate'], $matches);\n $rate = $matches[0];\n\n $title['rate'] = $xml_item->title;\n $title = explode('/', $title['rate']);\n $title = $title[0];\n\n return $rate . ' ' . $title;\n}\n</code></pre>\n\n<p>And now your <code>cityConfig.php</code> file can work more like this.</p>\n\n<pre><code>$theMoneyConverter = 'http://themoneyconverter.com/rss-feed/USD/rss.xml';\n\n$cities = array(\n 'London' => array(\n 'title' => '1 British Pound Sterling',\n 'currency_id' => 15\n ),\n 'New York' => array(\n 'title' => '1 US Dollar',\n 'currency_id' => 16\n ),\n 'Paris' => array(\n 'title' => '1 Euro',\n 'currency_id' => 56\n )\n);\n\n// now you can easily find and loop through each of your cities\nforeach( $cities as $city => $info ) {\n echo '<p>';\n echo \"$city - {$info['title']}\";\n echo get_rate($theMoneyConverter, $info['currency_id']);\n echo '</p>';\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T20:09:38.293",
"Id": "13747",
"Score": "1",
"body": "You might want to look into using a direct API for currency conversion (http://www.dynamicguru.com/php/currency-conversion-using-php-and-google-calculator-api/) That way you don't have to worry about the xml tag position changing."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T19:52:34.087",
"Id": "8785",
"ParentId": "8684",
"Score": "1"
}
},
{
"body": "<p>I would start by introducing a few variables, and a sub to set them.</p>\n\n<pre><code>function set_values(&$initial, &$matched, &$unmatched, &$matchFeed){\n $initial =15; //eur\n $matched=16; //GBP\n $unmatched=56; //USD\n $matchFeed = \"http://themoneyconverter.com/rss-feed/USD/rss.xml\";\n\n}\n\nfunction get_currency_rate($currencySource) {\n if (isset($currencySource)) {\n $feed = $currencySource;\n } else {\n echo 'Feed not found. Check URL';\n }\n\n if (!$feed) {\n echo('Feed not found');\n }\n\n $xml = new SimpleXmlElement($feed);\n\n set_values($initital, $matched, $unmatched, $matchFeed);\n\n $rate = get_rate($xml, $initial);\n if ($feed == $matchFeed) {\n $rate = get_rate($xml, $matched);\n } else {\n $rate = get_rate($xml, $unmatched);\n }\n}\n</code></pre>\n\n<p>Now you are ready to get the values from wherever you want to, without changing the primary function.</p>\n\n<p>Once that is done, you might want to take a look at the config.php file.</p>\n\n<pre><code>$currencyIds= array(15, 16, 56); \n$currencySource = array($theMoneyConverter . 'GBP/rss.xml', $theMoneyConverter . 'USD/rss.xml', $theMoneyConverter . 'EUR/rss.xml', $currencyIds );\n</code></pre>\n\n<p>Creates an array wih 3 strings and one array of three integers(four total). Depending upon your usage, that might be what you want.</p>\n\n<p>?></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-12T06:13:31.803",
"Id": "9907",
"ParentId": "8684",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T17:05:35.377",
"Id": "8684",
"Score": "3",
"Tags": [
"php",
"xml",
"url",
"configuration",
"rss"
],
"Title": "Configuring a currency converter to get exchange rate feeds for for multiple currencies"
}
|
8684
|
<p>It's often useful to strip carriage returns out of a plain text document, for example when copying and pasting into a field that automatically wraps lines. However, it's usually a good idea to leave some of the carriage returns in — most obviously at paragraph breaks, but also around bullet lists, section headings, etc. So one needs an algorithm to decide <em>which</em> carriage returns to retain.</p>
<p>In my <a href="http://gcbenison.wordpress.com/2011/07/03/a-program-to-intelligently-remove-carriage-returns-so-you-can-paste-text-without-having-it-look-awful/" rel="nofollow noreferrer">attempt to address this problem</a>, I came up with the following:</p>
<pre><code>shouldMerge::[Char]->[Char]->Bool
shouldMerge "" _ = False
shouldMerge _ "" = False
shouldMerge _ nextline | (not . isAlphaNum . head) nextline = False
shouldMerge line nextline | length (line ++ " " ++ (head . words) nextline) <
length nextline = False
shouldMerge _ _ = True
</code></pre>
<p>where <code>shouldMerge</code> is a function that attempts to guess whether a line should be merged with its successor. The rules state, roughly, 1) never merge blank lines; 2) don't merge with a line beginning with a non-alphanumeric character; and 3) if placing the first word on the next line at the end of the current line would result in a line shorter than the next line, don't merge, as the current line was probably cut short intentionally (catches things like section headings.) This set of rules "seems to work" :) much of the time.</p>
<p>My question is: how would you improve on this algorithm (perhaps by considering more than one line of text at a time?)</p>
|
[] |
[
{
"body": "<p>Two things:</p>\n\n<ol>\n<li>Try using <code>String</code> instead of <code>[Char]</code>, it reads a lot easier (imho).</li>\n<li>Don't use <code>head</code>, use pattern matching instead. It reads better, and it's good practice, because if it passes an empty list you will get an error (though you will not encounter that in this program, since you already check for empty lists).</li>\n</ol>\n\n<p>If you wanted to have your program consider multiple lines, a quick and dirty solution would be something like this:</p>\n\n<pre><code>function :: [String] -> [Bool]\nfunction [] = []\nfunction [line1,line2] = [(shouldMerge line1 line2)]\nfunction (line1:line2:morelines) = [(shouldMerge line1 line2)] ++ function (line2:morelines)\n</code></pre>\n\n<p>NOTE: I haven't tested the above code for bugs.</p>\n\n<p>Another solution would be to make shouldMerge recursive, with a type of <code>[String] -> [Bool]</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-18T14:56:05.613",
"Id": "19064",
"Score": "0",
"body": "From what I can tell, `function` lets you apply `shouldMerge` to a whole file, but still the decision to merge two lines is based only on those two lines, not any broader context. From experience this works most of the time, but sometimes fails (e.g. leaving a line break in the middle of a paragraph.) I thought perhaps adding in information from more neighboring lines could help, but I'm not sure how to go about it. Thanks for the input!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-18T18:58:39.693",
"Id": "19090",
"Score": "0",
"body": "@gcbenison I'm sorry, I misinterpreted what you meant by \"multiple lines\". Could you give me some more examples of when this function would need to consider multiple lines, and what this function should output when it encounters those solutions?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-18T00:10:18.950",
"Id": "11852",
"ParentId": "8687",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-02-05T18:42:58.530",
"Id": "8687",
"Score": "3",
"Tags": [
"algorithm",
"strings",
"haskell"
],
"Title": "\"Intelligent\" removal of carriage returns that preserves paragraph breaks, headings, etc"
}
|
8687
|
<p><a href="http://www.r-project.org" rel="nofollow noreferrer" title="R project homepage">R is an open source programming language and software environment</a> for statistical computing and graphics. It is an implementation of the <a href="http://lib.stat.cmu.edu/S/Spoetry/Tutor/slanguage.html" rel="nofollow noreferrer">S programming language</a> combined with lexical scoping semantics inspired by <a href="https://stackoverflow.com/tags/scheme/info" title="Scheme on StackOverflow">Scheme</a>. R was created by <a href="http://www.stat.auckland.ac.nz/~ihaka/" rel="nofollow noreferrer">Ross Ihaka</a> and <a href="http://gentleman.fhcrc.org/" rel="nofollow noreferrer">Robert Gentleman</a> and is now developed by the <a href="http://www.r-project.org/contributors.html" rel="nofollow noreferrer">R Development Core Team</a>. It is easily extended through a packaging system on <a href="http://cran.r-project.org" rel="nofollow noreferrer" title="CRAN The Comprehensive R Archive Network">CRAN</a>. </p>
<p>Resources:</p>
<ul>
<li><a href="http://www.r-project.org" rel="nofollow noreferrer" title="R project homepage">R homepage</a></li>
<li><a href="https://chat.stackoverflow.com/rooms/106/r">R tag chat</a> on Stack Overflow</li>
<li><a href="https://stackoverflow.com/q/5963269/602276">How to make a great R reproducible example</a></li>
<li>The tag for questions that are considered frequent <a href="/questions/tagged/r-faq" class="post-tag" title="show questions tagged 'r-faq'" rel="tag">r-faq</a></li>
</ul>
<p>Frequently asked questions:</p>
<p><a href="http://cran.r-project.org/doc/FAQ/R-FAQ.html" rel="nofollow noreferrer">R FAQ</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T05:56:36.363",
"Id": "8689",
"Score": "0",
"Tags": null,
"Title": null
}
|
8689
|
R is a free, open source programming language and software environment for statistical computing and graphics.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T05:56:36.363",
"Id": "8690",
"Score": "0",
"Tags": null,
"Title": null
}
|
8690
|
<p>I have an <code>NSArray</code> called <code>program</code> and I need to scan it and then produce an <code>NSSet</code> of objects that fit the test <code>isOperation:</code>. If none are found I should return <code>nil</code>. I wrote the following code. How would you make this better? (FYI - the fact the program is of type (id) comes directly from the assignment so I can't change that one thing)</p>
<p>Revised code:</p>
<pre><code>+ (NSSet *) variablesUsedInProgram:(id)program {
NSSet *programSet, *variablesUsed;
if([program isKindOfClass:[NSArray class]]) {
programSet = [NSSet setWithArray:program];
variablesUsed = [programSet objectsPassingTest:^BOOL(id term, BOOL *stop) {
return (! ([term isKindOfClass:[NSNumber class]] || [CalculatorBrain isOperation:term]));
}];
}
return ([variablesUsed count] > 0) ? variablesUsed : nil;
}
</code></pre>
|
[] |
[
{
"body": "<p>The only real issue I see is that you're leaking memory. You are allocating a mutable set that you never release and then copying it to presumably make it immutable thus leaking more memory.</p>\n\n<pre><code>+ (NSSet *) variablesUsedInProgram:(id)program {\n NSMutableSet *variablesUsed = [[NSMutableSet alloc] init];\n for (id term in program) {\n if(! ([term isKindOfClass:[NSNumber class]] || \n [self isOperation:term])) {\n /* term is a variable, because it's neither an operation or a number */\n [variablesUsed addObject:(NSString *)term];\n\n }\n }\n NSSet returnSet = nil;\n if (variablesUsed.count > 0) {\n returnSet = [NSSet setWithSetVariableSet];\n }\n [variablesUsed release];\n return returnSet;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T15:26:44.977",
"Id": "8701",
"ParentId": "8691",
"Score": "0"
}
},
{
"body": "<p>There is no need to return a copy of the variablesUsed set. It's actually wrong to do so, because naming conventions for your method imply an autoreleased object to be returned. Thus I would rewrite your return as:</p>\n\n<pre><code>return [variablesUsed autorelease];\n// or in case of ARC just\nreturn variablesUsed;\n</code></pre>\n\n<p>See the <a href=\"https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html\" rel=\"nofollow\">Advanced memory management programming guide</a></p>\n\n<p>Also set contains a useful method to filter using a block. In my opinion this results in slightly nicer code. You can convert your incoming array to a <code>NSSet</code> using <code>+ setWithArray:</code>. </p>\n\n<p>The if statement to return nil can be combined in your return.</p>\n\n<p>Combining this results in the following implementation</p>\n\n<pre><code>+ (NSSet *) variablesUsedInProgram:(id)program {\n NSSet *programSet = [NSSet setWithArray:program];\n NSSet *variablesUsed = [NSSet objectsPassingTest:^(id object, BOOL *stop) {\n return !([object isKindOfClass:[NSNumber class]] || [self isOperation:term])\n }];\n return ([variablesUsed count] > 0) ? variablesUsed : nil;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T09:20:48.417",
"Id": "13662",
"Score": "0",
"body": "Thank you - this is a very nice solution. By the way, I have two questions:"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T09:21:25.420",
"Id": "13663",
"Score": "0",
"body": "1. What is \"BOOL *stop\" used for? and"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T09:22:07.043",
"Id": "13664",
"Score": "0",
"body": "2. Why is it wrong to return a copy of variablesUsed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T09:23:17.307",
"Id": "13665",
"Score": "0",
"body": "Incidentally, I am using ARC - should I be calling release in any situation? I was under the impression that it is reserved for the compiler under ARC."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T10:17:59.850",
"Id": "13666",
"Score": "0",
"body": "1. \"The block can set the value to YES to stop further processing of the set.\" - see [the NSSet documentation](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSSet_Class/Reference/Reference.html). Not needed in your case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T10:21:57.707",
"Id": "13667",
"Score": "0",
"body": "2. You can still return a copy if you really want to, but the naming convention dictates an autoreleased object. A copy is actually owned. ARC will actually add an autorelease to your statement: [[variablesUsed copy] autorelease] to make up for the ownership. Even when you are using ARC, it's good to take the naming conventions into account, because ARC uses them too. See the documents I linked in the answer for more on those conventions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T10:22:50.450",
"Id": "13668",
"Score": "0",
"body": "No need to call release yourself when using ARC, just understand what's going and what ARC is actually doing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T01:52:53.280",
"Id": "13763",
"Score": "0",
"body": "In the end, I had some difficulty implementing this solution - can you think of a way to cast the terms as NSString* before adding them to the set I return?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T08:10:47.500",
"Id": "13781",
"Score": "0",
"body": "There's no need to. The `(NSString *)` cast in your original example code has no meaning, it would even work when the actual object was of a different type. A set accepts an `id` type, so it doesn't matter what object is added."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T04:43:02.893",
"Id": "13901",
"Score": "0",
"body": "Your right - I made a mistake in typing my test condition. It works now. Thank you! I'm still curious, however - do you know of a way to do a transformation (using built-in functions like objectsPassingTest etc.) as a last step before adding the object to the set as vikingosegundo's List Comprehensions-based solution below lets you do?"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T15:29:41.257",
"Id": "8702",
"ParentId": "8691",
"Score": "2"
}
},
{
"body": "<p>I want to propose something similar to the answer Joris gave.</p>\n\n<p>Inspired by <a href=\"http://en.wikipedia.org/wiki/List_comprehension\" rel=\"nofollow\">List Comprehensions</a></p>\n\n<pre><code>python: l = [i**2 for i in l if i%2] #filtes a list for all even numbers and squares them\n</code></pre>\n\n<p>I wrote a number of category methods on NSArray to be able to do something similar using Blocks.</p>\n\n<p>here one that fits to your needs:</p>\n\n<p><em>interface</em></p>\n\n<pre><code>#import <Foundation/Foundation.h>\n\n@interface NSArray (FunctionalTools)\n\n-(NSSet *)setByPerformingBlock:(id (^)(id element))performBlock\n ifElementPassesTest:(BOOL (^)(id element))testBlock;\n\n@end\n</code></pre>\n\n<p><em>implementation</em></p>\n\n<pre><code>@implementation NSArray (FunctionalTools)\n\n-(NSSet *)setByPerformingBlock:(id (^)(id))performBlock \n ifElementPassesTest:(BOOL (^)(id))testBlock\n{\n NSMutableSet *set = [NSMutableSet setWithArray:self];\n NSMutableSet *newSet = [NSMutableSet set];\n for (id element in set){\n if (testBlock(element)) {\n [newSet addObject:performBlock(element)];\n }\n }\n if ([newSet count]<1)\n return nil;\n return [NSSet setWithSet:newSet];\n}\n@end\n</code></pre>\n\n<p><em>usage</em></p>\n\n<pre><code>+ (NSSet *) variablesUsedInProgram:(id)program {\n return [program setByPerformingBlock:^id(id term) {\n return term;\n } ifElementPassesTest:^BOOL(id term) {\n return !([term isKindOfClass:[NSNumber class]] || [self isOperation:term]);\n }];\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T12:03:25.017",
"Id": "13669",
"Score": "0",
"body": "Cool! :) I like this technique... any downsides?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T13:43:24.417",
"Id": "13681",
"Score": "0",
"body": "I don't like `return [NSSet setWithSet:newSet];`, but I think, it is better, to not surprise the programmer by returning a mutable set."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T19:00:11.900",
"Id": "13805",
"Score": "0",
"body": "In the implementation why are you creating an NSMutableSet out of the array (self) just to turn it back into an array in the for statement?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T19:52:27.537",
"Id": "13809",
"Score": "0",
"body": "I am creating a set to avoid that possibly expensive blocks are executed more often than needed. `[set allObjects]`was a copy and past error."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T02:31:03.440",
"Id": "17855",
"Score": "0",
"body": "I disagree that it's at all important to care whether your set is mutable or not. Your return type is `NSSet*`, so if the programmer even finds out that your set is mutable, they already messed up bigtime."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T17:25:34.157",
"Id": "8709",
"ParentId": "8691",
"Score": "2"
}
},
{
"body": "<p>In your newer version, if <code>program</code> is not an NSArray then <code>variablesUsed</code> is uninitialized. Set it to nil where you declare it.</p>\n\n<p>Remember to always check failure paths in conditional statements.</p>\n\n<p>Also you should start using Xcode's <em>Build and Analyze</em> option to get the LLVM compiler to point out these kinds of errors. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T19:10:13.777",
"Id": "8825",
"ParentId": "8691",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "8702",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T06:26:56.213",
"Id": "8691",
"Score": "1",
"Tags": [
"objective-c"
],
"Title": "Scanning an NSArray to produce an NSSet"
}
|
8691
|
<p>This function takes an array of strings and numbers and recursively processes it as a kind of "calculating program". The structure is based on Reverse Polish Notation, so the top object in the stack (last in the array) determines what to do with the next one (or two) items in the program. For example, if the array was [1, 2, "+"], the solution would be 3. </p>
<ul>
<li><p>In the case of errors, it should return an <code>NSString</code> describing the
error that happened. </p></li>
<li><p>If more than one error occurs in processing, it is not clear which
error should receive priority, so I've chosen to prioritize the first
error found and ignore any further errors.</p></li>
</ul>
<p>I think that this code could be made much more simple, but I'm not sure how best to do that in Objective C. What suggestions do you have to improve this code?</p>
<pre><code> + (id)popOperandOffProgramStack:(NSMutableArray *)stack
{
id result;
double dResult;
id topOfStack = [stack lastObject];
if (topOfStack) [stack removeLastObject];
if ([topOfStack isKindOfClass:[NSNumber class]])
{
result = topOfStack;
}
else if ([topOfStack isKindOfClass:[NSString class]])
{
id rightSide = [self popOperandOffProgramStack:stack];
if (![rightSide isKindOfClass:[NSNumber class]]) {
return rightSide;
}
double r = [(NSNumber *)rightSide doubleValue];
NSString *operation = topOfStack;
if ([[self class] isBinaryOperation:operation]) {
id leftSide = [self popOperandOffProgramStack:stack];
if (![leftSide isKindOfClass:[NSNumber class]]) {
return leftSide;
}
double l = [(NSNumber *)leftSide doubleValue];
if([operation isEqualToString:@"+"]) {
dResult = l + r;
} else if([operation isEqualToString:@"-"]) {
dResult = l - r;
} else if([operation isEqualToString:@"*"]) {
dResult = l * r;
} else if([operation isEqualToString:@"/"]) {
if(r == 0.0) {
return @"Error: Tried to divide by zero";
} else {
dResult = l / r;
}
}
} else if ([operation isEqualToString:@"+/-"]) {
dResult = -r;
} else if([operation isEqualToString:@"sin"]) {
dResult = sin(r);
} else if([operation isEqualToString:@"cos"]) {
dResult = cos(r);
} else if([operation isEqualToString:@"sqrt"]) {
if(r < 0) {
return @"Error: tried to sqrt a negative number";
}
dResult = sqrt(r);
} else if([operation isEqualToString:@"π"]) {
dResult = 3.141592654;
} else {
/* unknown operations and unset variables will return 0 */
dResult = 0.0;
}
result = [NSNumber numberWithDouble:dResult];
}
return result;
}
</code></pre>
|
[] |
[
{
"body": "<p>Instead of returning an error-String, I would pass in a nil'ed-NSError object by reference, and write an error to it, in case it occurred. the returned object would be nil</p>\n\n<pre><code>+ (NSNumber *)popOperandOffProgramStack:(NSMutableArray *)stack error:(NSError **)error\n{\n //…\n error = [[NSError alloc] int…] ;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>NSError *error = nil;\nif ([Calculator popOperandOffProgramStack:parameters error:&error])\n{\n //returned object not nil -> success\n} else {\n //nil-object -> let's check the error \n}\n</code></pre>\n\n<p>this avoids type checking.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T09:28:47.900",
"Id": "17400",
"Score": "0",
"body": "There are two minor problems in the first method: First you need to assign to `*error` not `error` (remember you passed a pointer to an error ref), second, you should wrap the assignment in `if (error != nil) { ... }` so that people who are not interested in the error text can pass nil in."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T09:46:41.380",
"Id": "8800",
"ParentId": "8693",
"Score": "2"
}
},
{
"body": "<p>At the risk of exposing my C++ (lots of little objects) roots...</p>\n\n<p>I think this code shows signs of having complexity cornered into it for the sake of simplicity in the code that feeds it. In particular, there was likely some kind of parser that tokenized the input into the stack of <code>NSNumber</code> or <code>NSString</code>. Producing a stack and two operand types puts this code a couple steps up from a purely <a href=\"https://stackoverflow.com/a/2444303\">stringly typed</a> interface. But it could go further. Each element of the stack could have been created as an instance of an <code>Operand</code> base class, or actually an <code>Operand</code> sub-class like <code>NumberOperand</code>, <code>SumOperand</code>, <code>ProductOperand</code>, <code>SinOperand</code>, etc. where each class specializes a simple <code>popResult</code> method that gets called by <code>popOperandOffProgramStack</code> to deal with popping its operand(s if any), checking its error cases, and calculating its result. It's probably not that much extra work for the parser, assuming that each operand had to be validated against all the possible forms, anyway. You'd just have to use what you discovered during the successful validation to construct an operand of the right type -- or, for each function operand, possibly just reference a singleton object -- they're stateless, so different instances aren't very useful. With <code>Operand</code> objects, you don't lose the details, so <code>popOperandOffProgramStack</code> doesn't have to reconstruct them with all this matching.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T23:26:30.437",
"Id": "8832",
"ParentId": "8693",
"Score": "0"
}
},
{
"body": "<p>You are <strong>confusing the RPN expression</strong> (the stream of numbers and commands) <strong>with the stack</strong> that the RPN calculator operates on.</p>\n\n<p>The way an RPN calculator normally works is, it starts with an empty stack. When it encounters a number, it pushes it onto the stack. When it encounters an operation, the operation pops the necessary number of operands from the stack and pushes the result onto the stack. The stack only contains numbers — never operators.</p>\n\n<p>Therefore, your RPN calculator should either create a stack, or take an (empty) stack as a parameter. I've chosen the latter option for greater flexibility.</p>\n\n<p>There are some other improvements you could make. One is to write all of the operators as blocks in a dictionary, and do dynamic <strong>dispatching</strong> by looking up the operator by name. That is more elegant than a long chain of else-ifs.</p>\n\n<p>Also, contrary to common belief, <strong>division by zero is not an error</strong> in IEEE 754 <a href=\"/questions/tagged/floating-point\" class=\"post-tag\" title=\"show questions tagged 'floating-point'\" rel=\"tag\">floating-point</a> — it results in infinity (or negative infinity, if dividing by negative zero). Therefore, you would get better functionality by removing the check for division by zero.</p>\n\n<p>Finally, <strong>creating a result of 0.0 when faced with invalid input is reckless.</strong> The user will see a seemingly successful computation that is not what was intended. When encountering invalid input, the function <em>must</em> indicate an error. A good way to do that is to throw an exception.</p>\n\n<hr>\n\n<h3>Suggested implementation</h3>\n\n<p><strong>RPNCalc.h</strong></p>\n\n<pre><code>#import <Foundation/Foundation.h>\n\n@interface RPNCalc : NSObject\n+ (void) rpnCalc:(NSArray *)program stack:(NSMutableArray *)stack;\n@end\n</code></pre>\n\n<p><strong>RPNCalc.m</strong></p>\n\n<pre><code>#import \"RPNCalc.h\"\n\n#include <math.h>\n\nstatic NSDictionary *constants;\nstatic NSDictionary *unaryOperations;\nstatic NSDictionary *binaryOperations;\nstatic Boolean initialized = FALSE;\n\n@implementation RPNCalc\n+ (void) initialize\n{\n constants = [NSDictionary dictionaryWithObjectsAndKeys:\n [NSNumber numberWithDouble:acos(-1)], @\"π\",\n //[NSNumber numberWithDouble:exp(1)], @\"e\",\n nil\n ];\n unaryOperations = [NSDictionary dictionaryWithObjectsAndKeys:\n ^double (double a) { return -a; }, @\"+/-\",\n ^double (double a) { return sin(a); }, @\"sin\",\n ^double (double a) { return cos(a); }, @\"cos\",\n ^double (double a) { return sqrt(a); }, @\"sqrt\",\n nil\n ];\n binaryOperations = [NSDictionary dictionaryWithObjectsAndKeys:\n ^double (double a, double b) { return a + b; }, @\"+\",\n ^double (double a, double b) { return a - b; }, @\"-\",\n ^double (double a, double b) { return a * b; }, @\"*\",\n ^double (double a, double b) { return a / b; }, @\"/\",\n nil\n ];\n initialized = TRUE;\n}\n\n+ (void) rpnCalc:(NSArray *)program stack:(NSMutableArray *)stack\n{\n if (!initialized) {\n [RPNCalc initialize];\n }\n\n NSEnumerator *prog = [program objectEnumerator];\n id op;\n while (op = [prog nextObject]) {\n if ([op isKindOfClass:[NSNumber class]]) {\n [stack addObject:op];\n } else if ([op isKindOfClass:[NSString class]]) {\n id expr;\n if ((expr = [constants objectForKey:op])) {\n [stack addObject:expr];\n\n } else if ((expr = [unaryOperations objectForKey:op])) {\n double (^unaryOperation)(double) = expr;\n double top1 = [[stack lastObject] doubleValue];\n [stack removeLastObject];\n double result = unaryOperation(top1);\n [stack addObject:[NSNumber numberWithDouble:result]];\n\n } else if ((expr = [binaryOperations objectForKey:op])) {\n double (^binaryOperation)(double, double) = expr;\n double top1 = [[stack lastObject] doubleValue];\n [stack removeLastObject];\n double top2 = [[stack lastObject] doubleValue];\n [stack removeLastObject];\n double result = binaryOperation(top2, top1);\n [stack addObject:[NSNumber numberWithDouble:result]];\n\n } else {\n NSException *e = [NSException exceptionWithName:@\"RPNException\"\n reason:@\"Unrecognized string\"\n userInfo:nil];\n @throw e;\n }\n } else {\n NSException *e = [NSException exceptionWithName:@\"RPNException\"\n reason:@\"Encountered a value that is neither a number nor a string\"\n userInfo:nil];\n @throw e;\n }\n }\n}\n@end\n</code></pre>\n\n<p><strong>main.m</strong></p>\n\n<pre><code>int main(int argc, const char * argv[])\n{\n\n @autoreleasepool {\n @try {\n NSMutableArray *prog = [NSMutableArray arrayWithCapacity:(argc - 1)];\n for (int i = 1; i < argc; i++) {\n char *end;\n double d = strtod(argv[i], &end);\n if (*end == '\\0') {\n [prog addObject:[NSNumber numberWithDouble:d]];\n } else {\n [prog addObject:[[NSString alloc] initWithCString:argv[i] encoding:NSUTF8StringEncoding]];\n }\n\n }\n NSMutableArray *stack = [[NSMutableArray alloc] init];\n [RPNCalc rpnCalc:prog stack:stack];\n\n NSNumber *result;\n NSEnumerator *results = [stack reverseObjectEnumerator];\n while ((result = (NSNumber *)[results nextObject])) {\n printf(\"%f\\n\", [result doubleValue]);\n }\n } @catch (NSException *e) {\n NSLog(@\"%@\\n\", e);\n }\n }\n return 0;\n}\n</code></pre>\n\n<hr>\n\n<h3>Example usage</h3>\n\n<blockquote>\n<pre><code>$ ./cr8693 π 2 / sin 1 2 / +\n1.500000\n$ ./cr8693 1 -0 /\n-inf\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-25T08:41:19.013",
"Id": "45288",
"ParentId": "8693",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "8800",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T06:44:30.980",
"Id": "8693",
"Score": "3",
"Tags": [
"recursion",
"objective-c",
"math-expression-eval"
],
"Title": "RPN-Stack-Based Recursive Calculator Needs Tuneup"
}
|
8693
|
<p>This is a method which takes an input of a "page" object, which includes SortOrder. It then fetches the existing page items from a database and attempts to re-index.</p>
<p>I don't think this is at all efficient and reads horribly and wondered if anybody could make some recommendations?</p>
<pre><code> public Boolean ReIndexOutputTemplatePages(OutputTemplatePage page)
{
try
{
int? requiredIndex = page.SortOrder;
var items = from t1 in db.OutputTemplatePages
where (t1.OutputTemplateId == page.OutputTemplateId)
orderby t1.SortOrder
select t1;
Boolean boolHasBeenAdded = false;
int ctr = 0;
if (items.Count() == 0)
{
Add(page);
boolHasBeenAdded = true;
}
else
{
foreach (OutputTemplatePage template in items)
{
if (requiredIndex == ctr)
{
Add(page);
ctr++;
boolHasBeenAdded = true;
}
OutputTemplateRepository repo = new OutputTemplateRepository();
OutputTemplatePage pg = repo.GetOutputTemplatePageById(template.Id);
pg.SortOrder = ctr;
repo.Save();
ctr++;
}
}
if (!boolHasBeenAdded)
{
Add(page);
}
return true;
}
catch (Exception)
{
return false;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Here's a little bit of how I'd reorganize. The key elements which could affect speed are: creating the repository only once, using the LINQ extension <code>Any</code> which has the possibility of optimizing the SQL generated and early return if there are no entries in the database.</p>\n\n<pre><code> public bool ReIndexOutputTemplatePages(OutputTemplatePage page)\n {\n try\n {\n var items = from t1 in db.OutputTemplatePages\n where t1.OutputTemplateId == page.OutputTemplateId\n orderby t1.SortOrder\n select t1;\n\n if (!items.Any())\n {\n Add(page);\n return true;\n }\n\n var repo = new OutputTemplateRepository();\n var hasBeenAdded = false;\n var ctr = 0;\n\n foreach (var template in items)\n {\n if (page.SortOrder == ctr)\n {\n Add(page);\n hasBeenAdded = true;\n ctr++;\n }\n\n var pg = repo.GetOutputTemplatePageById(template.Id);\n\n pg.SortOrder = ctr;\n ctr++;\n repo.Save();\n }\n\n if (!hasBeenAdded)\n {\n Add(page);\n }\n\n return true;\n }\n catch (Exception)\n {\n return false;\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T15:52:46.143",
"Id": "8703",
"ParentId": "8699",
"Score": "1"
}
},
{
"body": "<p>I have the following comments and recommendations:</p>\n\n<ul>\n<li>The try/catch is too general: if anything goes wrong anywhere, you return false. This may mask errors. Catch more specific exceptions and narrow the scope of your try/catch to where you are okay with things going wrong. (If you don't EXPECT anything to ever go wrong in certain parts of the code, you probably want to \"fail fast\" and catch that exception at a higher level. This could hide lots of kinds of errors during dev/test.)</li>\n<li>Name mismatch: requiredIndex does not match .SortOrder (I'm not saying they need to be same exact name, but these seem to describe different concepts to me)</li>\n<li>Does .SortOrder need to be optional? Consider enforcing that it be set by changing the orginal OutputTemplatePage class to require it. Is it an enum? If so, perhaps the default value could be Default (as in \"use the default sort order\")</li>\n<li>Name choice: <code>Boolean boolHasBeenAdded</code> might be better as <code>Boolean pageHasBeenAdded</code> (prefix notation has been out of vogue for years - since .NET, certainly). Also, I usually prefer language types (<code>bool</code>) to the .NET types, but that's just style/preference.</li>\n<li><p>This block could go away if you invert the next conditional (since this block happens anyway at the end): </p>\n\n<pre><code> if (items.Count() == 0)\n {\n Add(page);\n boolHasBeenAdded = true;\n }\n else\n</code></pre></li>\n</ul>\n\n<p>... to ...</p>\n\n<pre><code> if (items.Count() != 0)\n</code></pre>\n\n<ul>\n<li><p>Consider moving the following code into a well-named helper method to make its intent more apparent:</p>\n\n<pre><code> OutputTemplateRepository repo = new OutputTemplateRepository();\n OutputTemplatePage pg = repo.GetOutputTemplatePageById(template.Id);\n pg.SortOrder = ctr;\n repo.Save();\n</code></pre></li>\n<li><p>It is unclear to me what <code>repo.Save()</code> does - seems like it might have side-effects. All the more reason for prior suggestion.</p></li>\n<li>Rename <code>ctr</code> to something more descriptive. Is it the sort <strong>index</strong>? Of course, setting <code>SortOrder = ctr</code> makes me wonder if <code>SortOrder</code> is named correctly. \"Sort order\" makes me thing of high level approach to sorting - like ascending vs. descending? Not clear. Makes it hard to grok.</li>\n</ul>\n\n<p>[Edit] Actually, this largest problem might be that this code is not in the right class which might be the source of some awkwardness. Consider making <code>ReIndexOutputTemplatePages</code> a method on <code>OutputTemplateRepository</code> to clean up the code leading up to <code>rep.Save</code>.</p>\n\n<p>Hope that helps!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T15:57:57.247",
"Id": "8704",
"ParentId": "8699",
"Score": "2"
}
},
{
"body": "<p>Here's my attempt to clean it up by LINQifying it. I <strong>think</strong> that I preserved all the logic but its hard to know for sure (I cannot emphasize how important it is to write tests).</p>\n\n<pre><code> public void ReIndexOutputTemplatePages(OutputTemplatePage page) {\n //I'm on a personal vendetta to stamp out the sql-style of syntax, it makes thing way more confusing than need be\n var items = db.OutputTemplatePages\n .Where(t => t.OutputTemplateId == page.OutputTemplateId)\n .OrderBy(t=> t.SortOrder)\n .ToArray(); //might as well load it all up, you're using each one it anyways\n\n OutputTemplateRepository repo = new OutputTemplateRepository();\n\n if(items.Length== 0 || (page.SortOrder != null && page.SortOrder > 0 && page.SortOrder < items.Length)) \n Add(page);\n\n Enumerable.Range(items.Length)\n .Zip(items, (i, item)=> new {\n SortOrder = i,\n // This is a select n+1 bug waiting to happen and only ok if you are sure that items will always have a low count \n // otherwise create a function repo.getTemplatePages(items.Select(p=>p.Id)) that is appropriately optimized\n // and get all of these in one shot\n // Also, since you're not using item directly, maybe you just want to fetch them out of \n // the db with a join rather than having the intermediate step\n Template = repo.GetOutputTemplatePageById(item.Id)\n }).ToList() // I usually write an ForEach(this IEnumerable<> extension so that you don't have to do this\n .ForEach(x=>x.Template.SortOrder = x.SortOrder);\n\n repo.Save();\n}\n</code></pre>\n\n<p>As the others have said, don't try...catch unless you know exactly what exception you're looking for. You should only catch exceptions you can do something about, something like an OutOfMemoryException should be allowed to go right through as there are better ways to handle them.</p>\n\n<p>I would also say it's a bit wierd to be newing objects up like this in a method. Newing an object up like this is theoretically no different from calling a static method and practically even a little worse. My understanding of proper OOP (and there is plenty of room for argument on this) is that dependencies should be passed in via the constructor or at least created as fields on the object. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T21:51:39.260",
"Id": "8719",
"ParentId": "8699",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "8704",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T14:38:18.830",
"Id": "8699",
"Score": "1",
"Tags": [
"c#",
"asp.net-mvc-3"
],
"Title": "Improving readability and logic on \"re-indexing\" method"
}
|
8699
|
<p>I have posted such question at StackOverflow but the single answer I got there was to ask here.<br>
My task is to get elements fading in while the user is scrolling. Here is my link - <a href="http://layot.prestatrend.com/" rel="nofollow">http://layot.prestatrend.com/</a> I have made it with the help of such jQuery code I've gathered from two sources:</p>
<pre><code><script type="text/javascript">
$(document).ready( function() {
tiles = $('.ajax_block_product').fadeTo(0,0);
$(window).scroll(function(d,h) {
tiles.each(function(i) {
a = $(this).offset().top + $(this).height();
b = $(window).scrollTop() + $(window).height();
if (a < b) $(this).fadeTo(500,1);
});
});
function inWindow(s){
var scrollTop = $(window).scrollTop();
var windowHeight = $(window).height();
var currentEls = $(s);
var result = [];
currentEls.each(function(){
var el = $(this);
var offset = el.offset();
if(scrollTop <= offset.top && (el.height() + offset.top) < (scrollTop + windowHeight))
result.push(this);
});
return $(result);
}
inWindow('.ajax_block_product').fadeTo(0,1);
});
</script>
</code></pre>
<p>Is this an elegant solution or is there a way to make the code shorter and more elegant?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T19:31:19.443",
"Id": "13642",
"Score": "0",
"body": "Can you clarify what you mean by \"fade for elements while scrolling\"? I see nothing on the page that does fade in while scrolling, I just see things fading in as you hover over them"
}
] |
[
{
"body": "<p>The onScroll event is generally very performance hungry, since it is called quite often, while scrolling. Looping through all \"ajax_block_product\" elements on every singel call, even if most of them might be outside of the viewport, makes it even worse. But you can use some specialities of JS to optimize it. As a short intro: In JS you can set an array element at a defined index, leaving the ones in between undefined while having the length of the array set to the highest index defined.</p>\n\n<pre><code>a[100] = 'one';\na[1000] = 'two';\nfor (var i = 0; i < a.length; i++) {\n console.log('iterate'); // called 1000 times\n}\nfor (var elm in a) {\n console.log('iterate'); // called two times\n}\n</code></pre>\n\n<p>Now if you loop through the array with a typical <code>for(var i = 0; i < a.length; i++)</code> you will have 1000 iterations BUT since an array is also an object in JS a <code>for(elm in a)</code> would only iterate 2 times. We can now use this to store all Y-positions of \"ajax_block_product\" elements as indexes of an array, than determine the dimension of the current viewport and cut out only those element who are inside that range.</p>\n\n<pre><code>$(document).ready(function () {\n var tiles = $('.ajax_block_product'),\n winHeight = $(window).height(),\n posArr = [];\n\n tiles.each(function () {\n var pos = $(this).offset().top;\n posArr[pos] = $(this);\n });\n\n $(window).scroll((function fadeIn() {\n var sTop = $(window).scrollTop(),\n range = posArr.slice(sTop, sTop + winHeight);\n range.forEach(function (elm) {\n elm.css('opacity', 1);\n });\n return fadeIn;\n }()));\n});\n</code></pre>\n\n<p>In this example I've used CSS3: <code>transition: opacity .5s ease-in;</code> for the fade in. You need to check out how to do this with jQuery's fadeIn, if needed... </p>\n\n<p>Last but not least, the onScroll event callback is somehow special. It a self-executing, self-referencing function. It is called once, when it's defined, to initially show all elements already in the viewport and then returns a reference to itself for later onScroll event calls.</p>\n\n<p>Hope this could help you, even if it's some time ago, you asked this question...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-28T23:32:07.610",
"Id": "18023",
"ParentId": "8700",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T15:18:46.640",
"Id": "8700",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "Fading in while scrolling - is this an elegant solution?"
}
|
8700
|
<p>I've reusing this code for multiple areas and will like to make it more short and/or portable. What suggestions or changes could I make to simplify shorten it's callback processes?</p>
<pre><code> $("#add_question_member").submit(function(){
$.ajax({
type:'post',
url: '/posts_in.php',
dataType: "json",
data: $(this).serialize(),
success: function(data){
var response = data[0];
$("#entry_area").fadeOut(function(){
if(response==1){
$("#msg0").stop().fadeIn("slow").delay(8000).fadeOut("slow",function(){
$("#entry_area").stop().fadeIn("slow");
});
}else{
$("#msg1").stop().fadeIn("slow").delay(8000).fadeOut("slow",function(){
$("#entry_area").stop().fadeIn("slow");
});
}
});
}
});
return false;
});
</code></pre>
|
[] |
[
{
"body": "<p><a href=\"http://jsfiddle.net/YNtPh/8\" rel=\"nofollow\">Here is a jsfiddle where I cleaned it up for you</a></p>\n\n<p>I did not actually test it so there might be a syntax error here and there but its how you would do it overall.\nIt might not be 100% but it should get you started as far as the techniques you should look into such as:</p>\n\n<ul>\n<li><a href=\"http://elegantcode.com/2011/02/15/basic-javascript-part-10-the-module-pattern/\" rel=\"nofollow\">Module pattern to create reusable code</a></li>\n<li>Callback or options to support the ability to pass in a simple callback or a more complex object</li>\n<li>Defaults with $.extend </li>\n<li><a href=\"https://github.com/raganwald/homoiconic/blob/master/2012/01/captain-obvious-on-javascript.md\" rel=\"nofollow\">Functions returning callbacks</a></li>\n</ul>\n\n<p>That's a lot of stuff and a bit overkill on this example but I wanted to showcase the techniques for you. Feel free to ask any questions.</p>\n\n<p>A couple additional notes</p>\n\n<ul>\n<li>You generally want to <a href=\"http://api.jquery.com/jQuery/#expressioncontext\" rel=\"nofollow\">use the expression context parameter to limit your selectors</a></li>\n<li>You probably want to avoid using ids and use classes instead since things get wierd if you accidentally end up with 2 of the same id on the page. This is something that happens more often as you start to make your views more composable. This is something that using the expression context can help with.</li>\n<li>submit is only available on forms anyways, you could denote that explicitly $('form#add_question_member')</li>\n<li><a href=\"http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/\" rel=\"nofollow\">Do you really want to be returning false?</a></li>\n<li><p>Consider using the form's action and method properties instead of hardcoding them - <code>$(this).prop('action')</code>, <code>$(this).prop('method')</code> at the same level as you serialize the form</p>\n\n<p>//<strong><em>*</em>***</strong><em>This part can be in a seperate script file <strong></em>**<em>*</em>**<em>*</em>**<em>*</em>*</strong>//\n(function() { //use an immediately executing function to limit scope\n var submitFormDefaults = { //set up all the defaults to be used the function\n type: 'post',\n url: '/posts_in.php',\n dataType: \"json\",\n myAppUnWrapData: true //a custom option to unrwap your returned data by default\n };</p>\n\n<pre><code>var standardSubmitForm = function(successFnOrOptions) {\n // This allows your input to be just the success function or a richer object\n var options = $.isFunction(successFnOrOptions) ? {\n success: successFnOrOptions\n } : successFnOrOptions;\n\n // return the actual submit handler\n return function() {\n var op = $.extend(true, //deep clone\n submitFormDefaults, //use defaults unless overridden\n { data: $(this).serialize() }, //not in the defaults cause it needs access to 'this'\n options //any overrides specified\n );\n if (op.myAppUnWrapData && op.success) { //if unwrap data custom option is truthy and there is a success callback\n var _oldSuccess = op.success;\n op.success = function(data) {\n _oldSuccess(data[0]);\n }\n }\n $.ajax(op);\n return false;\n }\n}\n\n//Export the local function to the gloabl namespace using Module pattern\nwindow.MyApp = window.MyApp || {}; //create a global MyApp namespace\n$.extend(window.MyApp, { //add some global functions. I prefer to use $.extend rather than directly assigning it - I have no good reason for this\n submitForm: standardSubmitForm //export our function to the global namespace \n});\n\nwindow.MyApp.submitForm.defaults = submitFormDefaults //export the defaults as a global property on this function\n</code></pre></li>\n</ul>\n\n<p>})(); //Invoke the above immediately invoking function</p>\n\n<pre><code>//******************** Elsewhere ********************************//\n$(\"#add_question_member\").submit(window.MyApp.submitForm(function(response) { //this will return a function handler\n if (response !== 1) {\n $(\"#msg0\").stop().fadeIn(\"slow\").delay(8000).fadeOut(\"slow\", function() {\n $(\"#entry_area\").stop().fadeIn(\"slow\");\n });\n } else {\n $(\"#msg1\").stop().fadeIn(\"slow\").delay(8000).fadeOut(\"slow\", function() {\n $(\"#entry_area\").stop().fadeIn(\"slow\");\n });\n }\n}));\n\n// or...\n$('form.blah').submit(window.MyApp.submitForm({\n url: '/somewhere/else',\n success: function() {\n console.log('ok', this, arguments);\n }\n});\n\n// or...\nwindow.MyApp.submitForm.defaults.action = 'GET'; //changes it globally\n$('form.blah').submit(window.MyApp.submitForm({\n url: '/somewhere/else',\n myAppUnWrapData: false, //keep it from doing the data[0] thing\n success: function(data) {\n console.log('ok', this, arguments);\n }\n</code></pre>\n\n<p>});</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T18:38:13.227",
"Id": "13638",
"Score": "0",
"body": "no no, he said shorten and simplify"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T18:40:49.947",
"Id": "13639",
"Score": "1",
"body": "Like I said, I don't know his exact usecase so I'm showing the techniques. However, the actual usage code is significantly shorter and simpler"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T18:46:57.490",
"Id": "13640",
"Score": "1",
"body": "yea, i was just poking fun. +1 btw you might want to add the code inline in case that jsfiddle ever gets removed"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T19:10:53.967",
"Id": "13641",
"Score": "0",
"body": "Oh wow, this is super. I definitely need to go through every single point you've included, learn it and make sense of it. The fiddle looks great! Thank you so much for this."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T18:21:27.083",
"Id": "8711",
"ParentId": "8705",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "8711",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T16:39:01.063",
"Id": "8705",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "How can I Shorten and Simplify Ajax callback processes?"
}
|
8705
|
<p>I wrote a bash script to print contents of files in a given directory in a loop.</p>
<p>How can I improve command line parameters handling to the script? I feel the parameter processing as of now uses too much code and it is quite clumsy. I think I had to write too much code to validate the the option arguments are numeric. </p>
<p>The script takes either <code>-c numeric_choice_id</code> and/or <code>-l time_in_seconds</code> and keep printing the contents of the files.</p>
<ul>
<li>only <code>-c</code> number: it cats the file and ends</li>
<li>only <code>-l</code> number: repeatedly cats all the files</li>
<li><code>-c num1</code> and <code>-l num2</code>: repeatedly cats that particular file every <code>num2</code> seconds</li>
</ul>
<p></p>
<pre><code>#!/bin/bash
SYSPATH="$PWD/"
FILES="$PWD/file1
$PWD/file2
$PWD/file3"
count=0
for i in $FILES
do
(( count++ ))
menu="${menu}\n${count}. `basename $i`"
list="${list} `basename $i`"
done
testNumeric()
{
if ! echo "$1" | grep -q '^[0-9]\+$'
then
echo "$0 Non numeric argument supplied to choice or time"
exit
fi
}
usage()
{
echo -e "`basename $0` -c numeric_choice [ -l time in seconds ]\n
-c numeric id for the choice
-l print o/p every time seconds
-h print this menu
choice could be: \n$menu"
exit
}
# Test if any arguments have been provided
if [ "x$1" = "x" ] || [ "$1" = "-h" ]
then
usage
fi
# Allow getopt to parse the options and report error if needed
args=`getopt "c:l:" "$@"`
if [ "$?" -ne "0" ]
then
usage
fi
# Set positional parameters
set -- $args
for i;
do
case "$i" in
-c )
choice=$2
testNumeric $choice
shift
shift ;;
-l ) repeatTime=$2
testNumeric "$repeatTime"
shift
shift ;;
-- )
break ;;
esac
done
[ "x$choice" = "x" ] && choice=`seq $count`
[ "x$repeatTime" = "x" ] && repeatTime=0
set -- $list
while [ true ]
do
if [ "$repeatTime" = "0" ]
then
for a in $choice
do
eval temp=\${${a}}
cat $SYSPATH${temp}
done
break;
else
for a in $choice
do
eval temp=\${${a}}
cat $SYSPATH${temp}
done
sleep $repeatTime
fi
done
</code></pre>
|
[] |
[
{
"body": "<p>A few suggestions at your disposal: You can make use of <code>getopts</code> instead of <code>getopt</code> to avoid <code>shift</code> operation. You can make use of a simple flag to make sure that the mandatory <code>-c</code> option has been passed. Also from <a href=\"https://stackoverflow.com/questions/806906/how-do-i-test-if-a-variable-is-a-number-in-bash\">this post</a> you can make use of any of the solutions for check for numeric value. Maybe something on these lines: </p>\n\n<pre><code>...\nusage(){\n...\n}\n...\n#Process arguments passed\nc_set=false # Flag to check if mandatory -c is passed or not\nrepeatTime=0 # Set repeatTime value to 0 which will be default\n\nwhile getopts \":c:l:h\" opt; do\ncase \"$opt\" in\n c)\n # Check is borrowed from the mentioned link\n ! [[ \"$OPTARG\" =~ ^[0-9]+$ ]] && echo \"Non-numeric passed to option:\\\"-c\\\"\" && usage\n # if can be used instead of the above one-liner as posted in the link\n choice=\"$OPTARG\"\n c_set=true\n\n ;;\n l)\n ! [[ \"$OPTARG\" =~ ^[0-9]+$ ]] && echo \"Non-numeric passed to option:\\\"-l\\\"\" && usage\n repeatTime=\"$OPTARG\"\n ;;\n h)\n usage\n ;;\n *)\n echo \"Invalid parameters passed\"\n usage\n ;;\nesac\ndone\n\n# If the mandatory option not provided exit\n# This will be false even if no arguments passed\n[[ $c_set != true ]] && usage\n#Actual operation\nset -- $list\n...\n</code></pre>\n\n<p>Edit: Added a version with <code>getopt</code> using the tips from <a href=\"http://tldp.org/LDP/abs/html/extmisc.html\" rel=\"nofollow noreferrer\">tldp</a> </p>\n\n<pre><code>...\nc_set=false # Flag to check if mandatory -c is passed or not\nrepeatTime=0 # Set repeatTime value to 0 which will be default\n\nargs=$(getopt :c:l:h \"$@\") || usage\neval set -- \"$args\"\n\nwhile [ ! -z \"$1\" ]\ndo\n case \"$1\" in\n -c)\n # One liner in case of -l can be used instead of this \"if\"\n if ! [[ \"$2\" =~ ^[0-9]+$ ]];then\n echo \"Non-numeric passed to option:\\\"-c\\\"\" && usage\n fi\n choice=\"$2\"\n c_set=true\n ;;\n -l)\n # \"if\" in case of -c can be used instead of this one-liner\n ! [[ \"$2\" =~ ^[0-9]+$ ]] && echo \"Non-numeric passed to option:\\\"-l\\\"\" && usage\n repeatTime=\"$2\"\n ;;\n -h)\n usage\n ;;\n esac\n\n shift\ndone\n\n[[ $c_set != true ]] && usage\n...\n</code></pre>\n\n<p>Improvements/comments/remarks are welcome. Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T18:37:17.733",
"Id": "13637",
"Score": "0",
"body": "Thanks. However this script is for an embedded device. It does not have getopts. I have to use getopt only."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T06:52:50.683",
"Id": "13659",
"Score": "0",
"body": "@abc: I have tried to add a version with `getopt`. Hopefully it can provide some pointers"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T11:24:34.650",
"Id": "8707",
"ParentId": "8706",
"Score": "2"
}
},
{
"body": "<h2>Storing a list of file names and iterating over it</h2>\n\n<blockquote>\n<pre><code>FILES=\"$PWD/file1\n$PWD/file2\n$PWD/file3\"\n</code></pre>\n</blockquote>\n\n<p>So you're setting <code>FILES</code> to a newline-separated list of files. That's a bad idea because your script will choke if a file name contains a newline. In some circumstances, where you control the file names, that can be ok, but don't do it unless you really have no better way. Since you're writing a bash script, you <strong>never</strong> need to do this. Store the file names in an array instead:</p>\n\n<pre><code>FILES=(\"$PWD/file1\" \"$PWD/file2\" \"$PWD/file3\")\n</code></pre>\n\n<p>Then, to iterate over the array:</p>\n\n<pre><code>for i in \"${FILES[@]}\"; do …\n</code></pre>\n\n<p>If you had a shell without arrays and decided to use a newline-separated list of file names, then you would need some extra effort to split the lines at newlines only. The <code>IFS</code> variable specifies where to split words in unquoted variable substitutions, so you need to set it to contain only a newline (the default value also contains the ordinary space character and the tab character). Also, the shell performs globbing (filename generation from wildcards) on the results of unquoted variable substitutions, so you need to turn that feature off. Here's a POSIX-compliant way of iterating over the pieces of a newline-delimited string:</p>\n\n<pre><code>IFS='\n'\nset -g\nfor i in $FILES; do …\n</code></pre>\n\n<p>Since you never change directories, you could store just the files' base names instead of full paths. If you control the file names, you then don't need to be so careful with special characters in the names.</p>\n\n<h2>Always use double quotes around variable substitutions</h2>\n\n<p>I see a lot of places where you write unquoted variable substitutions, e.g. <code>basename $i</code>. Do you really want to split <code>$i</code> into words, then perform globbing on the result? If you don't, then use double quotes: <code>\"$i\"</code>. Only leave off the double quotes if you intend to perform word splitting and filename generation (as in the for loop example above), and then be mindful of the assumptions you're making on the value of the variable.</p>\n\n<p>On the same note, if there was a risk that <code>$i</code> began with a <code>-</code>, you would need to call <code>basename -- \"$i\"</code> to avoid <code>$i</code> being interpreted by <code>basename</code> as an option. This is not going to happen with your script since <code>$i</code> is an absolute path, beginning with <code>/</code>.</p>\n\n<p>I also recommend not using the backquote command susbsitution, which behaves strangely with nested quotes sometimes. Use <code>$(…)</code>, which has an intuitive syntax.</p>\n\n<blockquote>\n<pre><code> menu=\"${menu}\\n${count}. $(basename -- \"$i\")\"\n</code></pre>\n</blockquote>\n\n<p>Incidentally, note that this puts the characters <code>\\n</code> into <code>menu</code>, not a newline. The <code>\\n</code> is expanded by <code>echo -e</code> below.</p>\n\n<h2>Testing for a number</h2>\n\n<blockquote>\n<pre><code> if ! echo \"$1\" | grep -q '^[0-9]\\+$'\n</code></pre>\n</blockquote>\n\n<p>No need to call <code>grep</code> for that! Here's a simple bash construct:</p>\n\n<pre><code> if [[ $1 = *[^0-9]* ]]; then … # non-numeric\n</code></pre>\n\n<p>Here's a POSIX construct:</p>\n\n<pre><code> case $1 in\n *[!0-9]*) …;; # non-numeric\n esac\n</code></pre>\n\n<h3>Here documents</h3>\n\n<p>To insert a multiline string in a script, use a <a href=\"http://en.wikipedia.org/wiki/Here_document\" rel=\"nofollow\">here document</a>. It's more readable.</p>\n\n<pre><code>usage()\n{\n cat <<EOF\n$(basename -- \"$0\") -c ID [-l TIME]\n-c ID numeric id for the choice \n-l TIME print output every TIME seconds\n-h print this menu \n\nID could be:\n$menu\nEOF\n}\n</code></pre>\n\n<p>It's conventional to use upper case for argument descriptions in the symbolic syntax. Clearly indicate the options that take an argument in the left-hand column. Don't use obscure abbreviations that barely save a few characters like <code>o/p</code> (I think you meant “output”, but I'm not sure).</p>\n\n<h2>Parsing the command line</h2>\n\n<p>Use the shell builtin <code>getopts</code> rather than the external command <code>getopt</code>. If you have bash, you have <code>getopts</code>. If you don't have <code>getopts</code>, then you're running an embedded shell which may lack other features, so check that the other features you want to use are supported.</p>\n\n<p>To test if there are any arguments, check the number of arguments, in <code>$#</code>.</p>\n\n<pre><code>if [ $# -eq 0 ] || [ \"$1\" = \"-h\"]; then …\n</code></pre>\n\n<p>Actually, you don't need any special handling for <code>-h</code>. Treat it like any other option.</p>\n\n<p>I'm not going to go over <code>getopts</code> usage, there are plenty of examples around.</p>\n\n<h2>Before the main loop</h2>\n\n<blockquote>\n<pre><code>set -- $args\n…\nset -- $list\n</code></pre>\n</blockquote>\n\n<p>Remember what I wrote about unquoted substitutions above? Each of these commands performs word splitting and filename generation.</p>\n\n<blockquote>\n<pre><code>[ \"x$choice\" = \"x\" ] && choice=`seq $count`\n[ \"x$repeatTime\" = \"x\" ] && repeatTime=0\n</code></pre>\n</blockquote>\n\n<p>You need to initialize <code>choice</code> and <code>repeatTime</code> before the argument parsing, unless you intended to allow them to be pulled from the environment.</p>\n\n<h2>The main loop</h2>\n\n<pre><code>while [ true ]\n</code></pre>\n\n<p>This is a strange way of writing <code>while true</code>. You could also write <code>while [ false ]</code> or <code>while ! [ ! true ]</code>. Keep it simple.</p>\n\n<blockquote>\n<pre><code> eval temp=\\${${a}}\n cat $SYSPATH${temp}\n</code></pre>\n</blockquote>\n\n<p>In bash, you can avoid the use of <code>eval</code>. Also, remember to double quote variable substitutions unless you have a good reason not to.</p>\n\n<blockquote>\n<pre><code> cat \"$SYSPATH${!a}\"\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T18:41:11.880",
"Id": "8923",
"ParentId": "8706",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "8923",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T02:15:01.783",
"Id": "8706",
"Score": "6",
"Tags": [
"bash",
"file-system",
"linux"
],
"Title": "Printing a directory's contents in a loop"
}
|
8706
|
<p>I have data that I want to insert in a database. Sometime a piece of data is already in the database, so I just want to update the fields that changed.</p>
<p>For example, if I insert these rows one after the other:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>id | field1 | field2 | field3
1 | foo | NULL | bar
1 | baz | hello | NULL
</code></pre>
</blockquote>
<p>I want to end up with:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>id | field1 | field2 | field3
1 | baz | hello | bar
</code></pre>
</blockquote>
<p>I use this query:</p>
<pre class="lang-sql prettyprint-override"><code>INSERT INTO `device` (`device_id`, `model`, `manufacturer`, `version`, `vendor_id`, `osd_name`)
VALUES (....)
ON DUPLICATE KEY UPDATE `version` = IFNULL(VALUES(`version`), `version`), `vendor_id` = IFNULL(VALUES(`vendor_id`), `vendor_id`), `osd_name` = IFNULL(VALUES(`osd_name`), `osd_name`)
</code></pre>
<p>Note that not all fields have to be updated. Is this the best way to do it?</p>
|
[] |
[
{
"body": "<p>I think it is.</p>\n\n<p>What you are asking for is known as <code>UPSERT</code> - a <a href=\"http://en.wikipedia.org/wiki/Portmanteau\" rel=\"nofollow\">portmanteau</a> of <code>UPDATE</code> and <code>INSERT</code>. Some databases support <code>UPSERT</code> intrinsically, but some don't. A quick search for \"MySQL UPSERT\" suggests that MySQL does not support an <code>UPSERT</code> keyword or the concept directly. However, as you discovered, the <code>ON DUPLICATE KEY</code> construct will simulate it.</p>\n\n<p>That seems the best way to do it in MySQL. (In SQL Server you would probably use <code>MERGE</code>.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T23:01:36.033",
"Id": "8721",
"ParentId": "8708",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "8721",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T17:08:44.853",
"Id": "8708",
"Score": "2",
"Tags": [
"sql",
"mysql",
"pdo"
],
"Title": "Updating only certain fields on a database row"
}
|
8708
|
<p>I'm fairly new to Ruby, and I've been refactoring this code (it's a silly app, but it's helping me learn) as I learn more and more best practices and features new to Ruby 1.9 (e.g., hashrocket alternative). I figure having more experienced Rubyists give feedback on the short program will help me learn faster. So, with that in mind, is there anything in this code that isn't a best practice, or anything not so clean about it?</p>
<pre><code>#!/usr/bin/env ruby
require 'twitter'
# Enter your creds
creds = {username: 'YourUsername',
consum_key: 'SomeLongKeyBlahBlah',
consum_secret: 'AnotherLongKeyButASecretOneThisTime',
oauth_token: 'OAuthTokenKeyBlahBlah',
oauth_secret: 'OAuthSecretTokenOfSecrets'}
# Twitter auth
def twitterAuth(creds)
Twitter.configure do |config|
config.consumer_key = creds[:consum_key]
config.consumer_secret = creds[:consum_secret]
config.oauth_token = creds[:oauth_token]
config.oauth_token_secret = creds[:oauth_secret]
end
end
def sendTweet(creds)
# Make string
msg = '@' + creds[:username] + ' ' + ARGV.join(' ')
# Send!
Twitter.update(msg)
# Return tweet
puts 'Your tweet: ' + msg
end
if __FILE__ == $0
twitterAuth(creds)
sendTweet(creds)
end
</code></pre>
|
[] |
[
{
"body": "<p>Generally Rubyists define methods in the underscore-lowercase pattern: <code>def twitter_auth</code>, <code>def send_tweet</code>. Additionally most that I've encountered prefer to drop the <code>()</code> from method calls: <code>twitter_authenticate creds; send_tweet creds</code></p>\n\n<p>Otherwise this looks OK!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T20:38:20.087",
"Id": "8716",
"ParentId": "8710",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T17:40:57.787",
"Id": "8710",
"Score": "3",
"Tags": [
"ruby",
"twitter"
],
"Title": "Entering and authorizing Twitter credentials"
}
|
8710
|
<p>I'm a JavaScript coder trying to teach myself Java using online tutorials and ebooks. I have now created my very first applet but feel it only really goes to show the depth of my unappreciation for Java's capabilities. Please, give me some advice as to how to use Java better so that my future projects can be less effort to make, easier to read, easier to maintain and altogether more smoothly designed, just like Java apps are supposed to be.</p>
<p>How would you have implemented the following applet? What would you have done differently? I really don't know what I'm doing here and wish I did because I get the feeling Java's gonna be great once I'm approaching things more sensibly.</p>
<pre><code>import java.applet.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
@SuppressWarnings("serial")
public class SlidePuzz extends Applet implements MouseMotionListener, MouseListener {
int gridDim = 3;
int animal = -1;
int pieceDim = 0;
int a; int b;
int gapX = -1; int gapY = -1;
int moveX = -1; int moveY = -1;
Image[][] pieces = new Image[7][7];
int[][] placement = new int[7][7];
String stage = "grid";
String[] imgUrl = { "7028/6814220663_4813a81531",
"7162/6814220921_acb3aa92ee", "7029/6814221019_41323ace8b" };
String imgUrlFlickr = "http://farm8.staticflickr.com/";
Image img;
MediaTracker tr;
public void init() {
setSize(420, 420);
addMouseMotionListener(this);
addMouseListener(this);
}
public void paint(Graphics g) {
if(stage=="grid") {
g.setColor(Color.lightGray);
g.fillRect(0,0,60*gridDim,60*gridDim);
g.setColor(Color.white);
g.fillRect(60*gridDim,0,(7-gridDim)*60,420);
g.fillRect(0,60*gridDim,60*gridDim,(7-gridDim)*60);
g.setColor(Color.black);
for (int i=1; i<7; i++) {
g.drawLine(i*60,0,i*60,460);
g.drawLine(0,i*60,460,i*60);
}
g.setColor(Color.black);
g.fillRect(120,0,180,20);
g.setColor(Color.white);
g.drawString("click to choose "+gridDim+"x"+gridDim+" grid", 145, 15);
} else if (stage=="animal") {
g.setColor(Color.white);
g.fillRect(0,0,420,420);
g.setColor(Color.black);
g.drawString("Please click an animal...", 80, 100);
g.setFont(new Font("Courier New", Font.BOLD, 22));
g.drawString("Mouse", 80, 150);
g.drawString("Cat", 80, 200);
g.drawString("Dog", 80, 250);
} else if (stage=="game") {
// download selected image and chop into pieces
if (gapX<0) {
g.setColor(Color.white);
g.fillRect(0,0,420,420);
g.setColor(Color.black);
g.setFont(new Font("Courier New", Font.PLAIN, 12));
g.drawString("Loading image...", 120, 50);
tr = new MediaTracker(this);
img = getImage(getCodeBase(), imgUrlFlickr+imgUrl[animal]+"_o.jpg");
tr.addImage(img,0);
try { tr.waitForID(0); }
catch (InterruptedException e) { e.printStackTrace(); }
for(int x=0; x<gridDim; x++) {
for(int y=0; y<gridDim; y++) {
pieces[x][y] = createImage(new FilteredImageSource(img.getSource(),
new CropImageFilter(x*pieceDim, y*pieceDim, pieceDim, pieceDim)));
placement[x][y] = (x==gridDim-1 && y==gridDim-1) ? -2 : -1;
tr.addImage(pieces[x][y],0);
}
}
try { tr.waitForID(0); }
catch (InterruptedException e) { e.printStackTrace(); }
Random r = new Random();
Boolean placed;
for(int x=0; x<gridDim; x++) {
for(int y=0; y<gridDim; y++) {
// if its the gap, no need to draw anything
if (placement[x][y]==-2) break;
// keep looping until piece is selected thats not already drawn
do {
do {
a = r.nextInt(gridDim);
b = r.nextInt(gridDim);
} while (a==gridDim-1 && b==gridDim-1);
placed = false;
for(int c=0; c<gridDim; c++) {
for(int d=0; d<gridDim; d++) {
if(placement[c][d]==a*10+b) placed=true;
}
}
} while (placed);
// draw on the screen and record what's gone here
g.drawImage(pieces[a][b], x*pieceDim, y*pieceDim, this);
placement[x][y] = a*10+b;
}
}
// record where the gap is
gapX = gridDim-1; gapY = gridDim-1;
// a piece needs to be moved
} else if (moveX>=0){
g.setColor(Color.white);
g.fillRect(moveX*pieceDim, moveY*pieceDim, pieceDim, pieceDim);
b = placement[moveX][moveY]%10;
a = (placement[moveX][moveY]-b)/10;
g.drawImage(pieces[a][b], gapX*pieceDim, gapY*pieceDim, this);
placement[gapX][gapY] = a*10+b;
placement[moveX][moveY] = -2;
gapX = moveX; gapY = moveY;
moveX = -1; moveY = -1;
// screen may need refreshing so draw all pieces again
} else {
for(int x=0; x<gridDim; x++) {
for(int y=0; y<gridDim; y++) {
if (placement[x][y]==-2) continue;
b = placement[x][y]%10;
a = (placement[x][y]-b)/10;
g.drawImage(pieces[a][b], x*pieceDim, y*pieceDim, this);
}
}
}
}
}
public void mouseMoved(MouseEvent me) {
if(stage=="grid") {
int mousePos = me.getX()>me.getY() ? me.getX() : me.getY();
int oldGridSize = gridDim;
gridDim = (mousePos/60)+1;
if(gridDim<3) gridDim=3;
if (gridDim!=oldGridSize) repaint();
}
}
public void mousePressed (MouseEvent me) {
int x = me.getX();
int y = me.getY();
if(stage=="grid") {
stage = "animal";
repaint();
} else if(stage=="animal") {
if(x<150 && x>80 && y<150 && y>130) animal=0;
else if(x<150 && x>80 && y<200 && y>180) animal=1;
else if(x<150 && x>80 && y<250 && y>130) animal=2;
if (animal>-1) {
stage="game";
pieceDim = 420/gridDim;
repaint();
}
} else if(stage=="game") {
x /= pieceDim;
y /= pieceDim;
Boolean right = (x-1==gapX && y==gapY);
Boolean left = (x+1==gapX && y==gapY);
Boolean down = (x==gapX && y-1==gapY);
Boolean up = (x==gapX && y+1==gapY);
if (right || left || down || up) {
moveX = x;
moveY = y;
repaint();
}
}
}
public void update(Graphics g) { paint(g); }
public void mouseDragged (MouseEvent me) {}
public void mouseExited (MouseEvent me) {}
public void mouseEntered (MouseEvent me) {}
public void mouseClicked (MouseEvent me) {}
public void mouseReleased (MouseEvent me) {}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T05:34:04.710",
"Id": "13635",
"Score": "2",
"body": "java applets aren't used much (if at all) anymore. Most java apps are server side only with frontend doing html/css/javascript."
}
] |
[
{
"body": "<p>Quick overview, I didn't run this code and only reading lines from top to the bottom:</p>\n\n<ol>\n<li><p>Use <code>JApplet</code> (Swing) instead of prehistoric <code>Applet</code> (AWT) that came from last millenium</p></li>\n<li><p>For <a href=\"http://docs.oracle.com/javase/tutorial/2d/index.html\" rel=\"nofollow\">painting in the Swing</a> you have to override <code>paintComponent</code> instead of <code>paint</code>, notice probably if you change method <code>paint</code> to <code>paintComponent</code> this code couldn't be works,</p></li>\n<li><p>I think method <code>public void update(Graphics g) { paint(g);</code> never will be used</p></li>\n<li><p>For comparing String use </p>\n\n<pre><code>if (stage.equals(\"animal\")) {\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>if (stage==\"animal\") {\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T13:03:34.227",
"Id": "8651",
"ParentId": "8712",
"Score": "1"
}
},
{
"body": "<p>You might write a book on this (which is a big hint this might be closed). But some general tips before that happens.</p>\n\n<ol>\n<li>Use Swing components rather than AWT components in this millennium.</li>\n<li>Use <code>ImageIO.read(URL/InputStream)</code> over any method that requires a <code>MediaTracker</code> (easier).</li>\n<li>A <code>MouseAdapter</code>/<code>MouseMotionAdapter</code> might be a better choice if you only need to override one or two methods.</li>\n<li>The paint method should be refactored. Each object painted might be a class that knows how to paint itself. The if/else structure would then be much shorter.</li>\n</ol>\n\n<p>Note that most things that people would normally do in applets, can be replaced by JS and the HTML5 canvas. Java really comes into it's own as free-floating desktop apps.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T05:48:09.960",
"Id": "8713",
"ParentId": "8712",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "8713",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T05:30:32.783",
"Id": "8712",
"Score": "3",
"Tags": [
"java"
],
"Title": "Sliding-Puzzle Applet"
}
|
8712
|
<p>I'm getting started with my first official jQuery plugin, and I'm just turning now looking for input. I want to know what I'm doing wrong or right so far and if everything is being developed in a manner that won't cause issue down the road. With no further adieu:</p>
<pre><code>$.fn.heftyBox = function(args) {
if ($(this).length) {
//Set up defaults
var a = $.extend({
type : "checkbox",
width : "auto",
height : ($(this).innerHeight() > 150) ? $(this).innerHeight() : 150
}, args);
//Gather original attributes, convert DOM, then reassgign attributes
var attributes = $(this)[0].attributes;
var optionsHTML = $(this).html();
$(this).after('<ul id="tmpul">' + optionsHTML + '</ul>');
$(this).remove();
var ul = $('#tmpul')[0];
for (var i = 0; i < attributes.length; i++) {
$(ul).attr(attributes[i].name, attributes[i].value);
}
//Convert options to checkbox or radios
var options = $(ul).children('option');
var name = $(ul).attr('name');
$(ul).removeAttr('name');
var f = 0;
$.each(options, function(key, option) {
var itemAttributes = $(this)[0].attributes;
var value = $(this).attr('value');
var label = $(this).text();
var selected = $(this).attr('selected') ? "checked" : ''
selected += $(this).attr('disabled') ? " disabled" : ''
var newLi;
$(this).replaceWith(newLi = $('<li ' + selected + '><input type="' + a.type + '" id="option_' + name + '_' + f + '" name="' + name + '" value="' + value + '" ' + selected + '/><label for="option_' + name + '_' + f + '">' + label + '</label></li>') )
for (var i = 0; i < itemAttributes.length; i++) {
$(newLi).children('input').attr(itemAttributes[i].name, itemAttributes[i].value);
}
f++;
})
//Add Filter Box
$(ul).before('<input id="' + name + '_filter" class="list_filter" />');
var list = $(ul).children('li');
var filter = $('#' + name + '_filter');
filterBox($(filter), list);
//Contain it all
$(filter).before('<div class="heftyBox" id="' + name + '_container"></div>');
var container = $('#' + name + '_container');
$(filter).appendTo($(container));
$(ul).appendTo($(container));
//Select all box for checkboxes
if (a.type == "checkbox") {
$(filter).after($('<a href="#">Select All</a>').bind('click', function() {
var checkboxes = $(this).next('ul').find('input:not([disabled])');
if ($(checkboxes).length > $(checkboxes + ':checked').length) {
$(checkboxes).attr('checked', 'checked').closest('li').attr('checked', 'checked');
} else {
$(checkboxes).removeAttr('checked', 'checked').closest('li').removeAttr('checked');
}
($(this).text() == "Select All") ? $(this).text("Select None") : $(this).text("Select All")
$(this).next('ul').trigger('change')
return false;
}))
}
//Write the Data to the DOM
$(ul).data({
heftyBox: a
})
//Apply DOM data
updateheftyBox($(ul));
//Handle Value Change
$(this).bind('change', function() {updateheftyBox($(this));})
}
//scroll to first selected DOM
if ($(ul).find('li[checked]:first').length) {
var itemTop = $(ul).find('li[checked]:first').offset().top || $(ul).offset().top;
var ulTop = $(ul).offset().top;
$(ul).scrollTop(itemTop - ulTop);
}
}
updateheftyBox = function(target) {
var a = $(target).data().heftyBox;
var container = $(target).parent('.heftyBox');
var filter = $(target).siblings('.list_filter');
var ul = $(target);
//Gather created data
a.value = [];
$(ul).find('input:checked').each(function() {
a.value.push($(this).val())
})
$(container).css({
width: a.width,
height: a.height,
"min-width": $(filter).outerWidth()
});
$(ul).css({
height: a.height - $(filter).outerHeight(),
"margin-top": $(filter).outerHeight()
})
$(ul).val(a.value);
}
filterBox = function(target, blocks) {
$(target).unbind('keyup change');
$(target).bind('keyup change', function() {
var inText = $(this).val().trim(); //remove trailing whitespace
$.each(blocks, function() {
var title = $(this).children('label').text(); //the title in the block
if (matchAll(title, inText)) {
$(this).show();
} else {
$(this).hide();
}
})
})
}
matchAll = function(string, args) { //string= string to match, args= search input
var die = 0; //return switch
var checks = args.split(' '); //break input into array
$.each(checks, function() {
var myReg = new RegExp(this, 'i'); //search term to regex
if (!string.match(myReg)) { //if it doesn't match, kill the function
die = 1;
}
})
if (die == 1) {
return false;
} else {
return true;
}
}
$('.heftyBox li:has(input:checkbox)').live('click', function() {
($(this).has(':checked').length) ? $(this).attr('checked', 'checked') : $(this).removeAttr('checked')
})
</code></pre>
<p>The concepts of thus plugin: </p>
<ul>
<li>The HeftyBox should be dynamic and not affect any attributes or user input that coould be collected by the original Select box</li>
<li>The HeftyBox should accept many options to match styling and uniqueness of the application it is being used for</li>
<li>The HeftyBox should be able to be modified and customized with calls to the object after it is initiated</li>
<li>The HefyBox should be easy to implement, attractive, and functional with defualt setting</li>
</ul>
<p>Source <a href="https://github.com/kmacey1249/heftybox" rel="nofollow noreferrer">github/kmacey1249/heftybox</a></p>
<p>Implemented like so: </p>
<p>Initial HTML</p>
<pre><code><select name="test" id="test" multiple="multiple" bar="baz">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3" foo="bar">Three</option>
</select>
</code></pre>
<p>jQuery Call</p>
<p><code>$('#test').heftyBox(); //{type: "checkbox"/"radio", width: "auto", height: 150}</code></p>
<p>Result: </p>
<pre><code><div class="heftyBox" id="test_container" style="width: auto; height: 178px; min-width: 155px; ">
<input id="test_filter" class="list_filter" />
<a href="#">Select All</a>
<ul id="test" multiple="multiple" bar="baz" style="height: 155px; margin-top: 23px; ">
<li>
<input type="checkbox" id="option_test_0" name="test" value="1">
<label for="option_test_0">One</label>
</li>
<li>
<input type="checkbox" id="option_test_1" name="test" value="2">
<label for="option_test_1">Two</label>
</li>
<li>
<input type="checkbox" id="option_test_2" name="test" value="3" foo="bar">
<label for="option_test_2">Three</label>
</li>
</ul>
</div>
</code></pre>
<p><img src="https://i.stack.imgur.com/3EEh5.jpg" alt="plugin preview"></p>
<p>Code in action at JSFiddle <a href="http://jsfiddle.net/kmacey1249/vXGke/" rel="nofollow noreferrer">http://jsfiddle.net/kmacey1249/vXGke/</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T20:06:48.187",
"Id": "13643",
"Score": "0",
"body": "Can you give us an use case, some HTML which one it will work. It'll be more easy to see how it works and what it is doing. I already can see some optimization but with an use case, it will help us to review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T20:58:55.563",
"Id": "13646",
"Score": "0",
"body": "Updated with example"
}
] |
[
{
"body": "<p>Well I forked it and will work on a refactoring but some comments:</p>\n\n<ul>\n<li>Cache variables so that you don't have to keep invoking <code>$()</code> - it is common to do <code>var $this = $(this);</code></li>\n<li>Don't use ids. They are a host of problems. What if there are 2 hefty boxes on a page? Or worse, what if my app uses one of those names? You virtually never need to do that</li>\n<li>I prefer using <code>$.each</code> to <code>for</code> loops - they are safer and the performance hit is unlikely to hurt you in this case. In any case you should cache the length since <code>arr.length</code> is recalculated at every invocation.</li>\n<li><a href=\"http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/\" rel=\"nofollow\">About <code>return false</code></a></li>\n<li><p>Enclose the same thing in an immediately executing function that makes usage of $ safe</p>\n\n<pre><code>(function($) {\n // your code\n})(jQuery);\n</code></pre></li>\n<li>When you're using jquery to create elements, you don't have to include the closing one.</li>\n<li>Also, include tests or at least a test page - I will have a hard time testing out my fork.</li>\n<li><p>Also I see this pattern a lot:</p>\n\n<p>$(filter).before('<div class=\"heftyBox\" id=\"' + name + '_container\"></div>');\nvar container = $('#' + name + '_container');</p>\n\n<p><strong>This will break</strong> if there's another heftybox before this or if they didn't include a name or for a million other reasons. Here is a much better approach:</p>\n\n<p>var container = $('<div class=\"heftyBox\" id=\"' + name + '_container\"').after(filter);</p>\n\n<p>Or at he very least use jQuery's <code>next</code> and <code>prev</code> methods.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T23:43:46.530",
"Id": "13653",
"Score": "0",
"body": "jsfiddle here http://jsfiddle.net/kmacey1249/vXGke/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T16:09:10.690",
"Id": "13688",
"Score": "1",
"body": "@KyleMacey Updated my answer with a few more items that I saw prevelant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T17:08:00.153",
"Id": "13695",
"Score": "0",
"body": "Thank you very much. This is why I posted here. I've been able to make code work well for specific instances, but needed a good line of correction to nail out best practices and making my code universal."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T23:00:38.493",
"Id": "8720",
"ParentId": "8714",
"Score": "2"
}
},
{
"body": "<p>See comments in the code that explain why I did some things.</p>\n\n<p>Here is the result of my refactoring:</p>\n\n<ul>\n<li>Putting the code in a self-executing function. Your three helpers functions don't have to be in the global scope.</li>\n<li>Caching almost all elements. You made too many calls to <code>$</code></li>\n<li>Adding a lot of semicolons which you forgot to use</li>\n<li>Used plain JavaScript instead of the equivalent jQuery function (<code>attr()</code>, <code>val()</code>, etc.)</li>\n<li>Stopped relying on id's. You were inserting elements and then using the DOM to retrieve them by ID. I just created elements, then inserted them.</li>\n</ul>\n\n<p><strong>Edit</strong> : I just added another closure function because the first wasn't taking <code>$.fb.heftyBox</code> into it's closure.</p>\n\n<p>PS: Setting invalid attributes for a tag is not a good solution. Use 'data-' attributes instead of putting invalid attributes in a tag.</p>\n\n<pre><code> (function($) {\n $.fn.heftyBox = (function() {\n // usefull functions\n // declared in a self-executing function to not charge the global scope\n\n var updateheftyBox = function($target) {\n // $target is already a jQuery object, don't need to $() it again\n var box = $target.data().heftyBox,\n $container = $target.parent('.heftyBox'),\n $filter = $target.siblings('.list_filter'); // caching $(filter)\n\n //Gather created data\n box.value = [];\n $target.find('input:checked').each(function() {\n // using this.value instead of .val(), jQuery tools is not needed\n box.value.push(this.value); \n });\n\n $container.css({\n width: box.width,\n height: box.height,\n \"min-width\": $filter.outerWidth()\n });\n\n $target.css({\n height: box.height - $filter.outerHeight(),\n \"margin-top\": $filter.outerHeight()\n })\n $target.val(box.value);\n };\n\n\n var filterBox = function($target, blocks) {\n // $target is already a jQuery object, don't need to $() it again\n\n // use chaining\n $target.unbind('keyup change')\n .bind('keyup change', function() {\n // input, don't need to use $(this).val(), just this.value\n var inText = this.value.trim(); //remove trailing whitespace\n\n $.each(blocks, function() {\n var $that = $(this);\n var title = $that.children('label').text(); //the title in the block\n if (matchAll(title, inText)) {\n $that.show();\n } else {\n $that.hide();\n }\n });\n\n });\n };\n\n var matchAll = function(string, args) { //string= string to match, args= search input\n var checks = args.split(' '); //break input into array\n for(var i = checks.length; i--; ) {\n if (!string.match(new RegExp(checks[i], 'i'))) { // test if args[i] match the string\n // return false if one don't match, don't need to get threw all\n return false; \n }\n }\n return true;\n };\n\n\n\n return function(args) {\n var $that = $(this);\n if ($that.length) {\n //Set up defaults\n var opt = $.extend({\n type : \"checkbox\",\n width : \"auto\",\n height : ($that.innerHeight() > 150) ? $that.innerHeight() : 150\n }, args\n ),\n attributes = $that[0].attributes, //Gather original attributes, convert DOM, then reassgign attributes\n optionsHTML = $that.html();\n $ul = $('<ul id=\"tmpul\">' + optionsHTML + '</ul>'); // build ul, then use it | maybe use a random id instead of hardcoding one\n\n for (var i = attributes.length; i--; ) {\n $ul.attr(attributes[i].name, attributes[i].value);\n }\n\n\n //Convert options to checkbox or radios\n var options = $ul.children('option'),\n name = $ul.attr('name'),\n f = 0;\n $ul.removeAttr('name'),\n\n $.each(options, function(key, option) {\n var $that = $(this),\n itemAttributes = $that[0].attributes,\n value = $that.value,\n label = $that.text(),\n selected = itemAttributes.selected ? \"checked\" : '';\n\n selected += itemAttributes.disabled ? \" disabled\" : '';\n\n var $newLi = $('<li ' + selected + '></li>'), \n $input = $('<input type=\"' + opt.type + '\" id=\"option_' + name + '_' + f + '\" name=\"' + name + '\" value=\"' + value + '\" ' + selected + '/><label for=\"option_' + name + '_' + f + '\">' + label + '</label>');\n $newLi.append($input);\n $that.replaceWith($newLi);\n for (var i = attributes.length; i--; ) {\n $input[0][attributes[i].name] = attributes[i].value;\n }\n\n f++;\n });\n\n //Add Filter Box\n var $filter = $('<input id=\"' + name + '_filter\" class=\"list_filter\" />');\n var list = $ul.children('li');\n filterBox($filter, list);\n\n // add filter and ul to new container\n var $container = $('<div class=\"heftyBox\" id=\"' + name + '_container\"></div>').append($filter, $ul);\n // replace existing element by new container\n $that.after($container).remove();\n\n //Select all box for checkboxes\n if (opt.type == \"checkbox\") {\n var $link = $('<a href=\"#\">Select All</a>')\n .bind('click', function() {\n var $that = $(this);\n //@todo get checked\n // directly using $ul not using specific dom manipulation\n var $checkboxes = $ul.find('input:not([disabled])');\n\n // btw... adding 'checked' attribute to an li is weird... maybe using a data-checked will be better\n if ($checkboxes.length > $checkboxes.filter(':checked').length) {\n $checkboxes.attr('checked', 'checked').closest('li').attr('checked', 'checked');\n } else {\n $checkboxes.removeAttr('checked').closest('li').removeAttr('checked');\n }\n\n $that.text( ($that.text() == \"Select All\") ? \"Select None\" : \"Select All\");\n $ul.trigger('change');\n return false;\n }\n );\n // divided creating and appending. just take one more line and is more readable\n $filter.after($link);\n }\n\n //Write the Data to the DOM\n $ul.data({ heftyBox: opt });\n\n //Apply DOM data\n updateheftyBox($ul);\n\n //Handle Value Change\n $ul.bind('change', function() { updateheftyBox($(this)); }) // change event when clickin\n .delegate('input:checkbox', 'click', function() { // delegate click event on checkbox\n var li = $(this).parent();\n (this.checked) ? li.attr('checked', 'checked') : li.removeAttr('checked');\n\n // trigger change\n $ul.trigger('change');\n });\n\n //scroll to first selected DOM\n if ($ul.find('li[checked]:first').length) {\n var itemTop = $ul.find('li[checked]:first').offset().top || $ul.offset().top,\n ulTop = $ul.offset().top;\n $ul.scrollTop(itemTop - ulTop);\n }\n }\n\n };\n })();\n })(jQuery);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T19:47:00.313",
"Id": "13709",
"Score": "0",
"body": "Thanks, I copied your code into a separate branch on the GitHub and will try refactoring on my own with the advice I get here, then determine the best end result to merge."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T00:52:20.103",
"Id": "8724",
"ParentId": "8714",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "8724",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T19:52:24.300",
"Id": "8714",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"plugin"
],
"Title": "My first jQuery plugin -- Heftybox"
}
|
8714
|
<p>After learning that <code>std::map</code> containers are not inherently atomic and therefore not thread-safe (check out <a href="https://stackoverflow.com/questions/9147258/object-of-shared-pointer-being-deleted-while-instances-of-shared-ptr-are-still-i">this</a> related Stack Overflow question and usage example), I decided to create code that would allow concurrent access to the container.</p>
<pre><code>#ifndef MAP_GUARD_H_
#define MAP_GUARD_H_
/*
This class was designed to make the standard map synchronized for the basic functions.
The intent was for it to be filled with shared_ptr as the value in the pair.
A Grand Central Dispatch serial queue is used for syncronising access to the map rather than raw mutexes.
*/
// A macro to disallow the copy constructor and operator= functions
// This should be used in the private: declarations for a class
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
#include <map>
#ifdef WIN32
#include <xdispatch\dispatch.h>
#else
#include <xdispatch/dispatch.h>
#endif
template <class K, class V>
class map_guard
{
public:
map_guard();
~map_guard();
void clear();
void erase(const K& key);
void insert(const K& key, const V& value);
/* Take a snopshot of map_ and fill target with it (usefull if you want to use iterators) */
void fill_map(std::map<K, V>& target) const;
V find(const K& key) const;
size_t size() const;
bool empty() const;
void swap(std::map<K, V>& map);
private:
void make_swap(std::map<K, V>* map);
void get(std::map<K, V>* target) const;
void get(const K& key, V* target) const;
void get_empty(bool* empty) const;
void get_size(size_t* size) const;
std::map<K, V> map_;
xdispatch::queue* dispatch_queue_;
DISALLOW_COPY_AND_ASSIGN(map_guard);
};
template <class K, class V>
map_guard<K, V>::map_guard() : dispatch_queue_(0)
{
dispatch_queue_ = new xdispatch::queue("test");
}
template <class K, class V>
map_guard<K, V>::~map_guard()
{
if(dispatch_queue_)
{
delete dispatch_queue_;
dispatch_queue_ = 0;
}
}
template <class K, class V>
void map_guard<K, V>::clear()
{
dispatch_queue_->sync(${
map_.clear();
});
}
template <class K, class V>
void map_guard<K, V>::erase(const K& key)
{
dispatch_queue_->sync(${
map_.erase(key);
});
}
template <class K, class V>
void map_guard<K, V>::insert(const K& key, const V& value)
{
dispatch_queue_->sync(${
map_[key] = value;
});
}
template <class K, class V>
void map_guard<K, V>::get(std::map<K, V>* target) const
{
dispatch_queue_->sync(${
target->insert(map_.begin(), map_.end());
});
}
template <class K, class V>
void map_guard<K, V>::get(const K& key, V* target) const
{
dispatch_queue_->sync(${
std::map<K, V>::const_iterator it = map_.find(key);
if(it != map_.end())
{
*target = it->second;
}
});
}
template <class K, class V>
void map_guard<K, V>::fill_map(std::map<K, V>& target) const
{
get(&target);
}
template <class K, class V>
V map_guard<K, V>::find(const K& key) const
{
V temp;
get(key, &temp);
return temp;
}
template <class K, class V>
void map_guard<K, V>::get_size(size_t* size) const
{
dispatch_queue_->sync(${
*size = map_.size();
});
}
template <class K, class V>
size_t map_guard<K, V>::size() const
{
size_t size;
get_size(&size);
return size;
}
template <class K, class V>
void map_guard<K, V>::get_empty(bool* empty) const
{
dispatch_queue_->sync(${
*empty = map_.empty();
});
}
template <class K, class V>
bool map_guard<K, V>::empty() const
{
bool empty;
get_empty(&empty);
return empty;
}
template <class K, class V>
void map_guard<K, V>::swap(std::map<K, V>& map)
{
make_swap(&map);
}
template <class K, class V>
void map_guard<K, V>::make_swap(std::map<K, V>* map)
{
dispatch_queue_->sync(${
map_.swap(*map);
});
}
#endif
</code></pre>
<p>Is this a valid method for solving the problem? Are there other ways that may be more efficient?</p>
|
[] |
[
{
"body": "<p>Use boost::noncopyable instead of DISALLOW_COPY_AND_ASSIGN:</p>\n\n<pre><code> template <class K, class V>\n class map_guard: boost::noncopyable\n {\n</code></pre>\n\n<ol>\n<li><p>boost::noncopyable resides in the first line instead of deep internals</p></li>\n<li><p>DRY -- you do not need to type <code>map_guard</code> again</p></li>\n<li><p>noncopyable.hpp is a small header-only library </p></li>\n</ol>\n\n<hr>\n\n<p>Probably, you do not need special case <code>#include <xdispatch\\dispatch.h></code> because compiler will translate <code>#include <xdispatch/dispatch.h></code> for you.</p>\n\n<hr>\n\n<p>Next, I have a vague idea \"what an xdispatch is\", but it seems to me that placing block in a queue is a costly operation, so locking have to be used. Also, may be lockless algorith will be appropriate, say, based on <a href=\"http://en.wikipedia.org/wiki/Compare-and-swap\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Compare-and-swap</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T23:54:47.423",
"Id": "13654",
"Score": "0",
"body": "Wouldn't `#include <xdispatch/dispatch.h>` work in Windows anyway? Windows supports both characters as path separators."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T00:28:30.687",
"Id": "13655",
"Score": "0",
"body": "@seand My last compiler run under Windows was around 10 years ago."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T23:28:57.143",
"Id": "8722",
"ParentId": "8715",
"Score": "1"
}
},
{
"body": "<p>If you would like to try out c++0x, you have <code>std::mutex</code> and <code>std::lock_guard</code>. An example forwarding some of methods in <code>std::map</code> is shown as following:</p>\n\n<pre><code>//hello.cc\n\n#include <map>\n#include <mutex>\n#include <iostream>\n\ntemplate <class K, class V, class Compare = std::less<K>, class Allocator = std::allocator<std::pair<const K, V> > >\nclass guarded_map {\n private:\n std::map<K, V, Compare, Allocator> _map;\n std::mutex _m;\n\n public:\n void set(K key, V value) {\n std::lock_guard<std::mutex> lk(this->_m);\n this->_map[key] = value;\n }\n\n V & get(K key) {\n std::lock_guard<std::mutex> lk(this->_m);\n return this->_map[key];\n }\n\n bool empty() {\n std::lock_guard<std::mutex> lk(this->_m);\n return this->_map.empty();\n }\n\n // other public methods you need to implement\n};\n\nint main(int argc, char ** argv) {\n guarded_map<int, int> m;\n m.set(1, 10);\n m.set(2, 20);\n m.set(4, 30);\n std::cout<<\"m[2]=\"<<m.get(2)<<std::endl;\n return 0;\n}\n</code></pre>\n\n<p>To compile, you will probably need to add some special flag to your compiler. For example, g++ would be:</p>\n\n<pre><code>g++ -std=c++0x -o hello hello.cc\n</code></pre>\n\n<p>The <code>std::lock_guard</code> here makes things much easier. It locks the mutex in its constructor, and automatically unlock the mutex in its destructor, which means you can initialize a <code>std::lock_guard</code> at the beginning of a block you need to synchronize concurrency, and leave it there, as the lock will be released when this block exit.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-06T05:11:49.753",
"Id": "9737",
"ParentId": "8715",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T20:27:59.117",
"Id": "8715",
"Score": "9",
"Tags": [
"c++",
"multithreading",
"thread-safety",
"synchronization",
"stl"
],
"Title": "Thread-safe std::map accessor"
}
|
8715
|
<p>After scouring the interweb, I am having trouble finding an efficient solution to the following issue (the biggest problem was knowing what to ask):</p>
<p>I'm trying to find a way to write a more efficient version of the jQuery script found on the <a href="http://redesign.mproven.com/sliding_example.html" rel="nofollow">example site</a> (also listed below). The biggest hurdle I'm facing is figuring out a way to dynamically match a trigger element (for example, <code>.logo_wrap div.logo.img1</code>) with its respective animating element (<code>.sliding_titles .img1</code>).</p>
<p>I've added numbers to the end of the <code>div</code>s that need to be matched, I just can't seem to find a way to properly match them, then apply a hover trigger to one and a slide-out animation to the other.</p>
<p>The example site I've created for this post only lists six objects, however there's another site that needs this to be done to 29 separate pairs of objects - which ends up being a ton of code.</p>
<p>Please see example site - which works fine. I just need to find a way to more efficiently write the script associated with it: <a href="http://redesign.mproven.com/sliding_example.html" rel="nofollow">http://redesign.mproven.com/sliding_example.html</a></p>
<p>Any and all help in this matter is greatly appreciated, thank you.</p>
<p>Here's a simple example:</p>
<p>Javascript (jQuery):</p>
<pre><code>$(document).ready(function(){
$('.logo.img1, .logo.img2, ...etc,').fadeTo("fast", 0);
$(".logo.img1").hover(function() {
$(this).stop().animate({"opacity": "1"}, "500");
$('.sliding_titles div.img1').stop().animate({opacity: 1, width: "500px", overflow: "visible" }, 400);
},
function() {
$(this).stop().animate({"opacity": "0"}, "500");
$('.sliding_titles div.img1').stop().animate({opacity: 0, width: "0px", overflow: "hidden" }, 1);
});
$(".logo.img2").hover(function() {
... etc.
});
</code></pre>
<p>HTML (in the order they appear in the <code>body</code> tag):</p>
<p>First are the content modules that slide out when its matched logo is hovered over:</p>
<pre><code><div id="sliding_titles" class="sliding_titles">
<!-- Youtube -->
<div class="img1" rel="slide_youtube">
<img class="fade_overlay" src="images/sliding_fade_overlay.png" width="100" height="110" />
<table>
<tr>
<td>
<img src="images_example/placeholder_100x100.png" width="100" height="100"></td>
<td>
<h3>YouTube slideout placeholder content</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</td>
</tr>
</table>
</div><!-- end .img1 -->
<div class="img2" rel="slide_facebook"> ... etc ... </div>
</code></pre>
<p>Then come the logo <code>div</code>s, which - when hovered - will trigger its respective content div to slide out (listed above):</p>
<pre><code><div class="logo_wrap">
<div class="logo img1" rel="youtube">
</div><!-- end .logo -->
<div class="logo img2" rel="facebook">
</div><!-- end .logo -->
<div class="logo img3" rel="rss">
</div><!-- end .logo -->
... etc ...
</div>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T21:37:38.727",
"Id": "13649",
"Score": "0",
"body": "[Please post the code in the question.](http://codereview.stackexchange.com/faq#questions)"
}
] |
[
{
"body": "<p>`</p>\n\n<pre><code>$(function(){\n\n $('.logo').fadeTo(\"fast\", 0);\n\n $(\".logo\").hover(function() {\n $(this).stop().animate({\"opacity\": \"1\"}, \"500\");\n $('.sliding_titles div#content-'+this.id).stop().animate({opacity: 1, width: \"500px\", overflow: \"visible\" }, 400);},\n function() {\n $(this).stop().animate({\"opacity\": \"0\"}, \"500\");\n $('.sliding_titles div#content-'+this.id).stop().animate({opacity: 0, width: \"0px\", overflow: \"hidden\" }, 1);\n });\n</code></pre>\n\n<p>`</p>\n\n<pre><code><div id=\"sliding_titles\" class=\"sliding_titles\"> \n\n<!-- Youtube -->\n<div id=\"content-img1\" rel=\"slide_youtube\">\n <img class=\"fade_overlay\" src=\"images/sliding_fade_overlay.png\" width=\"100\" height=\"110\" />\n <table>\n <tr>\n <td> \n <img src=\"images_example/placeholder_100x100.png\" width=\"100\" height=\"100\"></td>\n <td>\n <h3>YouTube slideout placeholder content</h3>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>\n </td>\n </tr>\n </table> \n</div><!-- end .img1 -->\n\n<div id=\"content-img2\" rel=\"slide_facebook\"> ... etc ... </div>\n\n\n<div class=\"logo_wrap\">\n\n <div class=\"logo\" id=\"img1\" rel=\"youtube\">\n </div><!-- end .logo -->\n\n <div class=\"logo\" id=\"img2\" rel=\"facebook\">\n </div><!-- end .logo -->\n\n <div class=\"logo\" id=\"img3\" rel=\"rss\">\n </div><!-- end .logo -->\n\n ... etc ...\n\n</div> \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T20:53:00.883",
"Id": "8763",
"ParentId": "8718",
"Score": "1"
}
},
{
"body": "<p>Grekz has made some really good suggestions with regard to html structure. I strongly concur that you should not couple the code with numbered classes!</p>\n\n<p>But I also wanted to give the code a shot as is. So I used the <code>rel</code> to determine which slide to grab.</p>\n\n<pre><code>$(document).ready(function(){\n\n var slideOpen = function() {\n var $this = $(this),\n $slide = $('#sliding_tile div[rel=slide_' + $this.attr('rel') + ']');\n\n $this.stop().animate({opacity: 1}, 500);\n $slide.stop().animate({opacity: 1, width: \"500px\", overflow: \"visible\" }, 400);\n }\n\n var slideClosed = function() {\n var $this = $(this),\n $slide = $('#sliding_tile div[rel=slide_' + $this.attr('rel') + ']');\n\n $this.stop().animate({opacity: 0}, 500);\n $slide.stop().animate({opacity: 0, width: \"0px\", overflow: \"hidden\" }, 1);\n }\n\n $(\".logo[rel]\").fadeTo(\"fast\", 0).hover(slideOpen, slideClosed);\n}\n</code></pre>\n\n<p>I've also found that relying on hover to turn-elements-off is error prone. You will find that quick mouse movements don't fire the mouseout event as expected. There are some good plugins that will help this.</p>\n\n<p>Hope it helps.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-09T00:57:16.080",
"Id": "9847",
"ParentId": "8718",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T21:25:09.293",
"Id": "8718",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "Efficiently matching pairs of elements and applying specific hover trigger/animation to each pair"
}
|
8718
|
<p>I recently started working on a project that had been dropped by the previous dev. When looking through the existing code, I came across this singleton Database Class.</p>
<pre><code>class Database{
private static $instance;
private $PDOInstance;
// Customize when ready
private function __construct(){
try{
$this->PDOInstance = new PDO("mysql:database=testdb;unix_socket=/tmp/mysql.sock", "username" , "password"/* , array driver_options*/);
}catch(PDOException $e){
throw $e;
}
}
public static function getInstance(){
if(!self::$instance){
try{
self::$instance = new self();
}catch(PDOException $e){
return false;
}
}
return self::$instance;
}
public function __clone(){
trigger_error("Cloning forbidden on Singleton", E_USER_ERROR);
}
public function __wakeup(){
trigger_error("Unserializing forbidden on Singleton", E_USER_ERROR);
}
// PDO Function Aliasing
public function __call($function, $args){
if(method_exists($this->PDOInstance, $function)){
return call_user_func_array(array($this->PDOInstance, $function), $args);
}
trigger_error("Unknown PDO Method Called: $function()\n", E_USER_ERROR);
}
}
</code></pre>
<p>I suppose my question revolves around the use of <code>__call()</code> to alias PDO functions. Is this the best way to go about it, and if not, what should be done instead?</p>
<p>As for why the database class doesn't simply extend PDO, from what I understand, PDO has a public <code>__construct()</code>, and when it gets extended, it isn't possible to change the visibility to private, hence this work around.</p>
<p>My instinct is to scrap this class and just rewrite it as a simple PDO wrapper, but I thought I would ask around first.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T15:25:24.597",
"Id": "13739",
"Score": "0",
"body": "Singletons are big trouble. I'd rethink your strategy if I were you. http://gooh.posterous.com/singletons-in-php"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T19:43:31.957",
"Id": "13807",
"Score": "0",
"body": "@GordonM Thanks for the link. I think I will go ahead and drop it."
}
] |
[
{
"body": "<p>A simple workaround, assuming that you want to keep the class a Singleton:</p>\n\n<pre><code>class Database {\n private static $instance;\n private $PDOInstance;\n\n public static function getInstance(){\n if(!self::$instance){\n try{\n self::$instance = new self();\n }catch(PDOException $e){\n return false;\n }\n }\n return self::$instance->getPDOInstance();\n }\n\n public function getPDOInstance() {\n return $this->PDOInstance;\n }\n}\n</code></pre>\n\n<p>Well, more of a <a href=\"http://en.wikipedia.org/wiki/Factory_method_pattern\" rel=\"nofollow\">factory method</a> now, which is silly. But not as silly as <code>__call() / call_user_func_array</code>. If you absolutely need to keep the class's signature as it is, go for it.</p>\n\n<p>If not, a PDO wrapper would be the better approach. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T19:44:02.783",
"Id": "13808",
"Score": "0",
"body": "Thanks for the review. Looking at a comment on the main question, I'm going to drop the singleton aspect of the class and just write a PDO wrapper."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T01:58:53.237",
"Id": "13839",
"Score": "0",
"body": "@Grexis That wasn't really a review, just a workaround :) If you don't need the singleton, go for the wrapper, and when you finish it post it here for a proper review..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T01:08:45.280",
"Id": "8725",
"ParentId": "8723",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "8725",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T00:12:22.523",
"Id": "8723",
"Score": "4",
"Tags": [
"php",
"pdo"
],
"Title": "Using PHP's __call() to emulate a Class instead of Extending"
}
|
8723
|
<p>I have 2 validation groups, VG1 and VG2. I have a button <code>BtnInsert</code> that saves data into <code>Datasource</code>. Its Validation Group is VG2. Now, I want to validate both VG1 and VG2 when a user clicks the <code>BtnInsert</code>.</p>
<pre><code>protected void BtnInsert_click(object sender,EventArgs e)
{
// validate VG1
Page.Validate("VG1");
// Page.Validate("VG2") is not required as BtnInsert is of that group
if(Page.IsValid)
{
// call insert function
}
}
</code></pre>
<p>Is this code right, and by clicking <code>BtnInsert</code>, both groups are validated?</p>
|
[] |
[
{
"body": "<p>AFAIK, you won't get client-side validation of VG2, but otherwise I can't see that it shouldn't work. (There is probably a client-side event and a method you could call to duplicate the behavior for the client)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T11:16:17.310",
"Id": "8804",
"ParentId": "8738",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T13:12:44.350",
"Id": "8738",
"Score": "1",
"Tags": [
"c#",
"asp.net",
"validation"
],
"Title": "Validate several validation groups"
}
|
8738
|
<p>I debated long and hard before posting this question, and I did a lot of experimenting. I just can't seem to work out an 'elegant', concise way to get done what I want done in the manner I want it done. I found it very hard to research because of the difficulty in not knowing exactly what to search for.</p>
<p>Again, I am writing a converter for binary, decimal and hex using Tkinter and not using any of Python's built-in math functions.</p>
<p>In the code I have one class, within it many methods. I have the methods to convert from binary to decimal and hex working correctly (<code>bin_to_dec</code> & <code>bin_to_hex</code>, respectively). I am now working on the 'from decimal' conversions. I have the <code>dec_to_bin</code> method working correctly, as well. My issue is with the <code>dec_to_hex</code> method. I want it to use the <code>dec_to_bin</code> method to convert the string to binary first and then use the <code>bin_to_hex</code> method for the final conversion. In doing this it has to overlook the lines of code that tell the 2 methods to display their results; but rather to store the results and transport them to the <code>dec_to_hex</code> method.</p>
<p>I'm going to post the entire code except for the method that creates the Tkinter widgets:</p>
<pre><code>def base_check(self):
""" Disable Checkbox that's connected with chosen Radiobutton. """
sel_radio = self.base.get()
for radio, cb in self.cb_to_radio.items():
if radio == sel_radio:
cb.configure(state = DISABLED)
else:
cb.configure(state = NORMAL)
def conv_segue(self):
""" Decides and directs towards proper conversion method.
Reading the 'convert from' radiobuttons. """
base = self.base.get()
if base == 'bin':
bits = self.input_str.get()
# test string validity
bit_list = list(bits)
ill_bits = ['2', '3', '4', '5', '6', '7', '8', '9']
for bit in bit_list:
if bit in ill_bits:
self.output_disp.delete(0.0, END)
self.output_disp.insert(0.0, "That bit string is invalid.")
break
else:
self.from_binary(self.dec_bttn, self.hex_bttn)
##
# learned here that I had to break once the match was found (if found) and that a 'for'
# loop can use an else block too
##
elif base == 'dec':
self.from_dec(self.bin_bttn, self.hex_bttn)
elif base == 'hex':
self.from_hex(self.bin_bttn, self.dec_bttn)
def from_binary(self, dec_bttn, hex_bttn):
""" Finds what base to convert to (Decimal or Hex) from binary. """
if self.dec_bttn.get():
self.bin_to_dec()
if self.hex_bttn.get():
self.bin_to_hex()
#if self.dec_bttn.get() and self.hex_bttn.get():
#(self.bin_to_dec, self.bin_to_hex)
def from_dec(self, bin_bttn, hex_bttn):
""" Finds what base to convert to (Binary or Hex) from decimal. """
if self.bin_bttn.get():
self.dec_to_bin()
if self.hex_bttn.get():
self.dec_to_hex()
def dec_to_bin(self):
""" Convert from decimal to binary. """
# get input string and convert to an integer
digits = self.input_str.get()
digits = int(digits)
bit_string = ""
# do the conversion
while digits:
bit, ans = digits%2, digits//2
bit = str(bit)
bit_string += bit
digits = ans
total = bit_string[::-1]
self.total = total
# print output
self.print_result(total)
#return total
def dec_to_hex(self):
bit_str = self.dec_to_bin().self.total
self.bit_str = bit_str
print(self.bit_str)
def bin_to_dec(self):
""" Convert from binary to decimal. """
# get input string
bits = self.input_str.get()
# set exponent
exp = len(self.input_str.get()) - 1
tot = 0
# do conversion
while exp >= 1:
for i in bits[:-1]:
if i == '1':
tot += 2**exp
elif i == '0':
tot = tot
exp -= 1
if bits[-1] == '1':
tot += 1
total = tot
# print output
self.print_result(total)
#return total
def bin_to_hex(self):
""" Convert from binary to hex. """
# get input string
bits = self.input_str.get()
# define hex digits
hex_digits = {
10: 'a', 11: 'b',
12: 'c', 13: 'd',
14: 'e', 15: 'f'
}
# add number of necessary 0's so bit string is multiple of 4
string_length = len(bits)
number_stray_bits = string_length % 4
# test if there are any 'stray bits'
if number_stray_bits > 0:
number_zeros = 4 - number_stray_bits
bits = '0'*number_zeros + bits
string_length = len(bits)
# index slicing positions
low_end = 0
high_end = 4
total = ""
# slice bit string into half byte segments
while high_end <= string_length:
exp = 3
half_byte = bits[low_end:high_end]
# do conversion
tot = 0
while exp >= 1:
for i in half_byte[:-1]:
if i == '1':
tot += 2**exp
elif i == '0':
tot = tot
exp -= 1
if half_byte[-1] == '1':
tot += 1
# check if tot needs conversion to hex digits
for i in hex_digits.keys():
if i == tot:
tot = hex_digits[i]
else:
tot = tot
# store and concatenate tot for each while iteration
tot = str(tot)
total += tot
# move right to next half byte string
low_end += 4
high_end += 4
# print the output
self.print_result(total)
#return total
def print_result(self, total):
""" display the result of conversion. """
self.output_disp.delete(0.0, END)
self.output_disp.insert(0.0, total)
</code></pre>
<p>I've tried to make it as easy to read for anyone who attempts to help me as possible. The <code>dec_to_hex</code> method is a bit of a mess right now, I have been messing with it.
With the code posted I think its a bit more clear what exactly I'm trying to do. Its very simple code as I haven't a lot of Python experience.</p>
<p>Its all in one class, and I'm trying to do it without the need to copy the code from the two methods I want to use for the <code>dec_to_hex</code> method (<code>dec_to_bin</code> & <code>bin_to_hex</code>).</p>
<p>I thought about breaking it into different classes and using inheritance, but I can't see where that will help me at all</p>
<p>My final decision to post the question now while I continue to mess with it came because I'm sure once its figured out I'm going to have learned something very important, and probably a concept or two that I don't have a complete grasp on will become clearer.</p>
<p>I hope someone will be willing to give me a little direction in this matter. I get an adrenalin rush when I see progress getting made. Its also very well commented and docstringed so it shouldn't be a problem for anyone.</p>
<p>I also thought that this would be a great situation to use some equivalent to the XHTML anchors, but then I realized they are about the same as the old <code>goto</code> command from my 6th grade BASIC days and figured Python was too 'clean' to use that.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T09:57:40.833",
"Id": "13676",
"Score": "0",
"body": "Kill dead code and variables; `from_binary` arguments dec_bttn and hex_bttn are useless and should be removed."
}
] |
[
{
"body": "<p>Use more python, e.g. instead of:</p>\n\n<pre><code>for i in hex_digits.keys():\n if i == tot:\n tot = hex_digits[i]\n else:\n tot = tot\n</code></pre>\n\n<p>Remove extraneous keys() and it becomes:</p>\n\n<pre><code>for i in hex_digits:\n if i == tot:\n tot = hex_digits[i]\n else:\n tot = tot\n</code></pre>\n\n<p>Then remove unnecessary else and it is:</p>\n\n<pre><code>for i in hex_digits:\n if i == tot:\n tot = hex_digits[i]\n</code></pre>\n\n<p>And finally remove the loop:</p>\n\n<pre><code>tot = hex_digits.get(i, tot)\n</code></pre>\n\n<p>There I saved you a loop, a branch and 4 out of 5 lines of code.</p>\n\n<p>A few iterations like this over the entire module and you might like your code after all!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T10:00:15.927",
"Id": "13678",
"Score": "0",
"body": "Thanks, I'll go through it and clean it up a bit. My problem is I don't prep with any pseudo-code, I just kinda wing it as I go. Terrible habit, I know."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T15:39:39.287",
"Id": "13686",
"Score": "0",
"body": "@Icsilk, no pseudo code is a terrible habit. I don't know of any serious coders who actually use it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T21:51:30.673",
"Id": "13716",
"Score": "0",
"body": "I write pseudocode from time to time, and I'd consider myself a serious (albeit not professional) coder... but I certainly wouldn't say not using pseudocode is a terrible habit."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T09:32:57.100",
"Id": "8741",
"ParentId": "8740",
"Score": "6"
}
},
{
"body": "<p>you could pass a second parameter to <code>dec_to_bin</code> and <code>dec_to_hex</code> to let the function know whether you want to return a value or print it.</p>\n\n<pre><code>def dec_to_bin(self,ret=0):\n\n ....\n if ret == 0:\n self.print_result(total)\n else:\n return total\n</code></pre>\n\n<p>Then call the function like:</p>\n\n<pre><code>binstr = dec_to_bin(1) #to assign the return value to binstr\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T12:11:43.513",
"Id": "13680",
"Score": "3",
"body": "When python has True and False built in, using numbers to approximate them seems odd..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T09:53:32.440",
"Id": "8742",
"ParentId": "8740",
"Score": "1"
}
},
{
"body": "<p>I'd split out the x_to_y methods into a separate package, and rather than having them do all of input, processing, output, have them just do processing.</p>\n\n<pre><code>def hex_to_bin(hex_input):\n ... processing goes here ...\n return bin_output\n</code></pre>\n\n<p>And then in your GUI app, you have the input and output:</p>\n\n<pre><code>hex_input = self.input_box.get_value()\nbin_output = hex_to_bin(hex_input)\nself.output_box.set_value(bin_output)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T12:14:58.707",
"Id": "8743",
"ParentId": "8740",
"Score": "0"
}
},
{
"body": "<pre><code>def base_check(self):\n \"\"\" Disable Checkbox that's connected with chosen Radiobutton. \"\"\"\n sel_radio = self.base.get()\n\n for radio, cb in self.cb_to_radio.items():\n if radio == sel_radio:\n cb.configure(state = DISABLED)\n else:\n cb.configure(state = NORMAL) \n\ndef conv_segue(self):\n \"\"\" Decides and directs towards proper conversion method. \n Reading the 'convert from' radiobuttons. \"\"\"\n base = self.base.get()\n\n if base == 'bin':\n bits = self.input_str.get()\n\n # test string validity \n bit_list = list(bits)\n</code></pre>\n\n<p>It's not neccessary to listify the bits. You can iterate over a string just like a list.</p>\n\n<pre><code> ill_bits = ['2', '3', '4', '5', '6', '7', '8', '9']\n</code></pre>\n\n<p>I'd make this a string rather then a list and iterate over that.</p>\n\n<pre><code> for bit in bit_list:\n if bit in ill_bits:\n</code></pre>\n\n<p>Instead, I'd use <code>if any(bit in ill_bits for bit in bit_list)</code>. Also, why don't you check for bits that are 1 or 0, rather then explicitly listing the other options. What if the user inputs a letter?</p>\n\n<pre><code> self.output_disp.delete(0.0, END)\n self.output_disp.insert(0.0, \"That bit string is invalid.\")\n break\n else: \n self.from_binary(self.dec_bttn, self.hex_bttn)\n\n ##\n # learned here that I had to break once the match was found (if found) and that a 'for'\n # loop can use an else block too\n ##\n\n elif base == 'dec':\n self.from_dec(self.bin_bttn, self.hex_bttn)\n elif base == 'hex':\n self.from_hex(self.bin_bttn, self.dec_bttn)\n</code></pre>\n\n<p>I don't see this function anywhere</p>\n\n<p>Why do you perform sanity checks for binary, and not the other bases?</p>\n\n<pre><code>def from_binary(self, dec_bttn, hex_bttn):\n \"\"\" Finds what base to convert to (Decimal or Hex) from binary. \"\"\"\n</code></pre>\n\n<p>Why are you ussing dec_bttn and hex_bttn around if you just use <code>self.dec_bttn</code> anyways?</p>\n\n<pre><code> if self.dec_bttn.get():\n self.bin_to_dec() \n\n if self.hex_bttn.get():\n self.bin_to_hex()\n\n #if self.dec_bttn.get() and self.hex_bttn.get():\n #(self.bin_to_dec, self.bin_to_hex)\n\ndef from_dec(self, bin_bttn, hex_bttn):\n \"\"\" Finds what base to convert to (Binary or Hex) from decimal. \"\"\"\n\n if self.bin_bttn.get():\n self.dec_to_bin()\n\n if self.hex_bttn.get():\n self.dec_to_hex()\n\ndef dec_to_bin(self):\n \"\"\" Convert from decimal to binary. \"\"\"\n\n # get input string and convert to an integer\n digits = self.input_str.get()\n digits = int(digits)\n\n bit_string = \"\"\n\n # do the conversion\n while digits:\n bit, ans = digits%2, digits//2\n bit = str(bit)\n bit_string += bit\n digits = ans\n\n total = bit_string[::-1]\n</code></pre>\n\n<p>Python has a function, <code>bin</code> that does this conversion to binary for you. </p>\n\n<pre><code> self.total = total\n\n # print output\n self.print_result(total)\n #return total\n\n\n\ndef dec_to_hex(self):\n bit_str = self.dec_to_bin().self.total\n</code></pre>\n\n<p>What?</p>\n\n<pre><code> self.bit_str = bit_str\n print(self.bit_str)\n</code></pre>\n\n<p>I'm not seeing the hex.</p>\n\n<pre><code>def bin_to_dec(self):\n \"\"\" Convert from binary to decimal. \"\"\"\n # get input string\n bits = self.input_str.get()\n\n # set exponent\n exp = len(self.input_str.get()) - 1\n\n tot = 0\n\n # do conversion\n while exp >= 1:\n for i in bits[:-1]:\n if i == '1':\n tot += 2**exp\n elif i == '0':\n tot = tot \n exp -= 1\n\n if bits[-1] == '1':\n tot += 1\n\n total = tot\n # print output\n self.print_result(total)\n #return total\n</code></pre>\n\n<p>Use <code>int(string_number, 2)</code> to read in a binary number.</p>\n\n<pre><code>def bin_to_hex(self):\n \"\"\" Convert from binary to hex. \"\"\"\n # get input string\n bits = self.input_str.get()\n\n # define hex digits\n hex_digits = {\n 10: 'a', 11: 'b',\n 12: 'c', 13: 'd',\n 14: 'e', 15: 'f'\n }\n\n # add number of necessary 0's so bit string is multiple of 4\n string_length = len(bits)\n number_stray_bits = string_length % 4\n\n # test if there are any 'stray bits'\n if number_stray_bits > 0: \n number_zeros = 4 - number_stray_bits\n bits = '0'*number_zeros + bits\n string_length = len(bits)\n</code></pre>\n\n<p>Python has an rjust method on strings that'll pad strings to a desired length. I think you can simplify this code using that.</p>\n\n<pre><code> # index slicing positions\n low_end = 0\n high_end = 4\n\n total = \"\"\n\n # slice bit string into half byte segments\n while high_end <= string_length:\n</code></pre>\n\n<p>You should really use a for loop like <code>for high_end in xrange(0, string_length, 4):</code>\n exp = 3\n half_byte = bits[low_end:high_end]</p>\n\n<pre><code> # do conversion\n tot = 0\n</code></pre>\n\n<p>Don't abbreviate variables. It saves you almost nothing and makes your code harder to read.</p>\n\n<pre><code> while exp >= 1:\n</code></pre>\n\n<p>This doesn't really serve a purpose because exp is decremented by the inner loop.</p>\n\n<pre><code> for i in half_byte[:-1]:\n</code></pre>\n\n<p>I'd use <code>for exponent, letter in enumerate(halt_byte[::-1])</code>. </p>\n\n<pre><code> if i == '1':\n tot += 2**exp\n\n elif i == '0':\n tot = tot \n</code></pre>\n\n<p>Completely pointless. Doesn't assign variables to themselves</p>\n\n<pre><code> exp -= 1\n\n if half_byte[-1] == '1':\n tot += 1\n</code></pre>\n\n<p>Why didn't you do this in the loop: <code>exp**0 = 1</code></p>\n\n<pre><code> # check if tot needs conversion to hex digits \n for i in hex_digits.keys():\n if i == tot:\n tot = hex_digits[i]\n else:\n tot = tot\n</code></pre>\n\n<p>Its a dictionary. don't use a loop on it. Put all of the numbers in it, not just the non-digit ones. Then use <code>tot = hex_digits[tot]</code></p>\n\n<pre><code> # store and concatenate tot for each while iteration \n tot = str(tot)\n total += tot \n</code></pre>\n\n<p>I'd combine those two lines</p>\n\n<pre><code> # move right to next half byte string \n low_end += 4\n high_end += 4\n</code></pre>\n\n<p>If you use a for loop like I suggested this should be unneccesary.</p>\n\n<p>Actually python has a <code>hex</code> function which will convert a number to hex. It'll replace pretty much this entire function.</p>\n\n<pre><code> # print the output \n self.print_result(total)\n #return total\n\ndef print_result(self, total):\n \"\"\" display the result of conversion. \"\"\"\n self.output_disp.delete(0.0, END)\n self.output_disp.insert(0.0, total)\n</code></pre>\n\n<p>This function doesn't really print. So I'd find a better name.</p>\n\n<p>Here's how I'd approach it.</p>\n\n<pre><code>def convert_base(number_text, from_base, to_base):\n BASES = {\n 'decimal' : 10,\n 'hex' : 16,\n 'binary', 2)\n number = int(number_text, BASES[from_base])\n\n if to_base == 'decimal':\n return str(number)\n elif to_base == 'hex':\n return hex(number)[2:]\n elif to_base == 'binary':\n return bin(number)[2:]\n else:\n raise ValueError('Unknown base: ' + base)\n</code></pre>\n\n<p>In general conversions work best by converting to some neutral format, (in this case, a python integer), and then into your final format. That way you don't have to write conversion between every possible format. Instead, you just a conversion for each format into the neutral format and then out of the neutral format. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T15:38:33.627",
"Id": "8746",
"ParentId": "8740",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T09:13:12.100",
"Id": "8740",
"Score": "3",
"Tags": [
"python",
"converting",
"tkinter"
],
"Title": "Binary/decimal/hex converter using Tkinter"
}
|
8740
|
<p>Recently I had the idea to write a module for the transformation of the dictionary into valid CSS code. And I would like to hear your comments on my code.
License MIT, BSD etc.</p>
<p>The code is very simple:</p>
<pre><code>#pss.py
class PSS:
def __init__(self, obj):
self.obj = obj
self.__data = {}
self.__parse(obj)
def __repr__(self):
return self.__build(self.obj)
def __build(self, obj, string = ''):
for key, value in sorted(self.__data.items()):
if self.__data[key]:
string += key[1:] + ' {\n' + ''.join(value) + '}\n\n'
return string
def __parse(self, obj, selector = ''):
for key, value in obj.items():
if hasattr(value, 'items'):
rule = selector + ' ' + key
self.__data[rule] = []
self.__parse(value, rule)
else:
prop = self.__data[selector]
prop.append('\t%s: %s;\n' % (key, value))
</code></pre>
<p>import module:</p>
<pre><code>#test.py
from pss import *
css = PSS({
'html': {
'body': {
'color': 'red',
'div': {
'color': 'green',
'border': '1px'
}
}
}
})
print(css)
</code></pre>
<p>Result:</p>
<pre><code>html body {
color: red;
}
html body div {
color: green;
border: 1px;
}
</code></pre>
<p>So I need your advice to improve the quality of the code.
Perhaps there are still places that can be done easier?</p>
|
[] |
[
{
"body": "<p>Two random remarks:</p>\n\n<ul>\n<li><p>\"__parse\" isn't a great method name since no actual parsing is going on.</p>\n\n<pre><code> for i in sorted(self.__data.keys()):\n</code></pre></li>\n<li><p>The variable name \"i\" is commonly used for (list) indexes. When iterating over a dict, it's more clear to use \"k\", \"key\" or (preferably) something more descriptive.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T16:51:30.307",
"Id": "8749",
"ParentId": "8747",
"Score": "2"
}
},
{
"body": "<pre><code>#pss.py\n</code></pre>\n\n<p>I'd recommend an actual docstring rather then a comment</p>\n\n<pre><code>__version__ = '1.0'\n\nclass PSS:\n def __init__(self, obj):\n if type(obj) is not dict:\n raise RuntimeError('There\\'s no any objects to parse!')\n</code></pre>\n\n<p>What if its a subclass of dict? What if its a dict-like object? In python we generally do not check types. So I'd just remove this bit. I'd also name it something more meaningful then <code>obj</code></p>\n\n<pre><code> self.obj = obj\n self.__data = {}\n</code></pre>\n\n<p>Use of <code>__</code> is controversial. I'm in the camp that you should only use one undescore.</p>\n\n<pre><code> def __repr__(self):\n return self.__build(self.obj)\n</code></pre>\n\n<p>This isn't what <code>__repr__</code> is for. <code>__repr__</code> should give a python representation of your object, not produce the string version. Look at repr() vs str() on python strings.</p>\n\n<pre><code> def __build(self, obj, string = ''):\n self.__parse(obj)\n</code></pre>\n\n<p>Why parse here instead of in the constructor?</p>\n\n<pre><code> for i in sorted(self.__data.keys()):\n</code></pre>\n\n<p><code>i</code> is a terrible name, it usually means index but you aren't using it that way here</p>\n\n<pre><code> if self.__data[i]:\n</code></pre>\n\n<p>Use <code>for key, value in sorted(self.__data.items()):</code> then you won't need to access <code>self.__data[i]</code></p>\n\n<pre><code> string += i[1:] + ' {\\n' + ''.join(self.__data[i]) + '}\\n\\n'\n</code></pre>\n\n<p>Adding strings can be expensive. Its generally better to build the strings in a list and then join them or use StringIO, and write the string pieces by piece.</p>\n\n<pre><code> return string\n\n def __parse(self, obj, selector = ''):\n for i in obj:\n</code></pre>\n\n<p><code>use for key, value in obj.items()</code> whenever you need both the keys and values in a dict. Python isn't stupid like some other languages</p>\n\n<pre><code> if type(obj[i]) is dict:\n</code></pre>\n\n<p>Checking types is considered bad form in python. If you must differentiate between types it is perferred to check some aspect of the dict interface, such as the items method. </p>\n\n<pre><code> rule = selector + ' ' + i\n</code></pre>\n\n<p>I'd store these as tuples rather then strings. </p>\n\n<pre><code> self.__data[rule] = []\n self.__parse(obj[i], rule)\n\n else:\n prop = self.__data[selector]\n prop.append('\\t%s: %s\\n' % (i, obj[i]))\n</code></pre>\n\n<p>Again, I'd store this as something besides a string. Probably keys in a dictionary.</p>\n\n<pre><code> return self\n</code></pre>\n\n<p>Why <code>return self</code></p>\n\n<p>Parsing usually refers to converting text into some internal representation. But you are actually doing the opposite. You are converting python objects into partial python objects, partial text. That's simply not parsing. Its also not clear that you gain anything by doing this pre-processing before converting entirely over to text.</p>\n\n<pre><code>from pss import *\n\ncss = PSS({\n 'html': {\n 'body': {\n 'color': 'red',\n 'div': {\n 'color': 'green',\n 'border': '1px'\n }\n }\n }\n})\n</code></pre>\n\n<p>I must admit that looks pretty sweet.</p>\n\n<p>Interface-wise, why is this a class? It seems to me that is should be a function. Its a one way transformation from dicts to css string representation. That seems to me to be a fit for a function not a class.</p>\n\n<p>Here is my tackle at the problem:</p>\n\n<pre><code>from StringIO import StringIO\n\ndef write_css(selector, data, output):\n children = []\n attributes = []\n\n for key, value in data.items():\n if hasattr(value, 'items'):\n children.append( (key, value) )\n else:\n attributes.append( (key, value) )\n\n if attributes:\n print >> output, ' '.join(selector), \"{\"\n for key, value in attributes:\n print >> output, \"\\t\", key + \":\", value\n print >> output, \"}\"\n\n for key, value in children:\n write_css(selector + (key,), value, output)\n\n\ndef PSS(data):\n output = StringIO()\n write_css((), data, output)\n return output.getvalue()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T17:21:05.093",
"Id": "13696",
"Score": "0",
"body": "Wow, More thanks! I've considered all your comments and try to avoid more of these errors. In the future I will try to extend the functionality of the one. `return self` is a typo, sorry\n`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T16:51:49.227",
"Id": "8750",
"ParentId": "8747",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "8750",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T16:07:04.260",
"Id": "8747",
"Score": "5",
"Tags": [
"python",
"css",
"hash-map"
],
"Title": "Transforming a Python dictionary into CSS"
}
|
8747
|
<p>I have a category table (brands) and 2 other tables (<code>Pens</code> and <code>Pencils</code>) that have parent-child relation with this table through a field <code>CatID</code>. Now I want to get a list of <code>Brands</code>and number of records in child tables.</p>
<p>I use this query:</p>
<pre><code>Select
B.* ,COUNT(P.ID) as PensCount, COUNT(Pc.ID) as PencilsCount
from
Brands B
left outer join
Pens P on B.ID=P.CatID
left outer join
Pencils Pc on B.ID= Pc.CatID
group by
B.ID,B.Title;
</code></pre>
<p>Is this correct? Is there any way to make this query better?</p>
|
[] |
[
{
"body": "<p>Did you try this query? Did it work? Unless ID and Title are the only columns in the Brands table this query would result in an error. </p>\n\n<p>I would use subqueries for this:</p>\n\n<pre><code>SELECT\n Brands.*,\n (SELECT COUNT(*) FROM Pens WHERE CatID = Brands.ID) AS PensCount,\n (SELECT COUNT(*) FROM Pencils WHERE CatID = Brands.ID) AS PencilsCount\nFROM \n Brands\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T19:24:19.980",
"Id": "8755",
"ParentId": "8748",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "8755",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T16:44:52.700",
"Id": "8748",
"Score": "2",
"Tags": [
"sql",
"sql-server"
],
"Title": "Query to get number of related records in 2 child tables"
}
|
8748
|
<p>I've been trying to learn how to develop jQuery plugins but have little guidance on the matter. I see lots of code on the web, of course, but am not sure what exactly constitutes best practices due to the level of variability in style.</p>
<ul>
<li><p><code>$.notify</code> - Displays a simple notification bar similar to that of WP7's notification bar.</p></li>
<li><p><code>$.every</code> - Calls a callback/handler every n-seconds with an additional delay (used for timing animations)</p></li>
</ul>
<p></p>
<pre><code>(function ($) {
$.notify = function (message, options) {
var bodyElement = $('body');
var controller = bodyElement.data('jscom.NotifyController');
if(controller == undefined || controller == null){
controller = new NotifyController(options);
bodyElement.data('jscom.NotifyController', controller);
}
controller.notify(message, options);
return controller;
};
function NotifyController(options){
// Helper elements & variables
var bodyElement = $('body');
var scope = this;
var notificationElement = bodyElement.find('#JSNotification');
if(notificationElement == undefined || notificationElement.length <= 0){
bodyElement.append('<div id="JSNotification"></div>');
notificationElement = bodyElement.find('#JSNotification');
notificationElement.html('<p></p><div class="progress"><!--progress--></div>');
}
this.updateSettings(options);
this.target = notificationElement;
this.timer = null;
this.timestamp = 0;
this.target.hover(
function() { $(this).addClass('mouse-over'); },
function() { $(this).removeClass('mouse-over'); scope.onMouseOut(); }
);
this.target.every(1, 0, function(){
scope.update();
});
};
NotifyController.prototype.updateSettings = function(options){
/* Setup the settings & options */
var defaults = { timeout: 4000, cssClass: 'default' };
var settings = $.extend(
{ },
defaults,
options
);
this.timeout = settings.timeout;
this.cssClass = settings.cssClass;
};
NotifyController.prototype.notify = function(message, options){
if(this.timer != null){
clearTimeout(this.timer);
this.timer = null;
}
this.target.attr('class', '');
this.updateSettings(options);
var timestamp = new Date();
this.target.find('p').html(
'<span class="datestamp">' +
timestamp.format("h:MM:ss TT").toString() +
'</span><span class="message">' +
message +
'</span>'
)
this.timestamp = timestamp;
this.target.addClass('active').addClass(this.cssClass);
var scope = this;
this.timer = setTimeout(
function() { scope.close(); },
this.timeout
);
};
NotifyController.prototype.update = function(){
if(this.target.hasClass('mouse-over')){
this.timestamp = new Date();
return;
}
var time = new Date();
var delta = time - this.timestamp;
var percent = (delta / this.timeout * 100).toFixed(0);
if(percent > 100) percent = 100;
this.target.find('.progress').css('width', percent.toString() + '%');
};
NotifyController.prototype.onMouseOut = function(){
if(this.timer != undefined && this.timer != null){
clearTimeout(this.timer);
this.timer = null;
}
var scope = this;
this.timer = setTimeout(
function() { scope.close(); },
this.timeout
);
this.timestamp = new Date();
};
NotifyController.prototype.close = function(){
if(this.target.hasClass('mouse-over')){
return;
}
this.target.removeClass('active'); //.removeClass(this.cssClass);
};
/* EVERY CONTROLLER */
$.fn.every = function(interval, pauseInterval, callback, id){
if(id == undefined || id == null) { id = ''; }
var controller = this.data('jscom.EveryController-' + id);
if(controller == undefined || controller == null){
controller = new EveryController(this, interval, pauseInterval, callback);
this.data('jscom.EveryController-' + id, controller);
}
controller.init();
return controller;
};
function EveryController(element, interval, pauseInterval, callback){
this.element = element;
this.interval = interval;
this.pauseInterval = pauseInterval;
this.callback = callback;
this.timerId = null;
}
EveryController.prototype.init = function(){
this.reset();
}
EveryController.prototype.reset = function(){
// Clear the timer
clearTimeout(this.timerId);
var scope = this;
// Wait for a bit...
this.timerId = setTimeout(function() { scope.timeOut(); }, this.interval);
}
EveryController.prototype.timeOut = function () {
// Reset the timer and perform the callback
clearTimeout(this.timerId);
if (this.callback) {
this.callback();
}
// Setup the delay (adjust for animation)
var scope = this;
this.timerId = setTimeout(function () { scope.reset(); }, this.pauseInterval);
}
})(jQuery);
</code></pre>
<p>How to invoke:</p>
<pre><code>$('#TestNotifyTimeoutColor').click(function(event){
event.preventDefault();
$.notify(
'<a href="index.htm">hello, world!</a>',
{ timeout: 1000, cssClass: 'red' }
);
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T19:29:26.557",
"Id": "13705",
"Score": "0",
"body": "C# techniques actually translate to js quite nicely if you are a big-time linq-over-collections user. Basically both languages support and encourage a partially functional paradigm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T19:41:27.323",
"Id": "13708",
"Score": "0",
"body": "Another minor note, $.notify and $.every are terms with a high probability of clashing with other plugins. You might want to prefix them or provide a no-conflict mode."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T20:03:08.730",
"Id": "13710",
"Score": "0",
"body": "Is there any benefit to (what I would call) namespacing them? Such as $.js.notify?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T20:39:04.100",
"Id": "13713",
"Score": "0",
"body": "The benefit is that you decrease the probability of conflicts"
}
] |
[
{
"body": "<p>OK, let's see.</p>\n\n<p>First of all by glancing on the code, you don't seem to know what <code>==</code> does.</p>\n\n<p>Especially by looking at <code>this.timer != undefined && this.timer != null</code> this does the <strong>exact same</strong> check twice as <em>type coercion</em> is happening behind the scenes. Type coercion also makes <code>0 == '' // true</code>. You should <a href=\"http://bonsaiden.github.com/JavaScript-Garden/#types.equality\" rel=\"nofollow\">read up on it</a>.</p>\n\n<p>No, concerning the style, I took the time to refactor your code a bit (while hopefully not introducing any errors :D )</p>\n\n<pre><code>(function ($) {\n\n $.notify = function(message, options) {\n\n var bodyElement = $('body'),\n controller = bodyElement.data('jscom.NotifyController');\n\n if (controller == null) { // using type coercion is fine, but only for a null and undefined check at the same time\n controller = new NotifyController(options);\n bodyElement.data('jscom.NotifyController', controller);\n }\n\n controller.notify(message, options);\n return controller;\n\n };\n\n function NotifyController(options) { // Whitespace before the {\n\n // Helper elements & variables\n var bodyElement = $('body'),\n that = this; // \"scope\" here well, most people use \"that\". There are some people that use \"self\", but keep in mind that there is a global variable called \"self\" that references the window object.\n\n var notificationElement = bodyElement.find('#JSNotification');\n\n if (notificationElement === undefined || notificationElement.length <= 0) {\n bodyElement.append('<div id=\"JSNotification\"></div>');\n notificationElement = bodyElement.find('#JSNotification');\n notificationElement.html('<p></p><div class=\"progress\"><!--progress--></div>');\n }\n\n this.updateSettings(options);\n\n this.target = notificationElement;\n this.timer = null;\n this.timestamp = 0;\n\n // you should avoid putting stuff on the same line\n this.target.hover(function() {\n $(this).addClass('mouse-over');\n\n }, function() {\n $(this).removeClass('mouse-over');\n that.onMouseOut();\n }\n );\n\n this.target.every(1, 0, function() {\n that.update();\n });\n\n };\n\n // Doing NotifyController.prototype.updateSettings = .. is cumbersome and bloated, just assign the prototype object\n // The style below is a lot more readable\n NotifyController.prototype = {\n\n\n updateSettings: function(options) {\n /* Setup the settings & options */\n var defaults = { // again avoid stuff on the same line\n timeout: 4000,\n cssClass: 'default'\n };\n\n // no need here though\n var settings = $.extend({}, defaults, options);\n this.timeout = settings.timeout;\n this.cssClass = settings.cssClass;\n\n },\n\n notify: function(message, options){\n\n if (this.timer != null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n\n this.target.attr('class', '');\n this.updateSettings(options);\n\n var timestamp = new Date();\n\n this.target.find('p').html(\n '<span class=\"datestamp\">' +\n timestamp.format(\"h:MM:ss TT\").toString() +\n '</span><span class=\"message\">' +\n message +\n '</span>'\n )\n\n this.timestamp = timestamp;\n this.target.addClass('active').addClass(this.cssClass);\n\n\n var that = this;\n this.timer = setTimeout(function() {\n that.close();\n\n }, this.timeout);\n\n },\n\n update: function() {\n\n if (this.target.hasClass('mouse-over')) {\n this.timestamp = new Date();\n return;\n }\n\n var time = new Date();\n var delta = time - this.timestamp;\n\n var percent = (delta / this.timeout * 100).toFixed(0);\n\n // Also stay away from shorthand ifs, not a good style to go with.\n if (percent > 100) {\n percent = 100; \n }\n\n this.target.find('.progress').css('width', percent.toString() + '%');\n },\n\n onMouseOut: function() {\n\n if (this.timer != undefined && this.timer != null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n\n var that = this;\n this.timer = setTimeout(\n function() { that.close(); },\n this.timeout\n );\n\n this.timestamp = new Date();\n };\n\n close: function() {\n\n // Whitespace on ifs also helps readability\n // it also aligns the body with the condition :)\n if (this.target.hasClass('mouse-over')){\n return;\n }\n\n this.target.removeClass('active'); //.removeClass(this.cssClass);\n\n }\n\n }\n\n /* EVERY CONTROLLER */\n $.fn.every = function(interval, pauseInterval, callback, id) {\n\n if (id != null) {\n id = '';\n }\n\n var controller = this.data('jscom.EveryController-' + id);\n\n if (controller != null) {\n controller = new EveryController(this, interval, pauseInterval, callback);\n this.data('jscom.EveryController-' + id, controller);\n }\n\n controller.init();\n return controller;\n\n };\n\n function EveryController(element, interval, pauseInterval, callback) {\n\n this.element = element;\n this.interval = interval;\n this.pauseInterval = pauseInterval;\n this.callback = callback;\n this.timerId = null;\n\n }\n\n EveryController.prototype = {\n\n init: function() {\n this.reset();\n },\n\n reset: function() {\n\n // Clear the timer\n clearTimeout(this.timerId);\n\n var that = this;\n\n // Wait for a bit...\n this.timerId = setTimeout(function() {\n that.timeOut();\n\n }, this.interval);\n\n },\n\n timeOut: function () {\n\n // Reset the timer and perform the callback\n clearTimeout(this.timerId);\n if (this.callback) {\n this.callback();\n }\n\n // Setup the delay (adjust for animation)\n var that = this;\n this.timerId = setTimeout(function() {\n that.reset();\n\n }, this.pauseInterval);\n\n }\n\n }\n\n})(jQuery);\n</code></pre>\n\n<p>Other than the stuff I've pointed out, I think it's quite good code ( I've seen a lot of horrible JavaScript from people who come from other languages and try to do some quick \"jQueries\" ).</p>\n\n<p>I suggest that you dig into some of JavaScripts quirks a bit more. I already pulled the shameless plug with the <a href=\"http://bonsaiden.github.com/JavaScript-Garden\" rel=\"nofollow\">JavaScript-Garden</a> but you might consider checking out two great books on the topic:</p>\n\n<ul>\n<li><p><a href=\"http://shop.oreilly.com/product/9780596517748.do\" rel=\"nofollow\">JavaScript: The Good Parts</a> - Pretty much the \"bible\" of JS, you should have read it , but take the author Douglas Crockford with a grain of salt, he's a very opinionated man. You should definitely reflect on his thoughts though, there's a lot of wisdom in the book but you have to know how to use it.</p></li>\n<li><p><a href=\"http://shop.oreilly.com/product/9780596806767.do\" rel=\"nofollow\">JavaScript Patterns</a> I consider this a great book, nothing in there I didn't know before, but I've been doing JS for years and this is a splendid compilation of common Patterns and Idioms and a great built up on top of Crockfords book. Also, if you only have the time to read one, I'd go with this, as it briefly covers some topics from <em>The Good Parts</em> in the beginning.</p></li>\n</ul>\n\n<p>Crockford also did a lot of Video talks on JS just Google for his name with Video and they should pop up :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T23:09:49.090",
"Id": "13719",
"Score": "0",
"body": "Thank you for the help - I updated the code based on your suggestions. Are there any downsides to using the \"NotifyController.prototype = { }\" setup? (https://github.com/jsedlak/jsMetro/blob/1edcceeaf03c8d516dd1a00ee7c8a9f3934d407c/source/content/scripts/jscom.metro-tools.js)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T20:08:53.320",
"Id": "8760",
"ParentId": "8754",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "8760",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T18:30:08.870",
"Id": "8754",
"Score": "4",
"Tags": [
"javascript",
"jquery"
],
"Title": "Am I on the right track with JavaScript/jQuery?"
}
|
8754
|
<p>Does anyone have suggestions on how to refactor this?</p>
<pre><code>$(document).ready(function () {
$("td,select,th").css("min-width", "150px");
$("#cancel").button({
disabled: true
});
$(".group-32 input").datepicker();
$(".group-6 input").datepicker();
$("#0LevelId").change(function () {
var currentYear = (new Date).getFullYear();
$("#0EffectiveDate").val("01/01/" + (currentYear + 1));
});
$("#1LevelId").change(function () {
var currentYear = (new Date).getFullYear();
$("#1EffectiveDate").val("01/01/" + (currentYear + 1));
});
$("#3LevelId").change(function () {
var currentYear = (new Date).getFullYear();
$("#3EffectiveDate").val("01/01/" + (currentYear + 1));
});
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T19:24:42.503",
"Id": "13703",
"Score": "2",
"body": "ID's can't start with a number."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T19:25:11.100",
"Id": "13704",
"Score": "0",
"body": "This really isn't something I'd worry about. Sure you could probably make it shorter but there's nothing particularly smelly about any of it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T19:40:08.920",
"Id": "13707",
"Score": "0",
"body": "@Spencer-Ruport thanks for pointing that out. that may be causing an error i have."
}
] |
[
{
"body": "<p>Since your code is all the same, you can dynamically create your selector:</p>\n\n<pre><code>...\n\n$( '#0LevelId,#1LevelId,#3LevelId' ).change( function(){\n ...\n $( '#' + this.id.substr( 0, 1 ) + 'EffectiveDate' )...\n} );\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T19:34:31.927",
"Id": "13706",
"Score": "0",
"body": "Nice suggestion!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T20:10:32.183",
"Id": "13711",
"Score": "0",
"body": "-1 .. you should use class instead fixed IDs"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T20:35:21.640",
"Id": "13712",
"Score": "2",
"body": "@teresko -- that assumes an associated DOM structure that the OP doesn't state he has. e.g. the ability to write code like `$( this ).find( '.effectiveDate' )`. Since no structure is given, I gave code based on the OP's code instead of telling him to potentially \"refactor everything and do this\""
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T19:22:26.670",
"Id": "8757",
"ParentId": "8756",
"Score": "5"
}
},
{
"body": "<p>Since you're setting the min-width attribute only once and at the start, consider adding this property to an actual css.</p>\n\n<p>Also, as cwolves noticed, you can select all three elements at once. But instead of specifing them by comma, make all the element to be of the same class.</p>\n\n<p>Besides that, it is a good practice to learn about jQuery's selectors before using it, because otherwise you're kind of missing the whole point of the library.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T20:30:47.963",
"Id": "8761",
"ParentId": "8756",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "8757",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T19:20:14.540",
"Id": "8756",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"datetime",
"form"
],
"Title": "Setting some element widths, disabling a button, and initializing some date fields"
}
|
8756
|
<p>My code has to download the source code of a page and parse it for URLs. I want it to ask for number which is increased inside the critical section. My problem happens on thread termination.</p>
<p>Main form code:</p>
<pre><code> unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, OverbyteIcsWndControl, OverbyteIcsHttpProt, StdCtrls,Unit2, Spin;
const
WM_DATA_IN_BUF = WM_APP + 1000;
type
TForm1 = class(TForm)
HttpCli1: THttpCli;
Button1: TButton;
ListBox1: TListBox;
Memo1: TMemo;
Button2: TButton;
SpinEdit1: TSpinEdit;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
FStringSectInit: boolean;
FGoogle: array [0..2] of TGoogle;
FStringBuf: TStringList;
FLink:integer;
procedure HandleNewData(var Message: TMessage); message WM_DATA_IN_BUF;
public
StringSection: TRTLCriticalSection;
property StringBuf: TStringList read FStringBuf write FStringBuf;
property Link: integer read FLink write FLink;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var i:integer;
begin
if not FStringSectInit then
begin
form1.FLink:=0;
InitializeCriticalSection(StringSection);
FStringBuf := TStringList.Create;
FStringSectInit := true;
for i:=0 to 2 do
begin
FGoogle[i]:= TGoogle.Create(true);
SetThreadPriority(FGoogle[i].Handle, THREAD_PRIORITY_BELOW_NORMAL);
FGoogle[i].Resume;
end;
end;
end;
procedure TForm1.HandleNewData(var Message: TMessage);
var k,i,s:integer;
begin
if FStringSectInit then
begin
EnterCriticalSection(StringSection);
s:=flink;
inc(s,8);
flink:=s;
memo1.Lines.Add(FStringBuf.Text);
FStringBuf.Clear;
LeaveCriticalSection(StringSection);
{Now trim the Result Memo.}
end;
if form1.Memo1.Lines.Count>20 then
for k:=0 to 2 do
begin
fgoogle[k].Terminate;
fgoogle[k].WaitFor;
fgoogle[k].Free;
FStringBuf.Free;
DeleteCriticalSection(StringSection);
FStringSectInit := false;
memo1.Lines.Add('Thread is done: ' + inttostr(k));
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
listbox1.Clear;
end;
end.
</code></pre>
<p>Worker thread code:</p>
<pre><code> unit Unit2;
interface
uses
Classes,Windows,IDHTTP, OverbyteIcsWndControl, StdCtrls,OverbyteIcsHttpProt,SysUtils,Dialogs;
type
TGoogle = class(TThread)
private
google:TStringList;
Upit:string;
Broj:integer;
Buffer : TStringList;
httpcli1:THTTPcli;
protected
procedure parsegoogleapi;
procedure SkiniSors;
procedure Execute; override;
public
property StartNum: integer read Broj write Broj;
end;
implementation
uses unit1,StrUtils;
function ExtractText(const Str, Delim1, Delim2: string; PosStart: integer; var PosEnd: integer): string;
var
pos1, pos2: integer;
begin
Result := '';
pos1 := PosEx(Delim1, Str, PosStart);
if pos1 > 0 then
begin
pos2 := PosEx(Delim2, Str, pos1 + Length(Delim1));
if pos2 > 0 then
begin
PosEnd := pos2 + Length(Delim2);
Result := Copy(Str, pos1 + Length(Delim1), pos2 - (pos1 + Length(Delim1)));
end;
end;
end;
function ChangeString(const Value: string; replace:string): string;
var i: Integer;
begin
Result := '';
for i := 1 to Length(Value) do
if Value[i] = ' ' then
Result := Result + replace
else
Result := Result + Value[i]
end;
(*Ovo je procedura za skidanje sorsa*)
procedure TGoogle.SkiniSors;
var
criter:string;
begin
HttpCli1:=THttpCli.Create(nil);
google:=TStringList.Create;
criter:= ChangeString(Upit,'%20');
With HttpCli1 do begin
URL := 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&start=' + inttostr(broj) + '&rsz=large&q=rocksongs';
RequestVer := '1.1';
Connection := 'Keep-Alive';
RcvdStream := TMemoryStream.Create;
try
Get;
except
RcvdStream.Free;
Exit;
(*How can I terminate thread here if I get error*)
end;
RcvdStream.Seek(0,0);
google.LoadFromStream(RcvdStream);
RcvdStream.Free;
ParseGoogleApi;
end;
end;
procedure TGoogle.ParseGoogleApi;
var Pos: integer;
sText: string;
begin
Buffer:= TStringList.Create;
sText := ExtractText(google.Text, '"url":"', '","visibleUrl"', 1, Pos);
while sText <> '' do
begin
buffer.Add(sText);
sText := ExtractText(google.Text, '"url":"', '","visibleUrl"', Pos, Pos);
end;
google.Clear;
end;
procedure TGoogle.Execute;
var i:integer;
begin
while not terminated do
begin
EnterCriticalSection(Form1.StringSection);
Broj:=form1.Link;
skinisors;
Form1.StringBuf.Add(buffer.Text);
LeaveCriticalSection(Form1.StringSection);
PostMessage(Form1.Handle, WM_DATA_IN_BUF, 0, 0);
end;
Google.Free;
Buffer.Free;
httpcli1.Free;
end;
end.
</code></pre>
<p>Also, how do I deal with timeouts with <code>THttpCli1</code>? Is it a smart idea to use <code>Timer</code> inside threads?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T16:30:23.413",
"Id": "13869",
"Score": "1",
"body": "It's been a while since I've done Delphi, but make sure the code between `EnterCriticalSection` and `LeaveCriticalSection` are within `try..finally` to clean up properly in the event of exceptional situations."
}
] |
[
{
"body": "<p>I haven't looked closely at your code .. yet. But I did a similar project some months ago.\nFirst off ... </p>\n\n<pre><code> Exit;\n (*How can I terminate thread here if I get error*)\n</code></pre>\n\n<p>Should be simple enough. Change skinisors into a <code>function skinisors : boolean</code> and let it do the <code>Exit(false);</code></p>\n\n<p>I've just realized you are on Delphi7. I can't remember if you can do a <code>Exit(false)</code> there, so just do it the old-fashioned way.</p>\n\n<pre><code>Result := false;\nExit;\n</code></pre>\n\n<p>Then in your execute of thread, you of course will have to change the main criteria for when to terminate into something that also includes the result of the function.</p>\n\n<p>I remember I used <code>TDownloadUrl</code> for getting a complete URL - and then parsing it with <code>JvclHtmlParser</code>. I can dig up the project and see if it could help you - if you are interested?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T16:08:43.757",
"Id": "13866",
"Score": "0",
"body": "If you can upload it to any free file sharing sites , it would be great.Thanks for answer :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-13T20:27:08.077",
"Id": "14016",
"Score": "0",
"body": "@DanijelMaksimovicMaxa. You could try this.\n\nBuilding on two specifik resources:\n\nWiki TJvHTMLParser:\nhttp://wiki.delphi-jedi.org/wiki/JVCL_Help:TJvHTMLParser\n\nand Using TDownloadURL:\nhttp://delphi.about.com/od/networking/a/html_scraping.htm\n\n...\n `SearchURL := <some url string>;\n // parse \n with TJvHTMLParser.Create(nil) do\n try\n FileName := tmpFileName;\n ClearConditions;\n AddCondition('URL', 'URL', '</td>'); // Look for URL\n OnKeyFoundEx := PageSectionFound; // your method for doing the string thing .....\n AnalyseFile;\n finally\n Free;\n end;`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T07:51:35.053",
"Id": "8849",
"ParentId": "8759",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "8849",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T19:54:35.060",
"Id": "8759",
"Score": "2",
"Tags": [
"multithreading",
"http",
"delphi"
],
"Title": "Parsing a page's source code for URLs"
}
|
8759
|
<p>I'm new to Ruby and trying to do a bit of metaprogramming. I want to declare some "properties" on a class, describing some field names and their access privileges:</p>
<pre><code>class Resource
# my_property(name, privilege => level)
my_property :id, :read => :admin # :write => :none
my_property :name, :read => :all, :write => :owner
my_property :pin, :read => :owner, :write => :owner
# ...
end
</code></pre>
<p>Where privileges are various symbols and levels are <code>[:all, :owner, :admin]</code>, and higher level implies all lower levels.</p>
<p>Later, I want to retreive the information in this way:</p>
<pre><code>res.readable_properties(:admin) # => [:id, :name, :pin]
res.writeable_properties(:admin) # => [:name, :pin]
res.writeable_properties(:all) # => []
</code></pre>
<p>Where method names are based on privilege names plus "able_properties" suffix.</p>
<p>Obviously, those declarations are on class level, so everything should be done only once when class is declared, and not on every instance creation.</p>
<p>I've tried to implement, but while it works fine, I suspect that my code is ugly and kludgy. Could someone please give me a hints on how to improve it? Here's what I came with:</p>
<pre><code>require 'set'
class ResourceBase
class << self
def my_property(name, access)
access_levels = %w[all owner admin].map {|s| s.to_sym}
puts "#{name}: #{access}"
@permissions ||= {}
permit = {}
access_levels.each do |level|
access.each do |permission, min_level|
@permissions[permission] ||= {}
@permissions[permission][level] ||= []
permit[permission] = true if level == min_level
@permissions[permission][level].push(name) if permit[permission]
end
end
@perm_methods ||= Set.new()
@permissions.keys.each do |permission|
next if @perm_methods.include? permission
@perm_methods.add permission
define_method "#{permission}able_properties".to_sym, do |level|
self.class.permissions[permission][level]
end
end
end
def permissions
@permissions
end
end
end
class Resource < ResourceBase
# Levels range: all < owner < admin
# Higher levels imply lower ones (i.e. admin always have owner access)
my_property :id, :read => :admin #, :write => :none
my_property :name, :read => :all, :write => :owner
my_property :pin, :read => :owner, :write => :owner
end
resource = Resource.new
puts "Readable: " + resource.readable_properties(:admin).to_s
puts "Writeable: " + resource.writeable_properties(:admin).to_s
</code></pre>
<p>I seek for <em>any</em> suggestions which could be phrased as "Rather than <em>[how OP did it]</em> it's better to <em>[how it should be done]</em>."</p>
|
[] |
[
{
"body": "<p>Rather than access the possibly uninitialized <code>@permissions</code> instance variable inside <code>my_property</code>, use your wrapper method <code>permissions</code> and put the initialization logic in there. Also use <a href=\"http://apidock.com/ruby/Hash/new/class\" rel=\"nofollow\"><code>Hash.new</code></a> to save you the <code>||=</code> statements. Also, the name list should be a <code>Set</code>, IMHO:</p>\n\n<pre><code>def permissions\n @permissions ||= Hash.new { |h,k| h[k] = Hash.new { |h,k| h[k] = Set.new }}\nend\n</code></pre>\n\n<p>That way you can simply call</p>\n\n<pre><code>permissions[permission][level].add\n</code></pre>\n\n<p>without bothering if the intermediate hashes and sets have been initialized</p>\n\n<p>Some other thoughts:</p>\n\n<ul>\n<li>The second half of your <code>my_property</code> method is only about updating the access methods. This should be a separate method.</li>\n<li>You don't use <code>@perm_methods</code> at all, you can remove it.</li>\n<li>Use <code>map(&:to_sym)</code> (or even better, don't create the temporary string array in the first place, it's not shorter!).</li>\n<li>Don't use <code>to_sym</code> on the first argument to <code>define_method</code>, it shouldn't be necessary.</li>\n<li><p>The <code>min_level</code> part can be improved in style and efficiency. You have at least two options here to get all the affected levels:</p>\n\n<ol>\n<li>Use array slicing: <code>access_levels[access_levels.index(level)..-1]</code></li>\n<li>Use <a href=\"http://apidock.com/ruby/Enumerable/drop_while\" rel=\"nofollow\"><code>drop_while</code></a>: <code>access_levels.drop_while { |level| level != min_level }</code></li>\n</ol></li>\n</ul>\n\n<p>After cleaning this up a bit, I came around with the following (untested) code:</p>\n\n<pre><code>require 'set'\n\nclass ResourceBase\n class << self\n def my_property(name, access)\n access_levels = [ :all, :owner, :admin ]\n puts \"#{name}: #{access}\"\n\n access.each do |perm, min_level|\n access_levels.drop_while { |level| level != min_level }.each do |level|\n permissions[perm][level].add name\n end\n end\n update_permission_methods\n end\n\n def update_permission_methods\n permissions.each do |name, perm|\n define_method(\"#{name}able_properties\") { |level| perm[level] }\n end\n end\n\n def permissions\n @permissions ||= Hash.new { |h,k| h[k] = Hash.new { |h,k| h[k] = Set.new }}\n end\n end\nend\n\nclass Resource < ResourceBase\n # Levels range: all < owner < admin\n # Higher levels imply lower ones (i.e. admin always have owner access)\n my_property :id, :read => :admin #, :write => :none\n my_property :name, :read => :all, :write => :owner\n my_property :pin, :read => :owner, :write => :owner\nend\n\nresource = Resource.new\nputs \"Readable: \" + resource.readable_properties(:admin).to_s\nputs \"Writeable: \" + resource.writeable_properties(:admin).to_s\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T22:02:05.823",
"Id": "13717",
"Score": "0",
"body": "Thank you for a great explaination.\n\nI wonder, if re-defining methods multiple times is considered okay? In your code, `readable_properties` is redefined each time a \"readable\" property is declared (`puts \"defining #{name}able_properties\"` in `update_permission_methods` shows it). This is why I've used `@perm_methods` (although I forgot to add elements to it, shame on me)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T22:29:31.277",
"Id": "13718",
"Score": "1",
"body": "@drdaeman: Hm, it doesn't give me a warning, so it's at least possible. It'd probably be better to check whether the method is already present first."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T21:02:57.583",
"Id": "8766",
"ParentId": "8765",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "8766",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T20:43:34.840",
"Id": "8765",
"Score": "5",
"Tags": [
"ruby"
],
"Title": "Ruby metaprogramming - declaring \"properties\" on a class"
}
|
8765
|
<p>I have reviewed the FAQ and I believed it was yes to all 5 q's of "What questions are on-topic for this site?"</p>
<p>Basically, the code below is used to perform the operation shown in the picture. I'm wondering what I can improve in the attached code to clean it up for future reference. Thanks in advance!
<img src="https://i.stack.imgur.com/LJStH.jpg" alt="enter image description here"></p>
<pre><code>Sub Button1_Click()
Dim orgFilename As String
Dim temp As String
Dim strarray(3) As String
Dim vert(4) As String
Dim vert2(3) As String
Dim newFilename As String
Dim numRows As Integer
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim segCount As Integer
Dim vertex(3, 100) As Double
Dim oldwb As Workbook
Dim newwb As Workbook
orgFilename = Application.GetOpenFilename(FileFilter:="All files (*.), *.", Title:="Please select a file")
If orgFilename = "False" Then Exit Sub
Workbooks.OpenText Filename:=orgFilename, _
Origin:=950, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=True, Semicolon:=False, _
Comma:=False, Space:=True, Other:=False, FieldInfo:=Array(Array(1, 1), _
Array(2, 1), Array(3, 1)), TrailingMinusNumbers:=True
Set oldwb = ActiveWorkbook
Set newwb = Workbooks.Add
oldwb.Activate
Cells(5, 1).Select
numRows = Cells(5, 1).End(xlDown).Row
' Parse through data
segCount = 0
j = 1
For i = 5 To numRows
If Cells(i, 1) <> "VRTX" And segCount <> 0 Then
For k = 1 To segCount - 1
newwb.Worksheets("Sheet1").Cells(j, 1) = "GLINE"
With newwb.Worksheets("Sheet1")
.Cells(j, 2) = vertex(1, k)
.Cells(j, 3) = vertex(3, k)
.Cells(j, 4) = vertex(2, k)
.Cells(j, 5) = vertex(1, k + 1)
.Cells(j, 6) = vertex(3, k + 1)
.Cells(j, 7) = vertex(2, k + 1)
End With
j = j + 1
Next k
segCount = 0
ElseIf Cells(i, 1) = "VRTX" Then
' Save vertices to save an endpoint
vertex(1, segCount + 1) = Cells(i, 3)
vertex(2, segCount + 1) = Cells(i, 4)
vertex(3, segCount + 1) = Cells(i, 5)
segCount = segCount + 1
End If
Next i
' Save as a new file
temp = Mid$(orgFilename, InStrRev(orgFilename, "\") + 1)
temp = Replace$(temp, ".pl", ".csv")
strarray(1) = Left(orgFilename, InStrRev(orgFilename, "\"))
strarray(2) = "processed_"
strarray(3) = temp
newFilename = Join(strarray, "")
newwb.SaveAs Filename:=newFilename, _
FileFormat:=xlCSV, _
Password:="", WriteResPassword:="", ReadOnlyRecommended:=False, _
CreateBackup:=False
End Sub
</code></pre>
|
[] |
[
{
"body": "<p>Some pointers off the top of my head:</p>\n\n<ol>\n<li><p>It's always good practice to have good variable names: <code>i</code>, <code>j</code>, and <code>k</code> aren't bad but they could be more explicit.\n(for example, <code>i</code> could be <code>currentRowIndex</code>)</p></li>\n<li><p><code>\"VRTX\"</code> would be better off as a string constant: <code>Const S_VRTX As String = \"VRTX\"</code></p></li>\n<li><p>I personally like to even out anything like this:</p>\n\n<pre><code>Workbooks.OpenText Filename:=orgFilename, _\n Origin:=950, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _\n xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=True, Semicolon:=False, _\n Comma:=False, Space:=True, Other:=False, FieldInfo:=Array(Array(1, 1), _\n Array(2, 1), Array(3, 1)), TrailingMinusNumbers:=True`\n</code></pre>\n\n<p>to something like this:</p>\n\n<pre><code>Workbooks.OpenText Filename:=orgFilename, _\n Origin:=950, _\n StartRow:=1, _\n DataType:=xlDelimited, _\n TextQualifier:= xlDoubleQuote, _ \n ConsecutiveDelimiter:=True, _\n Tab:=True, _\n Semicolon:=False, _\n Comma:=False, _\n Space:=True, _\n Other:=False, _\n FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1)), _\n TrailingMinusNumbers:=True`\n</code></pre></li>\n<li><p>It might be good to check that you <em>have</em> the requisite amount of data (e.g. 5 rows, 4 columns) before accessing it - say you open a file without the right amount of data, it won't handle it well in almost any language.</p></li>\n<li><p>Turn on <code>Option Explicit</code> and you'll find some things can tell you in advance how to improve themselves :)</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T04:05:57.917",
"Id": "13726",
"Score": "0",
"body": "Thanks for the feedback. I never learned VBA properly, let alone haven't used it in this depth for 3 years. Really interesting points to learn for the next project."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T02:56:31.630",
"Id": "8768",
"ParentId": "8767",
"Score": "2"
}
},
{
"body": "<p>Your code does not look bad overall. Here are my 2 cents:</p>\n\n<ol>\n<li><p>To improve readability, I would split your procedure in sub procedures / functions (does not make a difference if this is the only function in the module, but makes a difference in larger projects). The main procedure could look like this for example (simplified):</p>\n\n<pre><code>Sub main()\n openPlFile\n readPlFile\n writeCsvFile\n saveCsvFile\nEnd Sub\n</code></pre></li>\n<li><p>You could add some error handling logic:</p>\n\n<p>Right after your declarations:</p>\n\n<pre><code>On Error GoTo error_handler\n</code></pre>\n\n<p>And at the end of the code:</p>\n\n<pre><code>Exit Sub\nerror_handler:\n 'code to handle the error for example:\n MsgBox \"There was an error: \" & Err.Description\nEnd Sub\n</code></pre></li>\n<li><p>If performance is an issue there are a few steps to improve the code:</p>\n\n<p><strong>a.</strong> You can turn off ScreenUpdating and turn Calculation to manual (don't forget to turn them back on before exiting AND in the error_handler block if there is one).</p>\n\n<p><strong>b.</strong> If you want to improve performance further, you could use arrays instead of reading from / writing to the spreadsheet directly in a loop (see <a href=\"http://www.avdf.com/apr98/art_ot003.html\" rel=\"nofollow noreferrer\">http://www.avdf.com/apr98/art_ot003.html</a>)</p>\n\n<p><strong>c.</strong> If you want to improve performance even more, you could read and write the files directly without opening / creating workbooks.</p>\n\n<p><strong>d.</strong> I generally avoid using Integer as they use the same memory space as Longs anyway (on 32 or 64 bit systems) - VBA simply applies different overflow rules. Declaring Longs instead of Integers can result in <a href=\"https://msdn.microsoft.com/en-us/library/aa164754(v=office.10).aspx\" rel=\"nofollow noreferrer\">a slight performance gain</a> (not so much in your case, but can be useful when declared in a loop for example)</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-07-26T11:25:21.157",
"Id": "324380",
"Score": "0",
"body": "Regarding 'VBA automatically translates them into Long' this is certainly not the case. If you do `Dim Foo as Integer` and then try to use it as a long (say, loop through a million rows with it) you will get an Overflow error since an Integer can only hold numbers between `-32,768` to `32,768` whereas a Long can hold `-2,147,483,648` to `2,147,483,648`. The benefit of using Longs is that you are highly unlikely to ever encounter a situation where you reach an overflow error with it (and if you do hit the cap, chances are your code is bad)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-07-26T11:26:10.233",
"Id": "324381",
"Score": "0",
"body": "As far as I am aware, there is no performance gain with Longs (they do use more memory after all) but they are much safer than Integers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-07-26T13:31:51.283",
"Id": "324411",
"Score": "0",
"body": "@BrandonBarney If you are using a 32+ bit system, which is very likely to be the case nowadays, Integers effectively use 32 bits although the overflow rules for integers are applied (i.e. behaves as if it were a 16 bit variable). See for example: https://stackoverflow.com/questions/26717148/integer-vs-long-confusion"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-07-26T13:33:22.417",
"Id": "324412",
"Score": "0",
"body": "@BrandonBarney I've amended that section of my answer to clarify."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-07-26T13:35:31.813",
"Id": "324413",
"Score": "0",
"body": "I would argue that, while on the backend you are correct, suggesting that the Integer is being converted to a Long is misleading (case in point, the OP of the question you posted). While the memory used for the `Integer` is different, for all intents and purposes *it is an integer* and not *a Long*. Most users (especially users in the position of the OP) will have no foundation for even understanding how this makes a difference for their code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-07-26T13:37:08.730",
"Id": "324415",
"Score": "0",
"body": "@BrandonBarney Actually they are converted into Longs according to Microsoft: https://msdn.microsoft.com/en-us/library/aa164754(v=office.10).aspx \"*VBA converts all integer values to type Long, even if they are declared as type Integer. Therefore, there is no longer a performance advantage to using Integer variables; in fact, Long variables might be slightly faster because VBA does not have to convert them.*\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-07-26T13:39:48.320",
"Id": "324417",
"Score": "0",
"body": "Again though, the difference here is how the user perceives the variable. If I see an `Integer` I am not thinking of 'How much memory does this variable use?' or 'What incremental gains can I get from using a few bits less/more?' I am instead thinking 'Will I ever go over the max number of an Int.' The user (in the case of the OP) will have no understanding of what gains can be made by not having to Type-Convert (in fact, he is still using Cell references which, on their own, cost far more in performance)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-07-26T13:40:01.000",
"Id": "324418",
"Score": "0",
"body": "@assylias There are exceptions, such as Integers within Types - The size of a Type containing a single Integer is *always* 2 bytes, and not 4 bytes. And IIRC, I did some benchmarking with a HighPerformanceTimer, and couldn't see any performance gain in using Longs over Integers."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T09:53:32.400",
"Id": "8773",
"ParentId": "8767",
"Score": "3"
}
},
{
"body": "<p>The code below is in two parts. I have pasted code with your old code commented out, and then additional comments for clarity. I have also posted a cleaner version with just comments.</p>\n\n<p><strong>Note: From reading the code, it likely wont run properly. I was unable to figure out exactly what your loop is doing, and as a result there are still some bugs. Be sure to fully debug this code before using it.</strong></p>\n\n<h2>Full Version</h2>\n\n<pre><code>Option Explicit\nSub Button1_Click()\n ' Constants are declared at the beginning of the routine.\n Const ROW_SKIP As Long = 5\n\n ' Avoid Dim blocks like these. It is always best to declare variables as close to their initial use\n ' as possible. This makes your code easier to read/maintain as well.\n 'Dim orgFilename As String\n 'Dim temp As String\n 'Dim strarray(3) As String\n 'Dim vert(4) As String\n 'Dim vert2(3) As String\n 'Dim newFilename As String\n 'Dim numRows As Integer\n 'Dim i As Integer\n 'Dim j As Integer\n 'Dim k As Integer\n 'Dim segCount As Integer\n 'Dim vertex(3, 100) As Double\n '\n 'Dim oldwb As Workbook\n 'Dim newwb As Workbook\n\n ' I will declare the variable name, but I will also use a name that is slightly more descriptive.\n ' This will allow others to understand what I am doing. I also encapsulate this in a function to allow for\n ' easy error handling.\n 'orgFilename = Application.GetOpenFilename(FileFilter:=\"All files (*.), *.\", Title:=\"Please select a file\")\n\n\n\n ' Instead of just exiting the sub, handle this error.\n ' If orgFilename = \"False\" Then Exit Sub\n\n Dim InputFileName As String\n InputFileName = GetInputFileName\n\n If InputFileName = vbNullString Then\n ' We can add a messagebox here if needed. For now, we just exit the routine silently.\n Exit Sub\n End If\n\n ' For your field info here, you are using an uninitialized, undeclared, array. What effect are you intending to achieve?\n Workbooks.OpenText _\n Filename:=orgFilename, _\n Origin:=950, _\n StartRow:=1, _\n DataType:=xlDelimited, _\n TextQualifier:= _\n xlDoubleQuote, _\n ConsecutiveDelimiter:=True, _\n Tab:=True, Semicolon:=False, _\n Comma:=False, _\n Space:=True, _\n Other:=False, _\n FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1)), _\n TrailingMinusNumbers:=True\n\n ' I declare more descriptive workbook variable names, and separate the assignments.\n ' Set oldwb = ActiveWorkbook\n ' Set newwb = Workbooks.Add\n\n ' I am changing this to a Sheet reference since you seem to be referring to the ActiveSheet implicitly, and not just the ActiveWorkbook\n Dim CurrentWorksheet As Worksheet\n Set CurrentWorksheet = ActiveSheet\n\n ' While the default scope of `Workbooks.Add` is `Application.Workbooks.Add` it is better to be explicit.\n Dim OutputWorkbook As Workbook\n Set OutputWorkbook = Application.Workbooks.Add\n\n ' No need for Activate. Try to avoid this behavior.\n ' oldwb.Activate\n\n ' Avoid Select as well\n ' Cells(5, 1).Select\n ' numRows = Cells(5, 1).End(xlDown).Row\n\n ' Declare new variable, and qualify the range reference when finding the row. Without the qualifying reference\n ' to `CurrentWorkbook` the `Cells` reference refers to the `ActiveWorkbook`.\n Dim NumberOfRows As Long\n NumberOfRows = CurrentWorksheet.Cells(5, 1).End(xlDown).Row\n\n ' Instead of making changed within the loop, I am just going to rewrite it to make changes easier to read.\n ' Parse through data\n 'segCount = 0\n 'j = 1\n 'For i = 5 To numRows\n ' If Cells(i, 1) <> \"VRTX\" And segCount <> 0 Then\n ' For k = 1 To segCount - 1\n ' newwb.Worksheets(\"Sheet1\").Cells(j, 1) = \"GLINE\"\n ' With newwb.Worksheets(\"Sheet1\")\n ' .Cells(j, 2) = vertex(1, k)\n ' .Cells(j, 3) = vertex(3, k)\n ' .Cells(j, 4) = vertex(2, k)\n ' .Cells(j, 5) = vertex(1, k + 1)\n ' .Cells(j, 6) = vertex(3, k + 1)\n ' .Cells(j, 7) = vertex(2, k + 1)\n ' End With\n ' j = j + 1\n ' Next k\n ' segCount = 0\n ' ElseIf Cells(i, 1) = \"VRTX\" Then\n ' ' Save vertices to save an endpoint\n ' vertex(1, segCount + 1) = Cells(i, 3)\n ' vertex(2, segCount + 1) = Cells(i, 4)\n ' vertex(3, segCount + 1) = Cells(i, 5)\n ' segCount = segCount + 1\n ' End If\n 'Next i\n\n ' Assumes that the UsedRange of the Input sheet is the data we need\n Dim InputData As Variant\n InputData = CurrentWorksheet.UsedRange.Value\n\n Dim SegmentCount As Long\n\n Dim i As Long\n Dim j As Long\n Dim k As Long\n\n j = 1\n\n ' Re-creating your vertex array though it is not at all clear what it is being used for.\n Dim Vertices As Variant\n ReDim Vertices(3, 100)\n\n ' I use a constant variable instead of 5 here since the 5 may change, and it can be difficult to track it down later.\n For i = ROW_SKIP To NumberOfRows\n ' Note: This will always return false on the first pass since SegmentCount will always equal 0\n If InputData(i, 1) <> \"VRTX\" And SegmentCount <> 0 Then\n For k = 1 To segCount - 1\n OutputWorkbook.Worksheets(\"Sheet1\").Cells(j, 1) = \"GLINE\"\n With OutputWorkbook.Worksheets(\"Sheet1\")\n .Cells(j, 2) = Vertices(1, k)\n .Cells(j, 3) = Vertices(3, k)\n .Cells(j, 4) = Vertices(2, k)\n .Cells(j, 5) = Vertices(1, k + 1)\n .Cells(j, 6) = Vertices(3, k + 1)\n .Cells(j, 7) = Vertices(2, k + 1)\n End With\n j = j + 1\n Next k\n SegmentCount = 0\n ElseIf InputData(i, 1) = \"VRTX\" Then\n Vertices(1, SegmentCount + 1) = InputData(i, 3)\n Vertices(2, SegmentCount + 1) = InputData(i, 4)\n Vertices(3, SegmentCount + 1) = InputData(i, 5)\n\n SegmentCount = SegmentCount + 1\n End If\n Next i\n\n ' This can be condensed into a much more concise format\n\n ' Save as a new file\n ' temp = Mid$(orgFilename, InStrRev(orgFilename, \"\\\") + 1)\n ' temp = Replace$(temp, \".pl\", \".csv\")\n\n\n ' strarray(1) = Left(orgFilename, InStrRev(orgFilename, \"\\\"))\n ' strarray(2) = \"processed_\"\n ' strarray(3) = temp\n\n ' newFilename = Join(strarray, \"\")\n\n Dim OutputFileName As String\n\n ' This takes care of the entire operation in one line, and allows others to see what these operations are being used for.\n OutputFileName = Left(orgFilename, InStrRev(orgFilename, \"\\\")) & \"processed_\" & Replace$(Mid$(orgFilename, InStrRev(orgFilename, \"\\\") + 1), \".pl\", \".csv\")\n\n OutputWorkbook.SaveAs Filename:=OutputFileName, _\n FileFormat:=xlCSV, _\n Password:=\"\", _\n WriteResPassword:=\"\", _\n ReadOnlyRecommended:=False, _\n CreateBackup:=False\nEnd Sub\nPrivate Function GetInputFileName() As String\n ' I use a variant declaration because the return of `Cancel` is the Boolean false.\n Dim InputFileNameResult As Variant\n\n InputFileNameResult = Application.GetOpenFilename(FileFilter:=\"All files (*.), *.\", Title:=\"Please select a file\")\n\n If Not InputFileNameResult Then\n GetInputFileName = InputFileNameResult\n Else\n ' You can handle this as needed. For now, we just assume the user wants to exit the routine.\n ' As such, we do nothing.\n End If\nEnd Function\n</code></pre>\n\n<h2>Condensed Version</h2>\n\n<pre><code>Option Explicit\nSub Button1_Click()\n ' Constants are declared at the beginning of the routine.\n Const ROW_SKIP As Long = 5\n\n Dim InputFileName As String\n InputFileName = GetInputFileName\n\n If InputFileName = vbNullString Then\n ' We can add a messagebox here if needed. For now, we just exit the routine silently.\n Exit Sub\n End If\n\n ' For your field info here, you are using an uninitialized, undeclared, array. What effect are you intending to achieve?\n Workbooks.OpenText _\n Filename:=orgFilename, _\n Origin:=950, _\n StartRow:=1, _\n DataType:=xlDelimited, _\n TextQualifier:= _\n xlDoubleQuote, _\n ConsecutiveDelimiter:=True, _\n Tab:=True, Semicolon:=False, _\n Comma:=False, _\n Space:=True, _\n Other:=False, _\n FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1)), _\n TrailingMinusNumbers:=True\n\n ' I am changing this to a Sheet reference since you seem to be referring to the ActiveSheet implicitly, and not just the ActiveWorkbook\n Dim CurrentWorksheet As Worksheet\n Set CurrentWorksheet = ActiveSheet\n\n ' While the default scope of `Workbooks.Add` is `Application.Workbooks.Add` it is better to be explicit.\n Dim OutputWorkbook As Workbook\n Set OutputWorkbook = Application.Workbooks.Add\n\n ' Declare new variable, and qualify the range reference when finding the row. Without the qualifying reference\n ' to `CurrentWorkbook` the `Cells` reference refers to the `ActiveWorkbook`.\n Dim NumberOfRows As Long\n NumberOfRows = CurrentWorksheet.Cells(5, 1).End(xlDown).Row\n\n ' Assumes that the UsedRange of the Input sheet is the data we need\n Dim InputData As Variant\n InputData = CurrentWorksheet.UsedRange.Value\n\n Dim SegmentCount As Long\n\n Dim i As Long\n Dim j As Long\n Dim k As Long\n\n j = 1\n\n ' Re-creating your vertex array though it is not at all clear what it is being used for.\n Dim Vertices As Variant\n ReDim Vertices(3, 100)\n\n ' I use a constant variable instead of 5 here since the 5 may change, and it can be difficult to track it down later.\n For i = ROW_SKIP To NumberOfRows\n ' Note: This will always return false on the first pass since SegmentCount will always equal 0\n If InputData(i, 1) <> \"VRTX\" And SegmentCount <> 0 Then\n For k = 1 To segCount - 1\n OutputWorkbook.Worksheets(\"Sheet1\").Cells(j, 1) = \"GLINE\"\n With OutputWorkbook.Worksheets(\"Sheet1\")\n .Cells(j, 2) = Vertices(1, k)\n .Cells(j, 3) = Vertices(3, k)\n .Cells(j, 4) = Vertices(2, k)\n .Cells(j, 5) = Vertices(1, k + 1)\n .Cells(j, 6) = Vertices(3, k + 1)\n .Cells(j, 7) = Vertices(2, k + 1)\n End With\n j = j + 1\n Next k\n SegmentCount = 0\n ElseIf InputData(i, 1) = \"VRTX\" Then\n Vertices(1, SegmentCount + 1) = InputData(i, 3)\n Vertices(2, SegmentCount + 1) = InputData(i, 4)\n Vertices(3, SegmentCount + 1) = InputData(i, 5)\n\n SegmentCount = SegmentCount + 1\n End If\n Next i\n\n ' This takes care of the entire operation in one line, and allows others to see what these operations are being used for.\n Dim OutputFileName As String\n OutputFileName = Left(orgFilename, InStrRev(orgFilename, \"\\\")) & \"processed_\" & Replace$(Mid$(orgFilename, InStrRev(orgFilename, \"\\\") + 1), \".pl\", \".csv\")\n\n OutputWorkbook.SaveAs Filename:=OutputFileName, _\n FileFormat:=xlCSV, _\n Password:=\"\", _\n WriteResPassword:=\"\", _\n ReadOnlyRecommended:=False, _\n CreateBackup:=False\nEnd Sub\nPrivate Function GetInputFileName() As String\n ' I use a variant declaration because the return of `Cancel` is the Boolean false.\n Dim InputFileNameResult As Variant\n\n InputFileNameResult = Application.GetOpenFilename(FileFilter:=\"All files (*.), *.\", Title:=\"Please select a file\")\n\n If Not InputFileNameResult Then\n GetInputFileName = InputFileNameResult\n Else\n ' You can handle this as needed. For now, we just assume the user wants to exit the routine.\n ' As such, we do nothing.\n End If\nEnd Function\n</code></pre>\n\n<h2>Overall Observations</h2>\n\n<p>There are a number of inefficiencies that are holding you back. First, you are still using <code>Activate</code>, <code>Select</code> and <code>ActiveWorkbook</code>. While there is a time and a place for each of these, it is preferable, by far, to avoid them. You can do this by fully qualifying your references.</p>\n\n<pre><code>SomeWorkbook.Activate\nSheets(\"SomeSheet\").Select\nmsgbox Cells(1,10)\n</code></pre>\n\n<p>Becomes</p>\n\n<pre><code>msgbox SomeWorkbook.Sheets(\"SomeSheet\").Cells(1,10).Value\n</code></pre>\n\n<p>This allows you greater control over your code, and reduces the risk of errors being raised.</p>\n\n<p>For more detail on this, check out this link: <a href=\"https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba-macros\">https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba-macros</a> .</p>\n\n<h2>Dim Blocks</h2>\n\n<p>This is a lesser known rule, but is is an important one to learn as soon as possible. Not only are <code>Dim</code> blocks <em>ugly</em> they make it harder to see bad code.</p>\n\n<p>For example, how many variables do you have declared but never used? What about used and never declared? These are both code smells (with the latter being very likely to cause an error).</p>\n\n<p>To avoid this, declare your variables <strong>as close to their first use as possible</strong>. This comes with the caveat of not declaring them within Loops. Once you follow this practice, your code becomes easier to read and maintain.</p>\n\n<h2>Variable Names</h2>\n\n<p>Variable names should be descriptive, but concise. This sometimes can make it difficult to find the right name, but descriptive names make a difference. For example <code>newFileName</code> is a decent name. We know what it is. On the other hand <code>orgFileName</code> is obscure. I have no clue what this means. </p>\n\n<p>When writing code I tend to think of my procedures as having <code>Inputs</code> and <code>Outputs</code> so <code>orgFileName</code> becomes <code>InputFileName</code> and <code>newFileName</code> becomes <code>OutputFileName</code>. This changes a bit as you get into <code>Functions</code> <code>Subs</code> and <code>Classes</code> but, for in a simplified state this principle works fairly well.</p>\n\n<p>Dont only every use <code>Input</code> and <code>Output</code> though. There are other situations such as <code>segCount</code> which is really a <code>SegmentCount</code> and <code>numRows</code> (fairly strong) which can be <code>NumberOfRows</code>.</p>\n\n<p><strong>Loop Iterators</strong></p>\n\n<p>Loop iterators get away with being able to be less descriptive. Using <code>i, j, k, l, m, n...</code> is generally fine (though if you need that many loop iterators, get help). Be forewarned though that <code>l</code> is difficult to distinguish from <code>1</code> and <code>n</code> is generally used in equations.</p>\n\n<p><strong>Loop Iterator Types</strong></p>\n\n<p>As noted in another answer, the type of <code>Integer</code> should pretty much <strong>never</strong> be used. That is due to the limit of an <code>Integer</code> which is ~32,000 whereas the limit of a long is ~2,000,000,000. Yeah, <code>Long</code> is able to handle <strong>much</strong> bigger numbers.</p>\n\n<h2>Option Explicit</h2>\n\n<p>To say that <code>Option Explicit</code> is vital would be an understatement. I started using it, at the advice of others, and it literally has saved me countless hours of debugging for what would, otherwise be, stupid mistakes.</p>\n\n<p>You can type <code>Option Explicit</code> manually at the beginning of every routine, or you can use this shortcut to change the setting:</p>\n\n<ol>\n<li>ALT + T</li>\n<li>ALT + O</li>\n<li>In the <code>Editor</code> Tab, select the <code>Require Variable Declarations</code> checkbox.</li>\n</ol>\n\n<h2>Rubberduck</h2>\n\n<p>One of the frequent contributors, Mat's Mug, is working on a project called Rubberduck. Him and his team have made it into an amazing tool that is capable of Code Inspections, Refactoring, some better UI elements, and some other really cool stuff. I strongly suggest checking it out here: <a href=\"http://rubberduckvba.com/\" rel=\"nofollow noreferrer\">http://rubberduckvba.com/</a> .</p>\n\n<p>If you have any questions, please don't hesitate to ask. This is a lot to take in at once, but I would be doing you a disservice if I turned a blind eye to common mistakes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-07-26T12:25:39.013",
"Id": "171213",
"ParentId": "8767",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T01:59:30.127",
"Id": "8767",
"Score": "3",
"Tags": [
"vba"
],
"Title": "VBA Data Conversion (random printout -> CSV file)"
}
|
8767
|
<p>This is my first go at implementing the DAO pattern - let alone implementing it for MongoDB with Morphia - I was hoping someone could point out smells and answer questions from my below implementation.</p>
<pre><code>public interface GenericDAO<T, K extends Serializable>
{
public void insert(T entity);
public T queryByKey(Class<T> typeClass, K id);
}
</code></pre>
<p>My implementation of <code>GenericDAO</code> for MongoDB extends Morphia's <code>BasicDAO</code> - <strong>does this seem like the correct placement for this extension?</strong> The super I'm leveraging is performing the connection for me, if I was to drop Morphia and use something else, I would have to change the constructors for each of my DAO implementations, and achieve connection in a different way - <strong>is this a common kind of change people make to their DAO definition?</strong></p>
<pre><code>public class GenericDAOMongoImpl<T, K extends Serializable> extends BasicDAO<T, K>
{
public GenericDAOMongoImpl(Class<T> entityClass) throws UnknownHostException
{
super(entityClass, ConnectionManager.getDataStore());
}
}
</code></pre>
<p>All of my DTO's are coded against interfaces - this is so that I can use things like Morphia's annotations in my DTO's without coupling that specific DTO to any implementation technology.</p>
<pre><code>public interface EntryDTO extends GenericDTO
{
}
@Entity
public class EntryDTOMongoImpl implements EntryDTO
{
@Id
private ObjectId id;
private String name;
private int age;
private ArrayList<String> pets;
public EntryDTOMongoImpl()
{
this.name = "Colin";
this.age = 40;
this.pets = new ArrayList<String>();
pets.add("dog");
pets.add("cat");
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public ObjectId getId()
{
return id;
}
public void setId(ObjectId id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public ArrayList<String> getPets()
{
return pets;
}
public void setPets(ArrayList<String> pets)
{
this.pets = pets;
}
}
</code></pre>
<p>Then my DAO implementation for <code>EntryDTO</code> reads below. <strong>Does it make sense that the <code>EntryDAO</code> interface is parameterized such that it accepts a generic variable that extends <code>EntryDTO</code>? I was hoping I could simply parameterize it with <code>EntryDTO</code> as the generic type, but this causes issues in the below <code>Runner</code> class when I pass the concrete <code>Class</code> <code>EntryDTOMongoImpl.class</code> to the <code>queryByKey</code> method?</strong> </p>
<pre><code>public interface EntryDAO<T extends EntryDTO> extends GenericDAO<T, Serializable>
{
}
public class EntryDAOMongoImpl extends GenericDAOMongoImpl<EntryDTOMongoImpl, ObjectId> implements EntryDAO
{
private static final Logger logger = Logger.getLogger(EntryDAOMongoImpl.class);
public EntryDAOMongoImpl(Class<EntryDTOMongoImpl> entityClass) throws UnknownHostException
{
super(entityClass);
}
public void insert(Object entity)
s
save((EntryDTOMongoImpl) entity);
}
public Object queryByKey(Class typeClass, Serializable id)
{
EntryDTOMongoImpl dto = null;
try
{
dto = (EntryDTOMongoImpl) ConnectionManager.getDataStore().get(typeClass, id);
}
catch(UnknownHostException ex)
{
logger.error(ex);
}
return dto;
}
}
</code></pre>
<p>I'm then creating instances of my DAO's simply like below. This would ideally be done with some DI library.</p>
<pre><code>public class Runner
{
private static final Logger logger = Logger.getLogger(Runner.class);
private EntryDAO entryDAO;
public Runner() throws UnknownHostException
{
this.entryDAO = new EntryDAOMongoImpl(EntryDTOMongoImpl.class);
}
public static void main(String[] args) throws UnknownHostException
{
Runner runner = new Runner();
EntryDTOMongoImpl dtoA = new EntryDTOMongoImpl();
runner.entryDAO.insert(dtoA);
EntryDTOMongoImpl foundA = (EntryDTOMongoImpl) runner.entryDAO.queryByKey(EntryDTOMongoImpl.class, dtoA.getId());
logger.debug(dtoA.getId() + ", " + dtoA.getName());
logger.debug(foundA.getId() + ", " + foundA.getName());
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-13T15:46:51.363",
"Id": "14007",
"Score": "0",
"body": "What is exactly the question?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-14T22:42:04.087",
"Id": "14078",
"Score": "0",
"body": "@GeorgeMauer - the questions are in bold on the original SO post."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-15T05:39:32.807",
"Id": "14094",
"Score": "1",
"body": "You should really take the effort to copy your question over!"
}
] |
[
{
"body": "<p>I disagree with <code>Generic DAO</code> design, reason of it is : </p>\n\n<p>You design generic dao with to generic type <code>T</code>, <code>K</code>, <code>T</code> for entity type and <code>K</code> for entity id. Now I say: </p>\n\n<ol>\n<li><p>What happen with this design if in a part of application we have an entity with two key as <code>primary key</code> (We have this allow in <code>ORM</code>)</p></li>\n<li><p>What happen with this design if we want more operation in data layer such as <code>search</code> or <code>batch insert</code> operations.</p></li>\n</ol>\n\n<p>I suggest following design: </p>\n\n<ul>\n<li>Have for any entity a interface with itself operation.</li>\n<li>Have for any entity a or more implementation of above interface </li>\n<li>Have an interface as <code>DAOFactory</code></li>\n<li>Have a or more implementation of <code>DAOFactory</code>(such as <code>Spring</code> implementation or <code>Guice</code> or manually or etc)</li>\n</ul>\n\n<p>I show your application by my suggest design:</p>\n\n<p>first I define a entity for sample it's <code>Person</code>:</p>\n\n<pre><code>public class Person \n{\n private long id;\n private String name;\n private int age; \n\n /*\n * define accessible methods\n */\n}\n</code></pre>\n\n<p>Next define an interface as <code>DAO</code> for above entity:</p>\n\n<pre><code>public interface PersonDAO\n{\n public void insert(Person entity);\n public Person queryByKey(long id);\n public void remove(long id);\n public List<Person> searchByCriteria(/*custom criteria*/);\n}\n</code></pre>\n\n<p>In next step, we define implementation for <code>PersonDAO</code> interface by <code>MongoDB</code>:</p>\n\n<pre><code>public class MongoDBPersonDAO implements PersonDAO\n{\n\n public void insert(Person entity)\n {\n /*\n * MongoDB api for insert an entity\n */\n }\n\n public Person queryByKey(long id)\n {\n /*\n * MongoDB api for find an entity by its id\n */\n }\n\n public void remove(long id)\n {\n /*\n * MongoDB api for remove an entity by its id\n */\n }\n\n public List<Person> searchByCriteria(/*custom search criteria*/)\n {\n /*\n * MongoDB api for find set of entity by set of search criteria\n */\n }\n}\n</code></pre>\n\n<p>Now, we designed dao layer for <code>Person</code> entity. In next step we have to define a <code>Factory API</code>: </p>\n\n<pre><code>public DAOFactory\n{\n public PersonDAO getPersonDAO(); \n\n /*\n * define other abstract methods for other DAOs\n */\n}\n</code></pre>\n\n<p>In next step we define an implementation for above factory, in this case we want define <code>Spring</code> implementation:</p>\n\n<pre><code>public SpringDAOFactory implements DAOFactory\n{\n private ApplicationContext dao_ctx;\n /*\n * define constructor that spring context files parameter\n */\n public SpringDAOFactory(String...contexts)\n {\n this.dao_ctx = new ClassPathXmlApplicationContext(contexts);\n }\n\n public PersonDAO getPersonDAO()\n {\n return dao_ctx.getBean(PersonDAO.class);\n }\n}\n</code></pre>\n\n<p>saw we define a spring implementation of dao factory with context files path. We in next step show a sample of spring context:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<beans xmlns=\"http://www.springframework.org/schema/beans\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://www.springframework.org/schema/beans\nhttp://www.springframework.org/schema/beans/spring-beans.xsd\">\n\n <bean id=\"PersonDao\" class=\"MongoDBPersonDAO\" scope=\"singleton\">\n <!--\n do dependency injection\n --> \n </bean>\n</beans>\n</code></pre>\n\n<p>and in last we define a <code>singleton dao factory</code> by spring implementation as following:</p>\n\n<pre><code>DAOFactory dao_factory = new SpringDAOFactory(); // this instance have to singleton\n</code></pre>\n\n<p>and use <code>dao_factory</code> where need to it.\nWith this define we separating <code>DAO APIs</code> from its implementation and <code>PersonDao</code> from its implementations also. With this design any entity has itself dao and its operations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-25T14:56:40.783",
"Id": "31849",
"Score": "1",
"body": "`such as Spring implementation or Juice` - here's typo? I think you mean Guice (google DI framework)? Can you add some example with Guice? Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-26T10:22:00.927",
"Id": "31872",
"Score": "1",
"body": "@MyTitle Oh,Thanks, I correct it. Sorry, I don't working with `Guice` at real situation and only read its documents on web."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-04T13:42:49.743",
"Id": "9693",
"ParentId": "8769",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T04:28:07.737",
"Id": "8769",
"Score": "4",
"Tags": [
"java",
"design-patterns"
],
"Title": "Correct DAO implementation?"
}
|
8769
|
<p>The background is my question is SO <a href="https://stackoverflow.com/questions/9131481/how-to-create-a-list-of-totals-for-durations">How to create a list of totals for durations?</a>
where I found a recursive solution that I want to review. I could not test it for higher levels than 1 but to the best of my knowledge it should work.</p>
<p>What I'm trying to do is calculate a kind of "highscore", i.e. a level based on sales during the two historical months where sales where the most. So I find the oldest purchase, use the helper methods to calculate the bonus for that period and then check to see whether that period is the entitling to a level upgrade. It's basically going through all the historical orders.</p>
<p>Is my recursion written correctly?</p>
<pre><code>def level(self):
startdate = model.Order.all().filter('status =', 'PAID'
).filter('distributor_id =',
self._key.id()).get().created.date()
last_day_nextmonth = startdate + relativedelta(months=2) \
- timedelta(days=1)
total = self.personal_silver(startdate, last_day_nextmonth) + self.non_manager_silver(startdate, last_day_nextmonth)
if total >= 125:
level = 5
elif total >= 75:
level = 4
elif total >= 25:
level = 3
elif total >= 2:
level = 2
else:
level = 1
return self.levelHelp(level, last_day_nextmonth + timedelta(days=1))
def levelHelp(self, level, startdate):
last_day_nextmonth = startdate + relativedelta(months=2) \
- timedelta(days=1)
total = self.personal_silver(startdate, last_day_nextmonth) + self.non_manager_silver(startdate, last_day_nextmonth)
if total >= 125:
newlevel = 5
elif total >= 75:
newlevel = 4
elif total >= 25:
newlevel = 3
elif total >= 2:
newlevel = 2
else:
newlevel = 1
maxlevel = level if level > newlevel else newlevel
nextstart = last_day_nextmonth + timedelta(days=1)
now = datetime.now().date()
if nextstart > now: #next start in is the future
return maxlevel
else: return self.levelHelp(maxlevel, nextstart)
</code></pre>
<p>The helper functions are </p>
<pre><code>def non_manager_silver(self, startdate, enddate):
silver = 0
timeline = date(startdate.year, startdate.month, 1)
downline = User.query(User.sponsor == self._key).fetch()
distributor = self
while distributor.has_downline():
downline = User.query(User.sponsor
== distributor.key).fetch()
for person in downline:
orders = model.Order.all().filter('distributor_id =',
person.key.id()).filter('created >',
startdate).filter('created <',
enddate).filter('status =', 'PAID'
).fetch(999999)
for order in orders:
for (idx, item) in enumerate(order.items):
purchase = model.Item.get_by_id(long(item.id()))
amount = int(order.amounts[idx])
silver = silver + amount * purchase.silver \
/ 1000.000
distributor = person
return silver
def personal_silver(self, startdate, enddate):
p_silver = 0
timeline = date(startdate.year, startdate.month, 1) # first day of month
orders = model.Order.all().filter('distributor_id =',
self._key.id()).filter('created >',
timeline).filter('created <', enddate).filter('status ='
, 'PAID').fetch(999999)
for order in orders:
for (idx, item) in enumerate(order.items):
purchase = model.Item.get_by_id(long(item.id()))
amount = int(order.amounts[idx])
p_silver = p_silver + amount * purchase.silver \
/ 1000.000 # remember amounts
return p_silver
</code></pre>
|
[] |
[
{
"body": "<pre><code>def level(self):\n startdate = model.Order.all().filter('status =', 'PAID'\n ).filter('distributor_id =',\n self._key.id()).get().created.date()\n last_day_nextmonth = startdate + relativedelta(months=2) \\\n - timedelta(days=1)\n</code></pre>\n\n<p>Continuing lines with <code>\\</code> is generally frowned upon. Either split it onto multiple lines or wrap the expression with parenthesis</p>\n\n<pre><code> total = self.personal_silver(startdate, last_day_nextmonth) + self.non_manager_silver(startdate, last_day_nextmonth)\n</code></pre>\n\n<p>I think writing a self.silver(start_date, end_date) function would make sense to get the sum of those two.</p>\n\n<pre><code> if total >= 125:\n level = 5\n elif total >= 75:\n level = 4\n elif total >= 25:\n level = 3\n elif total >= 2:\n level = 2\n else:\n level = 1\n</code></pre>\n\n<p>I'd store all of these levels in a list like [0, 2, 25, 75, 125]. Then I'd use functions from bisect to figure out which level I was at.</p>\n\n<pre><code> return self.levelHelp(level, last_day_nextmonth + timedelta(days=1))\n\n\ndef levelHelp(self, level, startdate):\n\n last_day_nextmonth = startdate + relativedelta(months=2) \\\n - timedelta(days=1)\n total = self.personal_silver(startdate, last_day_nextmonth) + self.non_manager_silver(startdate, last_day_nextmonth)\n if total >= 125:\n newlevel = 5\n elif total >= 75:\n newlevel = 4\n elif total >= 25:\n newlevel = 3\n elif total >= 2:\n newlevel = 2\n else:\n newlevel = 1\n</code></pre>\n\n<p>Deja Vu! You've got the exact same code again, at the very least, move the common code into another function.</p>\n\n<pre><code> maxlevel = level if level > newlevel else newlevel\n</code></pre>\n\n<p>Use <code>maxlevel = max(level, newlevel)</code></p>\n\n<pre><code> nextstart = last_day_nextmonth + timedelta(days=1)\n now = datetime.now().date()\n if nextstart > now: #next start in is the future\n return maxlevel\n else: return self.levelHelp(maxlevel, nextstart)\n</code></pre>\n\n<p>You shouldn't really be using recursion here. This is very naturally a while loop. I think if you rewrite this as a while loop, it'll be clearer and you'll be able to combine these two functions.</p>\n\n<pre><code>def non_manager_silver(self, startdate, enddate):\n silver = 0\n timeline = date(startdate.year, startdate.month, 1)\n</code></pre>\n\n<p>I'm not clear why you back this up to the start of the month rather then using the startdate.</p>\n\n<pre><code> downline = User.query(User.sponsor == self._key).fetch()\n</code></pre>\n\n<p>This has no effect, because you throw it away as soon as you enter the loop</p>\n\n<pre><code> distributor = self\n while distributor.has_downline():\n downline = User.query(User.sponsor\n == distributor.key).fetch()\n\n for person in downline:\n orders = model.Order.all().filter('distributor_id =',\n person.key.id()).filter('created >',\n startdate).filter('created <',\n enddate).filter('status =', 'PAID'\n ).fetch(999999)\n</code></pre>\n\n<p>Why 999999?</p>\n\n<pre><code> for order in orders:\n for (idx, item) in enumerate(order.items):\n</code></pre>\n\n<p>No need for those parens.</p>\n\n<pre><code> purchase = model.Item.get_by_id(long(item.id()))\n amount = int(order.amounts[idx])\n</code></pre>\n\n<p>Using <code>int</code> and <code>long</code> seems a little odd. Are you converting from strings?</p>\n\n<pre><code> silver = silver + amount * purchase.silver \\\n / 1000.000\n</code></pre>\n\n<p>Use <code>silver += amount * purchase.silver / 1000.000</code></p>\n\n<pre><code> distributor = person\n</code></pre>\n\n<p>See, here is where you should be using recursion. I assume that you are trying to go through the downlines of all the downlines. However, as your code is written, you'll only go through the downlines of the last member of the downline.</p>\n\n<pre><code> return silver\n\ndef personal_silver(self, startdate, enddate):\n p_silver = 0\n timeline = date(startdate.year, startdate.month, 1) # first day of month\n orders = model.Order.all().filter('distributor_id =',\n self._key.id()).filter('created >',\n timeline).filter('created <', enddate).filter('status ='\n , 'PAID').fetch(999999)\n for order in orders:\n for (idx, item) in enumerate(order.items):\n purchase = model.Item.get_by_id(long(item.id()))\n amount = int(order.amounts[idx])\n p_silver = p_silver + amount * purchase.silver \\\n / 1000.000 # remember amounts\n\n return p_silver\n</code></pre>\n\n<p>This function is pretty much exactly the same as the previous function. You should be able to move common parts into a function.</p>\n\n<p>I'd approach this whole thing quite differently.</p>\n\n<pre><code>def find_downline(distributor):\n \"\"\"\n Given a distributor, collect all the members of his downline into a list\n \"\"\"\n downline = [distributor]\n immediate_downline = User.query(User.sponsor == distributor.key)\n for member in immediate_downline:\n downline.extend( find_downline(member) )\n return downline\n\ndef find_orders(distributor):\n return model.Order.all().filter('distributor_id =',\n self._key.id()).filter('status ='\n , 'PAID').fetch()\n\ndef silver_in_order(order):\n total = 0\n for item, amount in zip(order.items, order.amounts):\n purchase = model.Item.get_by_id(long(item.id()))\n total += amount * purchase.silver\n return total\n\ndef silver_bimonth(distributor):\n bimonths = collections.defaultdict(int)\n for member in find_downline(distributor):\n for order in find_orders(member):\n date = order.created.date\n bimonth_index = (date.year * 12 + date.month) / 2\n bimonths[bimonth_index] += silver_in_order(order)\n return = max(bimonths.value)\n\ndef level(distributor):\n silver = silver_bimonth(distributor)\n return bisect.bisect_left(LEVELS, silver) + 1\n</code></pre>\n\n<p>Zero testing. Probably doesn't work. But it should give an idea of an alternate approach. Basically, I figure that since you are going to fetch all the orders anyways, it makes more sense to fetch them all figure which bimonthly period they belong to, and figure out the maximum that way.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T20:21:03.783",
"Id": "8787",
"ParentId": "8770",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "8787",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T05:27:12.273",
"Id": "8770",
"Score": "7",
"Tags": [
"python",
"recursion",
"datetime"
],
"Title": "Calculate highscores based on sales data"
}
|
8770
|
<p>The code for the <code>LevelParser</code> is shown below. It is also documented using Java-doc; the docs are in the project directory.</p>
<p>Now by improving this piece of code, I do <strong>not</strong> mean optimizing it to incomprehension, or improving its performance. What I want is to make it a bit more readable and easier to maintain. Right now, in my opinion, it is a mess.</p>
<p>When I was writing it, I focused only on it <em>working</em> and didn't care about its readability and design. And I regret it now. But I can't completely rewrite it from scratch because it is closely connected with the entire project, and that would ultimately mean rewriting the entire project.</p>
<p>Is there any way to only improve parts of the code, making it more readable, without a complete rewrite? Because now that it is written and bug-free, unless I find any new bugs, I won't be looking at it for a few days, I'll be focusing on other features. When I give a second look to it, say, two weeks later, I don't want to end up like this:</p>
<p><img src="https://i.stack.imgur.com/LYhlU.jpg" alt="https://fbcdn-sphotos-a.akamaihd.net/hphotos-ak-ash4/399886_298637500185135_241806149201604_816235_1320960193_n.jpg"></p>
<p>Code (also on <a href="https://github.com/intermediate-hacker/Pro_RPG/blob/master/src/pro/LevelParser.java" rel="nofollow noreferrer">GitHub</a>):</p>
<pre><code>package pro;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JPanel;
public class LevelParser {
List<Sprite> tileArray = new ArrayList<Sprite>();
Map<Character, String> tileMapping = new HashMap<Character, String>();
Map<Character, String> messageMapping = new HashMap<Character, String>();
Point offset = new Point(0,0);
Dimension levelSize = new Dimension(0,0);
Dimension tileSize;
JPanel frame;
/* Constructors */
public LevelParser(Dimension tileSize, JPanel frame) {
super();
this.tileSize = tileSize;
this.frame = frame;
}
public LevelParser( int w, int h, JPanel applet ){
this( new Dimension(w,h), applet );
}
/* Other Methods */
public void reset(){
tileArray.clear();
tileMapping.clear();
messageMapping.clear();
offset = new Point(0,0);
levelSize = new Dimension(0,0);
}
/* Getters and Setters */
/* Parser Lists */
public List<Sprite> getTiles() {
return tileArray;
}
public List<Sprite> getTileArray() {
return tileArray;
}
public void setTileArray(List<Sprite> tileArray) {
this.tileArray = tileArray;
}
public Map<Character, String> getTileMapping() {
return tileMapping;
}
public void setTileMapping(Map<Character, String> tileMapping) {
this.tileMapping = tileMapping;
}
public void setTiles(List<Sprite> tiles) {
this.tileArray = tiles;
}
public Dimension getTileSize() {
return tileSize;
}
public void setTileSize(Dimension tileSize) {
this.tileSize = tileSize;
}
/* Members */
public JPanel getApplet() {
return frame;
}
public void setApplet(JPanel applet) {
this.frame = applet;
}
public int getTileWidth(){
return getTileSize().width;
}
public void setTileWidth(int w){
this.tileSize.width = w;
}
public int getTileHeight(){
return getTileSize().height;
}
public void setTileHeight(int h){
this.tileSize.height = h;
}
public Point getOffset() {
return offset;
}
public void setOffset(Point offset) {
this.offset = offset;
}
/* Level Size */
public Dimension getLevelSize() {
return levelSize;
}
public void setLevelSize(Dimension levelSize) {
this.levelSize = levelSize;
}
public void setLevelWidth(int w){
levelSize.width = w;
}
public int getLevelWidth(){
return levelSize.width;
}
public void setLevelHeight(int h){
levelSize.height = h;
}
public int getLevelHeight(){
return levelSize.height;
}
/* Collision Detection */
public boolean checkCollision( AstroSprite plyr ){
for( Sprite s : tileArray ){
if ( s.isCollideable() && s.isCollidingRect(plyr) ){
// if player is moving or the tiles are scrolling...
if(plyr.getVectorY() < 0 || offset.y > 0) plyr.setTop(s.getBottom());
else if(plyr.getVectorY() > 0 || offset.y < 0) plyr.setBottom(s.getTop());
else if(plyr.getVectorX() < 0 || offset.x > 0) plyr.setLeft(s.getRight());
else if(plyr.getVectorX() > 0 || offset.x < 0) plyr.setRight(s.getLeft());
}
}
return false;
}
public Sprite getCollidingTile( Sprite plyr ){
for( Sprite s : tileArray ){
if ( s.isCollideable() && s.isCollidingRect(plyr) ){
return s;
}
}
return null;
}
public void showTileMessage(AstroSprite plyr){
int dx = 0, dy = 0;
if ( plyr.getDirection() == AstroSprite.LEFT ){
dx = -2;
}
else if ( plyr.getDirection() == AstroSprite.RIGHT ){
dx = 2;
}
else if ( plyr.getDirection() == AstroSprite.UP ){
dy = -2;
}
else if ( plyr.getDirection() == AstroSprite.DOWN ){
dy = 2;
}
plyr.move(dx, dy);
Sprite s = getCollidingTile(plyr);
if ( s != null ){
Character c = getTileMappingKeyFromSprite( s );
if (messageMapping.containsKey(c)){
TextMessage.Display( messageMapping.get(c) );
}
}
plyr.move(-dx, -dy);
}
/* Lists etc. */
public Character getTileMappingKeyFromSprite( Sprite s ){
/* It definitely has an Image Url, because all tile sprites'
* Image URLs were set in the parseLine method, Note that this
* won't work on ordinary sprites.
*/
if ( tileMapping.containsValue( s.getImageUrl() ) ){
return Utility.getKeyByValue(tileMapping, s.getImageUrl());
}
return null;
}
/* Drawing */
public void drawTiles( Graphics g ){
for( Sprite s : tileArray ){
s.move(offset.x, offset.y);
if( onScreen( s, frame ) ){
if ( ! s.draw(g) )
g.drawImage(s.getImage(),
s.getX(),
s.getY(),
getTileWidth(), getTileHeight(), getApplet());
}
}
}
public void updateTiles(){
for( Sprite s : tileArray ){
if ( onScreen( s, frame ) ){
s.update(frame);
}
}
}
boolean onScreen(Sprite spr, JPanel applet){
if ( spr.getX() < applet.getWidth() && spr.getY() < applet.getHeight() ){
return true;
}
return false;
}
/* Parsing */
/* Mapping */
public void parseTileMapping( String filename ){
try{
BufferedReader reader = new BufferedReader( new FileReader(filename) );
String line;
while( (line = reader.readLine()) != null ){
if (line.startsWith("$")){
String[] tmp = line.split("=");
String p = tmp[0].substring(1).trim();
tileMapping.put( p.charAt(0), tmp[1].trim() );
if ( tmp.length > 2 ){
messageMapping.put( p.charAt(0), tmp[2].trim() );
}
}
}
} catch(FileNotFoundException e){
System.out.println("Could not find " + filename);
System.exit(1);
} catch( IOException e){
System.out.println("Could not read line!");
System.exit(1);
}
}
/* Level */
public void parseLevel( String filename ){
parseTileMapping( filename );
BufferedReader reader;
try{
reader = new BufferedReader( new FileReader(filename) );
parseTiles( reader );
} catch(FileNotFoundException e){
System.out.println("Could not find " + filename );
System.exit(1);
}
}
public void parseTiles( BufferedReader reader ){
String line;
try{
int count = 1;
while( (line = reader.readLine()) != null){
if( ! line.startsWith("#") && ! line.startsWith("$") ){
parseLine( line, count++ );
}
}
}catch(IOException e){
System.out.println("Failed to read line!");
System.exit(1);
}
}
void parseLine( String line, int count ){
int x = 0, y = count;
for( int i = 0; i < line.length(); i++){
char c = line.charAt(i);
Image img = null;
if (tileMapping.containsKey(c)){
img = Toolkit.getDefaultToolkit().getImage( ConfigurationLoader.IMAGE_URL
+ tileMapping.get(c) );
}
if ( img != null ){
Sprite s = new Sprite( new Point(x * getTileWidth(), y * getTileHeight()),
new Dimension( getTileWidth(), getTileHeight() ),
img);
/* c definitely exists, otherwise img would have been null */
s.setImageUrl( tileMapping.get(c) );
if ( Character.isDigit(c)) s.setCollideable(false);
tileArray.add( s );
}
x++;
setLevelWidth( Math.max( x*getTileWidth(), getLevelWidth() ) );
setLevelHeight( Math.max( y*getTileHeight(), getLevelHeight() ) );
}
}
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>public class LevelParser {\n List<Sprite> tileArray = new ArrayList<Sprite>();\n Map<Character, String> tileMapping = new HashMap<Character, String>();\n Map<Character, String> messageMapping = new HashMap<Character, String>();\n\n Point offset = new Point(0,0);\n Dimension levelSize = new Dimension(0,0);\n\n Dimension tileSize;\n JPanel frame;\n</code></pre>\n\n<p>At this point I'm suspicious. What does a Parser need a Panel? </p>\n\n<pre><code> /* Getters and Setters */\n</code></pre>\n\n<p>I'm suspicious of getters and setters. They often indicate that other classes are too tightly coupled with this one. Do you actually need all these getters and setters? I try to minimize them.</p>\n\n<pre><code> /* Collision Detection */\n\n public boolean checkCollision( AstroSprite plyr ){\n</code></pre>\n\n<p>What? Is there a tax on vowels? I recommend avoiding abbreviations. It doesn't really save you anything and makes your code harder to read</p>\n\n<pre><code> for( Sprite s : tileArray ){\n if ( s.isCollideable() && s.isCollidingRect(plyr) ){\n</code></pre>\n\n<p>Why <code>isCollidingRect</code> rather then <code>isColliding</code>? I'd also check isCollidable inside <code>isCollidingRect</code> and just have it return False when its not a collidable object.</p>\n\n<pre><code> // if player is moving or the tiles are scrolling...\n if(plyr.getVectorY() < 0 || offset.y > 0) plyr.setTop(s.getBottom());\n else if(plyr.getVectorY() > 0 || offset.y < 0) plyr.setBottom(s.getTop());\n else if(plyr.getVectorX() < 0 || offset.x > 0) plyr.setLeft(s.getRight());\n else if(plyr.getVectorX() > 0 || offset.x < 0) plyr.setRight(s.getLeft());\n</code></pre>\n\n<p>Vector doesn't imply movement, which I think you are saying here. I'd suggest maybe getVelocity(). This also really seems be something which should actually be player's concern. Its player whose position being modified to handle the collision, so it really ought to be the player object whose concerned with that.</p>\n\n<pre><code> }\n }\n\n return false;\n }\n\n public void showTileMessage(AstroSprite plyr){\n int dx = 0, dy = 0;\n if ( plyr.getDirection() == AstroSprite.LEFT ){\n dx = -2;\n }\n else if ( plyr.getDirection() == AstroSprite.RIGHT ){\n dx = 2;\n }\n else if ( plyr.getDirection() == AstroSprite.UP ){\n dy = -2;\n }\n else if ( plyr.getDirection() == AstroSprite.DOWN ){\n dy = 2;\n }\n</code></pre>\n\n<p>Dx and dy should really be a vector object of some kind. You should also have a function that gives you a vector given a direction. That way you can get the vector you want without breaking into 4 separate cases like this.</p>\n\n<pre><code> plyr.move(dx, dy);\n\n Sprite s = getCollidingTile(plyr);\n if ( s != null ){\n Character c = getTileMappingKeyFromSprite( s );\n\n if (messageMapping.containsKey(c)){\n TextMessage.Display( messageMapping.get(c) );\n }\n</code></pre>\n\n<p>The class name is LevelParser. Its clear that not really what this class is doing. You appear to performing display in this class as well as collision handling. I'd suggest that you really want to have the display code in a seperate class.\n }</p>\n\n<pre><code> plyr.move(-dx, -dy);\n }\n\n /* Lists etc. */\n\n public Character getTileMappingKeyFromSprite( Sprite s ){\n /* It definitely has an Image Url, because all tile sprites'\n * Image URLs were set in the parseLine method, Note that this\n * won't work on ordinary sprites.\n */\n\n if ( tileMapping.containsValue( s.getImageUrl() ) ){\n return Utility.getKeyByValue(tileMapping, s.getImageUrl());\n }\n</code></pre>\n\n<p>Having to reverse lookup through a dictionary usually hints that somethings not quite right. The question is why you want the Character?</p>\n\n<pre><code> return null;\n</code></pre>\n\n<p>Do you really want to return null? I'm guessing that shouldn't happen during execution. If so, you should throw an exception or something. There's no point handing null of to some code and getting a null pointer exception from some unrelated piece of code when you can pinpoint the problem here.\n }</p>\n\n<pre><code> /* Drawing */\n\n public void drawTiles( Graphics g ){\n for( Sprite s : tileArray ){\n\n s.move(offset.x, offset.y);\n</code></pre>\n\n<p>So, I'm kinda gathering that you move by offset once a frame or something. That's not really suggested by the name offset. Also, its generally considered better to avoid mixing drawing and logic.</p>\n\n<pre><code> if( onScreen( s, frame ) ){ \n</code></pre>\n\n<p>Does this really help you? See your drawing API almost certainly checks the bounds for you, and doesn't draw images that won't end up being displayed. So you may not be getting any benefit out of doing this check.</p>\n\n<pre><code> if ( ! s.draw(g) )\n g.drawImage(s.getImage(), \n s.getX(),\n s.getY(),\n getTileWidth(), getTileHeight(), getApplet());\n</code></pre>\n\n<p>The draw drawing really should be in the Sprite class. The sprite class is the one with all the information about how to draw. </p>\n\n<pre><code> }\n }\n }\n\n public void updateTiles(){\n for( Sprite s : tileArray ){\n if ( onScreen( s, frame ) ){\n s.update(frame);\n }\n</code></pre>\n\n<p>I find it slightly odd that you don't update your offscreen sprites.</p>\n\n<pre><code> }\n }\n\n boolean onScreen(Sprite spr, JPanel applet){\n if ( spr.getX() < applet.getWidth() && spr.getY() < applet.getHeight() ){\n return true;\n }\n\n return false;\n }\n</code></pre>\n\n<p>You don't need ifs to return bools</p>\n\n<pre><code>return spr.getX() < applet.getWidth() && spr.getY() < applet.getHeight();\n</code></pre>\n\n<p>Less messy.</p>\n\n<pre><code> /* Parsing */\n\n /* Mapping */\n\n public void parseTileMapping( String filename ){\n try{\n BufferedReader reader = new BufferedReader( new FileReader(filename) );\n\n String line;\n\n while( (line = reader.readLine()) != null ){\n\n if (line.startsWith(\"$\")){\n String[] tmp = line.split(\"=\");\n</code></pre>\n\n<p><code>tmp</code> is a bad variable name, it tells me nothing except that its a variable.</p>\n\n<pre><code> String p = tmp[0].substring(1).trim();\n</code></pre>\n\n<p>A comment explaining why you are doing this would be good.</p>\n\n<pre><code> tileMapping.put( p.charAt(0), tmp[1].trim() );\n\n if ( tmp.length > 2 ){\n messageMapping.put( p.charAt(0), tmp[2].trim() );\n }\n</code></pre>\n\n<p>Your parsing doesn't really check the text very completely. It'll accept a lot of variations. That might be good enough, I'd just be more strict.</p>\n\n<pre><code> }\n\n }\n\n } catch(FileNotFoundException e){\n System.out.println(\"Could not find \" + filename);\n System.exit(1);\n } catch( IOException e){\n System.out.println(\"Could not read line!\");\n System.exit(1); \n }\n</code></pre>\n\n<p>I'd recommend not just killing the program. Instead, I'd raise an exception indicating the failure to load the file. Sure that may just kill the program, but it feels cleaner to me. I'd also make sure to extract information from the exception object as to what went wrong. The error code might be useful.</p>\n\n<pre><code> }\n\n /* Level */\n public void parseLevel( String filename ){\n\n parseTileMapping( filename );\n\n BufferedReader reader;\n try{\n reader = new BufferedReader( new FileReader(filename) );\n</code></pre>\n\n<p>It's a little odd to read open the file twice.</p>\n\n<pre><code> parseTiles( reader );\n</code></pre>\n\n<p><code>parseTileMapping</code> takes a filename and <code>parseTiles</code> takes a Reader. I'd suggest more consistency.</p>\n\n<pre><code> } catch(FileNotFoundException e){\n System.out.println(\"Could not find \" + filename );\n System.exit(1);\n }\n\n }\n\n public void parseTiles( BufferedReader reader ){\n\n String line;\n\n try{\n\n int count = 1;\n</code></pre>\n\n<p>I'd call this <code>row</code> so that its easier to grasp why you are counting.</p>\n\n<pre><code> while( (line = reader.readLine()) != null){\n\n if( ! line.startsWith(\"#\") && ! line.startsWith(\"$\") ){\n parseLine( line, count++ );\n }\n }\n\n }catch(IOException e){\n System.out.println(\"Failed to read line!\");\n System.exit(1);\n }\n }\n\n void parseLine( String line, int count ){\n int x = 0, y = count;\n</code></pre>\n\n<p>Why not name the parameter y?</p>\n\n<pre><code> for( int i = 0; i < line.length(); i++){\n\n char c = line.charAt(i);\n Image img = null;\n\n if (tileMapping.containsKey(c)){\n img = Toolkit.getDefaultToolkit().getImage( ConfigurationLoader.IMAGE_URL\n + tileMapping.get(c) );\n }\n</code></pre>\n\n<p>Do you really want to handle the situation that the map contain a character that wasn't defined? Perhaps you should be raising an exception here.</p>\n\n<pre><code> if ( img != null ){\n\n Sprite s = new Sprite( new Point(x * getTileWidth(), y * getTileHeight()),\n new Dimension( getTileWidth(), getTileHeight() ),\n img);\n\n /* c definitely exists, otherwise img would have been null */\n s.setImageUrl( tileMapping.get(c) ); \n\n if ( Character.isDigit(c)) s.setCollideable(false);\n\n tileArray.add( s );\n }\n\n x++;\n setLevelWidth( Math.max( x*getTileWidth(), getLevelWidth() ) );\n setLevelHeight( Math.max( y*getTileHeight(), getLevelHeight() ) );\n }\n }\n}\n</code></pre>\n\n<p>Overall the class is doing too many different things. It purports to be a parser but only spends a relatively small amount of time doing that. Here is a list of your functions:</p>\n\n<pre><code>public void reset(){\npublic boolean checkCollision( AstroSprite plyr ){\npublic Sprite getCollidingTile( Sprite plyr ){\npublic void showTileMessage(AstroSprite plyr){\npublic Character getTileMappingKeyFromSprite( Sprite s ){\npublic void drawTiles( Graphics g ){\npublic void updateTiles(){\nboolean onScreen(Sprite spr, JPanel applet){\npublic void parseTileMapping( String filename ){\npublic void parseLevel( String filename ){\npublic void parseTiles( BufferedReader reader ){\nvoid parseLine( String line, int count ){\n</code></pre>\n\n<p>Firstly, I'll note that much of the code is concerned not with parsing but managing a group of sprites. So let's create a SpriteGroup class that will handle all that logic.</p>\n\n<pre><code>class SpriteGroup\n public boolean checkCollision( AstroSprite plyr ){\n public Sprite getCollidingTile( Sprite plyr ){\n public void showTileMessage(AstroSprite plyr){\n public void drawTiles( Graphics g ){\n public void updateTiles(){\n boolean onScreen(Sprite spr, JPanel applet){\n public void addSprite(Sprite sprite);\n\nclass LevelParser\n public Character getTileMappingKeyFromSprite( Sprite s ){\n public void parseTileMapping( String filename ){\n public void parseLevel( String filename, SpriteGroup sprites ){\n public void parseTiles( BufferedReader reader ){\n void parseLine( String line, int count ){\n</code></pre>\n\n<p>Next I'll observe that the TileMapping works somewhat seperately from the rest of the tile parsing. So I'd extract that into its own class</p>\n\n<pre><code>class TileMapping\n public Character getTileMappingKeyFromSprite( Sprite s ){\n public void parseTileMapping( String filename ){\n public Sprite spriteForCharacter(Character character);\n\nclass LevelParser\n public void parseLevel( String filename, SpriteGroup sprites ){\n public void parseTiles( BufferedReader reader ){\n void parseLine( String line, int count ){\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T06:09:33.100",
"Id": "13771",
"Score": "0",
"body": "+1, Thanks, from your code, I gather that the main problem ( along with many smaller ones) was that I was trying to do too much in a single class. So if I break the code up into the smaller classes you have suggested, along with all the other minor improvements you've highlighted, it will be better to maintain, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T15:10:25.340",
"Id": "13790",
"Score": "0",
"body": "@IntermediateHacker, that's the idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T19:56:27.363",
"Id": "13810",
"Score": "0",
"body": "@IntermediateHacker, I should note: without only a partial idea of what's going in your code my suggestions may or may not apply. Use your own judgement."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T05:20:43.427",
"Id": "8795",
"ParentId": "8771",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "8795",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T07:18:09.707",
"Id": "8771",
"Score": "2",
"Tags": [
"java",
"game",
"parsing",
"graphics"
],
"Title": "Game level parser"
}
|
8771
|
<p>This is my first OOP coding project and I would appreciate any constructive criticism as to how I could have used the benefits of Java and OOP to better effect. How would you have implemented this differently? I have been learning Java for less than a week but I hope to go on to make Android apps. See here for this applet working and also source code:
<a href="http://fleawhale.net/java/SlidePuzz2/" rel="nofollow">http://fleawhale.net/java/SlidePuzz2/</a></p>
<p>SlidePuzz2.java</p>
<pre><code>import java.applet.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import javax.imageio.*;
import java.util.*;
import javax.swing.Timer;
public class SlidePuzz2 extends Applet implements MouseMotionListener, MouseListener {
private static final long serialVersionUID = 1L;
static Integer animal;
static Integer grid;
static int piece;
static Board board;
static Element playButton;
static Element loadingText;
static boolean startGame;
Timer aniTimer;
static String[] imgUrls = { "7028/6814220663_4813a81531",
"7162/6814220921_acb3aa92ee", "7029/6814221019_41323ace8b" };
static String imgUrlFlickr = "http://farm8.staticflickr.com/";
public void init() {
startGame = false;
setSize(420, 420);
addMouseMotionListener(this);
addMouseListener(this);
new ElemText(50, 50, "Select animal:");
new ElemOption(65, 80, "mouse", "animal");
new ElemOption(65, 110, "cat", "animal");
new ElemOption(65, 140, "dog", "animal");
new ElemText(250, 50, "Select grid:");
new ElemOption(265, 80, "3x3", "grid");
new ElemOption(265, 110, "4x4", "grid");
new ElemOption(265, 140, "5x5", "grid");
new ElemOption(265, 170, "6x6", "grid");
new ElemOption(265, 200, "7x7", "grid");
playButton = new ElemOption(40, 280, "Play Game >>", "play", 36, false);
}
public void game() {
startGame = false;
animal = (Integer)Element.options.get("animal");
grid = (Integer)Element.options.get("grid");
grid = grid.intValue()+3;
piece = 420/grid;
board = new Board(grid);
Element.setVisibility(false);
Image img = null;
BufferedImage img_cr;
URL url = null;
try {url = new URL(imgUrlFlickr+imgUrls[animal]+"_o.jpg");}
catch (MalformedURLException e1) {}
try {img = ImageIO.read(url);}
catch (IOException e) {}
PieceLoc pl = new PieceLoc();
ArrayList pls = new ArrayList();
for(int x=0; x<grid; x++) {
for(int y=0; y<grid; y++) {
pl = new PieceLoc();
pl.x = x;
pl.y = y;
pls.add(pl);
}
}
Random r = new Random();
for(int x=0; x<grid; x++) {
for(int y=0; y<grid; y++) {
if (x==grid-1 && y==grid-1) break;
img_cr = ((BufferedImage)img).getSubimage(x*piece, y*piece, piece, piece);
pl = (PieceLoc)pls.remove(r.nextInt(pls.size()));
//pl.x=x; pl.y=y; // uncomment to cheat the game
board.add(new ElemImg(pl.x*piece, pl.y*piece, img_cr), pl);
}
}
board.makeClickables();
repaint();
}
public class AniTimer implements ActionListener {
public Element animating;
private PieceLoc blank;
private int orig_x;
private int orig_y;
private long timeStart;
private int delta;
public AniTimer(Element e, PieceLoc pl) {
animating = e;
blank = pl;
orig_x = animating.x;
orig_y = animating.y;
timeStart = System.currentTimeMillis();
}
public void actionPerformed(ActionEvent evt) {
int dx = (blank.x*piece-orig_x);
int dy = (blank.y*piece-orig_y);
int t = 200;
delta = (int)(System.currentTimeMillis()-timeStart);
if (delta>t) delta=t;
animating.x = orig_x + dx*delta/t;
animating.y = orig_y + dy*delta/t;
repaint();
if (delta==t) {
aniTimer.stop();
animating.updateCA();
board.checkCompleted();
}
}
}
public void paint(Graphics g) {
g.drawImage(Element.draw(),0,0,this);
if(startGame) game();
}
public void update(Graphics g) {
paint(g);
}
public void mouseMoved(MouseEvent evt) {
int x = evt.getX();
int y = evt.getY();
if(Element.isClickable(x, y)) setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
else setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
repaint();
}
public void mousePressed(MouseEvent evt) {
int x = evt.getX();
int y = evt.getY();
Element e = Element.clicked(x, y);
if(e==null) return;
if( e.type=="img") {
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
aniTimer = new Timer(30, new AniTimer(e, board.getBlankPl()));
aniTimer.start();
board.clicked(e);
} else if (e.group!=null && e.group=="play") {
loadingText = new ElemText(70, 255, "Loading game, please wait...");
startGame = true;
}
repaint();
}
public void destroy() {
destroy();
}
public void mouseDragged(MouseEvent evt) {}
public void mouseExited(MouseEvent evt) {}
public void mouseEntered(MouseEvent evt) {}
public void mouseClicked(MouseEvent evt) {}
public void mouseReleased(MouseEvent evt) {}
}
class PieceLoc {
int x;
int y;
}
</code></pre>
<p>Element.java</p>
<pre><code>import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.*;
public class Element {
public int x;
public int y;
private int h;
private int w;
private int minX;
private int minY;
private int maxX;
private int maxY;
public int mouseBleed;
private Image img;
public Image imgAlt;
public boolean visible;
public boolean clickable;
private boolean useAlt;
public String type;
public String group;
public Integer value;
public static HashMap options = new HashMap();
private static ArrayList elems = new ArrayList();
private static ArrayList clickables = new ArrayList();
public static int imgCount = 0;
public Element(int x, int y, String type, boolean visible, boolean clickable) {
this.x = x;
this.y = y;
this.type = type;
this.visible = visible;
this.clickable = clickable;
this.useAlt = false;
elems.add(this);
}
static Image draw () {
Image di;
BufferedImage buff = new BufferedImage(420, 420, BufferedImage.TYPE_INT_RGB);
Graphics2D g = buff.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, 420, 420);
for (int i=0;i<elems.size();i++) {
Element e = (Element)elems.get(i);
if (e.useAlt) di = e.imgAlt;
else di = e.img;
if(e.visible) g.drawImage(di, e.x, e.y, null);
}
return buff;
}
private Dimension getTextDim(String s, Font f) {
BufferedImage buff = new BufferedImage(420, 420, BufferedImage.TYPE_INT_RGB);
Graphics2D g = buff.createGraphics();
g.setFont(f);
FontMetrics metrics = g.getFontMetrics();
int w = metrics.stringWidth(s);
int h = metrics.getHeight();
return new Dimension(w, h);
}
public Image drawText(String s, Font f, boolean invert) {
Dimension dim = getTextDim(s, f);
int w = (int)dim.getWidth();
int h = (int)dim.getHeight();
int x = f.getSize();
BufferedImage buff = new BufferedImage(w+x*2, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = buff.createGraphics();
g.setFont(f);
g.setColor(Color.WHITE);
g.fillRect(0, 0, w+x*2, h);
if (invert) g.setColor(Color.BLACK);
else g.setColor(Color.WHITE);
g.fillRect(x, 0, w, h);
g.fillOval(h/4, -1, h, h+1);
g.fillOval(w+h/4, -1, h, h+1);
if (invert) g.setColor(Color.WHITE);
else g.setColor(Color.BLACK);
g.drawString(s, x, x);
return buff;
}
public Image drawBlank(int w, int h) {
BufferedImage buff = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = buff.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, w, h);
return buff;
}
public void setImg(Image img) {
this.img = img;
this.w = img.getWidth(null);
this.h = img.getHeight(null);
updateCA();
}
public void updateCA() {
this.minX = this.x-this.mouseBleed;
this.minY = this.y-this.mouseBleed;
this.maxX = this.x+this.w+this.mouseBleed;
this.maxY = this.y+this.h+this.mouseBleed;
}
static boolean isClickable(int x, int y) {
for (int i=0;i<elems.size();i++) {
Element e = (Element) elems.get(i);
if(!e.clickable || !e.visible) continue;
if(x>e.minX && x<e.maxX && y>e.minY && y<e.maxY) {
if(e.group!=null) changeSelected(e);
return true;
}
}
changeSelected();
return false;
}
static Element clicked(int x, int y) {
int a;
String groupClicked="";
for (int i=0;i<elems.size();i++) {
Element e = (Element)elems.get(i);
if(!e.clickable || !e.visible) continue;
else if(x>e.minX && x<e.maxX && y>e.minY && y<e.maxY) {
if(e.group=="restart") {
destroyVisible();
setVisibility(true);
SlidePuzz2.loadingText.visible = false;
break;
} else if(e.group!=null) {
options.put(e.group, new Integer(e.value));
if(!SlidePuzz2.playButton.visible && options.size()>4) SlidePuzz2.playButton.visible=true;
}
return e;
}
}
return null;
}
static void changeSelected() {
for (int i=0;i<elems.size();i++) {
Element e = (Element)elems.get(i);
if(e.group==null) continue;
if(!options.containsKey(e.group)) e.useAlt=false;
else {
if(options.get(e.group).equals(e.value)) e.useAlt=true;
else e.useAlt=false;
}
}
}
static void changeSelected(Element elem) {
elem.useAlt=true;
String g = elem.group;
int v = elem.value;
for (int i=0;i<elems.size();i++) {
Element e = (Element)elems.get(i);
if(e.group==g && e.value!=v) e.useAlt=false;
}
}
static void setVisibility(boolean b) {
for (int i=0;i<elems.size();i++) {
Element e = (Element)elems.get(i);
e.visible=b;
}
}
static void makeUnclickable() {
for (int i=0;i<elems.size();i++) {
Element e = (Element)elems.get(i);
if(e.clickable && e.visible) e.clickable=false;
}
}
static void destroyVisible() {
for (int i=0;i<elems.size();i++) {
Element e = (Element) elems.get(i);
if(e.visible) {
elems.remove(i);
i--;
}
}
imgCount=0;
}
}
class ElemText extends Element {
public ElemText(int x, int y, String s) {
super(x, y, "text", true, false);
Font f = new Font("Verdana", Font.BOLD, 14);
setImg(drawText(s, f, false));
}
}
class ElemImg extends Element {
int index;
public ElemImg(int x, int y, Image img) {
super(x, y, "img", true, false);
index = imgCount;
imgCount++;
setImg(img);
}
}
class ElemBlank extends Element {
int w;
int h;
public ElemBlank(int x, int y, int w, int h) {
super(x, y, "blank", true, false);
setImg(drawBlank(w, h));
}
}
class ElemOption extends Element {
public ElemOption(int x, int y, String s, String g, int size, boolean visible) {
super(x, y, "option", visible, true);
init(x, y, s, g, size, visible);
}
public ElemOption(int x, int y, String s, String g) {
super(x, y, "option", true, true);
int size = 12;
boolean visible = true;
init(x, y, s, g, size, visible);
}
public void init(int x, int y, String s, String g, int size, boolean visible) {
Integer v;
if(options.containsKey(g+"_count")) v = (Integer)options.get(g+"_count");
else v = 0;
Font f = new Font("Verdana", Font.PLAIN, size);
mouseBleed = size;
setImg(drawText(s, f, false));
imgAlt = drawText(s, f, true);
clickable = true;
group = g;
value = new Integer(v);
this.visible = visible;
v++;
options.put(g+"_count", new Integer(v));
}
}
</code></pre>
<p>Board.java</p>
<pre><code>import java.util.*;
class Board {
private static int grid;
private static int piece;
ArrayList locations = new ArrayList();
public Board(int grid) {
this.grid = grid;
this.piece = 420/grid;
for(int i=0; i<grid*grid; i++) locations.add(new Integer(0));
}
public void add(Element e, PieceLoc pl) {
locations.set(pl2loc(pl), e);
}
public void makeClickables() {
PieceLoc blankPiece = loc2pl(locations.indexOf(new Integer(0)));
addClick(blankPiece, -1, 0);
addClick(blankPiece, 1, 0);
addClick(blankPiece, 0, -1);
addClick(blankPiece, 0, 1);
}
private void addClick(PieceLoc blankPiece, int dx, int dy) {
PieceLoc pl = new PieceLoc();
pl.x = blankPiece.x+dx;
pl.y = blankPiece.y+dy;
if (pl.x>=0 && pl.y>=0 && pl.x<grid && pl.y<grid) {
((Element)locations.get(pl2loc(pl))).clickable=true;;
}
}
private PieceLoc loc2pl(int loc) {
PieceLoc pl = new PieceLoc();
pl.y = loc % grid;
pl.x = (loc-pl.y)/grid;
return pl;
}
private int pl2loc(PieceLoc pl) {
int loc = pl.x*grid+pl.y;
return loc;
}
public PieceLoc getBlankPl() {
return loc2pl(locations.indexOf(new Integer(0)));
}
public void clicked(Element elem) {
Element.makeUnclickable();
int blank = locations.indexOf(new Integer(0));
int clicked = locations.indexOf(elem);
Collections.swap(locations,blank,clicked);
}
public void checkCompleted() {
boolean completed = false;
if(locations.indexOf(new Integer(0))==locations.size()-1) {
completed = true;
for(int i=0; i<locations.size()-1; i++) {
ElemImg e = (ElemImg)locations.get(i);
if(e.index!=i) completed=false;
}
}
if(completed) {
new ElemBlank(280, 280, 140, 140);
new ElemText(292, 290, "Well done,");
new ElemText(295, 315, "you have");
new ElemText(292, 340, "completed");
new ElemText(290, 365, "the puzzle!");
new ElemOption(300, 390, "Play Again", "restart");
} else makeClickables();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>After a quick look:</p>\n\n<ul>\n<li>I would use anonymous inner classes for the listeners. One advantage is that you can inherit from Adapters</li>\n<li>in Swing, usually you should overwrite <code>paintComponent</code>, not <code>paint</code></li>\n<li><code>ArrayList locations</code> should be generic</li>\n<li>some methods like <code>game</code> are too long.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T13:38:45.557",
"Id": "8780",
"ParentId": "8772",
"Score": "4"
}
},
{
"body": "<p>In SlidePuzzle2.init(), you create a bunch of elements without storing their reference. I understand that the references are stored statically in Element, but it looks very unusual and it should be avoided. You should avoid static members or methods as much as possible in OO programming.</p>\n\n<p>The class Element does way too many things. The main problem is that you did not use the MVC (model-view-controller) pattern. You should define everything abstractly first (model), without thinking in the slightest about showing those things. Once you have completed the model, you can start doing the interface (view). There are two advantages: 1) your code is much cleaner and 2) if you want to port your program to Android later, you don't touch the model, but just rewrite the interface.</p>\n\n<p>P.S.: the controller handles the user input, which changes the model and ultimately the view. You don't have to have classes Model, View, Controller, but each class should belong to the model or the view. Note that in Swing the view and controller are pretty much fused into a view-controller since the Swing components carry both roles.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T15:54:57.150",
"Id": "13972",
"Score": "0",
"body": "Thank you, this is truly helpful. For my next project I shall use MVC as my mantra. So suppose I were creating a multi-level maze game. Could examples of Model classes be `Maze` to represent the current maze, `State` to represent the current position of items within the maze, and `Movement` to represent the direction items within the maze are moving? But all of these should be completely independent of how its all represented on the screen, this are all done with the View classes which take look at the properties of the Model objects to do their thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T15:55:08.493",
"Id": "13973",
"Score": "0",
"body": "Then the control objects simply listen for any mouse or key activity and call the Models' methods appropriately?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T22:13:48.890",
"Id": "13986",
"Score": "1",
"body": "Yes, and as I said, in Swing, the controllers are also the view objects -- the JComponents such as JButton. I guess it's the same in Android. But if you were to do a console (terminal) version of your game, than you would read in the move from the command line (the control), which would change the board state (the model) and then you would print some lines to represent the current board (the view). No matter which view/controller, you would always use the same code for the board which can receive a move and change the board state accordingly. The controller updates the view after a move."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T20:01:01.990",
"Id": "8890",
"ParentId": "8772",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "8890",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T08:36:32.930",
"Id": "8772",
"Score": "3",
"Tags": [
"java",
"object-oriented"
],
"Title": "My first OOP piece... how have I done?"
}
|
8772
|
<p>The following piece of code is used to re-position controls on a form considering different options.</p>
<p>Once you have multiple controls this becomes quite messy. I would appreciate your improvement suggestions.</p>
<pre><code>private void dlgOptionsForm_Load(object sender, System.EventArgs e)
{
if (_hideAccountingOption)
{
grpAccountingOption.Visible = false;
Height -= grpAccountingOption.Height;
grpPeriod.Top -= (grpAccountingOption.Height + 8);
grpPrintOptions.Top -= (grpAccountingOption.Height + 8);
grpInvoiceInformation.Top -= (grpAccountingOption.Height + 8);
grpHND.Top -= (grpAccountingOption.Height + 8);
chkPrint.Checked = false;
grpArchiveDocument.Top -= (grpAccountingOption.Height + 8);
grpBalanceControlList.Top -= (grpAccountingOption.Height + 8);
}
if (_hidePeriod)
{
grpPeriod.Visible = false;
Height -= grpPeriod.Height;
grpPrintOptions.Top -= (grpPeriod.Height + 8);
grpInvoiceInformation.Top -= (grpPeriod.Height + 8);
grpHND.Top -= (grpPeriod.Height + 8);
chkPrint.Checked = false;
grpArchiveDocument.Top -= (grpPeriod.Height + 8);
grpBalanceControlList.Top -= (grpPeriod.Height + 8);
}
if (_hidePrintOptions)
{
grpPrintOptions.Visible = false;
this.Height -= grpPrintOptions.Height;
grpInvoiceInformation.Top -= (grpPrintOptions.Height + 8);
grpHND.Top -= (grpPrintOptions.Height + 8);
chkPrint.Checked = false;
grpArchiveDocument.Top -= (grpPrintOptions.Height + 8);
grpBalanceControlList.Top -= (grpPrintOptions.Height + 8);
}
....
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T03:22:20.147",
"Id": "13936",
"Score": "0",
"body": "If you have to do this, then I think you are doing something wrong. When controls are not in one position but dance all over the screen, it confuses the user. Be nice to the user. Save \"clever\" code for something that happens under the hood, not on screen. http://www.uvsc.edu/disted/decourses/mct/2740/IN/steinja/lessons/04/krug_chapter_06/krug_6_street_signs_breadcrumbs_02.html?m=1\n\nHere is an example of a nice tabbed dialog in action: http://www.indezine.com/products/powerpoint/learn/fillslinesandeffects/images/solidfills_02.gif\n\nYou can hide individual tabs!"
}
] |
[
{
"body": "<p>Solution 1:</p>\n\n<p>If all of your grp* inherits of the same object (say Control), what you can do is:</p>\n\n<pre><code>private List<Control> _groups = new List<Control>();\n\n.ctor()\n{\n // Populate _groups\n _groups.Add(grpPeriod);\n _groups.Add(grpPrintOptions);\n _groups.Add(grpInvoiceInformation);\n _groups.Add(grpHND);\n _groups.Add(grpArchiveDocument);\n _groups.Add(grpBalanceControlList);\n}\n</code></pre>\n\n<p>Now you method becomes:</p>\n\n<pre><code>private void dlgOptionsForm_Load(object sender, System.EventArgs e)\n{\n if (_hideAccountingOption)\n { \n Adjust(grpAccountingOption);\n }\n if (_hidePeriod)\n {\n Adjust(grpPeriod);\n }\n\n if (_hidePrintOptions)\n {\n Adjust(grpPrintOptions);\n }\n\n ....\n}\n\nprivate void Adjust(Control control)\n{\n control.Visible = false;\n this.Height -= control.Height;\n chkPrint.Checked = false;\n\n foreach (var item in _groups)\n {\n if(control != item)\n item.Top -= (control.Height + 8);\n }\n}\n</code></pre>\n\n<hr>\n\n<h2>EDIT</h2>\n\n<p>Solution 2:</p>\n\n<pre><code>Dictionary<Func<bool>, Control> _groups= new Dictionary<Func<bool>, Control>();\n\n.ctor()\n{\n // Populate _groups\n _groups.Add(() => _hidePeriod, grpPeriod);\n _groups.Add(() => _hideInvoiceInformation, grpInvoiceInformation);\n _groups.Add(() => /* your bool variable */, /* the associated control */);\n // ...\n}\n\nprivate void dlgOptionsForm_Load(object sender, System.EventArgs e)\n{\n foreach (var item in _groups)\n {\n if (item.Key()) // Evaluate the boolean variable\n Adjust(item.Value);\n }\n}\n\nprivate void Adjust(Control control)\n{\n control.Visible = false;\n this.Height -= control.Height;\n chkPrint.Checked = false;\n\n foreach (var item in _groups)\n {\n if(control != item)\n item.Top -= (control.Height + 8);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T17:38:06.103",
"Id": "13742",
"Score": "0",
"body": "Isn't `.ctor(){ ... }` c++ ? Will this compile as c#?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T08:07:00.043",
"Id": "13780",
"Score": "0",
"body": "It is, I've written '.ctor' in order to explicitely say that it needs to be in it (I've not the name of his class ;-))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T09:18:22.767",
"Id": "13782",
"Score": "0",
"body": "Ah, I see, makes sense. Perhaps something like `public MyClass(){ ... }` would be explicit; and perhaps not."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T12:15:09.453",
"Id": "8778",
"ParentId": "8774",
"Score": "2"
}
},
{
"body": "<p>How about this?</p>\n\n<pre><code> private const int _standardInterval = 8;\n\n// private void dlgOptionsForm_Load(object sender, System.EventArgs e)\n// Type signatures like this are useless as they don't tell you what the method is about\n// (an important aspect of good naming) and contain parameters which you don't use\n// This can be solved with inline lambdas\n// The wire-up which used to be something like\n// form.Load += dlgOptionsForm_Load;\n// Can now be changed to\n// form.Load += (o,e) => RepositionControls();\n// Yes, I am suggesting that the microsoft guidance here is wrong. Most developers that I respect\n// do it this way.\n private RepositionControls()\n {\n if (_hideAccountingOption)\n HideOption(grpAccountingOption, dependencies: new Control[] { grpPeriod, grpPrintOptions, grpInvoiceInformation, grpHND, grpArchiveDocument, grpBlanceControlList });\n if (_hidePeriod)\n HideOption(grpPeriod, dependencies: new Control[] { grpPrintOptions, grpInvoiceInformation, grpHND, grpArchiveDocument, grpBlanceControlList });\n if (_hidePrintOptions)\n HideOption(grpPrintOptions, dependencies: new Control[] { grpInvoiceInformation, grpHND, grpArchiveDocument, grpBlanceControlList });\n //You're always doing this anyways\n chkPrint.Checked = false;\n }\n\n void HideOption(Control option, Control[] dependencies) {\n option.Visible = false;\n this.Height -= option.Height\n AdjustTopTo(option.Height, dependencies);\n }\n\n // I am assuming the .Top property is on the Control class and that that is the most common subtype...it's been a while\n // since I've done winforms but I think this is right, if not, change it to what it should be.\n private void AdjustTopTo(int height, params Control[] controls) {\n for(var c in controls)\n c.Top -= (height + _standardInterval)\n }\n</code></pre>\n\n<p>Note that I'm assuming c# 4.0 for the named properties, if you're using a lower version of C# remove the \"dependencies:\" from the HideOptions invocation. I am also assuming >C#3.5 for the inline lambda, if you are using a lower version than that even (sucks for you) then you'll have to keep the method signature the same.</p>\n\n<p>I will also point out that the only real logic in these if statements is the knowledge of which options depend on which others. There is probably a better way of doing this if you show us more of your code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T15:12:57.573",
"Id": "8781",
"ParentId": "8774",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T10:17:22.683",
"Id": "8774",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Re-positioning controls on a form"
}
|
8774
|
<p>This is one of my first OOP programs in normal PHP, without any framework. This combines all .css files into one and all .js files into one, and it works. Are there any suggestion on what I can make better in terms of OOP or anything else?</p>
<p>This is how it works:</p>
<p>I run this: <code>http://localhost/folderName/css/styleindex.css</code></p>
<ol>
<li><p>I have .htaccess that passes everything to index.php.</p></li>
<li><p>I extract the type as CSS and page as styleindex by exploding styleindex.css.</p></li>
<li><p>I get the array of files that needs to be combined for this page and join them.</p></li>
<li><p>I display this on the browser with the correct MIME type and cache header.</p></li>
</ol>
<p></p>
<pre><code><?php
define('DEBUGMODE',01);
class ResourceHandler
{
/**
* @var $FilesToParse files that needs to be parsed
*/
private $FilesToParse = array();
/**
* @var $type weather js or css
*/
private $type;
/**
* @var $page name/category of the page
*/
private $page;
/**
* @var $AllowedTypes array of allowed types js or css
*/
private $AllowedTypes = array('css','js');
/**
* @var $CacheTime time for which cache is valid
*/
private $CacheTime = 610000;
function __construct($type, $page)
{
$this->setType($type);
$this->setPage($page);
header('ETag: Ei07072012745');
//header('Content-type: text/'.$this->type." charset: UTF-8");
if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip'))
{
//ob_start("ob_gzhandler");
}
else
{
ob_start();
}
header ("Vary: negotiate,accept-language,accept-charset");
header ("Cache-control: public");
header('Content-Disposition: attachment; filename="'.$this->page.'.'.$this->type.'"');
if(DEBUGMODE ==0)
{
$expire = "expires: " . gmdate("D, d M Y H:i:s", time() + $this->CacheTime) . " GMT";
header ($expire);
}
}
function setPage($PageName)
{
$Resource = explode('.',$PageName);
$this->page = $Resource[0];
}
function setType($type)
{
$type = strtolower($type);
/*type needs to be js or css else dont proceed further*/
if(!in_array($type,$this->AllowedTypes))
{
exit;
}
$this->type = $type;
}
/**
* Function to minify data
* @return $FileContent Minified file data
*/
private function minifyFiles($data)
{
/* remove comments */
$data = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $data);
/* remove tabs, spaces, newlines, etc. */
$data = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $data);
return $data;
}
/**
* Function to parse file and merge into one variable
* @return $FileContent Merged file data
*/
private function parseFiles()
{
$FileContent = '' ;
foreach($this->FilesToParse as $File)
{
$FileContent = file_get_contents($File);
}
return $FileContent;
}
function __destruct()
{
ob_end_flush();
}
/**
* Function to display css file
* @return $output returns the combined, compresssed and gzipped data
*/
private function css()
{
switch($this->page)
{
case 'index' : $this->FilesToParse = array('style12.css','jquery.autocomplete.css');
break;
DEFAULT : header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
exit;
}
$data = $this->parseFiles('css');
if(DEBUGMODE ==0)
{
$data = $this->minifyFiles($data);
}
return $data;
}
/**
* Function to display js file
* @return $output returns the combined and gzipped data
*/
private function js()
{
switch($this->page)
{
case 'index' : $this->FilesToParse = array('jquery-1.6.2.js','jquery.autocomplete.js','facebox.js');
break;
default : header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
exit;
}
$data = $this->parseFiles('js');
return $data;
}
function load()
{
$type = $this->type;
$cwd = getcwd();
chdir($type);
echo $this->$type();
chdir($cwd);
}
}
$request = explode("/resources/", $_SERVER['REQUEST_URI']);
$params = array_filter(explode("/", $request[1]));
if(isset($params[0]) && isset($params[1]))
{
$resource = new ResourceHandler($params[0],$params[1]);
$resource->load();
}
else
{
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
}
?>
</code></pre>
|
[] |
[
{
"body": "<p>The first thing I notice is private everything. Generally I avoid <code>private</code> unless the function is really, really, <em>really</em> specific to <strong>only, and ever only, that class.</strong> This class could be extended but wouldn't really provide the extending class with anything but the public methods already available. Make them protected. I understand the concern in not wanting extending code to change the way the class works, but that's kind of the point. Trust the developers extending your class to know <em>why</em> they're extending the class and give them the opportunity to do so.</p>\n\n<p>A lot of your stuff is hard-coded. While this works now it means when you add/change a file you have to change the <em>class itself</em>. This, in combination with private everything, will force somebody to eventually break the <a href=\"http://en.wikipedia.org/wiki/Open/closed_principle\" rel=\"nofollow\">Open/Closed principle</a> of <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\" rel=\"nofollow\">SOLID</a>. Perhaps add some parameters to your <code>load()</code> that accept an array of files to add for each file type. This way your users can add their own files to the list of those included without having to actually go in and change your code.</p>\n\n<p>You're calling header a lot all over the place, especially in your <code>__construct()</code>. I would try to consolidate your <code>header()</code> calls into a centralized method; they're pretty important and might be a future pain point as you hunt your class over for where the invalid <code>header()</code> call is coming from. I would maybe do something like...</p>\n\n\n\n<pre><code>protected $headers = array();\n\nprotected function setDefaultHeaders() {\n $this->headers[] = 'Whatever headers you want for every request.';\n // rinse, repeat\n}\n\npublic function setOptionalHeader($header) {\n $this->headers[] = $header;\n}\n\nprotected function sendHeaders() {\n foreach ($this->headers as $header) {\n header($header);\n }\n}\n</code></pre>\n\n<p>Why? Well, I can get all of those header calls out of the <code>__construct()</code> and replace it with a <code>$this->setDefaultHeaders()</code>. Also, all of my headers are being sent by one method, <code>sendHeaders()</code>. When the pain comes I have a somewhat easier stack trace to follow back, it starts at one point and I know where that point is. I've found that in debugging finding a good starting point is the hardest thing. Finally, you also know that the likely error is coming from something not right in <code>setOptionalHeader()</code>.</p>\n\n<p>Your <code>__construct()</code> is probably doing a tad too much. Maybe it should set the default headers. But it probably shouldn't be starting output buffering, particularly since the output buffering only stops when the class is destroyed. This may wind up causing <em>everything echod</em> to be included in your CSS/JS minification output. Get rid of all the extra <em>actions</em> in the constructor; the constructor should try to be limited to only setting up the class state and data so <strong>other actions</strong> can do the heavy lifting.</p>\n\n<p>I also don't like that you are only echoing output on <code>__destruct()</code>, ultimately this means you have little direct control of when your data gets output. You see, the output buffering will only ever stop when your class is destroyed. Since the garbage collector decides when that is you're leaving your output buffering going the entire request; it doesn't stop until the garbage collector runs AND determines the class is no longer being used. With something as important as CSS and JavaScript I would want that output ASAP and exactly when I say. Get rid of the <code>__destruct()</code> and output your data in its own function. Perhaps this function can also be what starts and ends output buffering, solving the OB problem mentioned above.</p>\n\n<p>I really like most of your methods design though; the names are reasonably descriptive and, for the most part, they're sufficiently short and easy to read. There's some styling things I disagree with, for example if a variable is <code>PascalCase</code> I assume it to be an object and reserve <code>camelCase</code> for scalar types. Of course, that is just a picky personal preference and the important thing is to be consistent and follow whatever naming conventions strategies setup by your team/the project.</p>\n\n<p>Welcome to PHP and OOP! I hope you enjoy it as much as I have. :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T13:25:26.377",
"Id": "13735",
"Score": "1",
"body": "Would the downvoter explain how my review could be improved?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T08:52:17.757",
"Id": "13957",
"Score": "0",
"body": "thanks for such a long answer. I too taught headers needed to be separate. and thanks for the destructor point i never taught about it. Also thanks for the protected bit though no one will ever extend this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T08:52:50.313",
"Id": "13958",
"Score": "0",
"body": "just tell me when to use protected vs private"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-18T10:56:53.603",
"Id": "14286",
"Score": "1",
"body": "@WebDeveloper Generally, protected should be the default protection level for your class members. Public members describe the API of your class (how other people can use the service your class provides) and private members are intended for very specific cases where the class MUST behave in a particular way that CANNOT be changed. Protected means that you can inherit from the class and change its behaviour without changing its public API (this is a huge simplification but should suffice as a general rule of thumb)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T12:56:27.160",
"Id": "8779",
"ParentId": "8775",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T11:14:29.663",
"Id": "8775",
"Score": "3",
"Tags": [
"php",
"object-oriented"
],
"Title": "Combining .css and .js files"
}
|
8775
|
<p><strong>Summary: Please let me know, what weaknesses do you see in the described workaround for event handlers preventing garbage collection of registered listener objects...</strong></p>
<p>I'm in the development of and API for a set of devices communicating with each other, and optionally with a PC trough a socket based gateway. The API describes the multitude of different devices, channels as a class hierarchy, and also implements some kind of caching for the derived objects. </p>
<p>I'd like to make the API really simple to use for the developers, so I keep the interfaces as simple as possible: hiding background threading, etc... I ran into the already described problems, when registering event handlers from a windows form interface: </p>
<ol>
<li><p>The event source object is in the cache, it keeps the reference to the target object, preventing it from garbage collection. It's quite problematic, because the UI creates and destroys controls (providing some kind of user interface for the device objects) on the fly... for example when a new device is discovered, or when view is changed.</p></li>
<li><p>As the event raiser might be a different thread than the UI, so it requires checking in each of the event handler routines.</p></li>
</ol>
<p>I was reading the WeakEvent pattern guidelines - I'm not too happy with that solution:
- It's not "standard" - so the programmer has to register for events "manually"
- And quite complex to build.</p>
<p>I ended up with Custom Event declarations, like:
</p>
<pre class="lang-vb prettyprint-override"><code>Private EHL_Received As New PacketEventHandlerList("PacketReceived")
Public Custom Event PacketReceived As EventHandler Implements I_PacketEventRaiser.PacketReceived
AddHandler(ByVal value As EventHandler)
EHL_Received.Add(value)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
EHL_Received.Remove(value)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As PacketEventArgs)
EHL_Received.Invoke(sender, e)
End RaiseEvent
End Event
</code></pre>
<p>Then, in the "event handler" list, instead of storing real EventHandlers, I collect custom objects: they keep weak references to the targets.</p>
<pre class="lang-vb prettyprint-override"><code>Friend Class PacketEventHandler
Private targetRef As WeakReference = Nothing
Private IsStatic As Boolean = False
Friend IsValid As Boolean = True
Friend Method As System.Reflection.MethodInfo
Public Sub New(ByVal h As EventHandler)
IsStatic = IsNothing(h.Target)
If Not IsStatic Then targetRef = New WeakReference(h.Target)
Me.Method = h.Method
End Sub
Public ReadOnly Property Target
Get
If Not IsNothing(targetRef) Then Return targetRef.Target
Return Nothing
End Get
End Property
Public Sub Invoke(ByVal sender As Object, ByVal e As EventArgs)
' If method is static, there is not too much to do
If IsStatic Then
Me.Method.Invoke(Nothing, {sender, e})
Exit Sub
End If
' If the reference is invalid, then the object was probably collectd. Mark handler as invalid
Dim MyTarget As Object = Me.Target
If IsNothing(MyTarget) Then
Me.IsValid = False
Exit Sub
Else
' As we are in a different thread, do the invoke stuff if needed
If TypeOf (MyTarget) Is Windows.Forms.Control Then
Dim ctlTarget As Windows.Forms.Control = MyTarget
If ctlTarget.InvokeRequired Then
ctlTarget.Invoke(New System.Windows.Forms.MethodInvoker(Sub() Me.Invoke(sender, e)))
MyTarget = Nothing
Exit Sub
End If
End If
' For other objects it's simple
Me.Method.Invoke(MyTarget, {sender, e})
MyTarget = Nothing
End If
End Sub
End Class
</code></pre>
<p>Note, that each handler object holds reference to one single handler, so a list is created.</p>
<pre class="lang-vb prettyprint-override"><code>Friend Class PacketEventHandlerList
Private Handlers As New List(Of PacketEventHandler)
Private Name As String
Public Sub New(ByVal Name As String)
' Just keep the name for logging purposes
Me.Name = Name
End Sub
Friend Sub Add(ByVal value As EventHandler)
Console.WriteLine("{0} registers {1}", value.Target.ToString, Me.Name)
Handlers.Add(New PacketEventHandler(value))
End Sub
Friend Sub Remove(ByVal value As EventHandler)
Console.WriteLine("{0} unregisters {1}", value.Target.ToString, Me.Name)
For I As Integer = Handlers.Count - 1 To 0 Step -1
Dim MyEvh As PacketEventHandler = Handlers(I)
If Object.ReferenceEquals(MyEvh.Target, value.Target) And value.Method.Equals(value.Method) Then
Handlers.RemoveAt(I)
Console.WriteLine("Successful remove!")
End If
Next
End Sub
Friend Sub Invoke(ByVal sender As Object, ByVal e As EventArgs)
Dim InvalidHandlers As Integer = 0
' Go trough all registered handlers, and invoke them
For Each EVH As PacketEventHandler In Handlers
Try
EVH.Invoke(sender, e)
Catch ex As Exception
LogException(ex)
End Try
If Not EVH.IsValid Then InvalidHandlers += 1
Next
' If there were invalid handlers, just clean them up
If InvalidHandlers > 0 Then
For I As Integer = Handlers.Count - 1 To 0 Step -1
If Not Handlers(I).IsValid Then Handlers.RemoveAt(I)
Next
End If
End Sub
End Class
</code></pre>
<p>And, it seems to work. </p>
<p>Minor issue is, that I could't check the RemoveHandler part, as it's not called for some reasons. I'm not sure if I need that at all...</p>
<p>Do you see any problems with this implementation?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T10:51:06.573",
"Id": "13731",
"Score": "0",
"body": "This may be more suitable on StackOverflow (or CodeReview?). Please don't cross-post it though - it will get automigrated if enough people agree with this and votes to close here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T01:43:30.287",
"Id": "20819",
"Score": "0",
"body": "The solution proposed seems similar to Udi Dahan's Domain Events pattern: http://www.udidahan.com/2009/06/14/domain-events-salvation/ personally I think Udi's solution is easier to test and doesn't have any magic strings like \"PacketReceived\" and doesn't require any reflection."
}
] |
[
{
"body": "<p>At first glance, <code>PacketEventHandler</code> is a rather confusing name for a class, but then looking at it more thoroughly I see that it's actually a <em>wrapper</em> around an event handler, so I see what made you call it that way, but I'd still try harder to find a better name... although I have none to suggest right now (<em>naming</em> is one of the hardest things to do properly!).</p>\n\n<p>The way you're clearing your <code>InvalidHandlers</code> looks awkward.</p>\n\n<blockquote>\n<pre><code>' If there were invalid handlers, just clean them up\nIf InvalidHandlers > 0 Then\n For I As Integer = Handlers.Count - 1 To 0 Step -1\n If Not Handlers(I).IsValid Then Handlers.RemoveAt(I)\n Next\nEnd If\n</code></pre>\n</blockquote>\n\n<p><code>Handlers</code> being a <code>List(Of PacketEventHandler)</code>, I'm pretty sure you could simply do this:</p>\n\n<pre><code>Dim Handler As PacketEventHandler\nIf InvalidHandlers > 0 Then\n For Each Handler In Handlers\n If Not Handler.IsValid Then Handlers.Remove(Handler)\n Next\nEnd If\n</code></pre>\n\n<p>And reviewing this snippet made me wonder, are you using <code>Option Explicit</code>? I don't see your <code>I</code> declared anywhere - <strong><em>always use Option Explicit</em></strong>. The C# programmer in me would also advise you to use <code>Option Strict</code> just to be on a [type-]safe side (you don't have to specify <em>explicit</em> if you specify <em>strict</em> - the latter implies the former).</p>\n\n<p>This is by no means a full review - but it's all I could see on a first pass. The rest roughly looks good to me.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T02:03:28.977",
"Id": "35796",
"ParentId": "8776",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T09:25:29.233",
"Id": "8776",
"Score": "11",
"Tags": [
"vb.net"
],
"Title": "Another way to implement weak event handlers in vb.net"
}
|
8776
|
<p>I'm relatively familiar to Ruby, but I'm brand-new to testing code. I've decided to use RSpec because as it seems like a popular option.</p>
<p>The game works perfectly, but the spec has a lot of repetition and I have a feeling it can be improved.</p>
<h3>The Spec</h3>
<pre><code>require 'rock_paper_scissors'
# game = RockPaperScissors.new('rock')
# game.result => ['win!', 'lose!', 'tie!']
#
# 1 == rock
# 2 == paper
# 3 == scissors
describe "Rock Paper Scissors" do
let(:answers_snippet) { /valid answers/ }
context "when a number is passed" do
it "fails when invalid" do
game = RockPaperScissors.new(0)
game.result.should match(answers_snippet)
end
it "passes when valid and convert to string value" do
game = RockPaperScissors.new(1)
game.result.should_not match(answers_snippet)
game.choice.should == "rock"
end
end
context "when a string is passed" do
it "fails when invalid" do
game = RockPaperScissors.new('cheese')
game.result.should match(answers_snippet)
end
it "passes when valid" do
game = RockPaperScissors.new('rock')
game.result.should_not match(answers_snippet)
end
end
it "should tie when rock vs rock" do
RockPaperScissors.any_instance.stub(:random_choice).and_return('rock')
game = RockPaperScissors.new('rock')
game.result.should == "tie!"
end
it "rock should beat scissors" do
RockPaperScissors.any_instance.stub(:random_choice).and_return('scissors')
game = RockPaperScissors.new('rock')
game.result.should == "won!"
end
it "paper should beat rock" do
RockPaperScissors.any_instance.stub(:random_choice).and_return('rock')
game = RockPaperScissors.new('paper')
game.result.should == "won!"
end
it "scissors should beat paper" do
RockPaperScissors.any_instance.stub(:random_choice).and_return('paper')
game = RockPaperScissors.new('scissors')
game.result.should == "won!"
end
end
</code></pre>
<p>I've created a <a href="https://gist.github.com/1770891" rel="nofollow">gist</a> that has both the Rock Paper Scissors class and RSpec tests.</p>
|
[] |
[
{
"body": "<pre><code>let(:answers_snippet) { /valid answers/ }\n\nit \"fails when invalid\" do\n game = RockPaperScissors.new(0)\n game.result.should match(answers_snippet)\nend\n</code></pre>\n\n<p>When I read this spec code, I see that result should match <code>valid answers</code>, but from the spec name I see, that we test for invalid answers. Your specs code should be easy readable and I recommend to name constants correctly:</p>\n\n<pre><code>let(:invalid_answers_pattern) { /invalid answer/ }\n</code></pre>\n\n<hr>\n\n<p>Your specs are small and independent and if one spec will fail, it is enough to read this spec's code to understand how to reproduce problem. Specs are fine. But I would removed duplication in the last 4 specs, I think it won't hurt specs readability:</p>\n\n<pre><code>test_round_result(your_choice, opponent_choice, expected_result) do\n RockPaperScissors.any_instance.stub(:random_choice).and_return(opponent_choice)\n\n game = RockPaperScissors.new(your_choice)\n game.result.should == expected_result \nend\n\nit \"should tie when rock vs rock\" do\n test_round_result( 'rock', 'rock', 'tie!' )\nend\n\n#...\n</code></pre>\n\n<hr>\n\n<p>Also I found that you do too much logic in the initializer of your game class:</p>\n\n<pre><code>def initialize(choice)\n @choice = choice\n\n if is_valid_choice?\n @result = play\n else\n @result = instructions\n end\nend\n</code></pre>\n\n<p><em>Class initializer</em> should accept parameters and make sure your <em>class instance</em> is in the consistent state (<code>is_valid_choice?</code> in your case). You can write your class initializer this way:</p>\n\n<pre><code>def initialize(choice)\n raise ArgumentError, instructions unless valid_choice?(choice)\n @choice = choice\nend\n</code></pre>\n\n<p>Or even accepted <code>choice</code> in the <code>play</code> method because <code>choice</code> is a parameter for the round of the game, not for the whole game and leave initializer empty for now. When you will start doing BDD, you will likely star making design decisions like this.\nWith this refactoring your tests will be a little bit cleaner, something like this:</p>\n\n<pre><code>let(:game) { RockPaperScissors.new() }\n\ntest_round_result(your_choice, opponent_choice, expected_result) do\n game.stub(:random_choice).and_return(opponent_choice)\n game.play(your_choice).should == expected_result\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-15T08:34:13.483",
"Id": "8989",
"ParentId": "8782",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "8989",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T17:17:46.307",
"Id": "8782",
"Score": "2",
"Tags": [
"beginner",
"ruby",
"rock-paper-scissors",
"rspec"
],
"Title": "My first RSpec test - Rock Paper Scissors"
}
|
8782
|
<p>I've written a JavaScript table class to make it easy to display tabular data and allow the user to sort the data by clicking on the table headers.</p>
<p>However, when there are hundreds of rows, performance on the sorting is a bit sluggish. I would like to know what kind of improvements I can make. I suspect that my string concatenation methods in <code>displayData</code> may not be optimal.</p>
<pre><code>var tableUtility = (function () {
var fn = {};
// This is a constructor function for an object that represents a table
fn.DataTable = function (p_data, p_columnDataFields, p_tableId, p_displayCallback) {
// This is expected to be an array of objects.
var data = p_data;
// This is expected to be an array of strings that represents the names of the fields to use for the column data.
var columnDataFields = p_columnDataFields;
// This is expected to be the HTML ID of the table in which the data will be displayed.
// Note that this JavaScript will only affect the TBODY of the TABLE. It is expected that the HTML already contains the THEAD with the column headers.
var tableId = p_tableId;
// This is expected to be either null or a function to execute after the table is displayed.
var displayCallback = p_displayCallback;
// Find the TBODY element of the TABLE and cache it
var tbody = document.getElementById(tableId).getElementsByTagName('tbody')[0];
// softData sorts the table's data. fields is expected to be an array of strings with the names of the fields to sort by. sort functions is expected
// to be an array of functions describing how to sort each field.
// Note that fields must be distinct, or weird things will happen.
this.sortData = function (sortFields, sortFunctions) {
if (sortFields.length != sortFunctions.length)
throw new Error('fields and sortFunctions don\'t have the same length.');
var builtInSorts = this.sortData.sorts;
var sortFunction = function (x, y) {
var fieldIndex = 0;
for (var i = 0; i < sortFields.length; i++) {
var first = x[sortFields[i]];
var second = y[sortFields[i]];
var sortFunction = sortFunctions[i];
// This allows a calling function to reference a built-in sorting function.
if (typeof sortFunction === 'string')
result = builtInSorts[sortFunction](first, second);
else
result = sortFunction(first, second);
//var result = sortFunction(first, second);
if (result !== 0)
return result; // difference found
}
return 0; // no difference was found over any of the fields
};
data.sort(sortFunction);
}; // end sortData
// This object contains some built-in sorting functions that will be used on multiple pages
this.sortData.sorts = {
alphaSort: function (x, y) {
if (x.toString().toLowerCase() < y.toString().toLowerCase()) return -1;
else if (y.toString().toLowerCase() < x.toString().toLowerCase()) return 1;
else return 0;
},
numericSort: function (x, y) {
return parseInt(x, 10) - parseInt(y, 10);
}
} // end sortData.sorts
this.displayData = function () {
var numberOfFields = columnDataFields.length;
var numberOfRows = data.length;
var html = '';
for (x in data) {
var entry = data[x];
var row = '<tr>';
for (var i = 0; i < numberOfFields; i++) {
row += '<td>' + entry[columnDataFields[i]] + '</td>'
}
row += '</tr>'
html += row;
}
//tbody.innerHTML = html; I tried to do this without jQuery, but kept getting "Unknown Runtime Error in IE7"
$(tbody).html(html);
$(tbody)
.find('tr:even').addClass('EvenBar')
.find('tr:odd').addClass('OddBar');
// If a callback function was set, invoke it.
if (typeof displayCallback === 'function')
displayCallback();
} // end displayData
} // end DataTable Constructor Function
return fn;
})(); // end tableUtility
</code></pre>
|
[] |
[
{
"body": "<p>This was originally a comment, but it got long.</p>\n\n<ul>\n<li><p>The jQuery/innerHTML stuff is probably slowing it down, as it looks like you guessed. Tables in IE + innerHTML is broken. Instead, I'd use the DOM.</p></li>\n<li><p>Reconstituting the entire table for each sort is bound to be slow. Since you are doing the innerHTML thing, the entire table needs to be rebuilt, rather than just moving some tablerow nodes around.</p></li>\n</ul>\n\n<p>Most javascript table sort scripts take a different approach. The table is produced on the server or by a content writer in the normal way, and given a class like \"sortable-table\" for example, possibly with some columns having classes for type hinting or other metadata as well. Target tables with the appropriate classes and make them sortable. Sort tables by taking the tbody element and sorting its rows by removing and re-appending them, using the DOM.</p>\n\n<p>Even if you want to create the table element programatically, you could use a similar approach from there on.</p>\n\n<p><em>Recap:</em></p>\n\n<ul>\n<li>Use the DOM, not jQuery.</li>\n<li>Use the DOM, not innerHTML.</li>\n<li>Consider letting the table be created in the usual way instead of through an API.</li>\n<li>Use the DOM.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T21:07:27.713",
"Id": "13750",
"Score": "0",
"body": "Pro tip: Use the DOM."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T21:09:22.530",
"Id": "13751",
"Score": "0",
"body": "@Raynos essentially, yes ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T21:14:19.620",
"Id": "13752",
"Score": "0",
"body": "On this line: `$(tbody).html(html);`, I had originally written `tbody.innerHTML = html`, but that doesn't work in IE."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T21:19:43.217",
"Id": "13753",
"Score": "1",
"body": "That's because innerHTML is bad. Bad."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T21:32:51.663",
"Id": "13754",
"Score": "1",
"body": "@RiceFlourCookies you did see the part of my answer that says \"Use the DOM, not innerHTML,\" right? Or the \"Tables in IE + innerHTML is broken\" part?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T14:50:14.423",
"Id": "13787",
"Score": "0",
"body": "@Raynos, can you please let me know how to use the DOM to set the html of my table body without using `.innerHtml`?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T21:04:12.070",
"Id": "8789",
"ParentId": "8783",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "8789",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T19:30:40.727",
"Id": "8783",
"Score": "3",
"Tags": [
"javascript",
"strings"
],
"Title": "How can I improve performance for my JavaScript table class?"
}
|
8783
|
<p>What my script does is:</p>
<ol>
<li>Append data to a file on a continuous basis.</li>
<li>If an error pattern is observed, then do something.</li>
</ol>
<p>I need feedback on the way I am grepping for patterns in the continuously appended file. For grep, I am creating a pattern file first and then using it with -f option to grep. Can I do this better? Any other better way I can write my over all logic.</p>
<p>Here's my script</p>
<pre><code>#!/bin/bash
# List of error patterns to look for. Add more patterns to this list
p1='pattern1'
p2='pattern2'
p3='pattern3'
p4='pattern4'
PATTERNFILE=~/patternfile
FILETOCHECK=~/filetocheck
captureFileToCheck()
{
//appends data into filetocheck &
}
createPatternFile()
{
for i in `seq 100` # hopefully 100 is all we will need
do
if [ ! "x$p{$i}" = "x" ]
then
echo $p{$i} >> $PATTERNFILE
else
break
fi
done
}
createPatternFile
captureFileToCheck
while [ 1 ]
do
if grep -f $PATTERNFILE $FILETOCHECK
then
echo "something starting"
#doSometing
echo "something complete"
break
fi
done
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-21T08:09:37.703",
"Id": "14431",
"Score": "0",
"body": "Any specific issue you're having? Security? Efficiency? Accuracy? Complexity?"
}
] |
[
{
"body": "<p><a href=\"http://www.grymoire.com/Unix/Quote.html\" rel=\"nofollow\">Use more quotes</a>, as the saying goes.</p>\n\n<p>I find <code>while true</code> is more clear, but the idiomatic <code>while :</code> is also popular.</p>\n\n<p>You might want to use an array for the patterns, then you can simply loop over it (<code>for pattern in \"${patterns[@]}\"</code>) instead of using <code>seq</code> and the <code>if</code> statement.</p>\n\n<p>Uppercase variables are usually used for exports; that is, stuff which is relevant <em>outside</em> your script.</p>\n\n<p>You should avoid cluttering <code>~</code>; use <code>tmp_dir=\"$(mktemp -d)\"</code> instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-21T08:18:08.580",
"Id": "9213",
"ParentId": "8784",
"Score": "3"
}
},
{
"body": "<p>Here is another go at your function </p>\n\n<pre><code>patterns() {\ncat <<EOF\npattern1\npattern2\npattern3\npattern4\nEOF\n}\n</code></pre>\n\n<p>However, the <code>$patternfile</code> is not a necessity. I would go with just</p>\n\n<pre><code>while :\ndo \n grep -f <(patterns) $filetocheck && {\n echo found;\n break\n }\ndone\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-21T05:36:22.143",
"Id": "17627",
"Score": "0",
"body": "This is a good way to do it. I am concerned about portability!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-21T15:17:06.810",
"Id": "17635",
"Score": "0",
"body": "Ignore my comment about portability. Arrays are ok since this is explicitly bash."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T19:27:20.800",
"Id": "11049",
"ParentId": "8784",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "11049",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T19:50:58.720",
"Id": "8784",
"Score": "3",
"Tags": [
"optimization",
"bash",
"linux"
],
"Title": "How to improve the way I handle greping in this script"
}
|
8784
|
<p>So in my current application, I was thinking to make a extended class for all the datatypes. For <code>int</code>, it will be something like <code>ExtendedInt</code>, for <code>bool</code> it will be something like <code>ExtendedBool</code>.</p>
<p>These individual extended classes will expose some special functonality bound to that type. For example, this is how i think my <code>ExtendedInt</code> will look like:</p>
<pre><code>public interface IExtended
{
bool IsModified { get; set; }
}
Public class ExtendedInt: IExtended
{
private bool m_IsModified;
private int m_MaxValue = int.MaxValue ;
private int m_MinValue = int.MinValue;
private int m_Value=int.MinValue;
private int m_MaxValue = int.MaxValue ;
private int m_MinValue = int.MinValue;
public bool IsModified
{
get { return m_IsModified; }
set { m_IsModified = value; }
}
public int Value
{
get { return m_Value; }
set
{
// Only change the value if it is different.
if (m_Value != value)
{
// Only set the value if it is in the valid range, if any max/min exists.
if ((m_MaxValue > -1) && (value > m_MaxValue))
{
throw new ArgumentException("Value is above maximum value permitted.");
}
else if ((m_MinValue > -1) && (value < m_MinValue))
{
throw new ArgumentException("Value is below minimum value permitted.");
}
else
{
m_Value = value;
this.IsChanged = true;
if (m_Parent != null) m_Parent.DirtyState();
}
}
}
}
</code></pre>
<p>Similarly, I will provide <code>ExtendedBool</code>, <code>ExtendedDouble</code>, <code>ExtendedDate</code>, <code>ExtendedString</code>, etc..</p>
<p>Is this considered the best practice or it is overhead for my application?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T23:25:13.073",
"Id": "13756",
"Score": "0",
"body": "You do realize that basic types are *already* an abstraction, right? Why complicate things unnecessarily? What value do your abstractions provide and what potential problems could they possibly introduce? Is the time you are spending on this actually adding value or is it simply giving you something to toy around with?"
}
] |
[
{
"body": "<p>Too much overhead - <a href=\"http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx\" rel=\"nofollow\">nullable types</a> and <a href=\"http://msdn.microsoft.com/en-us/library/bb383977.aspx\" rel=\"nofollow\">extension methods</a> seem to give you what you need. The checking you do on your setters will never be executed because an int will never be less than <code>int.MinValue</code> or greater than <code>int.MaxValue</code> to begin with.</p>\n\n<p>Only create wrappers over types where you're adding intrinsic business (or technical) value that your consumers will benefit from. I'm afraid the <code>ExtendedInt</code> example you provide doesn't seem to meet that criteria over <code>int? myInt;</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T00:50:13.203",
"Id": "13758",
"Score": "1",
"body": "Agreed. You are absolutely right abt Extension methods and i think i shud use them if i need to give additional flexibility on my type. Thanks for the help."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T21:36:55.753",
"Id": "8791",
"ParentId": "8788",
"Score": "5"
}
},
{
"body": "<p>@Asdfg - Keep it simple!</p>\n\n<p>As written, I would say this is not a best practice at all, and should be avoided. It will be a (small) performance drag and a (large) addition of non-useful complexity if your plan is sweeping - any <code>int</code> will instead be <code>ExtendedInt</code>.</p>\n\n<p>[I say \"small\" performance drag since I don't think that will be a problem compared to the far larger penalty in the complexity you will be introducting. One example: will you be supporting all <code>int</code> primatives in <code>ExtendedInt</code> like +, /, %, ++, casting, bitmasks, and so forth? Other programmers working on your code will be confused. Very messy.]</p>\n\n<p>On the other hand, there is nothing wrong with writing a class that encapsulates needed behavior - in fact, that is a big part of object oriented design. Just that you would only use it when you have a good reason.</p>\n\n<p>In your particular example, my read of your code suggests perhaps you are attempting to create a <code>BoundedInt</code> abstraction rather than the (too) generic <code>ExtendedInt</code> which doesn't tell us anything about the intent of the class. What does \"Extended\" mean? Doesn't reveal much. </p>\n\n<p>Your comment <code>// Only set the value if it is in the valid range, if any max/min exists.</code> further suggests you intend to allow objects of this class to have settable ranges (though these methods are not shown). As Jesse points out, as written, the defaults you give are not useful, but with customizable ranges this might be a useful class. A plausible use case would be for a data object to associate with a UI element for which only a given range of values is allowed (disallowing negative age values, or rental dates in the past, and so forth).</p>\n\n<p>Similarly, the IsModified method suggests tracking data updates. Only useful if you have a scenario where knowing whether an int has changed value. And realize these are two separate concerns - dirty tracking & restricting its range.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T09:25:38.543",
"Id": "13783",
"Score": "2",
"body": "But if he is aiming for that \"range\" idea, I would suggest a generic class `Range<T>` or something similar, maybe with readonly properties `T? MinValue` and `T? MaxValue`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T14:49:35.460",
"Id": "13786",
"Score": "0",
"body": "I agree @ANeves that would be a good idea for implementing such a class."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T23:02:53.960",
"Id": "8792",
"ParentId": "8788",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "8791",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T20:52:09.233",
"Id": "8788",
"Score": "4",
"Tags": [
"c#",
"asp.net",
"classes"
],
"Title": "Is it a good practice to wrap datatypes in custom classes?"
}
|
8788
|
<p>I've implemented two different versions of the <a href="http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle" rel="nofollow">Fisher-Yates shuffle</a> in javascript, and I'd like to know if I've made any mistakes.</p>
<p>I'm creating a deck of playing cards. I'm interested in these shuffle algorithms. </p>
<p>The object passed to the <code>rng</code> parameters below is a wrapper for <a href="https://gist.github.com/1342599" rel="nofollow">Johannes Baagøe's Alea</a>, a seedable PRNG that should produce a better sample of random numbers than built-in <code>Math.random</code>. Its API is the same as that of <code>Math.random</code>.</p>
<p>I am mostly wondering if I have made any fencepost errors or misunderstood the examples I'm referencing.</p>
<pre><code>/** shuffle
Shuffle an array.
@see http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
@param {Array} array
@param {Function} random Optional RNG. Defaults to Math.random.
@return {Array} The original array, shuffled.
*/
function shuffle (array, random) {
var i = array.length, j, swap;
while (--i) {
j = (random ? random() : Math.random()) * (i + 1) | 0;
swap = array[i];
array[i] = array[j];
array[j] = swap;
}
return array;
}
/** pushRand
Insert a value into an array at a random index. The element
previously at that index will be pushed back onto the end.
@see http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_.22inside-out.22_algorithm
@param {Array} object to shuffle.
@param {Mixed} value to insert.
@param {Function} optional RNG. Defaults to Math.random.
@return {Number} The new length of the array.
*/
function pushRand (array, value, random) {
var j = (random ? random() : Math.random()) * array.length | 0;
array.push(array[j]);
array[j] = value;
return array.length;
}
</code></pre>
<p>Here's a <a href="http://jsbin.com/ujahar/3/" rel="nofollow">demo</a> of the shuffle. Reloading the page does the inside-out shuffle, and clicking the face-down card does the modern shuffle.</p>
<hr>
<p>Edit: I found a fencepost error in the "modern" version and fixed it here, but it's still in the demo. Not sure about the "inside-out" version yet.</p>
<hr>
<p>Edit: I stopped being lazy and factored this stuff out, so it should easier to look at now. New demo up. </p>
<hr>
<p>Edit: inside-out ver had the fencepost error too. It should look like this, I think:</p>
<pre><code>function pushRand (array, value, random) {
var j = (random ? random() : Math.random()) * (array.length + 1) | 0;
array.push(array[j]);
array[j] = value;
return array.length;
}
</code></pre>
<p>Thanks, Paul!</p>
<hr>
<p>Edit: Taking Adam's optimization suggestion into account, the new code looks like this:</p>
<pre><code>/** shuffle
Shuffle an array.
@see http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_.22inside-out.22_algorithm
@param {Array} array Array to shuffle.
@param {Object} rng Optional RNG. Defaults to Math.
@return {Array} The original array, shuffled.
*/
function shuffle (array, rng) {
var i = array.length, j, swap;
if (!rng) rng = Math;
while (--i) {
j = rng.random() * (i + 1) | 0;
swap = array[i];
array[i] = array[j];
array[j] = swap;
}
return array;
}
/** pushRand
Insert a value into an array at a random index. The element
previously at that index will be pushed back onto the end.
@see http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
@param {Array} array Array to insert into.
@param {Mixed} value Value to insert.
@param {Object} rng Optional RNG. Defaults to Math.
@return {Number} The new length of the array.
*/
function pushRand (array, value, rng) {
var j = (rng || Math).random() * (array.length + 1) | 0;
array.push(array[j]);
array[j] = value;
return array.length;
}
</code></pre>
<p>Here's the <a href="http://jsbin.com/ujahar/5/edit" rel="nofollow">updated editable demo</a> (relevant code at the bottom).</p>
|
[] |
[
{
"body": "<p>Unless you modify the inside out code to scale by <code>(index+1)</code></p>\n\n<pre><code> randomIndex = rand()*(index+1)|0;\n</code></pre>\n\n<p>You will not be covering all the possibilities.\nFor <code>index == 0</code>, you always generate 0 -- this is correct, but only by accident.</p>\n\n<p>For <code>index == 1</code>, you also always generate 0 -- instead of a 50/50 split between 0 and 1</p>\n\n<p>The second card in the deck misses its ONLY chance to get to be <code>card[1]</code>.</p>\n\n<p>The same problem continues for each card from then on, without the <code>+1</code>, <code>randomIndex < index</code> when you want <code>randomIndex <= index</code>.</p>\n\n<p>The problem may be even clearer for the last card placed in the deck. For a 52 card deck, <code>index == 51</code>, so <code>randomIndex</code> can be at most 50. So any prior card has a possibility of ending up at card[51], but not the last card. It can get no closer than card[50].</p>\n\n<p>It should be reassuring that this change makes the math for the initial shuffle look more like that of the re-shuffle.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T02:41:10.180",
"Id": "13764",
"Score": "0",
"body": "Sorry, looks like I edited my code while you were writing that. I had a feeling this might be the case, was just off to write a test harness to check the random distribution. So in the new code (second function), `array.length` should be `(array.length + 1)`, correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T02:42:49.210",
"Id": "13765",
"Score": "0",
"body": "I reviewed the unfactored version. I'm pretty sure the same bug still lurks. Also, the new code seems weird: Is it a safe no-op to `array.push(array[0])` on an empty array?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T02:44:40.847",
"Id": "13766",
"Score": "0",
"body": "yeah that part's safe, if you click the demo and then click the thing in the upper right hand corner you can edit the code live, shuffle stuff is at the bottom"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T03:31:01.427",
"Id": "13768",
"Score": "0",
"body": "So, it seems that `array.push(array[j])` is safe even accounting for the possibility of `j == array.length` -- it's just a little wierd. It's exactly the \"completely safe assignment from uninitialized data\" that the Wikipedia article warns about, but it gets a little confusing when you try to think of push as growing the array to include the exact non-pre-existent element that is being provided as its initializer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T05:53:42.737",
"Id": "13770",
"Score": "0",
"body": "I've come back to look at it three times to make sure the push wasn't messing things up, but since it always happens first it's safe... yeah this is the thing the article warns (or \"unwarns?\") about"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-22T00:30:16.987",
"Id": "192812",
"Score": "0",
"body": "@PaulMartel, Could you please tell me which one you think is better for shuffeling? (Link: http://ideone.com/pfRanN). As i tested, there is no difference between them."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T02:36:52.310",
"Id": "8794",
"ParentId": "8793",
"Score": "1"
}
},
{
"body": "<p>Note that you can optimize the first line inside the while loop:</p>\n\n<pre><code> function shuffle (array, random) {\n var i = array.length, j, swap;\n while (--i) {\n j = (random ? random() : Math.random()) * (i + 1) | 0;\n</code></pre>\n\n<p>The check for random's boolean value happens each time (depending on the compiler, I imagine some optimize around it nicely). It's likely to run a bit faster like this:</p>\n\n<pre><code> function shuffle (array, random) {\n var i = array.length, j, swap;\n random = random || Math.random;\n while (--i) {\n j = random() * (i + 1) | 0;\n</code></pre>\n\n<p><strong>Edit</strong>: had <code>random |=</code> incorrectly (which does <em>binary</em> OR) - replaced with <code>random = random ||</code> </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T06:30:50.477",
"Id": "13772",
"Score": "0",
"body": "Is it always safe to detach `random` from `Math` like that? I'm wary of getting references to built-in functions. I feel like some implementation might need its `this` reference or something."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T06:43:46.673",
"Id": "13773",
"Score": "0",
"body": "Good question! I take functions as objects so blindly I had to do some research for the special `Math` object. I'm going to have to say yes: [Here's an example](http://ejohn.org/blog/fast-javascript-maxmin/) where John Resig treats them directly as \"normal\" functions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T06:48:14.883",
"Id": "13774",
"Score": "0",
"body": "Take a look at the bottom of my question. I feel like this is probably safe in practice but i suspect that by definition it might be undefined behavior. I worked around it by changing the api to require an object with a `random` function property instead of a function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T06:52:06.157",
"Id": "13775",
"Score": "0",
"body": "of course pushRand could probably be further optimized by doing something like `pushRand.generator = rng` before calling it instead of passing it in every time, but I'd just as soon come up with a better api altogether"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T07:12:49.180",
"Id": "13776",
"Score": "0",
"body": "Well, I searched various compiled js sources (google websites, jquery-min, etc) and I couldn't find an instance where even those people used the `Math` methods any other way than \"normally\", so I'm not sure if there's really any risk or not. I think for the `Math` object you're safe, but others might have issues like you describe. That said, running this works fine in Chrome: `var x = Math.random; alert(x());`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T07:29:43.270",
"Id": "13777",
"Score": "0",
"body": "I had to look around a bit, but [this seems relevant](http://stackoverflow.com/questions/1007340/javascript-function-aliasing-doesnt-seem-to-work). I think it's best practice not to detach native functions, even if it's safe sometimes. `random |= Math.random` doesn't seem to work btw: `var foo = 4; foo |= 5; console.log(foo) // 5`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T07:37:54.873",
"Id": "13778",
"Score": "0",
"body": "I'll agree with that - I can't find any case where the `Math` methods are detached in the field other than old `with(Math)` examples, but I do know those functions are \"static\" in the sense that clearly they don't care too much about their scope since their scope is just the `Math` object. Hmm, unless one of them was written to call something else on `Math` relatively rather than statically, like `Math.tan = function(a) { return this.sin(a) / this.cos(a); };` - but I'd be disappointed if that actually happens anywhere."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T06:27:29.987",
"Id": "8796",
"ParentId": "8793",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "8794",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-08T23:41:26.913",
"Id": "8793",
"Score": "5",
"Tags": [
"javascript",
"algorithm",
"shuffle"
],
"Title": "Fisher-Yates shuffle algorithm in javascript, modern and inside-out versions"
}
|
8793
|
<p>This is not homework. I am trying to learn OOD principles and design patterns myself.</p>
<p>Suppose I have a problem like this:</p>
<blockquote>
<p>A book-shop buys and sells two types of books:</p>
<ol>
<li>Non-technical {Title, Author, Price}</li>
<li>Technical {Title, Author, Price, CD}</li>
</ol>
<p>Also, customer gets a CD when he buys a Technical book. A CD object is
defined as, CD {Title, Price}.</p>
<p>A Non-technical book's price will be only the price of the book. A
Technical book's price will be the sum of the price of the book and
the CD. </p>
<p>Create a C# program to show the following info:</p>
<ul>
<li>Total number of book Bought & Price: XXX & XXX.XX</li>
<li>Total number of book Sold & Price: XXX & XXX.XX</li>
<li>Total Technical Book Sold & Price: XXX & XXX.XX</li>
<li>Total Non-technical Book sold & Price: XXX & XXX.XX</li>
</ul>
</blockquote>
<p>I have designed the program like this:</p>
<pre><code>abstract class Publication
{
public virtual string Title { get; set; }
public virtual double Price { get; set; }
}
class CD : Publication
{
}
abstract class Book : Publication
{
public virtual string Author { get; set; }
}
class TechnicalBook : Book
{
public CD Cd { get; set; }
public override double Price
{
get
{
return (base.Price + Cd.Price);
}
}
}
class NonTechnicalbook : Book
{
}
abstract class Shop
{
private IDictionary<string, Book> boughtDictionary;
private IDictionary<string, Book> soldDictionary;
public Shop()
{
boughtDictionary = new Dictionary<string, Book>();
soldDictionary = new Dictionary<string, Book>();
}
public virtual void Buy(Book item)
{
boughtDictionary.Add(item.Title, item);
}
public virtual void Sell(string title)
{
Book book = boughtDictionary[title];
boughtDictionary.Remove(book.Title);
soldDictionary.Add(book.Title, book);
}
public virtual int GetBoughtBookCount()
{
return boughtDictionary.Count;
}
public virtual double GetBoughtBookPrice()
{
double price = 0.0;
foreach (string title in boughtDictionary.Keys)
{
price = price + boughtDictionary[title].Price;
}
}
public virtual int GetSoldBookCount()
{
return boughtDictionary.Count;
}
public virtual double GetSoldBookPrice()
{
double price = 0.0;
foreach (string title in soldDictionary.Keys)
{
price = price + soldDictionary[title].Price;
}
}
public virtual double GetTotalBookCount()
{
return this.GetBoughtBookCount() + this.GetSoldBookCount();
}
public virtual double GetTotalBookPrice()
{
return this.GetBoughtBookPrice() + this.GetSoldBookPrice();
}
public virtual void Show()
{
Console.WriteLine("Total number of books Bought & Price: ", this.GetTotalBookCount() + " & " + this.GetTotalBookPrice());
Console.WriteLine("Total number of books Sold & Price: ", this.GetSoldBookCount() + " & " + this.GetSoldBookPrice());
}
}
</code></pre>
<p>Does this design conform to the Open-Closed principle? Now I am unable to understand how to separate Technical and Non-technical books at this point.</p>
|
[] |
[
{
"body": "<p>I will not address the Open-Closed principle, as I do not know it.</p>\n\n<h2>How to separate Technical from NonTechnical books</h2>\n\n<p>This second question belongs in StackOverflow.<br>\nYet another reason to open a separate question for each real question you have...</p>\n\n<p>But you can do something like:</p>\n\n<pre><code>if(book is TechnicalBook) {\n // ...\n} else if(book is NonTechnicalBook) {\n // ...\n} else {\n // This is why I would suggest Book class not being abstract...\n // and removing the NonTechnicalBook class, making the TechnicalBook extend Book.\n throw new ArgumentException();\n}\n</code></pre>\n\n<h2>Remarks on the code</h2>\n\n<ol>\n<li><p><code>public CD Cd</code> should be either <code>Cd Cd</code> or <code>CD CD</code>.</p></li>\n<li><p>I don't see the advantage of Having the definition for <code>NonTechnicalbook</code>. Couldn't you just use regular books, if they were not abstract?<br>\nBut perhaps this is part of the principle you mention.</p></li>\n<li><p><code>IDictionary<string, Book> boughtDictionary;</code> What if I buy two books titled <code>C# for Dummies</code>? This should be a <code>Dictionary<Book, int></code>.</p></li>\n<li><p>Having the word <code>dictionary</code> in a variable's name is <a href=\"http://en.wikipedia.org/wiki/Hungarian_notation\" rel=\"nofollow\">Hungarian notation</a> - which I would avoid.</p></li>\n<li><p>What if I try to sell an inexistent book? KABOOM!</p></li>\n</ol>\n\n<p>Have you tried running your code? Case in point:\n- Your <code>Console.WriteLine()</code> is not working as you expect it to, you have a comma instead of a plus;\n- Some methods don't even return a value, and so do not compile;\n- The GetSoldBookCount is using the boughtDictionary;\n- Etc.</p>\n\n<p>It sure smells like homework.</p>\n\n<ol>\n<li>Some of </li>\n</ol>\n\n<p>This sure feels like homework.</p>\n\n<h2>Revised code suggestion</h2>\n\n<p>(Sorry about the brackets indentation. Too bothersome to change it back to your style.)</p>\n\n<pre><code>namespace BookSellers\n{\n using System.Linq;\n abstract class Publication\n {\n public virtual string Title { get; set; }\n public virtual double Price { get; set; }\n }\n\n class CD : Publication\n {\n }\n\n abstract class Book : Publication\n {\n public virtual string Author { get; set; }\n }\n\n class TechnicalBook : Book\n {\n public CD CD { get; set; }\n public override double Price {\n get {\n return (base.Price + CD.Price);\n }\n }\n }\n\n class NonTechnicalbook : Book\n {\n }\n\n abstract class Shop\n {\n private IDictionary<Book, int> BooksInStock;\n private IDictionary<Book, int> BooksSold;\n\n public Shop() {\n BooksInStock = new Dictionary<Book, int>();\n BooksSold = new Dictionary<Book, int>();\n }\n\n public virtual void Buy(Book book) {\n int count;\n if (!BooksInStock.TryGetValue(book, out count)) {\n count = 0;\n }\n BooksInStock[book] = count + 1;\n }\n\n public virtual void Sell(Book book) {\n int count;\n if (!BooksInStock.TryGetValue(book, out count)\n || count < 1\n ) {\n throw new ArgumentException(\"Book is not in stock.\", \"book\");\n }\n BooksInStock[book] = count - 1;\n\n if (!BooksSold.TryGetValue(book, out count)) {\n count = 0;\n }\n BooksSold[book] = count + 1;\n }\n\n public virtual int GetTotalBooksCount() {\n return GetStockCount() + GetSoldBooksCount();\n }\n public virtual int GetStockCount() {\n return BooksInStock.Values.Sum();\n }\n public virtual int GetSoldBooksCount() {\n return BooksSold.Values.Sum();\n }\n\n public virtual double GetTotalBooksPrice() {\n return GetStockBooksPrice() + GetSoldBooksPrice();\n }\n public virtual double GetStockBooksPrice() {\n return BooksInStock.Sum(pair => pair.Key.Price * pair.Value);\n /* Same as:\n double price = 0.0;\n foreach (var pair in BooksInStock) {\n Book book = pair.Key;\n int count = pair.Value;\n price += book.Price * count;\n }\n return price;*/\n }\n public virtual double GetSoldBooksPrice() {\n return BooksSold.Sum(pair => pair.Key.Price * pair.Value);\n }\n\n public virtual void Show() {\n Console.WriteLine(string.Format(\n \"Total number of books Bought & Price: {0} & {1}\",\n GetTotalBooksCount(),\n GetTotalBooksPrice()\n ));\n Console.WriteLine(string.Format(\n \"Total number of books Sold & Price: {0} & {1}\",\n GetSoldBooksCount(),\n GetSoldBooksPrice()\n ));\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T10:16:46.477",
"Id": "8802",
"ParentId": "8797",
"Score": "0"
}
},
{
"body": "<p>Overriding the <code>Price</code> property in <code>TechnicalBook</code> modifies the behavior of <code>Publication</code>. Which means you've broken the OCP. Besides, what do you expect <code>TechnicalBook.Price</code> to be if you have just set it to 10.0? (Does it even compile when you only override get?)</p>\n\n<p>What you could do is employ the template method pattern:</p>\n\n<pre><code>abstract class Publication\n{\n // ...\n public decimal IndividualPrice { get; set; }\n public decimal Price {\n get { return CalculatePrice(); }\n }\n\n protected decimal CalculatePrice() {\n decimal price = IndividualPrice;\n price += GetAdditionalPrices();\n return price;\n }\n\n protected virtual decimal GetAdditionalPrices() {\n return 0;\n }\n}\n\npublic class TechnicalBook : Publication\n{\n // ...\n protected override decimal GetAdditionalPrices() {\n return Cd.Price;\n }\n}\n</code></pre>\n\n<p>This makes <code>Publication</code> <em>closed</em> for modification (cannot change price / individual price), but <em>open</em> for extension (can add to price).</p>\n\n<p>(Naming and structure in my example could probably be improved, but it serves the purpose)</p>\n\n<p>The behavior is still possible to modify, though, so an even better solution would be to have some collection or set of rules you can add to, so you don't accidentaly override <code>GetAdditionalPrices</code> without calling <code>base.GetAdditionalPrices()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T14:54:21.743",
"Id": "13788",
"Score": "0",
"body": "What about my second question? How to show the prices of Technical and Non-technical books separately?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T15:39:57.140",
"Id": "13794",
"Score": "0",
"body": "For that you could for instance use LINQ.\nvar technicalBookTotal = soldBooks.Values.OfType<TechnicalBook>.Sum(b => b.Price);"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T10:39:14.773",
"Id": "8803",
"ParentId": "8797",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T07:31:42.317",
"Id": "8797",
"Score": "3",
"Tags": [
"c#"
],
"Title": "Bookstore classes design"
}
|
8797
|
<p>I'm trying to build a JavaScript library that does basic financial calculations, such as NPV, IRR, PV, FV, etc. So far I've added the NPV functionality only, and it's passed my test cases. But I want to know if the code overall can be written better.</p>
<pre><code>(function () {
/*
This library depends on underscore.js
*/
'use strict';
var root = this, previousFin = root.Fin, Fin = root.Fin = {}, _ = root._;
Fin.VERSION = '0.0.1';
Fin.PRECISION = 4; // floating point precision
/*
Runs Fin.js in noConflict mode and
returns reference to this Fin object
*/
Fin.noConflict = function () {
root.Fin = previousFin;
return this;
};
/*
NPV - Net Present Value
rate = the periodic discount rate
example: If the discount rate is 10% enter 0.1, not 10.
payments = an array or object (keys are the year numbers) of payments
example: [-100, 50, 60] means an initial cash outflow of 100 at time 0,
then cash inflows of 50 at the end of the period one, and 60 at
the end of the period two.
If you pass {0: -100, 2:50}, then the payment at the end of the
year one is assumed to be 0.
*/
Fin.npv = function (rate, payments, precision) {
if (isNaN(rate)) {
/* rate needs to be a number */
return null;
}
if (_.isArray(payments)) {
/* all elements of the array need to be numbers */
if (!_.all(payments, function (elem) { return !isNaN(elem); })) {
return null;
}
} else if (_.isObject(payments)) {
/* all key, value pairs of the object need to be numbers */
if (!_.all(payments, function (key, value) { return !isNaN(key) && !isNaN(value); })) {
return null;
}
} else {
/* payment needs to be either an array or an object */
return null;
}
if (typeof (precision) === 'undefined' || isNaN(precision)) {
precision = this.PRECISION;
}
var i, npv = 0;
for (i in payments) {
if (payments.hasOwnProperty(i)) {
npv += payments[i] / Math.pow((1 + rate), i);
}
}
return npv.toFixed(precision);
};
}).call(this);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T07:57:42.477",
"Id": "13779",
"Score": "1",
"body": "That's not much of an introduction. What does it do? Are there specific things you want to improve? Please paste the code in your question (highlight it and hit ctrl+k to format)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T15:01:46.817",
"Id": "13789",
"Score": "1",
"body": "As specified by our [faq], you must include your code in the post. I would edit it in myself, but it is not obvious to me what it's trying to accomplish. Please add the code and a brief description of the problem you're solving, and I'll be very happy to reopen the post."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T23:37:35.253",
"Id": "13828",
"Score": "0",
"body": "@MichaelK actually if you want to reopen it I'll fix it up, I think I see what he's after and have a pretty good idea for a review :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T13:19:48.880",
"Id": "13862",
"Score": "0",
"body": "@GGG That's what the edit button is for - go for it :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T17:00:42.860",
"Id": "13872",
"Score": "0",
"body": "@GGG, I've edited the post. Could you please give me your feedback on it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T17:06:27.097",
"Id": "13873",
"Score": "0",
"body": "@MichaelK, I've edited the question. Can you please open it now?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T18:37:07.413",
"Id": "13878",
"Score": "1",
"body": "wouldn't this produce an application wherby a bug in a client's JS interpreter could lead financial calculations gone wrong?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T18:49:50.247",
"Id": "13880",
"Score": "0",
"body": "@Gabriel I'm sure these aren't the end-all-be-all calculations, just some kind of preview thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T19:01:17.973",
"Id": "13882",
"Score": "0",
"body": "right, that makes sense"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T07:03:38.817",
"Id": "13903",
"Score": "1",
"body": "Do you really want to use the javascript built-in numerics for amounts of money? This is just asking for rounding errors. I strongly recommend coding up an implementation of decimal numbers."
}
] |
[
{
"body": "<ol>\n<li><p>Avoid getting a reference to the global object (\"window\") using <code>this</code>; it won't work in strict mode. If this is only meant to run in the browser, just use <code>window</code>; otherwise you can do <a href=\"https://stackoverflow.com/a/9647292/886931\">this</a>:</p>\n\n<pre><code>var root = (1,eval)('this');\n</code></pre></li>\n<li><p>Try to declare variables at the top of the function.</p></li>\n<li><p>Regarding <code>isArray</code>: Favor feature detection. Does it need to have a <code>length</code> property? A <code>push</code> function?</p></li>\n<li><p>Regarding <code>return null</code>: Just <code>return</code>. This will return <code>undefined</code>, which should be close enough 99.9% of the time.</p></li>\n<li><p><code>typeof (precision) === 'undefined'</code> can simply be <code>!precision</code> in this case.</p></li>\n<li><p>all those early isNaN checks seem redundant, why not just do the checks in the main loop? Or, better yet, leave out the checks entirely, let the calculation fail, and the function will return NaN by itself, which makes more sense than null or undefined.</p></li>\n</ol>\n\n<p>Incidentally, these changes will remove the underscore.js dependency.</p>\n\n<hr>\n\n<pre><code>(function () {\n\n 'use strict';\n\n var root = (1,eval)('this'),\n previousFin = root.Fin,\n Fin;\n\n root.Fin = Fin = {};\n\n Fin.VERSION = '0.0.1';\n Fin.PRECISION = 4; // floating point precision\n\n /*\n Runs Fin.js in noConflict mode and\n returns reference to this Fin object\n */\n Fin.noConflict = function () {\n root.Fin = previousFin;\n return this; \n };\n\n /*\n NPV - Net Present Value\n rate = the periodic discount rate\n example: If the discount rate is 10% enter 0.1, not 10.\n payments = an array or object (keys are the year numbers) of payments\n example: [-100, 50, 60] means an initial cash outflow of 100 at time 0,\n then cash inflows of 50 at the end of the period one, and 60 at\n the end of the period two.\n If you pass {0: -100, 2:50}, then the payment at the end of the\n year one is assumed to be 0.\n */\n Fin.npv = function (rate, payments, precision) {\n var i, npv = 0;\n if (!precision || isNaN(precision)) {\n precision = this.PRECISION;\n }\n for (i in payments) {\n if (payments.hasOwnProperty(i)) {\n // do the NaN check here if you want.\n // if (isNaN(payments[i])) return;\n npv += payments[i] / Math.pow((1 + rate), i);\n }\n }\n return npv.toFixed(precision);\n };\n}());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T19:20:25.543",
"Id": "13886",
"Score": "0",
"body": "Thanks. That's very helpful. I'll upvote you when I have 15 reputation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T19:30:17.623",
"Id": "13887",
"Score": "1",
"body": "No problem. Just remember it's not Java, you don't have to check everything... you can generally get away with just letting stuff fail by itself :) Also this will be way simpler if you do away with the noConflict thing. I'd really think about whether your intended users need that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T20:39:19.483",
"Id": "13889",
"Score": "0",
"body": "another great piece of advice! i'll definitely consider it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-10T23:12:16.100",
"Id": "210223",
"Score": "0",
"body": "is there an irr part to this as well?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T18:31:07.657",
"Id": "8859",
"ParentId": "8798",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "8859",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T07:45:44.707",
"Id": "8798",
"Score": "6",
"Tags": [
"javascript",
"library",
"finance"
],
"Title": "Basic financial calculation library"
}
|
8798
|
<p>For <a href="http://www.cs.rhul.ac.uk/home/joseph/teapot.html" rel="nofollow">this project</a>, I'm using a small piece of Python code to return an error 418 to any request. I'm interested in knowing if there is a much smaller piece of code that does the same thing.</p>
<pre><code>#Modfied from code provided by Copyright Jon Berg , turtlemeat.com import string,cgi,time from os import curdir, sep from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
#import pri
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_error(418,'I am a Teapot')
def main():
try:
server = HTTPServer(('', 80), MyHandler)
print 'started httpserver...'
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down server'
server.socket.close()
if __name__ == '__main__':
main()
</code></pre>
<p>PS - I considered putting this on Code Golf SE, but I wasn't sure if single-language-only requests are on-topic.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T17:26:06.027",
"Id": "13874",
"Score": "0",
"body": "Why do you want a shorter version?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T09:42:22.263",
"Id": "13905",
"Score": "0",
"body": "Oh, well, mainly out of interest and to perhaps illustrate to me that there are much more compact ways that this can be done..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-06T12:06:09.983",
"Id": "54428",
"Score": "1",
"body": "Code Golf questions should be asked exclusively on [codegolf.se] and are off-topic here."
}
] |
[
{
"body": "<p>Not really <em>smaller</em> but it will respond to any request, not just GET:</p>\n\n<pre><code>class MyHandler(BaseHTTPRequestHandler):\n def handle_one_request(self):\n self.send_error(418, 'I am a Teapot')\n</code></pre>\n\n<p>Usually, <code>handle_one_request</code> delegates to the appropriate <code>do_METHOD</code> method, but since we want to treat all of them equal, we may as well not let that delegation take place.</p>\n\n<p>In the interest of making things shorter, you generally don't need the <code>server.socket.close()</code>, unless you plan on restarting a server on that same port right after shutting down this server.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-29T18:40:11.477",
"Id": "9567",
"ParentId": "8799",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T08:52:33.457",
"Id": "8799",
"Score": "0",
"Tags": [
"python"
],
"Title": "Python server that only returns error 418"
}
|
8799
|
<p>I want to get a map of all the fields in a class (aka value object) in a generic way. The following works fine for me:</p>
<pre><code>class Baz {
String foo = "foo2"
int bar = 2
public Map asMap() {
def map = [:] as HashMap
this.class.getDeclaredFields().each {
if (it.modifiers == java.lang.reflect.Modifier.PRIVATE) {
map.put(it.name, this[it.name])
}
}
return map
}
}
</code></pre>
<p>But this doesn't feel like the proper way. Is there a better approach?</p>
|
[] |
[
{
"body": "<p>Here's one alternative:</p>\n\n<pre><code>class Baz {\n String foo = 'foo2'\n int bar = 2\n\n public Map asMap() {\n this.class.declaredFields.findAll { it.modifiers == java.lang.reflect.Modifier.PRIVATE }.\n collectEntries { [it.name, this[it.name]] }\n }\n}\n</code></pre>\n\n<p>Basically, I'm finding just the fields with the modifiers value set to private and then collecting those as Map entries.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-23T22:49:33.257",
"Id": "9343",
"ParentId": "8801",
"Score": "2"
}
},
{
"body": "<p>Another alternative (very similar to Matt's) is to use the synthetic field property (which is set for default class properties, but not for your own defined props):</p>\n\n<pre><code>class Baz {\n String foo = \"foo2\"\n int bar = 2\n\n public Map asMap() {\n this.class.declaredFields.findAll { !it.synthetic }.collectEntries {\n [ (it.name):this.\"$it.name\" ]\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-24T14:58:01.603",
"Id": "14759",
"Score": "1",
"body": "@neu242 as much I like having people choose my answer, the find criteria Tim is using is better. If you just look for properties with the modifiers bitmask equal to PRIVATE, you could miss properties that are (for example) private AND final."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-24T15:02:02.860",
"Id": "14760",
"Score": "0",
"body": "For the collectEntries expression, I'm using `[it.name, this[it.name]]` and you're using `[(it.name):this.\"$it.name\"]`. It's interesting that it works with both a list and a map..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-24T15:07:58.713",
"Id": "14761",
"Score": "1",
"body": "@MattPassell Yeah, `collectEntries` ends up calling the private [`addEntry` method](https://github.com/groovy/groovy-core/blob/master/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L2543) which deals with Maps and 2 element lists as separate cases (but with the same outcome) :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-24T15:35:02.833",
"Id": "14763",
"Score": "0",
"body": "cool. I think I'll go with your approach in the future - feels more intuitive to specify it as a Map entry. Thanks! (this comment is supposed to start with @Tim, but it keeps getting trimmed off! StackExchange bug?)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-24T15:51:10.687",
"Id": "14765",
"Score": "0",
"body": "@MattPassell See I didn't realise you could do it the 2 element list way until you mentioned it, I missed it in your code! ;-) And as for the `@Tim` thing, I got a reply notification... the StackOverflow rules about when it does and doesn't let you put an `@` are esoteric and seem to constantly shift, I always add it, then don't miss it when it's gone ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-04T10:34:18.557",
"Id": "189450",
"Score": "3",
"body": "But unfortunately it will not list fields, declared in parent class.\nNow I end with:\n`this.metaClass.properties.findAll{ 'class' != it.name }`\ninstead of yours `this.class.declaredFields.findAll { !it.synthetic }`"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-24T09:45:18.053",
"Id": "9353",
"ParentId": "8801",
"Score": "26"
}
},
{
"body": "<p>I took inspiration from @tim_yates answer and defined a <code>Mappable</code> trait which handles nested <code>Mappable</code> objects. The Trait (as opposed to a class) will make your <code>asMap</code> method more generically applicable, which is one of the goals you have stated.</p>\n\n<pre><code>trait Mappable {\n\n Map asMap() {\n this.metaClass.properties.findAll{ 'class' != it.name }.collectEntries {\n if( Mappable.isAssignableFrom(it.type) ){\n [ (it.name):this.\"$it.name\"?.asMap() ]\n }else{\n [ (it.name):this.\"$it.name\" ]\n }\n }\n }\n\n}\n</code></pre>\n\n<p>To use it just make the desired classes implement <code>Mappable</code>. Traits are a great way to achieve composition of behaviors, for those using groovy and still unfamiliar with them have a look at the <a href=\"http://docs.groovy-lang.org/next/html/documentation/core-traits.html\" rel=\"noreferrer\">docs</a> for enlightenment.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-23T16:45:00.510",
"Id": "260874",
"Score": "2",
"body": "Welcome to Code Review! This answer is OK, but it could be a lot better if you added a brief explanation of why you think your solution is better than the original."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-23T17:03:22.317",
"Id": "260876",
"Score": "1",
"body": "Another option could also be to just use the `asMap` method as a static method somewhere I guess."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-24T07:56:21.817",
"Id": "260999",
"Score": "1",
"body": "Thank you @200_success for the welcome! And thank you rolfl for complementing my thoughts. Simon Forsberg the static method is also a solution but is less object oriented and probably will end up in a [Util class](http://stackoverflow.com/questions/3340032/utility-classes-are-evil)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-23T15:48:59.550",
"Id": "139436",
"ParentId": "8801",
"Score": "8"
}
},
{
"body": "<p>If you don't mind using a few libraries, here's an option where you convert the object to JSON and then parse it back out as a map. I added mine to a baseObject which in your case object would extend.</p>\n\n<pre><code>class BaseObject {\n\n Map asMap() {\n def jsonSlurper = new groovy.json.JsonSlurperClassic()\n Map map = jsonSlurper.parseText(this.asJson())\n return map\n }\n\n String asJson(){\n def jsonOutput = new groovy.json.JsonOutput()\n String json = jsonOutput.toJson(this)\n return json\n }\n\n}\n</code></pre>\n\n<p>I also wrote it without the JSON library originally. This is like the other answers, but handles cases where the object property is a List.</p>\n\n<pre><code>class BaseObject {\n\n Map asMap() {\n Map map = objectToMap(this)\n return map\n }\n\n def objectToMap(object){\n Map map = [:]\n for(item in object.class.declaredFields){\n if(!item.synthetic){\n if (object.\"$item.name\".hasProperty('length')){\n map.\"$item.name\" = objectListToMap(object.\"$item.name\")\n } else if (object.\"$item.name\".respondsTo('asMap')){\n map << [ (item.name):object.\"$item.name\"?.asMap() ]\n } else{\n map << [ (item.name):object.\"$item.name\" ]\n }\n }\n }\n\n return map\n }\n\n def objectListToMap(objectList){\n List list = []\n for(item in objectList){\n if (item.hasProperty('length')){\n list << objectListToMap(item)\n } else {\n list << objectToMap(item)\n }\n }\n return list\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-11-28T15:58:52.197",
"Id": "181498",
"ParentId": "8801",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "9353",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T09:55:14.453",
"Id": "8801",
"Score": "18",
"Tags": [
"object-oriented",
"reflection",
"groovy"
],
"Title": "Returning Groovy class fields as a map"
}
|
8801
|
<p>I have a collection of radio buttons, and when I click on one, the label and text stay on the table.</p>
<p><strong>HTML - radio</strong></p>
<pre><code><div id="par01WraperAbsolute">
<div class="close"></div>
<div id="par01">
<form id="form01">
<fieldset>
<legend>Wykԡdzina</legend>
<div class="inputWraper clearfix">
<input type = "radio"
name = "wykladzina"
id = "par01par01"
value = ""
checked = "checked" />
<label id="par01par01Label" for = "par01par01">Label 01:</label>
<p id="par01par01text" class="formP ">Text01</p>
</div>
<div class="inputWraper clearfix">
<input type = "radio"
name = "wykladzina"
id = "par01par02"
value = "" />
<label id="par01par02Label" for = "par01par02">Label 02:</label>
<p id="par01par02text" class="formP ">Text02</p>
</div>
<div class="inputWraper clearfix">
<input type = "radio"
name = "wykladzina"
id = "par01par03"
value = "" />
<label id="par01par03Label" for = "par01par03">Label03:</label>
<p id="par01par03text" class="formP"><textarea></textarea></p>
</div>
<div class="inputWraper clearfix uwagi">
<label for = "par01par04">Comments:</label>
<p id="par01par04text" class="formP "><textarea></textarea></p>
</div>
</fieldset>
</form>
</div>
</div>
<div id="par02WraperAbsolute">
<div class="close"></div>
<div id="par02">
<form id="form02">
<fieldset>
<legend>ͣiany Dzialowe</legend>
<div class="inputWraper clearfix">
<input type = "radio"
name = "scianyDzialowe"
id = "par02par01"
value = ""
checked = "checked" />
<label id="par02par01Label" for = "par02par01">Label01:</label>
<p id="par02par01text" class="formP ">Text01</p>
</div>
<div class="inputWraper clearfix">
<input type = "radio"
name = "scianyDzialowe"
id = "par02par02"
value = "" />
<label id="par02par02Label" for = "par02par02">Label02:</label>
<p id="par02par02text" class="formP ">Text02</p>
</div>
<div class="inputWraper clearfix">
<input type = "radio"
name = "scianyDzialowe"
id = "par02par03"
value = "" />
<label id="par02par03Label" for = "par02par03">Label03:</label>
<p id="par02par03text" class="formP"><textarea></textarea></p>
</div>
<div class="inputWraper clearfix uwagi">
<label for = "par02par04">Comments:</label>
<p id="par02par04text" class="formP "><textarea></textarea></p>
</div>
</fieldset>
</form>
</div>
</div>
<div id="par03WraperAbsolute">
<div class="close"></div>
<div id="par03">
<form id="form03">
<fieldset>
<legend>ͣiany systemowe</legend>
<div class="inputWraper clearfix">
<input type = "radio"
name = "scianySystemowe"
id = "par03par01"
value = ""
checked = "checked" />
<label id="par03par01Label" for = "par03par01">Label01:</label>
<p id="par03par01text" class="formP ">Text01</p>
</div>
<div class="inputWraper clearfix">
<input type = "radio"
name = "scianySystemowe"
id = "par03par02"
value = "" />
<label id="par03par02Label" for = "par03par02">Label02:</label>
<p id="par03par02text" class="formP ">Text02</p>
</div>
<div class="inputWraper clearfix">
<input type = "radio"
name = "scianySystemowe"
id = "par03par03"
value = "" />
<label id="par03par03Label" for = "par03par03">Label03:</label>
<p id="par03par03text" class="formP"><textarea></textarea></p>
</div>
<div class="inputWraper clearfix uwagi">
<label for = "par03par04">Comments:</label>
<p id="par03par04text" class="formP "><textarea></textarea></p>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</code></pre>
<p><strong>HTML - table</strong></p>
<pre><code><table>
<tr>
<th colspan="2">Title01</th>
</tr>
<tr>
<td id="par01Label" class="par01table">Label01:</td>
<td id="par01Text" class="par01table">Text01</td>
<td id="par01TextHidden" style="display: none"></td>
</tr>
<tr>
<td id="par01LabelComments" class="comments">Comments:</td>
<td id="par01TextComments" class="comments"></td>
</tr>
<tr>
<th colspan="2">Title02</th>
</tr>
<tr>
<td id="par02Label" class="par02table">Label02:</td>
<td id="par02Text" class="par02table">Text02</td>
<td id="par02TextHidden" style="display: none"></td>
</tr>
<tr>
<td id="par02LabelComments" class="par02table comments">Comments:</td>
<td id="par02TextComments" class="par02table comments"></td>
</tr>
<tr>
<th colspan="2">Title03</th>
</tr>
<tr>
<td id="par03Label" class="par03table">Label03:</td>
<td id="par03Text" class="par03table">Text03</td>
<td id="par03TextHidden" style="display: none"></td>
</tr>
<tr>
<td id="par03LabelComments" class="par03table comments">Comments:</td>
<td id="par03TextComments" class="par03table comments"></td>
</tr>
</table>
</code></pre>
<p><strong>jQuery</strong></p>
<pre><code>$("#par01par01").click(function(){
var text = $('#par01par01Label').text();
$("#par01Label").text(text);
});
$("#par01par02").click(function(){
var text = $('#par01par02Label').text();
$("#par01Label").text(text);
});
$("#par01par03").click(function(){
var text = $('#par01par03Label').text();
$("#par01Label").text(text);
});
$("#par01par01").click(function(){
var text = $('#par01par01text').text();
$("#par01Text").text(text);
});
$("#par01par02").click(function(){
var text = $('#par01par02text').text();
$("#par01Text").text(text);
});
$("#par01par03").click(function(){
var text = $('#par01TextHidden').text();
$("#par01Text").text(text);
});
$("#par02par01").click(function(){
var text = $('#par02par01Label').text();
$("#par02Label").text(text);
});
$("#par02par02").click(function(){
var text = $('#par02par02Label').text();
$("#par02Label").text(text);
});
$("#par02par03").click(function(){
var text = $('#par02par03Label').text();
$("#par02Label").text(text);
});
$("#par02par01").click(function(){
var text = $('#par02par01text').text();
$("#par02Text").text(text);
});
$("#par02par02").click(function(){
var text = $('#par02par02text').text();
$("#par02Text").text(text);
});
$("#par02par03").click(function(){
var text = $('#par02TextHidden').text();
$("#par02Text").text(text);
});
$("#par03par01").click(function(){
var text = $('#par03par01Label').text();
$("#par03Label").text(text);
});
$("#par03par02").click(function(){
var text = $('#par03par02Label').text();
$("#par03Label").text(text);
});
$("#par03par03").click(function(){
var text = $('#par03par03Label').text();
$("#par03Label").text(text);
});
$("#par03par01").click(function(){
var text = $('#par03par01text').text();
$("#par03Text").text(text);
});
$("#par03par02").click(function(){
var text = $('#par03par02text').text();
$("#par03Text").text(text);
});
$("#par03par03").click(function(){
var text = $('#par03TextHidden').text();
$("#par03Text").text(text);
});
</code></pre>
<p>There will be many more of these radio buttons. Is there a way to write this shorter or more optimally?</p>
|
[] |
[
{
"body": "<p>I'm not sure if this would work. If it works, it seems like a very good first improvement.</p>\n\n<p>But it would be much better to have a generic approach, rather than having to write all cases one by one.</p>\n\n<pre><code>function triggerDependency(trigger, target) {\n $(trigger).click(function(){\n var text = $(trigger+'Label').text();\n $(target).text(text); \n });\n}\ntriggerDependency(\"#par01par01\", \"#par01Label\");\ntriggerDependency(\"#par02par03\", \"#par02Label\");\n// ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T15:38:48.530",
"Id": "8812",
"ParentId": "8805",
"Score": "3"
}
},
{
"body": "<p>You could add a data attribute to your radio that specifies the target label. Then the jQuery would be dynamic based on your HTML.</p>\n\n<h3>HTML</h3>\n\n<pre><code><input type = \"radio\"\n name = \"wykladzina\"\n id = \"par01par01\"\n value = \"\"\n checked = \"checked\"\n\n data-target = \"par01Label\" />\n\n<label id=\"par01par01Label\" for = \"par01par01\">Label 01:</label>\n</code></pre>\n\n<h3>jQuery</h3>\n\n<pre><code>$('radio').click(function() {\n var el = $(this),\n\n // get the corresponding label ID\n label = el.attr('id') + 'Label',\n\n // grab the text\n text = $('#' + label).text(),\n\n // find the target label\n target = el.data('target');\n\n // update the target's text\n $('#' + target).text(text);\n});\n</code></pre>\n\n<p><strong>Note:</strong> You may need to extend the way I choose each label's ID. I just noticed that you also need to update <code>#par01par01text</code> as well.</p>\n\n<hr>\n\n<p>I wouldn't recommend binding two separate click events that do relatively the same thing. It will become a pain to work with in the long run.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T15:40:31.037",
"Id": "8813",
"ParentId": "8805",
"Score": "1"
}
},
{
"body": "<p>Here is a refactoring for the first few blocks. You should be able to use the helper functions to refactor the rest yourself</p>\n\n<pre><code>$(function() { \n// immediately executing function since functions \n// are the only way of limiting variable scope in javascript\n\nvar onChangeTargetToLabelText(form, target) {\n var target = $(target); // target and form can be string selectors, jquery objects or DOM elements, all will behave the same because jquery wraps it\n $('input[type=checkbox]', form).change(function() { \n //this function copies the text from the label following the clicked checkbox\n // to the target \n target.text($(this).next('label').text()); //you might want to use nextAll - look up the difference\n });\n },\n\n onChangeCopyText = function(changeFrom, to){\n //this function abstracts away 'on change of X, copy the text of Y'\n $(changeFrom[0]).change(){$(to).text($(changeFrom[1]).text()); }\n };\n\n\nonChangeTargetToLabelText('#form01', '#par01Label');\nonChangeCopyText([\n ['#par01par01', '#par01par01text' ],\n ['#par01par02', '#par01par02text'],\n ['#par01par03', '#par01TextHidden']\n], $('#par01Text')); //only selecting the to variable once - looking up stuff in the DOM is expensive-ish\n\nonChangeTargetToLabelText('#form02', '#par02Label');\n\n// ... I you can write out the rest yourself \n\n})();//invoke the immediately executing function\n</code></pre>\n\n<p>Some notes:</p>\n\n<ul>\n<li><a href=\"http://screwlewse.com/2010/07/dont-use-id-selectors-in-css/\" rel=\"nofollow\">You avoid id selectors most of the time</a>, mostly because if you get 2 of the same one on the page things get wonky and very hard to debug.</li>\n<li>You should use the <a href=\"http://api.jquery.com/jQuery/\" rel=\"nofollow\">jquery context parameter</a> to make looking up your elements faster and less bug-prone</li>\n<li>What you are doing here is a bit weird, are you sure that what you want to copy is the label value? It's not going to change? Consider using the checkbox's value attribute instead</li>\n<li>It is uncommon to suffix element names/classes/ids with the element type - element types change and people forget to update them - it is more useful to name elements after what they are being used for.</li>\n<li>Take this with a grain of salt, but this sounds like a very intimidating UI design. So many options all at the same time? Maybe they should be broken down into pages and sections.</li>\n</ul>\n\n<p>Feel free to ask questions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-16T13:18:06.360",
"Id": "14185",
"Score": "0",
"body": "thx to all for your help, and tips"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T17:25:54.613",
"Id": "8820",
"ParentId": "8805",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "8812",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T11:29:48.847",
"Id": "8805",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Keeping labels and text on a table"
}
|
8805
|
<p>Here's my first attempt at creating a WeakAction using Expressions and Delegates. I would like it to be clear that this code was written after reading serveral blogs and taking snippets from various sources.</p>
<p>The Program class at the bottom shows a few examples of how to use it.</p>
<p>Does anyone have any performance improvements when it comes to creating delegates? I'm still trying to get my head around them. All suggestions and any constructive feedback is welcome.</p>
<pre><code>using System;
using System.Linq.Expressions;
using System.Reflection;
namespace WeakAction
{
public class WeakAction<T> where T : class
{
private readonly WeakReference weakRef;
private readonly Type ownerType;
private readonly string methodName;
public WeakAction(object instance, Expression expression)
{
var method = GetMethodInfo(expression);
methodName = method.Name;
if (instance == null)
{
if (!method.IsStatic)
{
throw new ArgumentException("instance cannot be null for instance methods");
}
this.ownerType = method.DeclaringType;
}
else
{
this.weakRef = new WeakReference(instance);
}
}
public T Delegate
{
get { return this.GetMethod(); }
}
public bool HasBeenCollected
{
get
{
return this.ownerType == null &&
(this.weakRef == null || !this.weakRef.IsAlive);
}
}
public bool IsInvokable
{
get { return !HasBeenCollected; }
}
private static MethodInfo GetMethodInfo(Expression expression)
{
LambdaExpression lambda = expression as LambdaExpression;
if (lambda == null)
{
throw new ArgumentException("expression is not LambdaExpression");
}
MethodCallExpression outermostExpression = lambda.Body as MethodCallExpression;
if (outermostExpression == null)
{
throw new ArgumentException("Invalid Expression. Expression should consist of a Method call only.");
}
return outermostExpression.Method;
}
private T GetMethod()
{
if (this.ownerType != null)
{
return System.Delegate.CreateDelegate(typeof(T), this.ownerType, this.methodName) as T;
}
if (this.weakRef != null && this.weakRef.IsAlive)
{
object localTarget = this.weakRef.Target;
if (localTarget != null)
{
return System.Delegate.CreateDelegate(typeof(T), localTarget, this.methodName) as T;
}
}
return null;
}
}
}
using System;
using System.Linq.Expressions;
namespace WeakAction
{
public class Program
{
public static void Main()
{
var testClass = new TestClass();
// instance method
Expression<Func<int>> instanceExpression = () => testClass.Stuff();
var weakStuff = new WeakAction<Func<int>>(testClass, instanceExpression);
if (!weakStuff.HasBeenCollected)
{
var result = weakStuff.Delegate();
}
// static method
Expression<Func<int>> staticExpression = () => TestClass.MoreStuff();
var staticWeakRef = new WeakAction<Func<int>>(null, staticExpression);
if (!staticWeakRef.HasBeenCollected)
{
var result = staticWeakRef.Delegate();
}
// instance method taking an arg
Expression<Action<string>> argExpression = (str) => testClass.TakesAnArg(str);
var instanceWithArg = new WeakAction<Action<string>>(testClass, argExpression);
if (instanceWithArg.IsInvokable)
{
instanceWithArg.Delegate("hello bert!");
}
Console.Read();
}
public class TestClass
{
public int Stuff()
{
Console.WriteLine("Stuff invoked!");
return 1;
}
public void TakesAnArg(string msg)
{
Console.WriteLine(msg);
}
public static int MoreStuff()
{
Console.WriteLine("More stuff invoked!");
return 1;
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T15:11:00.170",
"Id": "13791",
"Score": "0",
"body": "can you provide the links to blogs you sourced from?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T15:13:45.673",
"Id": "13792",
"Score": "1",
"body": "Sure thing: http://www.paulstovell.com/weakevents and http://msmvps.com/blogs/jon_skeet/archive/2008/08/09/making-reflection-fly-and-exploring-delegates.aspx were the main two sources. I also read over some code written at my workplace but i'm not sure who wrote it."
}
] |
[
{
"body": "<p><strong>Design</strong></p>\n\n<p>Reading the code it looks to me as if there are two separate things mixed. Effectively you have two different code paths through your class - one for static method calls and one for instance method calls which do not have much in common. I'd consider to refactor this into separate classes to simplify some of the logic and separate the concerns. Something along these lines:</p>\n\n<pre><code>public abstract class WeakAction<T> where T : class\n{\n protected readonly MethodInfo _Method;\n\n private class WeakActionStatic : WeakAction<T>\n {\n private readonly Type _Owner;\n\n public WeakActionStatic(MethodInfo method)\n : base(method)\n {\n if (!method.IsStatic)\n {\n throw new ArgumentException(\"static method expected\", \"method\");\n }\n _Owner = method.DeclaringType;\n }\n\n public override bool HasBeenCollected\n {\n get { return false; }\n }\n\n protected override T GetMethod()\n {\n return System.Delegate.CreateDelegate(typeof(T), _Owner, _Method.Name) as T;\n }\n }\n\n private class WeakActionInstance : WeakAction<T>\n {\n private readonly WeakReference _WeakRef;\n\n protected WeakActionInstance(MethodInfo method)\n : base(method)\n {\n }\n\n public WeakActionInstance(object instance, MethodInfo method)\n : this(method)\n {\n if (instance == null)\n {\n throw new ArgumentNullException(\"instance must not be null\", \"instance\");\n }\n _WeakRef = new WeakReference(instance);\n }\n\n public override bool HasBeenCollected\n {\n get { return !_WeakRef.IsAlive; }\n }\n\n protected override T GetMethod()\n {\n if (HasBeenCollected) { return null; }\n\n object localTarget = _WeakRef.Target;\n if (localTarget == null) { return null; }\n\n return System.Delegate.CreateDelegate(typeof(T), localTarget, _Method.Name) as T;\n }\n }\n\n protected WeakAction(MethodInfo method)\n {\n _Method = method;\n }\n\n public static WeakAction<T> Create(Expression expression)\n {\n return new WeakActionStatic(GetMethodInfo(expression));\n }\n\n public static WeakAction<T> Create(object instance, Expression expression)\n {\n return new WeakActionInstance(instance, GetMethodInfo(expression));\n }\n\n protected abstract T GetMethod();\n\n public T Delegate\n {\n get { return GetMethod(); }\n }\n\n public abstract bool HasBeenCollected { get; }\n\n public bool IsInvokable\n {\n get { return !HasBeenCollected; }\n }\n\n private static MethodInfo GetMethodInfo(Expression expression)\n {\n LambdaExpression lambda = expression as LambdaExpression;\n if (lambda == null)\n {\n throw new ArgumentException(\"expression is not LambdaExpression\");\n }\n\n MethodCallExpression outermostExpression = lambda.Body as MethodCallExpression;\n\n if (outermostExpression == null)\n {\n throw new ArgumentException(\"Invalid Expression. Expression should consist of a Method call only.\");\n }\n\n return outermostExpression.Method;\n }\n}\n</code></pre>\n\n<p>Seems slightly more OO style as it has less <code>if</code>s related to what kind of <code>WeakAction</code> you actually have (static or instance).</p>\n\n<p>That leads me to the point of questioning the purpose of static weak actions. Unless I'm missing something those are not really weak and you could just use an <code>Action<T></code> to store them for later execution.</p>\n\n<p><strong>Potential Bugs/Problems</strong></p>\n\n<p>The point of a weak action is to effectively weakly bind to an object so you can call a method on it if it is still alive if I'm not mistaken. Your examples show this basic usage:</p>\n\n<pre><code>if (weakAction.IsInvokable) weakAction.Delegate();\n</code></pre>\n\n<p>However between checking and actually obtaining the delegate the reference could have gone away and now you get a <code>NullReferenceException</code>. You could avoid it by doing this I guess:</p>\n\n<pre><code>var func = weakAction.Delegate;\nif (func != null) func();\n</code></pre>\n\n<p>But somehow I have the feeling there could be a nicer interface which doesn't require the caller to have all that implicit knowledge. I'm just not sure how to effectively deal with argument passing while still retaining the static compiler type checking. Just wanted to throw this out there.</p>\n\n<p><strong>Style</strong></p>\n\n<ol>\n<li><p>I would consider renaming <code>Delegate</code> into <code>Execute</code>. While it's a property and not a function somehow <code>weakAction.Execute()</code> reads slightly nicer than <code>weakAction.Delegate()</code>.</p></li>\n<li><p>Usual C# naming convention for class members seems to be <code>_camelCase</code> or <code>_PascalCase</code> reserving <code>camelCase</code> for local variables. This way you can also get rid of the <code>this.</code> which mostly just clutters the code.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T08:38:29.263",
"Id": "36185",
"ParentId": "8807",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T13:08:39.907",
"Id": "8807",
"Score": "4",
"Tags": [
"c#",
"delegates"
],
"Title": "WeakAction Implementation"
}
|
8807
|
<p>I wrote a simple program that takes the <code>enable1.txt</code> word list of scrabble/words with friends and searches it for an input. In order to search the massive list of 172,820 words I figured sorting it then using a binary search would be a good idea.</p>
<p>The sorting algorithm I used was <code>std::stable_sort</code> as I wanted similar words stay in their locations. After profiling, the <code>std::stable_sort</code> is taking 37% of the run time.</p>
<p>Should I have used <code>std::stable_sort</code>? Would <code>std::sort</code> have been better? Would a different sort entirely had been a better idea? Is there a faster sort other than rolling my own?</p>
<p>Code:</p>
<pre><code>#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
#include <ctime>
double Search(const std::vector<std::string>& obj);
double BSearch(const std::vector<std::string>& obj);
int main() {
std::cout << "Loading database...";
std::ifstream db;
db.open("enable1.txt", std::ios::in);
unsigned long number_of_words = 0;
const unsigned short max_length = 50;
while(db.fail() == false) {
char dump[max_length];
db.getline(&dump[0], max_length);
++number_of_words;
}
db.close();
db.clear();
std::cout << "done" << std::endl;
std::vector<std::string> words(number_of_words);
words.reserve(number_of_words);
db.open("enable1.txt", std::ios::in);
unsigned long i = 0;
while(std::getline(db, words[i], '\n')) {
++i;
}
db.close();
db.clear();
std::cout << "Sorting database...";
std::stable_sort(words.begin(), words.end());
std::cout << "done" << std::endl << std::endl;
double seconds = Search(words);
std::cout << "Time for Search: " << seconds << std::endl;
double b_seconds = BSearch(words);
std::cout << "Time for BSearch: " << b_seconds << std::endl;
std::cout << "Cleaning up resources, please wait..." << std::endl;
return 0;
}
double Search(const std::vector<std::string>& obj) {
std::cout << "Enter word: ";
std::string word;
std::getline(std::cin, word);
std::cout << "Searching database..." << std::endl;
std::vector<std::string, std::allocator<std::string> >::size_type s = obj.size();
unsigned long mid = s / 2;
unsigned long first = 0;
unsigned long last = s - 1;
std::clock_t end_time = 0;
std::clock_t start_time = clock();
while(first <= last) {
std::cout << "Checking: " << word << " with " << obj[mid] << std::endl;
int result = word.compare(obj[mid]);
if(result == 0) {
end_time = clock();
std::cout << "Valid word." << std::endl;
return std::difftime(end_time, start_time);
} else if(result < 0) {
last = mid - 1;
mid = ((last - first) / 2 + first);
} else {
first = mid + 1;
mid = ((last - first) / 2) + first;
}
}
end_time = clock();
std::cout << word << " is not a valid word." << std::endl;
return std::difftime(end_time, start_time);
}
double BSearch(const std::vector<std::string>& obj) {
std::cout << "Enter word: ";
std::string word;
std::getline(std::cin, word);
std::cout << "Searching database..." << std::endl;
std::clock_t end_time = 0;
std::clock_t start_time = clock();
if(std::binary_search(obj.begin(), obj.end(), word)) {
end_time = clock();
std::cout << "Valid word." << std::endl;
return std::difftime(end_time, start_time);
}
end_time = clock();
std::cout << word << " is not a valid word." << std::endl;
return std::difftime(end_time, start_time);
}
</code></pre>
<p>The <code>Search</code> and <code>BSearch</code> methods are the same, one uses a hand-coded binary search and the other uses the STL version. (I was verifying their speed differences...unsurprisingly, there isn't one.)</p>
<p>As an after thought: Is there a better way to count the number of lines in a file? Maybe without having to open and close the file twice?</p>
<p>P.S. If you're wondering about the message at the end of the program, that's due to the vector of 170,000+ strings cleaning up after going out of scope. It takes a while.</p>
|
[] |
[
{
"body": "<h3>Answer to generic questions</h3>\n<blockquote>\n<p>In order to search the massive list of 172,820 words</p>\n</blockquote>\n<p>That's relatively small (OK small->medium).</p>\n<blockquote>\n<p>I figured sorting it then using a binary search would be a good idea.</p>\n</blockquote>\n<p>Yes that's a good idea.</p>\n<blockquote>\n<p>The sorting algorithm I used was std::stable_sort as I wanted similar words stay in their locations.</p>\n</blockquote>\n<p>Why. Stable sort means that if two words have the same value (they are equal) they maintain their relative order. Since you are searching for a single value (not a group of values) should you not be dedupping your input anyway. Even if you want to maintain multiple entries of the same word is their position in the input file significant in any way?</p>\n<blockquote>\n<p>Should I have used std::stable_sort?</p>\n</blockquote>\n<p>No.</p>\n<blockquote>\n<p>Would std::sort have been better?</p>\n</blockquote>\n<p>Maybe.<br />\nI would consider using a sorted container that does the work of dedupping for you.</p>\n<blockquote>\n<p>Would a different sort entirely had been a better idea?</p>\n</blockquote>\n<p>The only way to know is to actually do it and test the difference. But std::sort provides a complexity of O(n.log(n)) on average which is hard to beat unless you know something about your input set.</p>\n<blockquote>\n<p>As an after thought: Is there a better way to count the number of lines in a file? Maybe without having to open and close the file twice?</p>\n</blockquote>\n<p>You can re-wind the file to the beginning by using seek() (seekg() of file streams).</p>\n<blockquote>\n<p>The Search and BSearch methods are the same, one uses a hand-coded binary search and the other uses the STL version. (I was verifying their speed differences...unsurprisingly, there isn't one.)</p>\n</blockquote>\n<p>Your timing is invalid. You are printing to a stream in the middle of the timed section. This will be the most significant cost in your search and will outweigh the cost of the search by an order of magnitude. Remove the prints <code>std::cout << message;</code> and re-time.</p>\n<blockquote>\n<p>P.S. If you're wondering about the message at the end of the program, that's due to the vector of 170,000+ strings cleaning up after going out of scope. It takes a while.</p>\n</blockquote>\n<p>Which message are you referring too. And define a while. I would not expect the cleanup of strings to be significantly slow (there there is a cost).</p>\n<h3>Comments on Code</h3>\n<p>Your code seems very dense. White space is your friend when writing readable code.</p>\n<p>There is no need to open/close and clear a file. Calling clear on a file after it has closed has no affect and the subsequent open() would reset the internal state of the stream anyway. When reading a file I see little point in explicitly opining and closing a file (let the constructor/destructor do that). See <a href=\"https://codereview.stackexchange.com/a/544/507\">https://codereview.stackexchange.com/a/544/507</a></p>\n<pre><code>std::ifstream db("enable1.txt");\n\n// Do Stuff\n\ndb.clear(); // Clear the EOF flag\ndb.seekg(ios_base::beg, 0); // rewind to beginning\n\n// Do more stuff\n</code></pre>\n<p>There is an easier way to count the number of words. Note there is also a safer version of getline() that uses strings and thus can't overflow.</p>\n<pre><code>std::string line;\nstd::getline(db, line); // Reads one line.\n</code></pre>\n<p>Given that you are actually reading the number of lines but counting it as words means that the file is one word per line. Also testing the state of the stream pre-using it is an anti-pattern and nearly always wrong.</p>\n<pre><code>while(db.fail() == false) {\n</code></pre>\n<p>This will result in an over-count of 1. This is because the last word read will read up-to but not past the EOF. Thus the EOF flag is not set and you re-enter the loop. You then try and read the next word (which is not there resulting in the stream setting the EOF flag but you increment the word count anyway. If you do it this way then you need to check the state of the stream after the read.</p>\n<pre><code>while( db.SomeActionToReadFromIt()) {\n</code></pre>\n<p>Thus in all common languages you do a read as part of the while condition. The result of the read indicates if the loop should be entered (if the read worked then do the loop and processes the value you just read).</p>\n<p>The operator >> when used on a string will read one white-space separated words. So to count the number of words in a file a trivial implementation would be:</p>\n<pre><code>std::string line;\nwhile(std::getline(db, line))\n{ ++number_of_words;\n}\n\n// Or alternatively\n\nstd::string word;\nwhile(db >> word)\n{ ++number_of_words;\n}\n</code></pre>\n<p>Note it is important to note the second version here. This is because you can use stream iterators and some standard functions to achieve the same results. Note: stream iterators use the operator >> to read their target.</p>\n<pre><code>std::size_t size = std::distance(std::istream_iterator<std::string>(db),\n std::istream_iterator<std::string>());\n</code></pre>\n<p>If you want absolute speed then the C interface could be used (though I would not recommend it).</p>\n<p>There is no need to set the size of the vector and then reserve the same size.</p>\n<pre><code>std::vector<std::string> words(number_of_words);\nwords.reserve(number_of_words);\n</code></pre>\n<p>Personally I would just use reserve(). That way you do not need to prematurely construct 170,000 empty strings. But then you would need to use push_back rather than explicit read into an element (so swings and roundabouts). An alternative to your loop is to use stream iterator again to copy the file into the vector:</p>\n<pre><code>unsigned long i = 0;\nwhile(std::getline(db, words[i], '\\n')) { // no need for the '\\n' here!\n ++i;\n}\n\n// Alternatively you can do this:\nstd::copy(std::istream_iterator<std::string>(db), std::istream_iterator<std::string>(),\n std::back_inserter(words)\n );\n</code></pre>\n<p>Now you sort the container:<br />\nAlternatively you can use a sorted container. I would consider using std::set. Then you can just insert all the words. std::set has a neat find() methods that searches the now sorted container:</p>\n<pre><code>std::set<std::string> words;\nstd::copy(std::istream_iterator<std::string>(db), std::istream_iterator<std::string>(),\n std::inserter(words, words.end())\n );\n</code></pre>\n<p>The container is automatically sorted and de-dupped. And you can just use find on it:</p>\n<pre><code>if (words.find("Loki") != words.end())\n{\n // We have found it.\n}\n</code></pre>\n<p>Unless you are doing something really clever then let the compiler default the template arguments you are not specifying:</p>\n<pre><code>std::vector<std::string, std::allocator<std::string> >::size_type s = obj.size();\n\n// Rather:\n\nstd::vector<std::string>::size_type s = obj.size();\n</code></pre>\n<p>You already know the type. Why are you changing type in mid function?</p>\n<pre><code>unsigned long mid = s / 2;\nunsigned long first = 0;\nunsigned long last = s - 1;\n</code></pre>\n<p>Use the same type you use for <code>s</code>. If that is too much to type then typedef it to something easier. But C++ is all about type and safety. Keep your types consistent.</p>\n<p>I believe there is a bug in your code. If you fail to find a value then it will lock up in an infinite loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T15:31:42.643",
"Id": "13793",
"Score": "0",
"body": "+1 although I'd note that set will probably less efficient then a sorted vector for searching."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T00:50:22.587",
"Id": "13837",
"Score": "0",
"body": "Thanks for the due diligence. One thing to note, the reason I used a vector instead of a non-duplicate container is that there ARE no duplicates in the word list and I needed random-access-speed for the binary search to work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T05:33:02.630",
"Id": "13854",
"Score": "0",
"body": "@Casey: Yes you used std::vector so you can use binary search. If you use std::set the binary search becomes redundant as the set is implemented to have the same characteristics as a binary tree. Thus the find on the tree is already O(log(n)). Alternatively if you had used an unordered set the complexity becomes O(1)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-02-09T15:11:46.833",
"Id": "8811",
"ParentId": "8808",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "8811",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T13:17:27.830",
"Id": "8808",
"Score": "2",
"Tags": [
"c++",
"sorting"
],
"Title": "C++: Data sorting taking a long time"
}
|
8808
|
<p>I'm starting to reuse this pattern, and was wondering if there was a more succinct/clear way to write it.</p>
<p>Given a function <code>foo</code> taking a callback argument:</p>
<pre><code>function foo(..., cb) { ... }
</code></pre>
<p>And function <code>bar</code> which calls <code>foo</code> with several different arguments taking a callback function of its own to be called when all the 'dependent' callbacks have been called, I write:</p>
<pre><code>function bar(data, cb) {
var promises = [];
function createPromise() {
var p = $.Deferred();
promises.push(p);
return function() { p.resolve(); };
};
for (var i = 0; i < data.length; i++) {
foo(data[i], createPromise());
}
$.when.apply($, promises).then(cb);
}
</code></pre>
<p>I'm quite happy with the pattern, but the <code>apply</code> and closure-returning-a-function make me suspect that there might be a simpler way of doing the same... Ideas?</p>
|
[] |
[
{
"body": "<p>Well, first of all, your closure doesn't have to create a function. This will work just as well:</p>\n\n<pre><code>function createPromise() {\n var p = $.Deferred();\n promises.push(p);\n return p.resolve; // Doesn't create an anonymous function\n};\n</code></pre>\n\n<p>Second of all, if you're doing this pattern a lot, I would make a generic method that lets you convert any function that accepts a callback to one that returns a promise:</p>\n\n<pre><code>function callbackToPromise(func) {\n return function() {\n var args = $.makeArray(arguments);\n\n var p = $.Deferred();\n args.push(p.resolve); // Add the deferred as a callback\n\n func.apply(this, args);\n\n return p.promise();\n };\n}\n\nvar improvedFoo = callbackToPromise(foo);\n\nfunction bar(data, cb) {\n var promises = [];\n for (var i = 0; i < data.length; i++) {\n promises.push(improvedFoo(data[i]));\n }\n $.when.apply($, promises).then(cb);\n}\n</code></pre>\n\n<p><code>$.when</code> really should accept an array of <code>Deferred</code>'s as an argument, but until that feature is added, I don't think there's a way to avoid using <code>.apply</code> here, except to add another helper function: </p>\n\n<pre><code>function when(promises) {\n return $.when.apply($, promises);\n}\n\nfunction bar(data, cb) {\n var promises = [];\n for (var i = 0; i < data.length; i++) {\n promises.push(improvedFoo(data[i]));\n }\n when(promises).then(cb);\n}\n</code></pre>\n\n<p>A slightly less-readable version can eliminate the <code>promises</code> variable entirely, though I prefer the more-readable version above:</p>\n\n<pre><code>function bar(data, cb) {\n when($.map($.makeArray(data), function(item) {\n return improvedFoo(item);\n })).then(cb);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-23T22:13:42.270",
"Id": "9342",
"ParentId": "8809",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T13:49:48.170",
"Id": "8809",
"Score": "6",
"Tags": [
"javascript",
"jquery",
"promise"
],
"Title": "Multiple jQuery promises"
}
|
8809
|
<p>I've written a php function and some helper functions that checks for cookies when somebody lands on a page but it's not so fast. I want to know is there any way to make it faster or improve it i know it's possible to check for cookies client side using javascript but what if it is disabled also so i need a pure server side solution.</p>
<pre><code><?php
function check_cookie(){
if(is_cookie_disabled()){
header("location:cookie_is_disabled.php");
exit;
}
}
function is_cookie_disabled(){
$curr_url = $_SERVER['PHP_SELF'];
if(isset($_COOKIE['testCookie']) && !(isset($_COOKIE['cookie']))){
$original_url = original_url ($curr_url);
header("location: ".$original_url);
setcookie("cookie", 'enabled');
exit;
} elseif(!(isset($_COOKIE['testCookie']))) {
if(isset($_GET['temp'])){
return true;
} else{
if(if_parameters_exist_in_url($curr_url)){
$url = $curr_url."&temp=temp";
} else {
$url = $curr_url."?temp=temp";
}
header("location: ".$url);
setcookie("testCookie", 'test');
exit;
}
}
return false;
}
function original_url ($curr_url){
if (!empty($_GET)){
if (isset($_GET['temp'])) {
if(count($_GET)>0){
return removeqsvar($curr_url, 'temp');
} else {
return removeallvars($curr_url);
}
}
}
return $curr_url;
}
function removeqsvar($url, $varname) {
return preg_replace('/([?&])'.$varname.'=[^&]+(&|$)/','$1',$url);
}
function removeallvars($url){
return $url = strtok($url, '?');
}
function if_parameters_exist_in_url($url){
if (strpos($url, '=')) {
return true;
} else {
return false;
}
}
//at the top of your pages
check_cookie();
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T03:36:56.327",
"Id": "13795",
"Score": "1",
"body": "How slow is it? How fast do you need it to be?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T03:38:45.257",
"Id": "13796",
"Score": "6",
"body": "Look, people with cookies and JavaScript both disabled are few and far between. You're spending more time than it's worth dealing with."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T04:16:39.997",
"Id": "13797",
"Score": "0",
"body": "@sarnold as fast as possible"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T04:16:57.173",
"Id": "13798",
"Score": "0",
"body": "yeah but both cookies and javascript are crucial to website performance and i wanna have complete control on them"
}
] |
[
{
"body": "<p>It could be slow from all of the location redirects. But I've never done anything like that so I can't be sure.</p>\n\n<p>Is it possible to lazily set the cookies. For instance, set a session and cookie on the first page load. And then, on the second page load check if the cookie is present.</p>\n\n<p>This is how you could check if the page has loaded.</p>\n\n<pre><code>session_start();\n$_SESSION['first_load'] = isset($_SESSION['first_load']) ? false : true;\n\nif( !$_SESSION['first_load'] && isset($_COOKIE['testCookie']) )\n echo 'cookies enabled!'\nelse\n echo 'no cookies for you!'\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T16:14:07.073",
"Id": "8815",
"ParentId": "8814",
"Score": "2"
}
},
{
"body": "<p>It's certainly not slow. Measure the time it takes:</p>\n\n<ul>\n<li>to execute this code (using <code>microtime(true)</code>),</li>\n<li>and for your browser to receive the page (eg. Chrome has a \"Network\" tab in the Developers Tool).</li>\n</ul>\n\n<p>You'll see that optimizing this code won't yield any improvement, since this PHP code probably takes a few milliseconds to execute while the page load can take up to a second for small pages.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-07T16:54:13.737",
"Id": "9770",
"ParentId": "8814",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T03:35:18.100",
"Id": "8814",
"Score": "2",
"Tags": [
"php"
],
"Title": "A PHP function to check for cookies"
}
|
8814
|
<p>I'm trying to create a <code>Bindable FlowLayoutPanel</code> that can take a <code>DataSource</code> and map it the specified generic parameter <code><T></code> controls. Only minimal requirements are to have a selectable index and to be able to change the background color of the selected and deselected controls. I've tried to leave out the implementation of the selected index except for obvious cases. This leaves the option to the developer as to how to move the selected index when a control is added/removed/etc. I have an example program that uses the below and it seems to work ok (it's not very large, but too big to post here).</p>
<p>I was hoping someone else could take a look at this and see if there are any obvious issues.</p>
<pre><code>using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Design;
namespace DataBindingListOfUserControls
{
/// <summary>
/// Create a Bindable FlowLayoutPanel
/// </summary>
/// <typeparam name="T">The control type that will be in the FlowLayoutPanel</typeparam>
/// <remarks>Note!!! If you wish to use this in a designer, you must create a class
/// that does not use or derive from this generic class. For example, doing something
/// like: BindableFlowLayoutPanel[MyCtrl] would give you designer errors. To fix this,
/// you need to create a class that does not derive from the generic class. So you
/// would do this: class MyCtrlBflp : MiddleBflp,
/// then class MiddleBflp : BindableFlowLayoutPanel[MyCtrl] Then you would use
/// MyCtrlBflp from the Toolbox (and you can create an instance of this through the
/// designer)</remarks>
public partial class BindableFlowLayoutPanel<T> : UserControl, INotifyPropertyChanged
where T : Control, IBindableObject, new()
{
#region Constants
/// <summary>
/// The constant value if no control is selected
/// </summary>
private const int NO_SELECTED_INDEX = -1;
#endregion
#region Member Variables
/// <summary>
/// The data source that will bind to the controls
/// </summary>
private BindingSource mDataSource = null;
/// <summary>
/// The deselected background color of the controls
/// </summary>
private Color mDeselectedControlColor = SystemColors.Control;
/// <summary>
/// The selected background color of the controls
/// </summary>
private Color mSelectetedControlColor = SystemColors.GradientInactiveCaption;
/// <summary>
/// The selected control within the FlowLayoutPanel
/// Let the model control this so you can implement your own desired
/// navigation when items are added, removed, inserted, etc
/// </summary>
private int mSelectedIndex = NO_SELECTED_INDEX;
#endregion
#region Constructor
/// <summary>
/// Creates an instance of the Bindable FlowLayoutPanel
/// </summary>
public BindableFlowLayoutPanel()
{
InitializeComponent();
}
#endregion
#region Properties
/// <summary>
/// Set the data source that will bind to the controls in the FlowLayoutPanel
/// </summary>
/// <param name="bindingSource">The binding source</param>
[TypeConverter("System.Windows.Forms.Design.DataSourceConverter, System.Design")]
[Editor("System.Windows.Forms.Design.DataSourceListEditor,
System.Design", typeof(UITypeEditor))]
[AttributeProvider(typeof(IListSource))]
[DefaultValue(null)]
public object DataSource
{
set
{
// Only change if its different
if (mDataSource != value)
{
// Unregister the events if we were already bound to a source
CleanUpDataSource();
// Check to make sure the object is a data source
BindingSource new_binding_source = value as BindingSource;
if ((value != null) && (new_binding_source == null))
{
throw new ArgumentException("DataSource must be a BindingSource");
}
// Setup the binding source to listen for list changes and Enter event
// listeners for each control
mDataSource = new_binding_source;
if (mDataSource != null)
{
mDataSource.ListChanged +=
new ListChangedEventHandler(DataSourceListChangedEventHandler);
for (int i = 0; i < mDataSource.Count; i++)
{
AddControl(i);
}
}
}
}
}
/// <summary>
/// Get/Set the deselected background color of the controls
/// </summary>
public Color DeselectedControlColor
{
get
{
return mDeselectedControlColor;
}
set
{
mDeselectedControlColor = value;
}
}
/// <summary>
/// Get/Set the selected background color of the controls
/// </summary>
public Color SelectetedControlColor
{
get
{
return mSelectetedControlColor;
}
set
{
mSelectetedControlColor = value;
}
}
/// <summary>
/// Get/Set the currently selected control index
/// Make this bindable and let the outside world control
/// how this is updated
/// <remarks>The selected index will be internally set to
/// -1 if the selected index is removed or if a control
/// is attempted to be selected but fails</remarks>
/// </summary>
[System.ComponentModel.Bindable(true)]
public int SelectedIndex
{
get
{
return mSelectedIndex;
}
set
{
if (mSelectedIndex != value)
{
// Clear the currently selected control
ClearSelectedControl();
mSelectedIndex = value;
// Set the selected control
if (SetSelectedControl(value))
{
// Notify this change since its custom
NotifyPropertyChanged("SelectedIndex");
}
else
{
// Dont notify the reset and set internally as not set
mSelectedIndex = NO_SELECTED_INDEX;
}
}
}
}
#endregion
#region Functions
/// <summary>
/// Add a new control at the specified index
/// </summary>
/// <param name="indexOfControl">The index to add/insert the new
/// control</param>
private void AddControl(int indexOfControl)
{
// Create a new control
T new_control = new T();
// Setup the bindings from the UI to the data source
new_control.BindingObject = mDataSource[indexOfControl];
// Keep track of when the control is entered
new_control.Enter += new EventHandler(ControlEnteredEventHandler);
// Update the background color
new_control.BackColor =
(SelectedIndex == indexOfControl) ?
SelectetedControlColor : DeselectedControlColor;
// Add the new control to the end (no insert option, so add to end
// and then set the child index)
mFlowLayoutPanel.Controls.Add(new_control);
// Change the location of the control to the index desired
mFlowLayoutPanel.Controls.SetChildIndex(new_control, indexOfControl);
}
/// <summary>
/// Remove listeners from the data source and from the individual controls
/// Also call on Dispose
/// </summary>
private void CleanUpDataSource()
{
if (mDataSource != null)
{
// Unregister for list change events and remove the Enter event
// listeners for each control
mDataSource.ListChanged -=
new ListChangedEventHandler(DataSourceListChangedEventHandler);
while (mFlowLayoutPanel.Controls.Count > 0)
{
RemoveControl(0);
}
// No selected controls
SelectedIndex = NO_SELECTED_INDEX;
}
}
/// <summary>
/// Clear the selected control (Change background color to deselected)
/// </summary>
private void ClearSelectedControl()
{
if (SelectedIndex != NO_SELECTED_INDEX)
{
T last_ui_control_selected = GetControl(SelectedIndex);
if (last_ui_control_selected != null)
{
last_ui_control_selected.BackColor = DeselectedControlColor;
}
}
}
/// <summary>
/// Get the control at the specified index from the FlowLayoutPanel
/// </summary>
/// <param name="indexOfControl">The index of the control to get</param>
/// <returns>The control at the specified index. null if the control does
/// not exist</returns>
private T GetControl(int indexOfControl)
{
// Make sure the index is valid, otherwise return null
if (indexOfControl >= mFlowLayoutPanel.Controls.Count)
{
return null;
}
return mFlowLayoutPanel.Controls[indexOfControl] as T;
}
/// <summary>
/// Fire the property changed event with the specified property name
/// </summary>
/// <param name="propName">The property name that was updated</param>
private void NotifyPropertyChanged(String propName)
{
PropertyChangedEventHandler prop_changed = PropertyChanged;
if (prop_changed != null)
{
prop_changed(this, new PropertyChangedEventArgs(propName));
}
}
/// <summary>
/// Remove the control at the specified index
/// </summary>
/// <param name="indexOfControl">The index of the control to remove
/// from the FlowLayoutPanel</param>
private void RemoveControl(int indexOfControl)
{
// Get the control to remove from the FlowLayoutPanel
T control_to_remove = mFlowLayoutPanel.Controls[indexOfControl] as T;
// Unregister the Enter event
control_to_remove.Enter -= new EventHandler(ControlEnteredEventHandler);
control_to_remove.BindingObject = null;
// Remove the control from the FlowLayoutPanel
mFlowLayoutPanel.Controls.Remove(control_to_remove);
if (mSelectedIndex == indexOfControl)
{
// Internally clear the selected because the control was removed
mSelectedIndex = NO_SELECTED_INDEX;
}
}
/// <summary>
/// Set the specified control as selected
/// </summary>
/// <param name="indexOfControl">The index of the control
/// in the FlowLayoutPanel</param>
/// <returns>True if the control was selected, False otherwise</returns>
private bool SetSelectedControl(int indexOfControl)
{
if (indexOfControl >= 0)
{
T control_to_select = GetControl(indexOfControl);
if (control_to_select != null)
{
control_to_select.Select();
control_to_select.BackColor = SelectetedControlColor;
mFlowLayoutPanel.ScrollControlIntoView(control_to_select);
return true;
}
}
return false;
}
#endregion
#region Event Handlers
/// <summary>
/// Handle when a control in the FlowLayoutPanel is entered
/// </summary>
/// <param name="sender">The control that fired the event</param>
/// <param name="e">The event arguments</param>
private void ControlEnteredEventHandler(object sender, EventArgs e)
{
// Keep track of the currently selected index since this could be user fired
SelectedIndex = mFlowLayoutPanel.Controls.IndexOf(sender as Control);
}
/// <summary>
/// Handle when the data source has changed. Update the UI accordingly
/// </summary>
/// <param name="sender">The control that fired the event</param>
/// <param name="e">The event arguments</param>
private void DataSourceListChangedEventHandler(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Add the new control to the UI at the end that maps to the new model added
AddControl(e.NewIndex);
}
else if (e.ListChangedType == ListChangedType.ItemDeleted)
{
// Make sure the new index is ok to be deleted
if (mFlowLayoutPanel.Controls.Count > e.NewIndex)
{
// Remove the control from the UI at the specified index
RemoveControl(e.NewIndex);
}
}
}
#endregion
#region INotifyPropertyChanged Members
/// <summary>
/// The Property Changed event
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
#endregion
} // BindableFlowLayoutPanel
} // DataBindingListOfUserControls
</code></pre>
<p>Here is the <code>IBindableObject</code> definition:</p>
<pre><code>public interface IBindableObject
{
object BindingObject { set; }
}
</code></pre>
|
[] |
[
{
"body": "<p>Turns out I was going about this the wrong way. I updated this to use the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.currencymanager.aspx\" rel=\"nofollow\"><code>CurrencyManager</code></a> class instead to manage the bindings for me. This was a much better solution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-04T17:02:03.643",
"Id": "16954",
"Score": "0",
"body": "It would be useful to edit your question or this answer to include the change, so anyone searching for the same information can see what the solution was."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-04T17:35:44.037",
"Id": "16957",
"Score": "0",
"body": "@DanLyons - Fair enough, if anyone shows interest or ask questions I'll give more detail. Posted for over a month and not even a comment or answer, so I dont think anyones interested. Hopefully pointing out what I added will help anyone if they decide to do something similar. I had never heard of the CurrencyManager."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-22T00:42:38.203",
"Id": "218705",
"Score": "1",
"body": "I'd be interested... I know it was a long time ago, but it was an interesting idea. Id love to know how it was ultimately solved."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-04T15:14:56.163",
"Id": "10621",
"ParentId": "8816",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "10621",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T16:14:55.057",
"Id": "8816",
"Score": "5",
"Tags": [
"c#",
"winforms"
],
"Title": "Binding FlowLayoutPanel"
}
|
8816
|
<p>I need this kind of <code>ORDER BY</code> to list my curriculum vitae data: when <code>ep.data_termino</code> is <code>null</code> it means that the job is your current job (you can have multiple current jobs), then I must list them first. Then, I need to list all the others ordered by the <code>ep.data_termino ASC</code>.</p>
<p>The <code>IF</code> was my only choice. I know that it is never a good option to use <code>IF</code>s in queries (at least that's how I learned it), so I am asking here if there is any better solution.</p>
<pre><code> SELECT ep.nome_empresa, ep.data_inicio, ep.descricao, ct.nome as contratacao_tipo_nome, p.nome as profissao_nome,
IF(ep.data_termino IS NULL,NOW(),ep.data_termino) as data_term
FROM experiencia_profissional as ep
JOIN contratacao_tipo as ct ON ct.codigo = ep.codigo_contratacao_tipo
JOIN profissao as p ON p.codigo = ep.codigo_profissao
JOIN experiencia_profissional_membro as epm ON epm.codigo_experiencia_profissional = ep.codigo
JOIN membro as m ON m.codigo = epm.codigo_membro
JOIN usuario as u ON u.codigo_membro = m.codigo
WHERE u.codigo = 124
ORDER by data_term DESC, ep.data_inicio ASC
</code></pre>
|
[] |
[
{
"body": "<p>Try:</p>\n\n<pre><code>ORDER BY ep.data_termino IS NOT NULL, ep.data_termino DESC, ep.data_inicio ASC\n</code></pre>\n\n<p>BTW,</p>\n\n<pre><code>IFNULL(ep.data_termino,NOW()) \n</code></pre>\n\n<p>is a cleaner way to express:</p>\n\n<pre><code>IF(ep.data_termino IS NULL,NOW(),ep.data_termino)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T18:28:19.777",
"Id": "13876",
"Score": "0",
"body": "Wow that was awesome! thank you! =) and thanks for the tip on the IFNULL, i can't +1 you for this tip, sorry =X"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T03:31:20.577",
"Id": "8844",
"ParentId": "8817",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "8844",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T16:30:10.483",
"Id": "8817",
"Score": "1",
"Tags": [
"sql",
"mysql"
],
"Title": "Listing curriculum vitae data"
}
|
8817
|
<p>I wanted to parse lines of text as tab-delimited items, and I had just been using a StringReader for something else and I came up with this:</p>
<pre><code>class TabDelimitedFieldReader : StringReader
{
private string _nextLine;
public TabDelimitedFieldReader(string s)
: base(s)
{
}
public IEnumerable<string> ReadFields()
{
if (_nextLine != null)
{
var fields = _nextLine.Split('\t');
foreach (string field in fields)
{
yield return field;
}
}
}
public bool HasMore
{
get
{
_nextLine = this.ReadLine();
return (_nextLine != null);
}
}
}
</code></pre>
<p>I can't think of another time I directly subclasses a .NET framework class like this. I figure maybe I'm just strange and it's normal for others, or maybe there's a reason I wouldn't want to do it.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T17:45:09.140",
"Id": "13800",
"Score": "0",
"body": "Not a bad idea. How do you use it, however? Say, I wanted to get text out of clipboard which got pasted in Excel. Then, I would want to make sure that row length is consistent - something that an enumerator would not give me. I would also add an optional bool flag to the `ReadFields` function which would cause the fields to be trimmed if `true`. I would run StyleCop on this, which would force you to add comments and rename `_nextLine` to `nextLine`, and refer to it as `this.nextLine`, etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T17:49:58.000",
"Id": "13801",
"Score": "0",
"body": "The context was an ad-hoc report loader service that aggregated data from a list of databases, which I copied/pasted from excel data formatted as a table, so even blanks will generate a blank field, and rows all the same length. Really, style cop would make me use \"this\" everywhere? I just changed my ambition to work at MS :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T19:36:46.257",
"Id": "13806",
"Score": "0",
"body": "You can turn off the rules that you do not agree with."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T00:36:29.500",
"Id": "13836",
"Score": "0",
"body": "actually i decided to code the rest of the day using no underscores and \"this\", and I realized it has a sort of leveling effect that lets me move code in/out/around namespaces/classes/nested classes more freely, so I think I'll stick with it"
}
] |
[
{
"body": "<p>Conceptually, I do not see anything inherently wrong with subclassing a framework object, particularly since many of them provide <code>virtual</code>/<code>abstract</code> members specifically to allow it.</p>\n\n<p>In this case, it may be better to wrap a <code>TextReader</code> object instead of inheriting from <code>StringReader</code>. This would allow you to provide tab delimited reading for multiple data sources instead of limiting yourself to in-memory strings. For example, you could still pass in a <code>StringReader</code> for reading strings, but you could also pass in a <code>StreamReader</code> if you wanted to support reading from files instead.</p>\n\n<p>Additionally, I noticed that <code>HasMore</code> is dangerous to call due to its side-effect. It is not immediately obvious to a caller that checking <code>HasMore</code> would alter the reader's current position. I would suggest using <code>Peek</code> instead.</p>\n\n<p>You would then need to update <code>_nextLine</code> elsewhere. You could have it be a side-effect of calling <code>ReadFields</code>. Or, perhaps better, you could add another method (e.g., <code>AdvanceLine</code>) that is simply responsible for moving the reader to the next line.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T18:00:49.623",
"Id": "13802",
"Score": "0",
"body": "Thanks for the feedback - question: are you a TDD developer? I'm not but have been lightly using/learning it for a while, and from my limited understanding, code that works is the goal and pre-empting the future is frowned upon... which goes against my instincts too, but seems to be the primary directive (as I understand it)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T17:53:40.957",
"Id": "13875",
"Score": "2",
"body": "By wrapping the class, you are actually reducing the test surface area, as you only need test your externally visible (public/protected) members. By extending StringReader, you would be stuck testing for cases where callers use the public base class methods to ensure you properly handle side-effects. For example, if someone called ReadLine (from TextReader), it would skip a line, changing expected behavior for either ReadFields or HasMore (or both!)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-11T13:54:05.857",
"Id": "275799",
"Score": "0",
"body": "@AaronAnodide it's called the decorator pattern. All stream in .NET work in this way. For example you can create a `MemoryStream` from a `FileStream`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T17:56:59.423",
"Id": "8821",
"ParentId": "8818",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T17:16:23.547",
"Id": "8818",
"Score": "4",
"Tags": [
"c#",
"object-oriented",
"parsing",
"csv"
],
"Title": "Parser for tab-delimited data as a subclass of StringReader"
}
|
8818
|
<p>This is really simple but I would like to improve the efficiency as it's run frequently on the client:</p>
<pre><code>function resizeSidebar() {
var h_tmp = 0;
if ($("#internal-holder").length > 0)
{ h_tmp = 250; }
else
{ h_tmp = 181; }
var h_var = $(window).height() - h_tmp;
var h_fixed = $(window).height();
$("#aside-holder").css("height", h_fixed - 225 + "px");
$("#main-content").css("height", h_var + "px");
$("#main-inner").css("height", h_var - 115 + "px");
$("#main-inner-scroll .viewport").css("height", h_var - 110 + "px");
$("#aside-holder-scroll .viewport").css("height", h_fixed - 225 + "px");
$("#main-inner-scroll").tinyscrollbar();
if (hideAsideScrollBar != "true") {
$("#aside-holder-scroll").tinyscrollbar();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>If the items which you are selecting in the function are a part of the same container, you must avoid to do full lookups in DOM. Look at your html, select the parent container in which you do the manipulations, and store it's value. After that, just search for it's children for desired components.</p>\n\n<p>For example, you have the following snippet:</p>\n\n<pre><code>...\n<div class=\"container\">\n <div class=\"someItem\">\n <div class=\"someOtherItem\">\n...\n</code></pre>\n\n<p>Now, if you have a function that is called pretty often, the ideal case is to select the elements in the following manner:</p>\n\n<pre><code>function doSomething () {\n var element = $('.container')\n var someItem = element.find('.someItem')\n var otherItem = someItem.find('.someOtherItem')\n\n someItem.doSomeStuff()\n otherItem.doSomeStuff()\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T18:40:46.130",
"Id": "8824",
"ParentId": "8819",
"Score": "1"
}
},
{
"body": "<ol>\n<li><p><code>$(\"#foo\")</code> is <a href=\"http://jsperf.com/jquery-id-vs-getelementbyid-id\" rel=\"noreferrer\">slow</a>, use the DOM: <code>document.getElementById(\"foo\")</code>.</p></li>\n<li><p><code>$(\"#foo .bar\")</code> is slow, get rid of that by navigating the DOM. I can't say exactly how without seeing the markup, but look at the <code>FIXME</code> comments below. </p></li>\n<li><p><code>$(\"#foo\").css()</code> is <a href=\"http://jsperf.com/jquery-css-vs-dom-css/3\" rel=\"noreferrer\">slow</a>, use the DOM: <code>foo.style.height = \"24px\"</code>.</p></li>\n<li><p>Get the reference to the elements once, not every time the function is called.</p></li>\n</ol>\n\n<p>Other notes:</p>\n\n<ol>\n<li><p>Don't do that weird thing with the braces on your <code>if</code> statements.</p></li>\n<li><p>Use the <code>var</code> keyword as little as possible by combining variable declarations.</p>\n\n<ol>\n<li><p>This appeases linters and reduces minified file size.</p></li>\n<li><p>It also pretty much forces you to declare all your variables at the top of the function, which is generally considered to be a good practice. </p></li>\n</ol></li>\n<li><p>Avoid the use of <code>_</code> in variable names; prefer <code>camelCase</code> instead. Also try to use meaningful variable names.</p>\n\n<ol>\n<li><p>Except for variables or properties representing constants. In these cases the UPPER_CASED words are joined by underscores.</p></li>\n<li><p>An exception may be made for variables or properties meant to be considered \"private\". In these cases the camelCased words are prefixed or suffixed with an underscore. </p></li>\n</ol></li>\n</ol>\n\n<hr>\n\n<pre><code>var internalHolder = document.getElementById(\"internal-holder\"),\n asideHolder = document.getElementById(\"aside-holder\"),\n mainContent = document.getElementById(\"main-content\"),\n mainInner = document.getElementById(\"main-inner\"),\n mainInnerScroll = document.getElementById(\"main-inner-scroll\"),\n asideHolderScroll = document.getElementById(\"aside-holder-scroll\"),\n mainInnerScrollViewport = mainInnerScroll.children[0], // FIXME \n asideHolderScrollViewport = asideHolderScroll.children[0]; // FIXME \n\nfunction resizeSidebar() {\n\n var tmpHeight = internalHolder.children.length ? 250 : 181,\n height = window.innerHeight,\n innerHeight = height - tmpHeight;\n\n asideHolder.style.height = height - 225 + \"px\";\n mainContent.style.height = innerHeight + \"px\";\n mainInner.style.height = innerHeight - 115 + \"px\";\n\n mainInnerScrollViewport.style.height = innerHeight - 110 + \"px\";\n asideHolderScrollViewport.style.height = height - 225 + \"px\";\n\n $(mainInnerScroll).tinyscrollbar();\n if (hideAsideScrollBar != \"true\") {\n $(asideHolderScroll).tinyscrollbar();\n }\n}\n</code></pre>\n\n<hr>\n\n<p>I can almost guarantee this will be at least 10 times faster if you fix the <code>FIXME</code>s.</p>\n\n<p><strong>BUT.</strong></p>\n\n<p>What you are doing feels really wrong. Using javascript to get and set a bunch of heights should be avoidable. Again I can't say exactly what to do without seeing the markup, but you should be able to achieve most (if not all) of the <code>$('#foo').css</code> stuff through plain old HTML/CSS. Try giving things 100% height, try inline-block and vertical-align, hell, try tables, but javascript css styling should, IMO, be kept to an absolute minimum. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T23:54:15.360",
"Id": "13829",
"Score": "0",
"body": "I disagree with combining `var` declarations like this. It makes for more awkward diffs, and it's easy to mess up: if you leave out a comma, or have an extra semicolon, the remaining \"declarations\" will merely be assignments (they won't establish variable scope). Also, what's wrong with `_` in variable names?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T00:19:01.957",
"Id": "13833",
"Score": "1",
"body": "Combining var declarations is mostly to appease linters and reduce minified file size. I personally make a lot of silly mistakes with commas in object literals, but rarely in var declarations. As for `_`, javascript variable names and properties should be camel-cased. Underscores should only be used for CONSTANTS like FLAG_NAMES. I'm sure I can find a reference to back that up if you want."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T23:14:57.757",
"Id": "8831",
"ParentId": "8819",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "8831",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T17:24:52.540",
"Id": "8819",
"Score": "4",
"Tags": [
"javascript",
"jquery"
],
"Title": "Resizing a sidebar"
}
|
8819
|
<p>I am learning some OOP on PHP and I have developed some sample code to practise. </p>
<p>Ignoring the functionality, I just want to learn the "best" or "better" way to write OOP codes in PHP. </p>
<p>The following is my code and I hope anyone who has been doing PHP can help to review or comment for any improvements or weaknesses on my code.</p>
<p>I want to develop my style of code in which copy-and paste is minimum and functionality expandability is rich. For example, the <code>execute()</code> function in the <code>UserDB</code> class is basically the same function and can be used widespread in many diff db class. Do I need to copy and paste the code again or should I just moved this piece of code to abstract class? </p>
<p>How can I optimized my code to made it better for future functionalities such as other select, insert, update and delete while maintaining readability and still within OOP standards? </p>
<pre><code><?php
require_once "sys_config.php";
require_once "general.inc";
$para[":user"]= "%";
$dataset = UserFactory::getUsers($para);
var_dump($dataset);
?>
</code></pre>
<p><strong><code>UserFactory</code> class</strong></p>
<pre><code><?php
class UserFactory{
public static function getUsers($para)
{
$db = new UserDB("CALL getUsers(:user)",$para); //sp
$objs = $db->execute();
if(!empty($objs))
foreach( $objs as $obj)
{
$users[] = new user($obj);
}
return $users;
}
}
?>
</code></pre>
<p><strong><code>UserDB</code> class</strong></p>
<pre><code><?php
Class UserDB extends Database{
protected $conn;
protected $SQL;
protected $para;
function __construct($SQL, $para)
{
parent::__construct();
$this->conn = parent::getConn();
$this->SQL = $SQL;
$this->para = $para;
}
function execute()
{
$query = $this->conn->prepare($this->SQL);
if(!empty($this->para))
foreach($this->para as $key=>$val)
{
$query->bindParam($key,$val);
}
$results = $query->execute();
$dataset = null;
if($results)
{
while($row = $query->fetch(PDO::FETCH_OBJ))
{
$dataset[]=$row;
}
}
unset($this->conn);
parent::__destruct();
return $dataset;
}
}
?>
</code></pre>
<p><strong><code>Database</code> abstract class</strong></p>
<pre><code><?php
abstract Class Database{
protected $conn;
function __construct()
{
$this->conn = new PDO ("mysql:host=".DB_LOCATION.";dbname=".DB_NAME,DB_USER,DB_PASS);
}
function __destruct()
{
unset($this->conn);
}
function getConn()
{
return $this->conn;
}
abstract function execute();
}
?>
</code></pre>
<p><strong><code>User</code> object class</strong></p>
<pre><code><?php
class User{
private $fullname;
private $id;
function __construct($userObj)
{
$this->fullname = $userObj->fullName;
$this->id = $userObj->id;
}
function setFullname($fullname)
{
$this->fullname = $fullname;
}
function getFullname()
{
return $this->fullname;
}
function setId($id)
{
$this->id = $id;
}
function getId()
{
return $this->id;
}
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T04:59:29.223",
"Id": "13851",
"Score": "0",
"body": "Melvin the code in itself looks good. What you are doing, not so much. `Ignoring the functionality, I just want to learn the \"best\" or \"better\" way to write OOP codes in PHP` doesn't work well on Code Review, everything you post is fair game for reviewers. But it would help if you tell us a bit about the purpose of the classes. Not in excruciating detail, but just a little bit so we won't have to guess."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T06:01:11.720",
"Id": "13856",
"Score": "0",
"body": "I want to develop my style of code in which copy-and paste is minimum and functionality expandability is rich. \n\nfor eg : the execute() function in UserDB class..basically the same function can be used widespread in many diff db class, so do I need to copy and paste the code again or should I just moved this piece of code to abstract class ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T06:09:11.077",
"Id": "13857",
"Score": "0",
"body": "Edit the question and add clarifications there, not in comments. I've favourited the question to not forget about and will come back for a proper review, hopefully soon (work is crazy, so, not a promise)."
}
] |
[
{
"body": "<p>Just a few comments on the code as it stands so far: </p>\n\n<ol>\n<li>You're using pretty old-school file dependency management (which isn't the same as dependency management) by explicitly including things. I'd strongly suggest you look into the SPL autoload system, write an autoloader that can find where your classes are located in the filesystem and rely on the autoloader to handle the file dependency management instead. It means that only code that's actually going to be used will be included and you won't get into a situation where you have loads of included classes but only a few get used, or where you're not sure what's been included. </li>\n<li>You're using static methods. Generally, statics are frowned upon because they're not considered to be good OO practice. Sometimes they're necessary, but as a rule you should avoid them. Any other class that makes use of the static call becomes tightly coupled to the class that implements it, reducing re-usability and testability (it becomes very difficult to test the dependant modules in isolation because you can't easily replace the static with a mock implementation). I'd advise refactoring your factory to work in a non-static way. </li>\n<li>Your Database class seems like it might not be necessary. It's merely a wrapper around PDO, and actually hides most of the PDO class functionality. I'd suggest you might be better off using PDO directly, as it's got a well-documented interface and you'll have full access to all the PDO functionality in the consuming classes instead of the small subset your Database class provides. </li>\n</ol>\n\n<p>I would say that on the whole you're on basically the right track though. It's certainly better than my own early efforts with OOP. Don't worry, thinking in an \"objecty\" way is something that comes with practice and experience. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-18T10:49:54.050",
"Id": "9105",
"ParentId": "8823",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T18:15:36.843",
"Id": "8823",
"Score": "4",
"Tags": [
"php",
"object-oriented"
],
"Title": "User and Database classes in PHP"
}
|
8823
|
<p>Does this snippet take too much memory? How can I let the connection opened with the function <code>connectTo</code> outside the forever loop?</p>
<pre><code>import Control.Concurrent
import Network
import System.IO
import Control.Monad
import System.Environment
main = do
[host,port]<-getArgs
let pn1 = fromIntegral ( read port::Int)
forever $ do
h <- connectTo host $ PortNumber pn1
hSetBuffering h NoBuffering
getLine >>= hPutStrLn h
forkIO $ hGetContents h >>= putStrL
</code></pre>
<p>If I put the line <code>forever ...</code> after the line <code>hSetBuffering</code>, the connection is lost after one input. </p>
<p>It seems to me that this code open too much connection. </p>
|
[] |
[
{
"body": "<p><a href=\"http://hackage.haskell.org/packages/archive/base/latest/doc/html/System-IO.html#v%3ahGetContents\" rel=\"nofollow\"><code>hGetContents</code></a> gets <em>all</em> remaining input, using lazy IO. The second call to <code>hGetContents</code> throws an error because the first call has already claimed the data, in a sense.</p>\n\n<p>What I would do is have a separate thread tunnel data from the handle to standard output, and have the main thread tunnel data from standard input to the handle:</p>\n\n<pre><code>_ <- forkIO $ hGetContents h >>= putStr\ngetContents >>= hPutStr h\n</code></pre>\n\n<p>I would also use <code>LineBuffering</code> rather than <code>NoBuffering</code>, so it doesn't have to transmit a TCP packet for every character (*).</p>\n\n<p>Thus, we have:</p>\n\n<pre><code>import Control.Concurrent\nimport Network\nimport System.Environment\nimport System.IO\n\nmain :: IO ()\nmain = do\n [host, port] <- getArgs\n h <- connectTo host $ PortNumber $ toEnum $ read port\n hSetBuffering stdout LineBuffering\n hSetBuffering h LineBuffering\n _ <- forkIO $ hGetContents h >>= putStr\n getContents >>= hPutStr h\n</code></pre>\n\n<p>A couple notes:</p>\n\n<ul>\n<li><p>I was able to avoid the type signature by using <code>toEnum</code> rather than <code>fromIntegral</code>.</p></li>\n<li><p><code>_ <- forkIO $ ...</code> suppresses a warning when the program is compiled with <code>-Wall</code>.</p></li>\n</ul>\n\n<p>We can do better, though. Currently, if the server disconnects, the user does not see that the server disconnected until hitting enter a couple times, which produces an ugly error message:</p>\n\n<pre><code>tcp-client: <socket: 3>: commitBuffer: resource vanished (Broken pipe)\n</code></pre>\n\n<p>Let's see if we can get the program to terminate when either the server or the client closes the connection. Bear in mind that:</p>\n\n<ul>\n<li><p><code>getContents</code> and <code>hGetContents</code> terminate the list when EOF is reached. Thus:</p>\n\n<ul>\n<li><p><code>hGetContents h >>= putStr</code> terminates when the server closes the connection</p></li>\n<li><p><code>getContents >>= hPutStr h</code> terminates when the user presses <kbd>Ctrl+D</kbd></p></li>\n</ul></li>\n<li><p>The program terminates when the main thread terminates, regardless if child threads still have work to do.</p></li>\n</ul>\n\n<p>A good way to do this, I think, is to perform the receiving and sending in two separate threads, and have the main thread wait on an MVar:</p>\n\n<pre><code>done <- newEmptyMVar\n\n_ <- forkIO $ (hGetContents h >>= putStr)\n `finally` tryPutMVar done ()\n\n_ <- forkIO $ (getContents >>= hPutStr h)\n `finally` tryPutMVar done ()\n\n-- Wait for at least one of the above threads to complete\ntakeMVar done\n</code></pre>\n\n<p><sub>* Actually, sending individual characters at a time will probably trigger <a href=\"http://en.wikipedia.org/wiki/Nagle%27s_algorithm\" rel=\"nofollow\">Nagle's algorithm</a>. Still, sending characters one at a time creates a lot of unnecessary CPU overhead.</sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T09:37:25.920",
"Id": "13861",
"Score": "0",
"body": "in order to better understand your comment i will try with a tcp simple server . I have found one here or in stackoverflow but can't find it again. Once i have some more code to share i will post it again."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T01:15:12.390",
"Id": "8842",
"ParentId": "8828",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "8842",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T21:28:18.367",
"Id": "8828",
"Score": "5",
"Tags": [
"haskell",
"memory-management",
"networking"
],
"Title": "Simple TCP client - memory issues"
}
|
8828
|
<p>I'm wanting to create a Reusable class to work on Enumerations so that I can decorate various Enums with different attributes and I can use this class to get a particular attribute property to display.</p>
<p>An UnitTest example of how I would use the class is:</p>
<pre><code> internal enum TestEnum
{
[System.ComponentModel.Description("Description Attribute")]
[System.Xml.Serialization.XmlAttribute("XML Attribute")]
EnumWithDescription,
[System.ComponentModel.Category("Display name attribute")]
[System.ComponentModel.Description("Description Attribute over category attribute")]
EnumWithXMLAttribute,
EnumNoAttributes,
}
protected EnumAttributeDescriptor CreateEnumAttributeDescriptor()
{
EnumAttributeDescriptor descriptor = new EnumAttributeDescriptor();
descriptor.AddAttributePriority<System.ComponentModel.DescriptionAttribute>("Description");
descriptor.AddAttributePriority(new PropertyDecoration("Category", typeof(System.ComponentModel.CategoryAttribute)));
return descriptor;
}
internal class IntAttributeDescriptor : PropertyAttributeDescriptor
{
public IntAttributeDescriptor()
: base()
{
AddAttributePriority<System.ComponentModel.DescriptionAttribute>("Description");
}
}
internal class EnumSwitchableDescriptor : IObjectDescriptor
{
public string GetDescription(object record)
{
TestEnum item = (TestEnum)record;
switch (item)
{
case TestEnum.EnumWithDescription:
return "This is a test attribute";
case TestEnum.EnumWithXMLAttribute:
return "How did you sneak in here";
default:
throw new NotSupportedException(string.Format("Enumeration not supported {0}", item));
}
}
}
internal class TestObject
{
[System.ComponentModel.Description("Testable integer")]
public int TestInteger
{
get;
set;
}
}
[TestMethod]
public void EnumDescriptionHardCodedTest()
{
ObjectDescription descriptions = new ObjectDescription(new EnumSwitchableDescriptor());
string name = descriptions.GetDisplayName(TestEnum.EnumWithDescription);
Assert.AreEqual("This is a test attribute", name);
}
[TestMethod]
public void EnumDescriptionMissingAttributeTest()
{
ObjectDescription descriptions = new ObjectDescription(CreateEnumAttributeDescriptor());
string name = descriptions.GetDisplayName(TestEnum.EnumNoAttributes);
Assert.IsNull(name);
}
[TestMethod]
public void EnumDescriptionDefaultAttributeTest()
{
ObjectDescription descriptions = new ObjectDefaultableDescription((obj) => { return null; });
string name = descriptions.GetDisplayName(TestEnum.EnumWithDescription);
Assert.AreEqual("EnumWithDescription", name);
}
[TestMethod]
public void EnumDescriptionFromSingleAttributeTest()
{
ObjectDescription descriptions = new ObjectDescription(CreateEnumAttributeDescriptor());
string name = descriptions.GetDisplayName(TestEnum.EnumWithDescription);
Assert.AreEqual("Description Attribute", name);
}
[TestMethod]
public void EnumDescriptionFromObjectTest()
{
ObjectDescription descriptions = new ObjectDescription(CreateEnumAttributeDescriptor());
TestEnum testable = TestEnum.EnumWithXMLAttribute;
string name = descriptions.GetDisplayName(testable);
Assert.AreEqual("Description Attribute over category attribute", name);
}
[TestMethod]
public void IntDescriptionFromObjectTest()
{
TestObject testable = new TestObject();
ObjectDescription descriptor = new ObjectDescription(new IntAttributeDescriptor());
string description = descriptor.GetDisplayName(testable);
Assert.AreEqual("Testable integer", description);
}
</code></pre>
<p>My ObjectInspector class responsible for getting a property :</p>
<pre><code>public class ObjectInspector
{
public string GetProperty(object record, string propertyName)
{
Type typeOf = record.GetType();
object value = typeOf.GetProperty(propertyName).GetValue(record, null);
if (value == null)
return null;
else
return value.ToString();
}
public bool IsOfType(object record, Type typeOf)
{
Type typeOfRecord = record.GetType();
return typeOfRecord.Equals(typeOf) || typeOfRecord.IsSubclassOf(typeOf);
}
public bool IsOfType<T>(object record)
{
Type typeOf = typeof(T);
return IsOfType(record, typeOf);
}
}
</code></pre>
<p>My Descriptor class and interface:</p>
<pre><code>public interface IObjectDescriptor
{
string GetDescription(object record);
}
public abstract class AttributeDescriptor : IObjectDescriptor
{
private readonly List<PropertyDecoration> _attributes;
public AttributeDescriptor()
{
_attributes = new List<PropertyDecoration>();
}
public string GetDescription(object record)
{
var priorities = GetAttributes();
if (priorities == null || record == null)
return null;
var attributes = GetAttributes(record);
if (attributes != null)
return GetAttributeDescription(attributes);
else
return null;
}
public virtual void AddAttributePriority(PropertyDecoration attr)
{
_attributes.Add(attr);
}
public virtual void AddAttributePriority<T>(string propertyName)
{
PropertyDecoration lookup = new PropertyDecoration(propertyName, typeof(T));
AddAttributePriority(lookup);
}
public virtual IEnumerable<PropertyDecoration> GetAttributes()
{
return _attributes;
}
protected abstract object[] GetAttributes(object record);
protected virtual string GetAttributeDescription(object[] attributes)
{
ObjectInspector inspector = new ObjectInspector();
object attribute = null;
// looping from highest precedence
foreach (var attr in GetAttributes())
{
// find a matching attribute on our object
attribute = attributes.FirstOrDefault(p => inspector.IsOfType(p, attr.GetPropertyType()));
if (attribute != null)
{
//return attribute;
return attr.GetDescription(attribute);
}
}
return null;
}
}
public class EnumAttributeDescriptor : AttributeDescriptor
{
protected override object[] GetAttributes(object record)
{
var typeOf = record.GetType();
var info = typeOf.GetMember(record.ToString());
return info[0].GetCustomAttributes(false);
}
}
</code></pre>
<p>And finally the Object description classes to actually get the description:</p>
<pre><code>public class ObjectDescription
{
private IObjectDescriptor _objectDescriptor;
public ObjectDescription(IObjectDescriptor attributePriorities)
{
_objectDescriptor = attributePriorities;
}
public string GetDisplayName(object record)
{
return GetDescription(record, _objectDescriptor);
}
protected virtual string GetDescription(object record, IObjectDescriptor descriptor)
{
return descriptor.GetDescription(record);
}
}
public class ObjectDefaultableDescription : ObjectDescription
{
private Func<object, string> _defaultIfEmpty;
public ObjectDefaultableDescription(Func<object, string> defaultIfEmpty)
: base(null)
{
_defaultIfEmpty = defaultIfEmpty;
}
protected override string GetDescription(object record, IObjectDescriptor descriptor)
{
if (record == null)
return _defaultIfEmpty(record);
else
return record.ToString();
}
private string GetDefaultIfEmpty(object record)
{
if (_defaultIfEmpty != null)
return _defaultIfEmpty(record);
else
return null;
}
}
</code></pre>
<p>I want to keep it flexible so that I can decorate Enums with different Attributes as the requirements may vary i.e. using System.Xml.Serialization.XmlEnumAttribute in conjunction with System.ComponentModel.DescriptionAttribute so a UI can use the Description attribute to display a nice name while an XML serialiser can use the XmlEnumAttribute etc</p>
<p>I would expect to either provide a wrapper class for this on my various projects so that I wouldn't have to create the delegate method everywhere however unsure of this approach.</p>
<p>EDIT: After re-looking I thought the GetProperty() method is pretty generic and doesn't really necessary only belong to an Enum so I moved that out into it's own ObjectInspector class.</p>
<p>EDIT: After some further thought into this I decided that actually it's not directly related to Enum's but rather the ability to get descriptions from properties in general. I've made some tweaks to the classes to try and separate this out. Any comments would be most appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T03:08:13.227",
"Id": "13934",
"Score": "0",
"body": "Not having access to VS2010 at the moment, why not steal code from http://weblogs.asp.net/grantbarrington/archive/2009/01/19/enumhelper-getting-a-friendly-description-from-an-enum.aspx but rework the signature to be `public static string GetDescription<T>(Enum en) where T : something` instead? Instead of `return en.ToString();` you can do `return null;` as a way to indicate that this particular attribute was missing. Once this works, you can add wrapper methods which provide even more convenient ways of getting the info you want."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T09:41:32.100",
"Id": "13963",
"Score": "0",
"body": "@Leonid. hmmm, doesn't seem to provide enough flexibility. How could I use a category attribute easily, or perhaps an Xml AttributeAttribute. These don't have the Description property so I couldn't cast accordingly?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T15:27:04.993",
"Id": "13969",
"Score": "0",
"body": "Right ... I am not in front of VS2010. What if the main worker method could get you anything you ask for and helper methods making it easier. The usage: `public static GetCategory(enum) { return GetCustomAttributevalue<CategoryAttribute>(enum, \"Category\");}` and so on. I do not like `GetEnumAttribute` - it decides what you want for you. I want to be able to ask for a specific attribute and get a null if it is not there. Then I can add a method on top of this that will look for the first non-null attribute string in some prioritized order."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-13T01:21:22.887",
"Id": "13988",
"Score": "2",
"body": "Related: http://codereview.stackexchange.com/a/5354/3902"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-13T01:46:13.970",
"Id": "13990",
"Score": "1",
"body": "@finnw Sort of but not quite. I'm wanting to decorate my Enum's etc with a number of attributes not just the one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-27T04:08:27.063",
"Id": "21193",
"Score": "0",
"body": "Are you doing this in .NET 4? I'm wondering if I can use DynamicObject in a solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-27T04:19:55.797",
"Id": "21194",
"Score": "0",
"body": "@Brannon I believe I originally did this in .NET 3.5, but not 100% sure on that. My current code base this is used in is .NET 4.0 though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T04:45:00.190",
"Id": "28446",
"Score": "0",
"body": "@Brannon Did you work a solution with DynamicObject at all? Be interested to see if you came up with an alternative solution..."
}
] |
[
{
"body": "<p>I don't really see the point of XmlAttribute on a specific enumeration constant. I think that would go as a TypeConverter on the enum itself or on a property of the enum type. I can see some uses for DisplayName and Description. Unfortunately, DisplayName is not supported on Enums. The DynamicObject didn't actually end being that useful, but maybe it will give you some ideas. You could add some additional properties to the class like \"enum name\"Desc. I was thinking that might be useful for WPF binding, but only if you structured the helper class to have a current value. (And if you have the current value, then I don't see what you're gaining over a non-dynamic wrapper.) The ICustomTypeConverter also provided some interesting functionality. Here's a pass with DynamicObject:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Dynamic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Reflection;\n\nnamespace TestEnumDO\n{\n sealed class EnumHelper<T> : DynamicObject, ICustomTypeDescriptor where T: struct // ,System.Enum -- you wished\n {\n public override IEnumerable<string> GetDynamicMemberNames()\n {\n return Enum.GetNames(typeof(T));\n }\n\n public override bool TryGetMember(GetMemberBinder binder, out object result)\n {\n T t;\n if(!Enum.TryParse<T>(binder.Name, out t))\n return base.TryGetMember(binder, out result);\n result = t;\n return true;\n }\n\n public AttributeCollection GetAttributes()\n {\n return TypeDescriptor.GetAttributes(typeof(T));\n }\n\n public string GetClassName()\n {\n return TypeDescriptor.GetClassName(typeof(T));\n }\n\n public string GetComponentName()\n {\n return TypeDescriptor.GetComponentName(this, true);\n }\n\n public TypeConverter GetConverter()\n {\n return TypeDescriptor.GetConverter(typeof(T));\n }\n\n public EventDescriptor GetDefaultEvent()\n {\n return TypeDescriptor.GetDefaultEvent(typeof(T));\n }\n\n public PropertyDescriptor GetDefaultProperty()\n {\n return TypeDescriptor.GetDefaultProperty(typeof(T));\n }\n\n public object GetEditor(Type editorBaseType)\n {\n return TypeDescriptor.GetEditor(typeof(T), editorBaseType);\n }\n\n public EventDescriptorCollection GetEvents(Attribute[] attributes)\n {\n return TypeDescriptor.GetEvents(typeof(T), attributes);\n }\n\n public EventDescriptorCollection GetEvents()\n {\n return TypeDescriptor.GetEvents(typeof(T));\n }\n\n public PropertyDescriptorCollection GetProperties(Attribute[] attributes)\n {\n var values = (T[])Enum.GetValues(typeof(T));\n var props = new PropertyDescriptor[values.Length];\n for (int i = 0; i < values.Length; i++)\n {\n props[i] = new EnumPropertyDescriptor(values[i], attributes);\n }\n return new PropertyDescriptorCollection(props, true);\n }\n\n public PropertyDescriptorCollection GetProperties()\n {\n return GetProperties(null);\n }\n\n public object GetPropertyOwner(PropertyDescriptor pd)\n {\n return this;\n }\n\n private class EnumPropertyDescriptor : PropertyDescriptor\n {\n private readonly T _t;\n public EnumPropertyDescriptor(T value, Attribute[] atts):base(Enum.GetName(typeof(T), value), atts)\n {\n _t = value;\n }\n\n public override AttributeCollection Attributes\n {\n get\n {\n var attributeDefs = typeof(T).GetMember(Name).Single().CustomAttributes;\n var attributes = new List<Attribute>();\n foreach(var ad in attributeDefs){\n var constructorArgs = ad.ConstructorArguments.Select(ca => ca.Value).ToArray<object>();\n var attribute = (Attribute)ad.Constructor.Invoke(constructorArgs);\n foreach (var na in ad.NamedArguments)\n {\n if (na.MemberInfo is PropertyInfo)\n ((PropertyInfo)na.MemberInfo).SetValue(attribute, na.TypedValue.Value);\n else if (na.MemberInfo is FieldInfo)\n ((FieldInfo)na.MemberInfo).SetValue(attribute, na.TypedValue.Value);\n else throw new NotImplementedException();\n }\n attributes.Add(attribute);\n }\n return new AttributeCollection(attributes.ToArray());\n }\n }\n\n public override bool CanResetValue(object component)\n {\n return false;\n }\n\n public override Type ComponentType\n {\n get { return typeof(T); }\n }\n\n public override object GetValue(object component)\n {\n return _t;\n }\n\n public override bool IsReadOnly\n {\n get { return true; }\n }\n\n public override Type PropertyType\n {\n get { return typeof(T); }\n }\n\n public override void ResetValue(object component)\n {\n }\n\n public override void SetValue(object component, object value)\n {\n throw new NotSupportedException();\n }\n\n public override bool ShouldSerializeValue(object component)\n {\n return true;\n }\n }\n }\n\n class Program\n {\n enum TestEnum\n {\n [Description(\"Go One\")]\n Go1,\n [Description(\"Go Two\")]\n Go2,\n Go3\n }\n\n static void Main(string[] args)\n {\n dynamic helper = new EnumHelper<TestEnum>();\n Console.WriteLine(\"Names:\");\n foreach (var name in helper.GetDynamicMemberNames())\n Console.WriteLine(\" \" + name);\n\n Console.WriteLine();\n Console.WriteLine(\"Display Names:\");\n\n var pdc = TypeDescriptor.GetProperties(helper) as PropertyDescriptorCollection;\n var desc = pdc.OfType<PropertyDescriptor>().Single(pd => pd.Name == \"Go1\").Description;\n Console.WriteLine(\"Go1 Value = {0}, Description = {1}\", (int)helper.Go1, desc);\n\n if (Debugger.IsAttached)\n {\n Console.WriteLine();\n Console.WriteLine(\"Press any key...\");\n Console.ReadKey();\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T19:03:46.743",
"Id": "28826",
"Score": "0",
"body": "Cheers Brannon. The xmlAttribute is used for when the enum is to be used for serialisation and you want to give it a different xml value. We had to use both that attribute and the description to give it a different display value to the user."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T03:22:27.143",
"Id": "28844",
"Score": "0",
"body": "I still think a TypeConverter on the enum declaration would be more appropriate than an XmlAttribute, but I'm not sure what deserializer you were using and if it supported TypeConverters."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-31T05:19:49.510",
"Id": "28849",
"Score": "0",
"body": "System.Xml.Serialization.XmlSerializer"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-30T05:18:36.083",
"Id": "18069",
"ParentId": "8838",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T23:39:17.200",
"Id": "8838",
"Score": "23",
"Tags": [
"c#",
"lookup"
],
"Title": "Create a re-usable class to get different values from enum attribute decorations"
}
|
8838
|
<p>This is a C++ wrapper for the National Instruments ANSI C library for interfacing with NA-DAQmx devices such as the USB-6008. I wrote it for use in real-time data processing to test algorithms developed in my dissertation research.</p>
<p>I'm sure there's lots of room for improvement. Suggestions on style are welcome, in addition to contributions to support more features of the NI hardware (the emphasis of the current code is on near-simultaneous acquisition of a few analog voltage channels)</p>
<pre><code>#pragma once
/** @file daqmxcpp.h
** @author R Benjamin Voigt (richardvoigt@gmail.com)
**
** Rights reserved. This code is not public domain.
**
** Licensed under CC BY-SA 3.0 http://creativecommons.org/licenses/by-sa/3.0/
** or Lesser GPL 3 or later http://www.gnu.org/copyleft/lesser.html
** with the following restrictions (per GPL section 7):
** - all warranties are disclaimed, and if this is prohibited by law, your sole remedy shall be recovery of the price you paid to receive the code
** - derived works must not remove this license notice or author attribution
** - modifications must not be represented as the work of the original author
** - attribution is required in the "about" or "--version" display of any work linked hereto, or wherever copyright notices are displayed by the composite work
**/
#include <string>
namespace NIDAQmx
{
namespace innards
{
extern "C" {
#include <NIDAQmx.h>
#pragma comment(linker, "/DEFAULTLIB:nidaqmx-32.lib")
}
}
class DAQException : public std::exception
{
const innards::int32 m_code;
DAQException& operator=(const DAQException&);
public:
DAQException(innards::int32 errorCode)
: exception("exception in NI-DAQmx library")
, m_code(errorCode)
{
}
int code() const { return m_code; }
std::string description() const
{
std::string buffer;
innards::int32 neededSize = innards::DAQmxGetErrorString(m_code, NULL, 0);
if (neededSize > 0) {
buffer.resize(neededSize);
innards::DAQmxGetErrorString(m_code, &buffer[0], neededSize);
}
return buffer;
}
};
class Task sealed
{
typedef innards::TaskHandle TaskHandle;
const TaskHandle m_handle;
Task(TaskHandle handle)
: m_handle(handle)
{
}
TaskHandle CreateNamedTask(std::string name)
{
TaskHandle retval;
innards::int32 error = innards::DAQmxCreateTask(name.c_str(), &retval);
if (error < 0)
throw DAQException(error);
return retval;
}
Task& operator=(const Task&); // not provided
public:
Task(std::string name)
: m_handle(CreateNamedTask(name))
{
}
~Task()
{
innards::DAQmxClearTask(m_handle);
}
void AddChannel(std::string physicalName, int terminalConfig, double minVal, double maxVal, std::string customScale = std::string())
{
innards::int32 error = innards::DAQmxCreateAIVoltageChan(m_handle, physicalName.c_str(), NULL, terminalConfig, minVal, maxVal, customScale.empty()? DAQmx_Val_Volts: DAQmx_Val_Custom, customScale.empty()? NULL: customScale.c_str());
if (error < 0)
throw DAQException(error);
}
size_t GetChannelCount( void ) const
{
innards::uInt32 chanCount;
innards::int32 error = innards::DAQmxGetTaskNumChans(m_handle, &chanCount);
if (error < 0)
throw DAQException(error);
return chanCount;
}
void SetupContinuousAcquisition(double samplesPerSecond, unsigned int bufferSize)
{
innards::int32 error = innards::DAQmxCfgSampClkTiming(m_handle, NULL, samplesPerSecond, DAQmx_Val_Rising, DAQmx_Val_ContSamps, bufferSize);
if (error < 0)
throw DAQException(error);
}
void Start()
{
innards::int32 error = innards::DAQmxStartTask(m_handle);
if (error < 0)
throw DAQException(error);
}
void Stop()
{
innards::int32 error = innards::DAQmxStopTask(m_handle);
if (error < 0)
throw DAQException(error);
}
size_t TryRead(double buffer[], size_t bufferSize, innards::bool32 fillMode = DAQmx_Val_GroupByScanNumber)
{
innards::int32 truncatedBufferSize = (innards::int32)bufferSize;
if (truncatedBufferSize < 0 || bufferSize != (size_t)truncatedBufferSize)
throw "invalid bufferSize";
innards::int32 samplesRead;
innards::int32 error = innards::DAQmxReadAnalogF64(m_handle, DAQmx_Val_Auto, 0, fillMode, buffer, truncatedBufferSize, &samplesRead, NULL);
if (error < 0)
throw DAQException(error);
return samplesRead;
}
void SyncReadNonInterleaved(double buffer[], size_t bufferSize, size_t samplesToRead)
{
innards::int32 truncatedBufferSize = (innards::int32)bufferSize;
if (truncatedBufferSize < 0 || bufferSize != (size_t)truncatedBufferSize)
throw "invalid bufferSize";
innards::int32 truncatedSamplesToRead = (innards::int32)samplesToRead;
if (truncatedSamplesToRead < 0 || samplesToRead != (size_t)truncatedSamplesToRead)
throw "invalid samplesToRead";
innards::int32 samplesRead;
innards::int32 error = innards::DAQmxReadAnalogF64(m_handle, truncatedSamplesToRead, -1, DAQmx_Val_GroupByChannel, buffer, truncatedBufferSize, &samplesRead, NULL);
if (error < 0)
throw DAQException(error);
if (samplesRead != truncatedSamplesToRead)
throw "DAQmxReadAnalogF64 misbehaved?";
}
template<size_t N>
size_t TryRead(double (&buffer)[N])
{
return TryRead(buffer, N, DAQmx_Val_GroupByScanNumber);
}
template<size_t N>
size_t TryReadNonInterleaved(double (&buffer)[N])
{
return TryRead(buffer, N, DAQmx_Val_GroupByChannel);
}
template<size_t N>
void SyncReadNonInterleaved(double (&buffer)[N], size_t samplesToRead)
{
SyncReadNonInterleaved(buffer, N, samplesToRead);
}
template<size_t N>
void SyncReadTimeout(double (&buffer)[N], size_t samplesToRead, double secondsTimeout)
{
innards::int32 truncatedBufferSize = (innards::int32)N;
if (truncatedBufferSize < 0 || N != (size_t)truncatedBufferSize)
throw "invalid bufferSize";
innards::int32 truncatedSamplesToRead = (innards::int32)samplesToRead;
if (truncatedSamplesToRead < 0 || samplesToRead != (size_t)truncatedSamplesToRead)
throw "invalid samplesToRead";
innards::int32 samplesRead;
innards::int32 error = innards::DAQmxReadAnalogF64(m_handle, truncatedSamplesToRead, secondsTimeout, DAQmx_Val_GroupByScanNumber, buffer, truncatedBufferSize, &samplesRead, NULL);
if (error < 0)
throw DAQException(error);
if (samplesRead != truncatedSamplesToRead)
throw "DAQmxReadAnalogF64 misbehaved?";
}
template<typename TFunctor>
void* SubscribeSamplesRead(unsigned int blockSize, TFunctor* callbackFunctor)
{
struct ReadSamplesRegistration
{
Task* const m_pTask;
TFunctor* const m_functor;
static innards::int32 CVICALLBACK Callback(innards::TaskHandle taskHandle, innards::int32, innards::uInt32 /*nSamples*/, void* pCallbackData)
{
ReadSamplesRegistration* that = static_cast<ReadSamplesRegistration*>(pCallbackData);
if (that->m_pTask->m_handle != taskHandle)
return -1;
return (*that->m_functor)(that->m_pTask);
}
ReadSamplesRegistration(Task* pTask, TFunctor* callbackFunctor)
: m_pTask(pTask)
, m_functor(callbackFunctor)
{
}
private:
ReadSamplesRegistration& operator=(const ReadSamplesRegistration&) { __assume(false); }
}* pRegistration = new ReadSamplesRegistration(this, callbackFunctor);
innards::int32 error = innards::DAQmxRegisterEveryNSamplesEvent(m_handle, DAQmx_Val_Acquired_Into_Buffer, blockSize, 0, &ReadSamplesRegistration::Callback, pRegistration);
if (error < 0)
throw DAQException(error);
return pRegistration;
}
};
}
</code></pre>
|
[] |
[
{
"body": "<p>A C header inside extern \"C\" inside a nested namespace?\nThis is a new one on me, so maybe I am missing something. \nApparent benefit of the namespace nesting:</p>\n\n<ul>\n<li>the origin of the definitions becomes apparent by the innards:: qualification in this header.</li>\n<li>a module including this header only gets its namespace a little bit polluted by the C definitions.\nIt gets any #defines from the C header, but not other definitions and declarations.</li>\n</ul>\n\n<p>Apparent drawbacks:</p>\n\n<ul>\n<li>If any of those #defines get used in the module and they reference the namespace-hijacked declarations, things could get awkward.</li>\n<li>Also, if the C header has traditional macro-based guards against multiple inclusion,\nany module with a prior include of the C header -- possibly added in desperation to resolve the references leaked via #defines -- will effectively empty innards, breaking the C++ header code.</li>\n</ul>\n\n<p>.</p>\n\n<pre><code>namespace innards\n{\n extern \"C\" {\n#include <NIDAQmx.h>\n#pragma comment(linker, \"/DEFAULTLIB:nidaqmx-32.lib\")\n }\n}\n</code></pre>\n\n<p>It would be clearer to use a typedef like DAQErrorCode in place of innards::int32\nin the cases (predominant) where that is its purpose. \nThe details of its representation are secondary.</p>\n\n<p>If you are going to use \"sealed\", #define an ifdef'ed shim for it for platforms that don't support it.</p>\n\n<p>Initial uppercase for member functions -- is that a Windows convention?</p>\n\n<p>The following block could be encapsulate as <code>DAQException::throwIfError(error);</code>\neverywhere it occurs, leaving it to that function to determine which values justify an \nexception and possibly which type of exception to throw for each value.</p>\n\n<pre><code> if (error < 0)\n throw DAQException(error);\n</code></pre>\n\n<p>Suggestion: It MAY be better to force the \"no custom scale\" case of AddChannel to explicitly use a different overload.\nThe code for the simplified overload would be considerably more readable.\nThis could also enable treating use of an explicit empty string as an \nerror, so that if the caller bothers to pass a customScale, it should serve a purpose vs. specifying the default.\nThe usefulness of such error catching depends on how convenient it is for the \ncaller(s) to distinguish the default case vs. it being typically hidden\nfrom them in a string that was passed down from a higher level caller.</p>\n\n<p>If an already constructed std::string is typically being passed into the caller, \na const std::string & customScale argument would seem preferable.</p>\n\n<p>Is there any assurance from the C API documentation that the customScale c_str passed into the C api can be immediately deleted upon return (i.e. is never cached as a pointer)?</p>\n\n<p>If the expectation is that bufferSize can ALWAYS be determined by a static vector declaration matching a template argument, the explicit bufferSize overloads wrapped by the template member functions of Task should be made private.</p>\n\n<p>It seems strangely inconsistent not to have a non-templated variant of SyncReadTimeout as there are for these others.</p>\n\n<p>SyncReadNonInterleaved and SyncReadTimeout (adjusting for it being a single template function vs. an overloaded function with a template wrapper) are 20-line functions that differ only in 2 function arguments, which SyncReadNonInterleaved simply hard-codes.\nSyncReadNonInterleaved could take additional arguments defaulting to its hard-coded values: <code>double secondsTimeout = -1, innards::bool32 fillMode = DAQmx_Val_GroupByChannel</code>\nso that SyncReadTimeout could be/make a call to SyncReadNonInterleaved overriding those defaults.</p>\n\n<p>OR a separate neutral private function with no argument defaults could be factored out and called by both functions.</p>\n\n<p>A generic declaration like this can help to take the static casting clutter out of the callback code (see modified code below).\nDisclaimer: This change has not been test-compiled.</p>\n\n<pre><code> typedef innards::int32 CVICALLBACK (*genericCallback)(innards::TaskHandle, innards::int32, innards::uInt32 /*nSamples*/, void* pCallbackData);\n</code></pre>\n\n<p>This void* return seems like a dead end. <code>ReadSamplesRegistration</code> is so well-hidden that there's not even any way to deallocate one.\nShould ReadSampleRegistration be broken out of the function AND some more explicitly typed (but possibly still opaque) pointer be returned, so that a corresponding Unsubscribe function can unregister and delete the instance?</p>\n\n<pre><code> template<typename TFunctor>\n void* SubscribeSamplesRead(unsigned int blockSize, TFunctor* callbackFunctor)\n {\n struct ReadSamplesRegistration\n {\n Task* const m_pTask;\n TFunctor* const m_functor;\n</code></pre>\n\n<p>I'd properly specialize this signature and use a function pointer cast (below) instead of a callbackData cast (here).</p>\n\n<pre><code> static innards::int32 CVICALLBACK Callback(innards::TaskHandle taskHandle, innards::int32, innards::uInt32 /*nSamples*/, ReadSamplesRegistration* that)\n {\n</code></pre>\n\n<p>The member function of a struct defined within a member function gets private access (like to m_handle) just like its containing member function? I had no idea.\nI'd have provided (public) overloaded <code>Task::operator!=(const TaskHandle&)</code> ( and matching \"==\" ) to use here.</p>\n\n<pre><code> if (that->m_pTask->m_handle != taskHandle)\n return -1;\n\n return (*that->m_functor)(that->m_pTask);\n\n }\n</code></pre>\n\n<p>The requisite casting can get handled here at the function signature level:</p>\n\n<pre><code> static genericCallback GenericizedCallback = static_cast<genericCallback*>Callback;\n\n ReadSamplesRegistration(Task* pTask, TFunctor* callbackFunctor)\n : m_pTask(pTask)\n , m_functor(callbackFunctor)\n {\n }\n\n private:\n ReadSamplesRegistration& operator=(const ReadSamplesRegistration&) { __assume(false); }\n }* pRegistration = new ReadSamplesRegistration(this, callbackFunctor);\n\n innards::int32 error = innards::DAQmxRegisterEveryNSamplesEvent(m_handle, DAQmx_Val_Acquired_Into_Buffer, blockSize, 0, ReadSamplesRegistration::GenericizedCallback, pRegistration);\n if (error < 0)\n throw DAQException(error);\n\n return pRegistration;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T20:41:32.300",
"Id": "45874",
"Score": "0",
"body": "A bunch of good points which I agree with and will incorporate next time I work on that piece of code... except for the suggestion about casting function pointers. The only legal thing you can do with the result of a function pointer cast is to cast it back, you cannot safely call it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T05:06:35.810",
"Id": "8872",
"ParentId": "8840",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-09T23:50:26.673",
"Id": "8840",
"Score": "4",
"Tags": [
"c++"
],
"Title": "NI-DAQmx C++ wrapper code (for analog data acquisition using National Instruments measurement hardware)"
}
|
8840
|
<p>I like this. Anyone want to rain on my parade here?</p>
<pre><code>public void LoadDatabasesTest()
{
string[] args = new[] { "LoadDatabases" };
ReportsService.Program_Accessor.Main(args);
With(GetModel(), m => m.Databases.ToList().ForEach(c => Console.WriteLine(c.Name)));
}
void With<T>(T target, Action<T> action) where T : IDisposable
{
using (target)
{
action(target);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>What is more clearer here?</p>\n<p>This:</p>\n<pre><code>using (Model model = GetModel())\n{\n foreach (var item in model.Databases)\n {\n Console.WriteLine(item.Name);\n }\n}\n</code></pre>\n<p>or this:</p>\n<pre><code>With(GetModel(), model =>\n model.Databases.ToList().ForEach(c =>\n Console.WriteLine(c.Name)\n )\n)\n</code></pre>\n<p>You've defined some method so you could rearrange some things and add additional levels of indirection to run slower and more inefficient than if you had just written the standard way using the <code>using</code> and <code>foreach</code> blocks. What did you gain here? I'll tell you, <em>nothing</em>.</p>\n<p>Any half-decent C# programmer should know what the <code>using</code> and <code>foreach</code> blocks do. There should be no question about it. Seeing your block of code, it's not so clear... we'd have to figure out what you're doing here.</p>\n<p>What if someone saw your block of code and wanted to know what is going on? I look at that and see <code>With</code>... "With" what? What the heck is that supposed to mean? If anything, it is only more confusing to people who are familiar with VB.NET's <code>With</code> keyword (which does something completely different). The name isn't very great. You should have given it a more descriptive name. <code>UsingDisposable</code> might have been a better choice or something along those lines.</p>\n<p>Don't even get me started on the ToList/ForEach combo... You can <em>never</em> go right doing this instead of using a simple <code>foreach</code> loop. Why would to take a perfectly good collection, copy that collection into another list, just so you can call some method to do stuff with the added overhead of calling another method to do something on each item? The <code>ForEach</code> method has it's place and that's <em>if and only if</em> you start out with a list in the beginning. The overhead of the delegate is more forgivable here since that's what it was designed for. I understand that this particular usage is just a "hack" just to make this loop work, but this should never be the answer. If you <em>must</em>, write an extension at least.</p>\n<p>See reason number two of Eric Lippert's <a href=\"https://docs.microsoft.com/en-us/archive/blogs/ericlippert/foreach-vs-foreach\" rel=\"nofollow noreferrer\">"foreach" vs "ForEach"</a>. The same can be said here twofold, both for the <code>With()</code> method and your use of <code>ForEach()</code>.</p>\n<p>What happens if you need to do more than one statement in each of the blocks:</p>\n<pre><code>With(GetModel(), model =>\n{\n HelloThere();\n model.Databases.ToList().ForEach(c =>\n {\n DoSomething();\n Console.WriteLine(c.Name);\n DoSomethingElse();\n });\n DoMoreStuff();\n});\n</code></pre>\n<p>Here come the braces again and even more typing when instead you could have just done:</p>\n<pre><code>using (var model = GetModel())\n{\n HelloThere();\n foreach (var item in model.Databases)\n {\n DoSomething();\n Console.WriteLine(item.Name);\n DoSomethingElse();\n }\n DoMoreStuff();\n}\n</code></pre>\n<p>Save yourself the grief, just use the <code>using</code> and <code>foreach</code> blocks.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T04:11:43.587",
"Id": "13842",
"Score": "1",
"body": "Sorry if it seems I came on strong here, but I am fully against what you are doing here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T04:20:14.887",
"Id": "13843",
"Score": "0",
"body": "its cool, that's why i posted it to get perspectives, thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T04:22:35.990",
"Id": "13845",
"Score": "0",
"body": "I'll tell you something else, thinking on the matter, I believe if my editor auto inserted closing braces for me, I would never have bothered with it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T04:34:06.840",
"Id": "13847",
"Score": "0",
"body": "+1 very good answer, I'm not savvy with C# but shouldn't it be Console.WriteLine(item.Name); where you use foreach? in the last code paragraph I mean."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T04:37:16.740",
"Id": "13848",
"Score": "0",
"body": "@Dorin: You're right, I overlooked that change. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T16:04:40.767",
"Id": "13865",
"Score": "0",
"body": "Looking at this again today, a defense for the staement that the additional indirection gains nothing might be that it builds in a naturally occuring interception point for statement(s) that use resources. Another observation is that I could renamt With to Using to make it clearer. Finally, I believe it falls into the category of micro opimiazation when comparing performance. I really think for me it comes down to (a) wanting to be able to type certain bits of code on one line and (b) having a automatic nevative response to one liners with {}'s and single statement using/foreach/etc.."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-02-10T04:10:41.170",
"Id": "8846",
"ParentId": "8845",
"Score": "18"
}
},
{
"body": "<p>You could also have just</p>\n\n<pre><code>GetModel().Databases.ToList()\n .ForEach(item => Console.WriteLine(item.Name));\n</code></pre>\n\n<p>instead of duplicating an existing function. ;)</p>\n\n<p>(I like linq, but sometimes, what Jeff suggested is actually more readable)</p>\n\n<p>But more importantly:</p>\n\n<p>I don't see why you should have to dispose model. Do you have unmanaged resources within the model? If so, shouldn't <code>GetModel</code> dispose of the unmanaged stuff and return some plain old Clr objects to you as a model?</p>\n\n<p>If the model is adapter(s) for SQLDMO or such, could you translate instead of adapting inside <code>GetModel</code>?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T15:56:04.180",
"Id": "13864",
"Score": "0",
"body": "The model is an entity framework container with out-of-box code generation. I have been assuming it could leak SQL Server resources if not disposed, but I admit I do not know this for a fact."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T16:47:33.533",
"Id": "13871",
"Score": "0",
"body": "You're code is not the same. There is no call to Dispose() here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T10:14:30.040",
"Id": "13906",
"Score": "0",
"body": "That's why i question the disposing. The model shouldn't be disposed, the data context should be disposed. The entities returned from the context, as long as you don't need to lazy-load, does not need the context to be around. (undisposed)\nHence, dispose the context already in the GetModel() method."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T12:05:27.703",
"Id": "8853",
"ParentId": "8845",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "8846",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T03:32:36.943",
"Id": "8845",
"Score": "3",
"Tags": [
"c#"
],
"Title": "Generic function With<T> to do a one-liner using block"
}
|
8845
|
<p>I am writing some library code that is mostly templates and so is all contained in header files. I know that placing a using declaration in a header will pollute all the files that include it, but I'm also starting to be really annoyed by having to spell out all the namespaces..
After a bit of tinkering I came up with these macros:</p>
<pre><code>#define MACRO_CONCAT_IMPL( x, y ) x##y
#define MACRO_CONCAT( x, y ) MACRO_CONCAT_IMPL( x, y )
#define PRIVATE_NAMESPACE_IMPL( name ) namespace name { namespace exports{} } using namespace name::exports; namespace name {
#define PRIVATE_NAMESPACE PRIVATE_NAMESPACE_IMPL(MACRO_CONCAT(private_namespace_,__COUNTER__))
#define END_PRIVATE_NAMESPACE }
#define PUBLIC_SECTION namespace exports{
#define END_PUBLIC_SECTION }
</code></pre>
<p>To be used like this:</p>
<pre><code>namespace MyNamespace{
PRIVATE_NAMESPACE
using namespace std;
using namespace ThirdParty::Library;
using namespace MyCompany::OtherProduct;
PUBLIC_SECTION
class Class{
wstring GetString();
};
END_PUBLIC_SECTION
END_PRIVATE_NAMESPACE
}
</code></pre>
<p>This will create a private namespace with the using declarations and a nested one with the publicly available code that is then imported into the topmost namespace (MyNamespace).</p>
<p>This is different from a plain nested namespace as it expands into this:</p>
<pre><code>namespace MyNamespace{
namespace private_namespace_0{
using namespace std;
using namespace ThirdParty::Library;
using namespace MyCompany::OtherProduct;
namespace exports{
class Class{
wstring GetString();
};
}
}
using namespace private_namespace_0::exports;
}
</code></pre>
<p>This way the "public" section has access to the "private" one and only the public one is accessible with <code>MyNamespace::</code>.
The weird thing with the counter is to ensure each header has its own private namespace so that declarations are not shared between separate header files. Giving an ID to the namespaces is also the only reason that i'm using macros.</p>
<p>Using a "private" namespace seems to be accepted practice as boost does it too. I also know that <code>__COUNTER__</code> isn't really portable but vc++ and gcc both support it..</p>
<p>Is there anything really wrong with this idea or a better/standard way to do it?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T05:37:42.937",
"Id": "13855",
"Score": "8",
"body": "Yes it is stupid. Stop it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T16:16:11.543",
"Id": "13867",
"Score": "1",
"body": "I agree that you shouldn't do it, but you're getting a +1 for noticing that there might be something wrong with your approach."
}
] |
[
{
"body": "<p>Make a private namespace to be used separately.Why are you trying to complicate things</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T07:00:17.003",
"Id": "8848",
"ParentId": "8847",
"Score": "1"
}
},
{
"body": "<p>You're writing a lot of code, but what is the benefit? How is this any worse?</p>\n\n<pre><code>namespace MyNamespace {\n namespace ImplDetails {\n // Non-public code.\n }\n // Public code.\n}\n</code></pre>\n\n<p>Yes, people can access things in <code>ImplDetails</code>, but you can't get around that sanely. Obscuring namespace names is only going to hurt compatibility (when a namespace gets renamed after you insert a new one, which will happen eventually). If people want to access your internals, they will.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T19:18:46.207",
"Id": "13885",
"Score": "0",
"body": "I updated my question!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T20:45:17.493",
"Id": "13890",
"Score": "0",
"body": "@Roald: Your premise is flawed: the code is just as accessible with `MyNamespace::private_namespace_n::exports`. I'm somewhat surprised `__COUNTER__` works when files are built one by one, by the way, and you can still run into problems if you add more files."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T21:09:39.923",
"Id": "13891",
"Score": "0",
"body": "I'm not trying to make it really private.. that wasn't my goal. I just want to have using namespace ; statements that don't leak out of the header. I know that someone can still get to them if they really want to but that's not the point. You can now safely say: \"using namespace MyNamspace;\" in a .cpp without importing the additional namespaces used in the header. The counter can have a different value every time the file is included, I'm not relaying on that, there are no direct references to private_namespace_n besides the one the macro makes. Adding files would not really change anything.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T21:34:13.000",
"Id": "13892",
"Score": "0",
"body": "@Raold: Ah, I see. I would advise just using less using-directives. Yes, what you're doing gives you somewhat easier access to the names, but really, is renaming the third-party namespaces (and not `using namespace std;`, of course) really end up with your code being unreadable? I would say that the macro does more damage to readability than some qualifiers would."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T16:06:29.873",
"Id": "8857",
"ParentId": "8847",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T05:01:21.917",
"Id": "8847",
"Score": "6",
"Tags": [
"c++",
"macros"
],
"Title": "Solving the problem of using directives in a header file with a macro. Is this stupid?"
}
|
8847
|
<p>I'm currently in the process of clearing out the final parts of this question <a href="https://stackoverflow.com/questions/9192347/generics-polymorphism-interfaces-what-is-the-solution">here</a>.</p>
<p>Am I going about this the wrong way / could it be done smarter (interface perhaps) - or am I just plain silly, trying to keep my polymorphism hierarchy alive at "all means"?</p>
<p>I have a <code>TBaseObject</code> class - with a <code>TBaseList<T:TBaseObject></code> class in the same Unit. And I'm using inheritance to re-use a lot of functionality/properties:</p>
<pre><code>Base Unit;
TBaseObject = class
end;
TBaseList<T:TBaseObject> = class(TObjectList<T>)
end;
CustomCustomer Unit;
TCustomCustomer = class(TBaseObject)
end;
TCustomCustomerList<T:TCustomCustomer> = class(TBaseList<T>)
end;
Customer Unit;
TCustomer = class(TCustomCustomer)
end;
TCustomerList<T:TCustomer> = class(TCustomCustomerList<T>)
end;
</code></pre>
<p>I'm going for a solution where every single class in my hierarchy can be marshalled into a JSON string notation.</p>
<p>Having a look at my <code>TBaseObject</code>, I thought I'll use a <code>property Mar:TJsonMarshal</code> and a <code>class procedure TBaseObject.RegisterConverters(aClass:TClass; aMar:TJsonMarshal);</code> to aid me in the process. This is also working as long as we don't get too creative. Let me explain with a bit more source code.</p>
<p>The <code>BaseObject</code> <code>RegisterConverter</code> procedure is somewhat like this:</p>
<pre><code>class procedure TBaseObject.RegisterConverters(aClass:TClass; aMar:TJsonMarshal); virtual;
begin
aMar.RegisterConverter(aClass, 'fMar',
function(Data: TObject; Field: String): TObject
begin
Result := nil;
end);
end;
</code></pre>
<p>In a subclass - lets look at <code>TCustomer</code> I will now override the RegisterConverters procedure like this.</p>
<pre><code>class procedure TCustomer.RegisterConverters(aClass:TClass; aMar:TJsonMarshal); override;
begin
inherited;
aMar.RegisterConverter(aClass, 'fTimeOfLastContact',
function(Data: TObject; Field: String): string
var
ctx: TRttiContext;
date: TDateTime;
begin
date := ctx.GetType(Data.ClassType).GetField(Field).GetValue(Data).AsType<TDateTime>;
Result := FormatDateTime('yyyy-mm-dd hh:nn:ss', date);
end);
end;
</code></pre>
<p>Now we place the central marshalling in TBaseObject like this :</p>
<pre><code>function TBaseList<T>.Marshal: TJSONObject;
begin
fMar := TJSONMarshal.Create();
try
RegisterConverters;
try
Result := fMar.Marshal(Self) as TJSONObject;
except
on e: Exception do
raise Exception.Create('Marshal Error : ' + e.Message);
end;
finally
fMar.Free;
end;
end;
</code></pre>
<p>By doing this I have very easy access to do complete marshalling of my class <code>TCustomer</code>.
Simply by declaring a <code>TJsonObject</code> variable and do this:</p>
<pre><code>SomeJsonObj := SomeCustomer.Marshal;
</code></pre>
<p>And every other subclass (I have a lot) can do the same - just remember to override the <code>RegisterConverter</code> procedure in the subclass to support "special types".</p>
<p>But is this really the <strong>best</strong> solution?</p>
<p><strong>Marshalling the List part</strong></p>
<p>Is this an OK way of doing it?</p>
<p>Remember - it actually works. And REALLY eases the process of writing new units base on <code>TBaseObject</code> to achieve marshalling.</p>
<p>I always implement a List class to go alongside with my object class.
Hence I have <code>TBaseObject = class</code> and <code>TBaseList<T:TBaseObject> = TObjectList<T></code> declared in my base unit.</p>
<p>Now with the "nice" feature of being able to marshal any instance (ie. <code>TCustomer</code>) I would also like the possibility of marshaling a <code>TCustomerList<TCustomer></code> class.</p>
<p>What I came up with was:</p>
<p>Make a copy of the <code>RegisterConverters</code> and <code>Marshal</code> method from the <code>BaseObject</code> implementation and use it in the List. That way - I should be able to get started.</p>
<p>I end up with a <code>RegisterConverters</code> procedure like this for the List:</p>
<pre><code>procedure TBaseList<T>.RegisterConverters(aClass:TClass; aMar:TJsonMarshal); virtual;
begin
aMar.RegisterConverter(aClass, 'fMar',
function(Data: TObject; Field: String): TObject
begin
Result := nil;
end);
T.RegisterConverters(T, fMar); // class method - Register element specific converters.
end;
</code></pre>
<p>Note that the List version of the <code>RegisterConverter</code>s is NOT a class procedure. I do not see the need (but that might be my problem later). But now it should be clear as to WHY it was declared as a class method on the <code>BaseObject</code> class.</p>
<p>Implementing a <code>TCustomerList<T>.RegisterConverters</code> is easy as pie. Let's say we have a <code>property DataBuildTime : TDateTime;</code> on the list. Then again we would need a converter to ensure our datetime format is maintained:</p>
<pre><code>procedure TCustomerList<T>.RegisterConverters(aClass:TClass; aMar:TJsonMarshal); override;
begin
inherited;
aMar.RegisterConverter(aClass, 'fDataBuildTime',
function(Data: TObject; Field: String): string
var
ctx: TRttiContext;
date: TDateTime;
begin
date := ctx.GetType(Data.ClassType).GetField(Field).GetValue(Data).AsType<TDateTime>;
Result := FormatDateTime('yyyy-mm-dd hh:nn:ss', date);
end);
end;
</code></pre>
<p>And finally we can do this with a <code>TCustomerList<TCustomer></code> variable called <code>aList</code>:</p>
<pre><code>SomeJsonObject := aList.Marshal;
</code></pre>
<p><strong>The problem:</strong></p>
<p>This still works - my problem first arises when combining my hierarchy classes.
Having a <code>TWorker</code> that holds a <code>TCustomerList<TCustomer></code>, then my whole marshaling act falls apart.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-15T15:22:46.027",
"Id": "14115",
"Score": "0",
"body": "You spend *lots* of text describing what works, but your entire explanation of \"the problem\" is that something \"falls apart.\" That's probably why this question was closed on Stack Overflow."
}
] |
[
{
"body": "<p>Your <code>RegisterConverters</code> functions are bad, and part of the reason is that they're not sure <em>what</em> they're registering anything for. The class methods actually receive <em>two</em> classes as arguments. The first is the obvious one in <code>aClass</code>, but then there's also <code>Self</code>. Ideally, <code>aClass</code> should be a descendant of <code>Self</code>, so you should assert that:</p>\n\n<pre><code>Assert(aClass.InheritsFrom(Self),\n 'I''m being asked to register things for an unrelated class');\n</code></pre>\n\n<p>Once you've determined that the assertion never fails, you can simplify your code by removing the <code>aClass</code> parameter entirely. That way, it's clear that the <code>RegisterConverters</code> method is to register converters that the class needs for <em>its own</em> marshaling. For example, <code>TCustomer</code> has an <code>fTimeOfLastContact</code> field, so when the program calls <code>TCustomer.RegisterConverters</code>, it should register a converter for that field on <code>TCustomer</code> classes. And since we already know that the <code>Data</code> argument will be an instance of <code>TCustomer</code>, we don't really need all the RTTI exercises, either. Just type-cast to the type you already know it is, and read the <code>fTimeOfLastContact</code> field directly.</p>\n\n<pre><code>class procedure TCustomer.RegisterConverters(aMar: TJsonMarshal); override;\nbegin\n inherited; \n aMar.RegisterConverter(aClass, 'fTimeOfLastContact',\n function(Data: TObject; Field: string): string\n var\n date: TDateTime;\n begin\n Assert(Data is TCustomer);\n Assert(Field = 'fTimeOfLastContact');\n date := TCustomer(Data).fTimeOfLastContact;\n Result := FormatDateTime('yyyy-mm-dd hh:nn:ss', date);\n end); \nend;\n</code></pre>\n\n<hr>\n\n<p>The <code>RegisterConverters</code> methods for your list classes should be class methods. You say you don't \"see the need\" for them to be class methods, but if that's the case, then you're looking at things backward. <em>Every</em> method should be a class method <em>unless</em> it requires access to instance data. Your lists' <code>RegisterConverters</code> methods never access any instance data. In particular, they never consider their own lengths or their contents. They're designed to teach the marshaller how to marshal an <em>arbitrary instance</em> of the list class. Your example tells the marshaller that instances of <code>TCustomerList<T></code> should have a JSON property named <code>fDataBuildTime</code>, and when it's time to marshal a list, the marshaller will call the callback function to ask what value that property should have for the given instance. None of that depends on the instance you call <code>RegisterConverters</code> on.</p>\n\n<pre><code>class procedure TCustomerList<T>.RegisterConverters(aMar: TJsonMarshal); override;\nbegin\n inherited;\n aMar.RegisterConverter(Self, 'fDataBuildTime',\n function(Data: TObject; Field: String): string\n var\n ctx: TRttiContext;\n date: TDateTime;\n begin\n date := ctx.GetType(Data.ClassType).GetField(Field).GetValue(Data).AsType<TDateTime>;\n Result := FormatDateTime('yyyy-mm-dd hh:nn:ss', date);\n end);\n T.RegisterConverters(aMar);\nend;\n</code></pre>\n\n<p>I've added a call to <code>T.RegisterConverters</code> at the end so that when you register the list class, you implicitly register the contents, too.</p>\n\n<hr>\n\n<p>I see no reason for <code>fMar</code> to be a member of your <code>TBaseObject</code> class. It being a member suggests that every single one of your objects will have its own JSON marshaller, which is ludicrous, especially since you've demonstrated how that field is used in practice. You create the marshaller, use it, and destroy it all in the same <code>Marshal</code> method. Here's how your <code>Marshal</code> method should look instead:</p>\n\n<pre><code>function TBaseList<T>.Marshal: TJSONObject;\nvar\n Mar: TJSONMarshal;\nbegin\n Mar := TJSONMarshal.Create;\n try\n RegisterConverters(Mar);\n try\n Result := Mar.Marshal(Self) as TJSONObject;\n except\n on e: Exception do\n raise Exception.Create('Marshal Error : ' + e.Message);\n end;\n finally\n Mar.Free;\n end;\nend;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-16T19:24:43.580",
"Id": "14207",
"Score": "0",
"body": "GREAT answer Rob. I will try and explain some of my insanity :-)\nYour absolutely right - No need for mar and unmar properties. I wonder why I haven't seen this before! And the RTTI stuff is also not needed - so that's gone too :-)\nAbout the aClass parameter to my RegisterConverter method - your right on the money again - that was a leftover from an earlier test design. Regarding the call to Registerconverter from the list - I've done that already - on the BaseList. But the miracle happened and it actually seems to be working.\nI stuffed it all into one unit - if anyone is interested."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-15T15:58:38.900",
"Id": "8999",
"ParentId": "8850",
"Score": "3"
}
},
{
"body": "<p>This is just to let everyone see my final test. All stuffed into on unit.\nThis has all the changes suggested by Rob Kennedy (thanks again) and it also has a few other methods.</p>\n\n<pre><code>unit uDataObject;\n\ninterface\n\nuses\n System.SysUtils, System.Classes, Generics.Collections, Data.DBXJson, Data.DBXJsonReflect, System.DateUtils, System.RTTI;\n\ntype\n TMyClass = class\n private\n aInteger: integer;\n aString: String;\n class procedure RegisterConverters(aMar: TJsonMarshal); virtual;\n class procedure RegisterReverters(aUnMar: TJSONUnMarshal); virtual;\n public\n constructor Create; virtual;\n procedure Assign(aSource: TMyClass); virtual;\n procedure SetupData; virtual;\n function Marshal: TJSONObject; virtual;\n procedure UnMarshal(aJsonObj: TJSONObject); virtual;\n function SaveToJsonFile(sFileName: String; bOverWriteIfExists: Boolean = true): Boolean; virtual;\n procedure LoadFromJsonFile(sFileName: String); virtual;\n property pInteger: integer read aInteger write aInteger;\n property pString: String read aString write aString;\n end;\n\n TMyClassList<T: TMyClass, constructor> = class(TObjectList<T>)\n private\n class procedure RegisterConverters(aMar: TJsonMarshal); virtual;\n class procedure RegisterReverters(aUnMar: TJSONUnMarshal); virtual;\n public\n constructor Create; virtual;\n procedure Assign(aSource: TMyClassList<T>); virtual;\n function Marshal: TJSONObject; virtual;\n procedure UnMarshal(aJsonObj: TJSONObject); virtual;\n function SaveToJsonFile(sFileName: String; bOverWriteIfExists: Boolean = true): Boolean; virtual;\n function AsBaseList: TMyClassList<TMyClass>; virtual;\n procedure LoadFromJsonFile(sFileName: String); virtual;\n procedure Populate100Elements;\n end;\n\n // COMPLEX OBJECT - Contains TStringList as property.\n TMyComplexClass = class(TMyClass)\n private\n aStringList: TStringList;\n class procedure RegisterConverters(aMar: TJsonMarshal); override;\n class procedure RegisterReverters(aUnMar: TJSONUnMarshal); override;\n public\n constructor Create; override;\n destructor Destroy; override;\n procedure Assign(aSource: TMyClass); override;\n procedure SetupData; override;\n property pStringList: TStringList read aStringList write aStringList;\n end;\n\n TMyComplexClassList<T: TMyComplexClass, constructor> = class(TMyClassList<T>)\n private\n public\n constructor Create; override;\n procedure Assign(aSource: TMyClassList<T>); override;\n end;\n\n // VERY COMPLEX CLASS - Contains a TMyComplexClassList as property.\n\n // Class to test one instance with a Complex List as property.\n TMyCompositeClass = class(TMyComplexClass)\n private\n aRandomAbove100: integer;\n aTimeStamp: TDateTime;\n aComplexList: TMyComplexClassList<TMyComplexClass>; // Complex list\n class procedure RegisterConverters(aMar: TJsonMarshal); override;\n class procedure RegisterReverters(aUnMar: TJSONUnMarshal); override;\n public\n constructor Create; override;\n destructor Destroy; override;\n procedure Assign(aSource: TMyClass); override;\n procedure SetupData; override;\n property pRandomAbove100: integer read aRandomAbove100 write aRandomAbove100;\n property pTimeStamp: TDateTime read aTimeStamp write aTimeStamp;\n property pComplexList: TMyComplexClassList<TMyComplexClass> read aComplexList write aComplexList;\n end;\n\nvar\n initComplexList: TMyComplexClassList<TMyComplexClass>;\n\nimplementation\n\n{ TMyClass }\n\nprocedure TMyClass.Assign(aSource: TMyClass);\nbegin\n aInteger := aSource.aInteger;\n aString := aSource.aString;\nend;\n\nconstructor TMyClass.Create;\nbegin\n inherited Create;\n aString := '';\n aInteger := 0;\nend;\n\nprocedure TMyClass.LoadFromJsonFile(sFileName: String);\nvar\n aSL: TStringList;\n aObj: TJSONObject;\nbegin\n aSL := TStringList.Create;\n try\n aSL.LoadFromFile(sFileName);\n aObj := TJSONObject.Create;\n try\n aObj.Parse(TEncoding.ASCII.GetBytes(aSL.Text), 0);\n UnMarshal(aObj);\n finally\n aObj.Free;\n end;\n finally\n aSL.Free;\n end;\nend;\n\nfunction TMyClass.Marshal: TJSONObject;\nvar\n FMar : TJsonMarshal;\nbegin\n FMar := TJsonMarshal.Create;\n try\n RegisterConverters(FMar);\n try\n Result := FMar.Marshal(Self) as TJSONObject;\n except\n Result := nil;\n end;\n finally\n FMar.Free;\n end;\nend;\n\nclass procedure TMyClass.RegisterConverters(aMar: TJsonMarshal);\nbegin\n // none yet - abstract?\nend;\n\nclass procedure TMyClass.RegisterReverters(aUnMar: TJSONUnMarshal);\nbegin\n // none yet - abstract ?\nend;\n\nfunction TMyClass.SaveToJsonFile(sFileName: String; bOverWriteIfExists: Boolean): Boolean;\nvar\n aSL: TStringList; // makes it easy to save a file :-)\n aJObj: TJSONObject;\nbegin\n if not(bOverWriteIfExists) and (FileExists(sFileName)) then\n Exit(false);\n aSL := TStringList.Create;\n try\n aJObj := Marshal;\n try\n aSL.Add(aJObj.ToString);\n aSL.SaveToFile(sFileName);\n Result := true;\n finally\n aJObj.Free;\n end;\n finally\n aSL.Free;\n end;\nend;\n\nprocedure TMyClass.SetupData;\nbegin\n aString := 'Created : ' + FormatDateTime('ddmmyyyy hhnnss_zzz', now);\n aInteger := Random(100);\nend;\n\nprocedure TMyClass.UnMarshal(aJsonObj: TJSONObject);\nvar\n tmpObj: TMyClass;\n FUnMar : TJSONUnMarshal;\nbegin\n FUnMar := TJSONUnMarshal.Create;\n try\n RegisterReverters(FUnMar);\n try\n tmpObj := TMyClass(FUnMar.UnMarshal(aJsonObj)); // MUST USE CAST ... not as ... as uses RTTI and therefore needs info about class.\n try\n try\n Assign(tmpObj);\n except\n on e: Exception do\n raise Exception.Create('ERROR - UnMarshal MyClass(Assign) : ' + e.Message);\n end;\n finally\n tmpObj.Free;\n end;\n except\n on e: Exception do\n raise Exception.Create('ERROR - UnMarshal MyClass : ' + e.Message);\n end;\n finally\n FUnMar.Free;\n end;\nend;\n\n{ TMyComplexClass }\n\nprocedure TMyComplexClass.Assign(aSource: TMyClass);\nvar\n aStr: String;\n aCC: TMyComplexClass;\nbegin\n inherited Assign(aSource);\n aStringList.Clear;\n aCC := aSource as TMyComplexClass;\n for aStr in aCC.aStringList do\n aStringList.Add(aStr);\nend;\n\nconstructor TMyComplexClass.Create;\nbegin\n inherited Create;\n aStringList := TStringList.Create;\nend;\n\ndestructor TMyComplexClass.Destroy;\nbegin\n aStringList.Free;\n inherited;\nend;\n\nclass procedure TMyComplexClass.RegisterConverters(aMar: TJsonMarshal);\nbegin\n inherited;\n // register class specifik converters here.\n aMar.RegisterConverter(TStringList,\n function(Data: TObject): TListOfStrings\n var\n i, Count: integer;\n begin\n Count := TStringList(Data).Count;\n SetLength(Result, Count);\n for i := 0 to Count - 1 do\n Result[i] := TStringList(Data)[i];\n end);\nend;\n\nclass procedure TMyComplexClass.RegisterReverters(aUnMar: TJSONUnMarshal);\nbegin\n inherited;\n // register class specific reverters here\n aUnMar.RegisterReverter(TStringList,\n function(Data: TListOfStrings): TObject\n var\n StrList: TStringList;\n Str: string;\n begin\n StrList := TStringList.Create;\n for Str in Data do\n StrList.Add(Str);\n Result := StrList;\n end);\nend;\n\nprocedure TMyComplexClass.SetupData;\nvar\n i: integer;\nbegin\n inherited SetupData;\n for i := 0 to aInteger do\n aStringList.Add(IntToStr(aInteger) + ' - Text - ' + IntToStr(i));\nend;\n\n{ TMyClassList<T> }\n\nprocedure TMyClassList<T>.Populate100Elements;\nvar\n i: integer;\n Element: T;\nbegin\n for i := 1 to 100 do\n begin\n Element := T.Create;\n Element.SetupData;\n Add(Element);\n end;\nend;\n\nfunction TMyClassList<T>.SaveToJsonFile(sFileName: String; bOverWriteIfExists: Boolean): Boolean;\nvar\n aSL: TStringList;\n aJObj: TJSONObject;\nbegin\n if not(bOverWriteIfExists) and (FileExists(sFileName)) then\n Exit(false);\n aSL := TStringList.Create;\n try\n aJObj := Marshal;\n try\n aSL.Add(aJObj.ToString);\n aSL.SaveToFile(sFileName);\n Result := true;\n finally\n aJObj.Free;\n end;\n finally\n aSL.Free;\n end;\nend;\n\nprocedure TMyClassList<T>.UnMarshal(aJsonObj: TJSONObject);\nvar\n tmpList: TMyClassList<T>;\n FUnMar : TJSONUnMarshal;\nbegin\n FUnMar := TJSONUnMarshal.Create;\n try\n RegisterReverters(FUnMar);\n try\n tmpList := TMyClassList<T>(FUnMar.UnMarshal(aJsonObj)); // MUST CAST .. not use as ... since as uses RTTI ???\n try\n try\n Assign(tmpList);\n except\n on e: Exception do\n raise Exception.Create('ERROR - TMyClassList.UnMarshal(Assign) : ' + e.Message);\n end;\n finally\n tmpList.Free;\n end;\n except\n on e: Exception do\n raise Exception.Create('ERROR - TMyClassList.UnMarshal : ' + e.Message);\n end;\n finally\n FUnMar.Free;\n end;\nend;\n\nfunction TMyClassList<T>.AsBaseList: TMyClassList<TMyClass>;\nvar\n Element: T;\n NewBase: TMyClass;\nbegin\n Result := TMyClassList<TMyClass>.Create;\n Result.OwnsObjects := false;\n for Element in Self do\n begin\n NewBase := Element;\n Result.Add(NewBase);\n end;\nend;\n\nprocedure TMyClassList<T>.Assign(aSource: TMyClassList<T>);\nvar\n newObj, Element: T;\nbegin\n Clear; // delete data - if present\n for Element in aSource do\n begin\n newObj := T.Create;\n newObj.Assign(Element);\n Add(newObj);\n end;\nend;\n\nconstructor TMyClassList<T>.Create;\nbegin\n inherited Create; // WARNING .... specify create here - otherwise we leak mem ???? WHY ? (seen in XE2)\nend;\n\nprocedure TMyClassList<T>.LoadFromJsonFile(sFileName: String);\nvar\n aSL: TStringList;\n aObj: TJSONObject;\nbegin\n aSL := TStringList.Create;\n try\n aSL.LoadFromFile(sFileName);\n aObj := TJSONObject.Create;\n try\n aObj.Parse(TEncoding.ASCII.GetBytes(aSL.Text), 0);\n UnMarshal(aObj);\n finally\n aObj.Free;\n end;\n finally\n aSL.Free;\n end;\nend;\n\nfunction TMyClassList<T>.Marshal: TJSONObject;\nvar\n FMar : TJsonMarshal;\nbegin\n FMar := TJsonMarshal.Create;\n try\n RegisterConverters(FMar);\n try\n Result := FMar.Marshal(Self) as TJSONObject;\n except\n Result := nil;\n end;\n finally\n FMar.Free;\n end;\nend;\n\nclass procedure TMyClassList<T>.RegisterConverters(aMar: TJsonMarshal);\nbegin\n // call class method to get element converters registered with list marshaller\n T.RegisterConverters(aMar); // class method - Register element specific converters.\nend;\n\nclass procedure TMyClassList<T>.RegisterReverters(aUnMar: TJSONUnMarshal);\nbegin\n // List property specific reverters goes here\n // call class method to get element reverters registered with list unmarshaller\n T.RegisterReverters(aUnMar); // class method - Register element specific reverters.\nend;\n\n{ TMyComplexClassList<T> }\n\nprocedure TMyComplexClassList<T>.Assign(aSource: TMyClassList<T>);\nbegin\n inherited Assign(aSource);\nend;\n\nconstructor TMyComplexClassList<T>.Create;\nbegin\n inherited Create;\n\nend;\n\n{ TMyListComplexClass }\n\nprocedure TMyCompositeClass.Assign(aSource: TMyClass);\nvar\n aCC: TMyCompositeClass;\nbegin\n inherited Assign(aSource);\n aCC := aSource as TMyCompositeClass;\n aRandomAbove100 := aCC.aRandomAbove100;\n aTimeStamp := aCC.aTimeStamp;\n aComplexList.Assign(aCC.aComplexList);\nend;\n\nconstructor TMyCompositeClass.Create;\nbegin\n inherited Create;\n aRandomAbove100 := 0;\n aTimeStamp := 0;\n aComplexList := TMyComplexClassList<TMyComplexClass>.Create;\nend;\n\ndestructor TMyCompositeClass.Destroy;\nbegin\n aComplexList.Free;\n inherited;\nend;\n\nclass procedure TMyCompositeClass.RegisterConverters(aMar: TJsonMarshal);\nbegin\n inherited;\n aMar.RegisterConverter(Self, 'aTimeStamp',\n function(Data: TObject; Field: String): string\n begin\n Result := FormatDateTime('yyyy-mm-dd hh:nn:ss:zzz', TMyCompositeClass(Data).aTimeStamp);\n end);\n\n TMyComplexClassList<TMyComplexClass>.RegisterConverters(aMar);\nend;\n\nclass procedure TMyCompositeClass.RegisterReverters(aUnMar: TJSONUnMarshal);\nbegin\n inherited;\n aUnMar.RegisterReverter(Self, 'aTimeStamp',\n procedure(Data: TObject; Field: string; Arg: string)\n begin\n TMyCompositeClass(Data).aTimeStamp := EncodeDateTime(StrToInt(Copy(Arg, 1, 4)), StrToInt(Copy(Arg, 6, 2)), StrToInt(Copy(Arg, 9, 2)), StrToInt(Copy(Arg, 12, 2)),\n StrToInt(Copy(Arg, 15, 2)), StrToInt(Copy(Arg, 18, 2)), StrToInt(Copy(Arg, 21, 3)));\n end);\n\n TMyComplexClassList<TMyComplexClass>.RegisterReverters(aUnMar);\nend;\n\nprocedure TMyCompositeClass.SetupData;\nbegin\n inherited SetupData;\n aRandomAbove100 := Random(1000) + 100;\n aTimeStamp := now;\n aComplexList.Populate100Elements;\nend;\n\ninitialization\n\ninitComplexList := TMyComplexClassList<TMyComplexClass>.Create;\n\nfinalization\n\ninitComplexList.Free;\n\nend.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-02T13:31:46.463",
"Id": "112280",
"Score": "0",
"body": "RegisterConverters and RegisterReverters should be protected."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-12T10:27:49.287",
"Id": "114435",
"Score": "0",
"body": "Your probably correct about that - but it could be a matter of design. But since this is a few years old now, newer and better technologies have been implemented, and Embacadero is deprecating the DBX. Marshal / UnMarshal is no longer needed as described."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-16T20:11:58.107",
"Id": "9059",
"ParentId": "8850",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "8999",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T09:20:01.290",
"Id": "8850",
"Score": "2",
"Tags": [
"delphi"
],
"Title": "Is Marshalling converters/reverters via polymorphism realistic?"
}
|
8850
|
<p>My JS looks like this:</p>
<pre><code>preLoadImages("/media/img/elements/frontpage/1.jpg","/media/img/elements/frontpage/2.jpg","/media/img/elements/frontpage/3.jpg","/media/img/elements/frontpage/4.jpg","/media/img/elements/frontpage/5.jpg","/media/img/elements/frontpage/6.jpg","/media/img/elements/frontpage/7.jpg","/media/img/elements/frontpage/8.jpg","/media/img/elements/frontpage/9.jpg","/media/img/elements/frontpage/10.jpg");
</code></pre>
<p>What would be a better way to do this?</p>
<pre><code>var directory = "/media/img/elements/frontpage/"
preLoadImages(directory+"1.jpg",directory+"2.jpg",directory+"3.jpg",directory+"4.jpg",directory+"5.jpg",directory+"6.jpg",directory+"7.jpg",directory+"8.jpg",directory+"9.jpg",directory+"10.jpg");
</code></pre>
<p>Doesn't seem much better. There must be a zip/map/join type thing I can use here?</p>
|
[] |
[
{
"body": "<p>perhaps you can try apply(), then you can pass in the image paths as an array:</p>\n\n<pre><code>preLoadIamges.apply(this, absoluteFileNames)\n</code></pre>\n\n<p>then you can build you array in a the way you like, perhaps looking at <a href=\"http://www.tutorialspoint.com/javascript/array_map.htm\" rel=\"nofollow\">this unobtrusive implementation of Array.map</a>:</p>\n\n<pre><code>var directory = \"/media/img/elements/frontpage/\"\nvar fileNames = [\"1.jpg\",\"...\",\"9.jpg\"]; \nvar absoluteFileNames = fileNames.map(function (value) { \n return directory + value; \n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T14:22:59.750",
"Id": "13863",
"Score": "0",
"body": "Good answer, this is probably how I would approach it too."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T10:47:24.323",
"Id": "8852",
"ParentId": "8851",
"Score": "3"
}
},
{
"body": "<p>If the files are all named sequentially, doesn't using a simple loop make sense?</p>\n\n<pre><code>var directory = \"/media/img/elements/frontpage/\",\n images = [],\n i = 11;\n\nwhile (--i) {\n images.push(directory + i + \".jpg\");\n}\n\npreLoadImages(images);\n\n// ...\n\nfunction preLoadImages(images) {\n console.log(\"preloading: \" + images);\n // TODO: preload stuff\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T16:59:19.397",
"Id": "8858",
"ParentId": "8851",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T09:32:09.623",
"Id": "8851",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Combining text in an array in JavaScript"
}
|
8851
|
<p>I have a text file that uses the convention <code>#\d+</code> to mean ASCII character number <code>\d+</code>. I want to replace any such representations with the actual character. This is what I've come up with. It works but it feels kludgy. Suggestions to improve efficiency?</p>
<pre><code><?php
$line= 'stuff #65 more #66 and #67; other';
preg_match_all("/\#\d+/",$line,$p);//find any #numbers that should be translated to ascii
$r=array_map(
function($x){ return chr(trim($x,'#')); },
$p[0]); //assemble set of replacements
$line=str_replace($p[0],$r,$line); //replace
echo $line; //stuff A more B and C; other
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T18:54:04.857",
"Id": "13881",
"Score": "0",
"body": "You might want to check out the [`/e` modifier](http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php). It's usually disabled on hardened systems, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T19:07:39.313",
"Id": "13883",
"Score": "0",
"body": "@GGG: nice idea! but unfortunately off on my system."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T19:16:07.990",
"Id": "13884",
"Score": "0",
"body": "It only works on `preg_replace`. But if you're on shared hosting or using suhosin, yeah, it's probably disabled entirely."
}
] |
[
{
"body": "<p>Warning: The code below is intended to be compatible with the original post.\nIts main benefit is that it retains all of the useful detail discovered in the pattern match (unmatched substrings, relative position of matches), eliminating the need to rescan the line. I'd expect it to be faster for that reason.</p>\n\n<p>It retains the problem that <code>chr</code> is a blunt instrument that can effortlessly\nconsume many digits (not just one, two, or three), using \"wrapping\"\n(a.k.a. modulo 256 math) to scale the resulting integer down to a legal byte value,\npossibly not the one intended.</p>\n\n<p>In other words, this code would fail the conversion of a string with ASCII codes \nimmediately followed by digits, e.g. \nif \"From A1 to z52\" needs to be expressable as \"From #651 to #12252\".\nSo, a different approach may be needed.</p>\n\n<p>One approach is for the conversion step to convert the digit string to integer digits one digit at a time,\ndoing the <code>(digits*10 + digit)</code> math and stopping (or actually backing up one digit) \nwhen a value of 256 or greater is reached.</p>\n\n<p>Another approach, probably faster, is for the conversion step to convert a substring (up to three digits) of\nthe digit string to an integer and if it is 256 or greater \"back up one digit\", dividing\nthe integer by 10. </p>\n\n<p>In either case, any unused/backed-up digits would be appended to the result\nof chr applied to the integer.</p>\n\n<p>In either of these approaches, but especially the first,\nsome work might be saved by having the regex match at most\nthree digits instead of any number of digits -- leaving the rest as unmatched characters \nat the head of the next \"surrounding text\" part. \nThat way, there would be no need to test for integer overflow from way too many digits.</p>\n\n<p>A \"higher-tech\" approach could go further, enabling the current simple \n<code>$parts[$i] = chr($parts[$i])</code> conversion to be retained.\nThis would require beefing up the regex so that it matched, in order of preference, \na 3-digit number less than 256 OR a 2-digit number (that possibly had another \nunmatched digit following it) OR a 1-digit number (that was not followed by another digit).</p>\n\n<p>That seems like a lot of trouble, except maybe for a regex aficionado, so I'd probably opt for the middle approach, converting and testing a 3-digit substring.</p>\n\n<pre><code><?php\n $line= 'stuff #65 more #66 and #67; other';\n // break out any #numbers that should be translated to ascii, \n // retaining the surrounding text and the numbers parts.\n // The '#' parts are kept outside the parens to be matched and discarded.\n $parts = preg_split(\"/\\#(\\d+)/\",$line,NULL,PREG_SPLIT_DELIM_CAPTURE);\n $count = count($parts);\n // Even-indexed entries (possibly empty) contain unchanging surrounding text.\n\n // Odd-indexed entries are the numbers part of #numbers, so convert them.\n for ($i = 1; $i < $count; $i += 2) {\n $parts[$i] = chr($parts[$i]); // Problem here for input >= 256.\n }\n\n $line = implode($parts);\n?>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-15T04:55:08.900",
"Id": "8986",
"ParentId": "8860",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "8986",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T18:35:39.033",
"Id": "8860",
"Score": "3",
"Tags": [
"php",
"performance",
"strings"
],
"Title": "Find ASCII codes and replace with characters"
}
|
8860
|
<p>This code is for a problem in which I'm to find the total number of numbers that exist between A and B, of which sum of digits and sum of square of digits are prime.</p>
<p>How can I make this optimal?</p>
<pre><code>import java.util.Scanner;
public class LuckyNumbers {
static int T,ans[];
static long A,B;
public static void main(String ar[]){
Scanner scan=new Scanner(System.in);
T=scan.nextInt();
ans=new int[T];
for(int i=0;i<T;i++){
A=scan.nextLong();
B=scan.nextLong();
for(long j=A;j<=B;j++){
if(getLucky(j)){
ans[i]++;
}
}
}
for(int i=0;i<T;i++){
System.out.println(ans[i]);
}
}
public static boolean getLucky(long j){
boolean lucky=false;
long rem,sum=0,sum1=0;
while(j>0){
rem=j%10;
sum=sum+rem;
sum1=sum1+(rem*rem);
j=j/10;
}
if(isPrime(sum)&&isPrime(sum1)){
lucky=true;
}
return lucky;
}
public static boolean isPrime(long sum){
boolean status=true;
if(sum!=1){
for (int i=2; i < sum ;i++ ){
long n =sum % i;
if (n==0){
status=false;
break;
}
}
}else{
status=false;
}
return status;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T19:21:25.503",
"Id": "13912",
"Score": "0",
"body": "You need to invest some time in profiling this code (whether by adding your own timers or by leveraging some sort of tools / frameworks / profilers. The run this (or improved) code with increasingly large input and get a sense for what the complexity is. Do try to break things up as much as you can, so that you can experiment with swapping individual pieces in and out."
}
] |
[
{
"body": "<p>Code optimization can be tricky. Make the code optimal can be something different.</p>\n\n<p>There's a lot of sub-question: Optimization, in term of speed / memory ? On which device? From a fresh start, or after a long running time ?</p>\n\n<p>But first, give variable a explicit name, because A,B,T means nothing to me/ others code, and longer variable name won't slow down your code. Second, use a profiler may help you, I usually use jvisualvm.exe (in the jdk). Third, a faster code on your machine won't necessary be faster on a other computer / device.</p>\n\n<p>In your getLucky method, the lucky variable is not necessary, you could do: return (isPrime(sum)&&isPrime(sum1));</p>\n\n<p>but it will render your code less readable.</p>\n\n<p>In your isPrime method, the for loop check the i is a integer and the sum is a long. So if the sum is bigger than MAX_INTEGER you will be in trouble.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T13:00:46.057",
"Id": "13907",
"Score": "0",
"body": "Algebra does math with one-letter variables all the time. Why does it magically become hard to understand once it's written down as code? And they're being used _as limits of an iteration_. How is that hard to spot?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T20:32:53.137",
"Id": "8864",
"ParentId": "8863",
"Score": "2"
}
},
{
"body": "<p>Some thoughts on speed:</p>\n\n<ul>\n<li>Start caching results in <code>isPrime</code>.</li>\n<li>Print things as soon as you calculate them, no need to store them back into an array. (This makes debugging easier, too.)\n<ul>\n<li>As Leonid pointed out, storing things may be a good idea. I would keep it an array in that case, not a linked list, as that costs less time.</li>\n<li>However, I would simply disable output when profiling, and keep my suggestion for debugging.</li>\n<li>On a similar note, consider splitting both the main algorithm and the output into separate functions so that you can easily disable both. That makes it much easier to check how much each stage of the algorithm (parsing, processing, printing) is taking.</li>\n</ul></li>\n<li>You could try caching <code>rem*rem</code>, as you know there's only ten possibilities. May be faster, may be slower.</li>\n<li>You should take a look at the input you'll be dealing with and figure out what values your program needs to have that could be given beforehand. What values can the numbers you're checking for primality be? (I would guess you need up to around 2000, but I'm not sure.)</li>\n</ul>\n\n<p>Some general thoughts:</p>\n\n<ul>\n<li>Add some comments. What is a lucky number?</li>\n<li>Add some blank lines.</li>\n<li>Rename <code>getLucky</code> to <code>isLucky</code> or <code>checkIsLucky</code>. I'd go for the first, but some people will tell you that functions need a verb other than \"is\". If Java supports it, you could make it an extension method and then do <code>arr[i].isLucky()</code>.</li>\n<li>Don't make variables static unless they have to be. Both <code>T</code> and <code>ans</code> can be local to <code>main</code>.</li>\n<li>Make your variable names more meaningful. In particular, replacing <code>T</code> with <code>numberOfInputPairs</code> (or <code>numInputPairs</code>, at least) would improve matters.</li>\n<li>Don't use the same name for two variables, with one letter difference. Why do you have <code>sum</code> and <code>sum1</code>? What's the difference between them?</li>\n<li>Use the <code>+=</code> operator when possible. <code>sum1 += rem*rem</code> is easier to read than what you have.</li>\n</ul>\n\n<p>To address the question of <code>numberOfInputPairs</code> being too long: let's reformat the code a little and change the name appropriately:</p>\n\n<pre><code>public static void main(String ar[]){\n Scanner scan = new Scanner(System.in);\n int numberOfInputPairs = scan.nextInt();\n int ans[] = new int[numberOfInputPairs];\n\n for (int i = 0; i < numberOfInputPairs; i++){\n A = scan.nextLong();\n B = scan.nextLong();\n for (long j = A; j <= B; j++) {\n if (getLucky(j)) {\n ans[i]++;\n }\n }\n }\n\n for (int i = 0; i < numberOfInputPairs; i++) {\n System.out.println(ans[i]);\n }\n}\n</code></pre>\n\n<p>Yes, if no whitespace is added, the longer variable names make a wall of text a bigger wall of text, and convey very little meaning. However, with just a slight increase in the amount of whitespace, I find that the longer variable name is no less clear and makes it clear what is being done.</p>\n\n<p>(By the way, I think this is partially a language problem: as things are, it is used three times, while a proper for-each loop would mean it would only need to be used once.)</p>\n\n<p>I do not agree with <code>n</code> or <code>T</code> offering that clarity; <code>numPairs</code> would do, too, and is down to personal preference.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T19:24:40.413",
"Id": "13913",
"Score": "1",
"body": "Depending on the problem/algorithm at hand, `System.out.println` can be the slowest part. When reasoning about / profiling the run time, I would not want to analyze the mix of IO and CPU crunching. I would stick the result into say a LinkedList, and then print it out all at once at the end."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T19:28:08.753",
"Id": "13914",
"Score": "0",
"body": "Good answer overall, but `totalNumberOfInputs`? Really? Awfully verbose for something that is arguably misleading--you actually have _two_ inputs for each iteration! `nInputPairs` or just plain `n` (or `T`) would be better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T21:39:02.413",
"Id": "13923",
"Score": "0",
"body": "@RexKerr, Leonid: Edited to react to your suggestions, thanks."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T20:52:14.160",
"Id": "8865",
"ParentId": "8863",
"Score": "6"
}
},
{
"body": "<p>Not sure about optimisation, but I think readability is really important, and conciseness is a big part of readability. So I would write the <code>isPrime</code> method like this.</p>\n\n<pre><code>public static boolean isPrime(long sum){ \n if( sum == 1 ){\n return false;\n }\n for( int i = 2; i < sum ;i++ ){ \n if( sum % i == 0 ){\n return false;\n }\n }\n return true; \n} \n</code></pre>\n\n<p>Also, lots of work has been done on good algorithms for testing primality. Running through and testing for divisibility by every integer is far from optimal. So you could do some research on this - it's a mathematics question, not a computer science one.</p>\n\n<p>One idea that you could try is the whole difference of squares thing. If you've got an array in which you've stored lots of square numbers, then you can use this to test with subtraction, rather than division. That is, if you're testing some odd number <code>z</code>, which happens to be <code>x * y</code>, then it's also</p>\n\n<p><code>((x+y)/2)^2 - ((x-y)/2)^2</code></p>\n\n<p>And since <code>x</code> and <code>y</code> must both be odd, both of the entities being squared are integers. So looking for two squares that differ by <code>z</code> turns out to be equivalent to looking for factors, but computationally much easier.</p>\n\n<p>Have a try at turning this approach into Java code. Post a comment on this answer if you get stuck, and I'll try to give you some more guidance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T22:23:44.880",
"Id": "13926",
"Score": "0",
"body": "Factorization is an NP problem, primality testing a P problem (as proven by the AKS theorem), so generally you can say much faster if a number is prime or composite than calculating the actual factors (that's the fact RSA and other encryption methods rely on). Further Wikipedia states for the Fermat factorization you describe \"In its simplest form, Fermat's method might be even slower than trial division (worst case).\""
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T07:00:00.037",
"Id": "8874",
"ParentId": "8863",
"Score": "1"
}
},
{
"body": "<p>I think you chould consider improving the isPrime(long sum) (i don't think sum is a luckily chosen name here, by the way).</p>\n\n<p>Consider using a better algorythm, e.g. a <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Atkin\" rel=\"nofollow\">sieve fo atkin</a> instead of looping all values.</p>\n\n<p>See e.g. <a href=\"http://introcs.cs.princeton.edu/java/14array/PrimeSieve.java.html\" rel=\"nofollow\">this implementation</a></p>\n\n<p>On this basis you can improve caching on your specific needs.</p>\n\n<p>I would give you the advice to optimize your code for readability and start measuring. Only pull in optimizations that are worth. Don't clutter up your code without value.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T07:01:00.257",
"Id": "8875",
"ParentId": "8863",
"Score": "3"
}
},
{
"body": "<p>While everybody mentioned optimizing <code>isPrime</code>, nobody spotted the one glaring ineffiency: You can break the loop as soon as <code>i*i > sum</code>. Further you can skip the even divisors except 2:</p>\n\n<pre><code>public static boolean isPrime(long sum){\n if (sum < 2) return false;\n if (sum < 4) return true;\n if (sum % 2 == 0) return false;\n int limit = (int) (Math.sqrt(sum)); \n for (int i = 3; i <= limit; i += 2 ){\n if (sum % i==0){\n return false;\n }\n }\n return true;\n}\n</code></pre>\n\n<p>Alternatively you can use <code>BigInteger.isProbablePrime()</code>. Despite its name it returns correct results - at least in the <code>long</code> range.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T19:20:10.530",
"Id": "13911",
"Score": "0",
"body": "I was waiting for someone to point that one out."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T13:28:10.677",
"Id": "8885",
"ParentId": "8863",
"Score": "5"
}
},
{
"body": "<p>isPrime(long num) method can be improved by using other prime number checking algorithms such\nas Fermat theoram, reducing check space or by simply incrementing by 2 instead of i++.You don't need to check every even number upto n.Infact, you don't need to check every odd number upto n.just check it upto sqrt(number).</p>\n\n<p>eg -></p>\n\n<pre><code> if(num%2==0)\n return false;\n for(i=3;(i*i)<num;i+=2)\n {\n .............\n } \n\n onw more \n</code></pre>\n\n<p>For more details , refer to 1st chapter of Fundamentals of Algorithms by Sahni</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-16T06:02:11.463",
"Id": "9030",
"ParentId": "8863",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "8885",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-10T20:15:06.050",
"Id": "8863",
"Score": "2",
"Tags": [
"java",
"optimization",
"primes"
],
"Title": "Finding \"lucky numbers\""
}
|
8863
|
<p>The code below has been a pet project of mine for some time. It allows simplified browsing of websites that have a predictable URL structure, namely TGP websites.</p>
<p>It has been greatly modified from it's original version to be effective on Android, and there is probably alot of room to improve on it. I'm not asking anyone to do my work for me, though.</p>
<pre><code> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-Equiv="Cache-Control" Content="no-cache">
<meta http-Equiv="Pragma" Content="no-cache">
<meta http-Equiv="Expires" Content="0">
<script type="text/javascript">
window.onload = function() {
if(location.href.lastIndexOf('?')>0)(splitURL(location.href.substring(location.href.lastIndexOf('?')+1)))
BROWSEbar.style.display='none';
EDITbar.style.display='block';
};
window.onscroll = function() {
document.getElementById('fixdiv').style.top =
(window.pageYOffset) + 'px';
};
function splitURL(newURL)
{
EDITbar.fullURL.value=newURL;
EDITbar.splitURL.click();
EDITbar.goURL.click();
}
function combine(a,b,c,d,e,f,g){return a+b+c+d+e+f+g;}
function highlight(field) {field.focus();field.select();}
function minusone(a)
{
b = a.length;
a = Number(a);
a = ((a > 1) ? a - 1 : a);
a = String(a);
while(a.length < b)
{
a = "0" + a;
}
return a;
}
function plusone(a)
{
b = a.length;
a = Number(a);
a++;
a = String(a);
while(a.length < b)
{
a = "0" + a;
}
return a;
}
function gotoURL(sURL)
{
var iTail=Math.round(Math.random()*100000);
if (sURL.search('http://')<0){sURL="http://"+sURL;}
sURL=sURL+'?r+'+iTail;
top.frames['mframe'].location.href=sURL;
}
function URLsplit()
{
var newURL = EDITbar.fullURL.value.replace('http://','');
var testI=null;
var i=0;
var j=1;
EDITbar.clearURL.click();
while (i<newURL.length)
{
switch(j)
{
case 1:
EDITbar.url2.value = EDITbar.url2.value + newURL.charAt(i);
if(testI == false){j++;}
break;
case 2:
EDITbar.url3.value = EDITbar.url3.value + newURL.charAt(i);
if(testI == true){j++;}
break;
case 3:
EDITbar.url4.value = EDITbar.url4.value + newURL.charAt(i);
if(testI == false){j++;}
break;
case 4:
EDITbar.url5.value = EDITbar.url5.value + newURL.charAt(i);
if(testI == true){j++;}
break;
case 5:
EDITbar.url6.value = EDITbar.url6.value + newURL.charAt(i);
if(newURL.charAt(i+1) == "."){j++;}
break;
case 6:
EDITbar.url7.value = EDITbar.url7.value + newURL.charAt(i);
break;
}
i++;
testI = isNaN(newURL.charAt(i+1));
}
BROWSEbar.url3.value=EDITbar.url3.value;
BROWSEbar.url5.value=EDITbar.url5.value;
}
</script>
<title>
Filter-Kilter Browser
</title>
<style type="text/css">
#fixdiv {filter: alpha(opacity=86); -moz-opacity: .86; background-color:#EEE;}
html, body { margin: 0; padding: 0; height: 100%; overflow:hidden;}
p, h1 {top-margin: 0; padding: 0;}
.button
{
color: #900;
border: 1px solid #900;
font-size: 24px;
font-weight: bold;
}
.browse
{
color: #862;
border: 2px solid #806020;
font-size: 240%;
font-weight: 900;
}
iframe
{
position: absolute;
top: 0; left: 0; width: 100%; height: 100%;
border: none;
}
table,th,td
{
border-collapse : collapse;
padding:0;
}
th
{
background-color:green;
color:white;
}
input.groovybutton
{
font-size:46px;
font-family:Comic Sans MS,sans-serif;
font-weight:bold;
color:#ffffff;
width:990px;
height120px;
background-color:#800;
border-style:solid;
border-color:#000000;
}
input.smallbtn
{
font-size:24px;
font-family:Comic Sans MS,sans-serif;
font-weight:bold;
color:#ffffff;
width:100px;
height60px;
background-color:#800;
border-style:solid;
border-color:#000000;
}
input.medbtn
{
font-size:36px;
font-family:Comic Sans MS,sans-serif;
font-weight:bold;
color:#fff;
width:100px;
height80px;
background-color:#f60;
border-style:solid;
border-color:#000000;
}
input.medtxt
{
font-size:50px;
font-family:Comic Sans MS,sans-serif;
font-weight:bold;
color:#000000;
width:100px;
background-color:#FFF0D0;
border-style:solid;
border-color:#000000;
}
input.bigtxt
{
font-size:38px;
font-weight:bold;
color:#800;
height60px;
background-color:#ffffff;
border-style:solid;
border-color:#800;
}
</style>
</head>
<body>
<iframe id="mframe" name="mframe" src="MAIN.html" frameborder="0" marginheight="0" marginwidth="0" width="100%" height="100%" scrolling="auto"></iframe>
<div id="fixdiv" style="background-color: transparent; position: absolute; z-index: 1; visibility: show; left: 10%;">
<center>
<form name=EDITbar method=get action="javascript:gotoURL(EDITbar.fullURL.value);" onsubmit="EDITbar.fullURL.value=combine(url1.value,url2.value,url3.value,url4.value,url5.value,url6.value,url7.value);">
<input class='smallbtn' name=clearURL type=reset value="CLEAR">
<input class='bigtxt' name=fullURL type=text size=40>
<input class='smallbtn' name=splitURL type=submit value="SPLIT" onclick="javaScript:URLsplit();">
<br>
<input class='button' name=url1 type=text size=4 value="http://" onkeyup="url1.value=('http://');">
<input class='button' name=url2 type=text size=20 value="">
<input class='button' name=url3 type=text size=4 value="">
<input class='button' name=url4 type=text size=12 value="">
<input class='button' name=url5 type=text size=4 value="">
<input class='button' name=url6 type=text size=9 value="">
<input class='button' name=url7 type=text size=4 value="">
<br>
<input class='groovybutton' name=cancelURL type=submit value="BROWSE" onclick="BROWSEbar.url3.value=url3.value; BROWSEbar.url5.value=url5.value; EDITbar.style.display='none'; BROWSEbar.style.display='block';">
</form>
<form name=BROWSEbar method=get action="javascript:gotoURL(EDITbar.fullURL.value);" onsubmit="EDITbar.fullURL.value=combine(EDITbar.url1.value,EDITbar.url2.value,EDITbar.url3.value,EDITbar.url4.value,EDITbar.url5.value,EDITbar.url6.value,EDITbar.url7.value);">
<input class='medbtn' name=minus1 type=submit value="-" onClick="url3.value=minusone(url3.value);EDITbar.url3.value=url3.value;">
<input class='medtxt' name=url3 type=text size=42 value="">
<input class='medbtn' name=add1 type=submit value="+" onClick="url3.value=plusone(url3.value);EDITbar.url3.value=url3.value;">
<input class='medbtn' name=editURL type=button value="EDIT" onmouseover="BROWSEbar.style.display='none'; EDITbar.style.display='block';">
<input class='medbtn' name=minus2 type=submit value="-" onClick="url5.value=minusone(url5.value);EDITbar.url5.value=url5.value;">
<input class='medtxt' name=url5 type=text size=6 value="">
<input class='medbtn' name=add2 type=submit value="+" onClick="url5.value=plusone(url5.value);EDITbar.url5.value=url5.value;">
</form>
</center>
</div>
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T00:33:55.817",
"Id": "13894",
"Score": "0",
"body": "Can you provide a not-NSFW url where I can pont this thing to test it? I made a [thing for it](http://jsfiddle.net/UW49J/)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T00:38:59.773",
"Id": "13895",
"Score": "0",
"body": "Suprisingly, yes: http://cygwin.com/ml/cygwin/2004-05/msg00250.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T00:42:50.533",
"Id": "13896",
"Score": "0",
"body": "The date directory and the page are both usable to test it out. By default it will split it at the first two numeric instances (year-month), I paln on implementing skipping instances eventually."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T00:56:53.893",
"Id": "13897",
"Score": "0",
"body": "Hmm, I got it to work from a file:// url, but not a jsfiddle. It seems to have some weird bugs in chrome. I'll review it later if I have time :)"
}
] |
[
{
"body": "<p>I will ignore the android specific parts. And i will fix/ignore the missing semicolons & unnecessary brackets </p>\n\n<p>Ok .. here it goes.</p>\n\n<ul>\n<li><p>it's 2012, please use HTML5 doctype.</p>\n\n<pre><code><!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\">\n</code></pre></li>\n<li><p>english is not the only language on planet, you should be using UTF-8 for ages already</p>\n\n<pre><code><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />\n</code></pre></li>\n<li><p>if possible, avoid meeing with style object. Each time you modify it, browser executed <code>reflow</code> stage</p>\n\n<pre><code>BROWSEbar.style.display='none'; \nEDITbar.style.display='block';\n</code></pre></li>\n<li><p>this is just madness</p>\n\n<pre><code>function minusone(a) {\n b = a.length;\n a = Number(a);\n a = ((a > 1) ? a - 1 : a);\n a = String(a);\n while (a.length < b) {\n a = \"0\" + a;\n }\n return a;\n}\n\nfunction plusone(a) {\n b = a.length;\n a = Number(a);\n a++;\n a = String(a);\n while (a.length < b) {\n a = \"0\" + a;\n }\n return a;\n}\n</code></pre></li>\n<li><p>you should learn how to use arrays in javascript</p>\n\n<pre><code>switch (j) {\n case 1:\n EDITbar.url2.value = EDITbar.url2.value + newURL.charAt(i);\n if (testI == false){\n j++;\n }\n break;\n case 2:\n EDITbar.url3.value = EDITbar.url3.value + newURL.charAt(i);\n if(testI == true){\n j++;\n }\n break;\n case 3:\n EDITbar.url4.value = EDITbar.url4.value + newURL.charAt(i);\n if(testI == false){\n j++;\n }\n break;\n case 4:\n EDITbar.url5.value = EDITbar.url5.value + newURL.charAt(i);\n if(testI == true){\n j++;\n }\n break;\n case 5:\n EDITbar.url6.value = EDITbar.url6.value + newURL.charAt(i);\n if(newURL.charAt(i+1) == \".\"){\n j++;\n }\n break;\n case 6:\n EDITbar.url7.value = EDITbar.url7.value + newURL.charAt(i);\n break;\n }\n</code></pre></li>\n<li><p>firefox and IE are <strong>not</strong> the only browsers </p>\n\n<pre><code> #fixdiv {\n filter: alpha(opacity=86); \n -moz-opacity: .86; \n background-color:#EEE;\n }\n</code></pre></li>\n<li><p>this is just nasty</p>\n\n<pre><code> font-family:Comic Sans MS,sans-serif;\n</code></pre></li>\n<li><p>you should not be using iframes just to create layout. Go and learn what XHR is.</p>\n\n<pre><code> <iframe id=\"mframe\" name=\"mframe\" src=\"MAIN.html\" frameborder=\"0\" marginheight=\"0\" marginwidth=\"0\" width=\"100%\" height=\"100%\" scrolling=\"auto\"></iframe>\n</code></pre></li>\n<li><p>please , stop using inline css</p>\n\n<pre><code> <div id=\"fixdiv\" style=\"background-color: transparent; position: absolute; z-index: 1; visibility: show; left: 10%;\">\n</code></pre></li>\n<li><p>this tag is considered outdate , you have css for it</p>\n\n<pre><code> <center>\n</code></pre></li>\n<li><p>do not attach javascrit events in HTML tags</p>\n\n<pre><code> <form name=EDITbar method=get action=\"javascript:gotoURL(EDITbar.fullURL.value);\" onsubmit=\"EDITbar.fullURL.value=combine(url1.value,url2.value,url3.value,url4.value,url5.value,url6.value,url7.value);\">\n <input class='smallbtn' name=splitURL type=submit value=\"SPLIT\" onclick=\"javaScript:URLsplit();\">\n <input class='button' name=url1 type=text size=4 value=\"http://\" onkeyup=\"url1.value=('http://');\">\n <input class='groovybutton' name=cancelURL type=submit value=\"BROWSE\" onclick=\"BROWSEbar.url3.value=url3.value; BROWSEbar.url5.value=url5.value; EDITbar.style.display='none'; BROWSEbar.style.display='block';\">\n</code></pre></li>\n<li><p>line breaks are not for layout</p>\n\n<pre><code> <br>\n</code></pre></li>\n</ul>\n\n<p>Essentially , it looks like your HTML/JS/CSS skills are at least 10 yours out of date.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T00:11:03.603",
"Id": "16628",
"Score": "0",
"body": "You are right in your assumption that my skills are out of date, thank you for the apt analysis. My original implementation made use of old style framesets, the iframes was a pretty big step up for me. Is XHR android compatible? My switch to iframes was mainly due to layout errors with scroll bars.\n\nThe addition and subtraction functions were written in such a way to account for and return leading zeroes. I am sure there is a cleaner way to do it but I can't squeeze blood from a turnip, so to speak. If i remember correctly it was the strongly defined variables that were giving me trouble."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T00:11:16.753",
"Id": "16629",
"Score": "0",
"body": "All, and I mean ALL CCS was added in a recent revision, there are still some vesiges of usless html here and there. Thanks for pointing some of it out.\n\nThanks again for the look over, any examples that you know of that fit my code for a variable array? It was my intention to use a dynamic array originally but I never got it to work and took the easy way out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T00:35:24.150",
"Id": "16630",
"Score": "0",
"body": "@user1203156 Yes, it is possible to use XHR on android devices. It is available even on all the new non-smart phones. As for plusone/minusone functions, it depends on what you exactly are trying to do, but it would be much easier accomplished with closure .. and not in such an ugly way. As for that large switch statement: i have no idea what you are doing there, but it could be rewritten in ~8 lines."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T00:53:50.907",
"Id": "16632",
"Score": "0",
"body": "The plus/minus function adjusts the number while retaining leading zeroes. The issue I was having was when converting \"001\" to an integer it would drop the zeroes and only return a \"1\", making the url invalid."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T01:01:21.273",
"Id": "16633",
"Score": "0",
"body": "The switch statement loads the URL into the \"array\" one character at a time, when it detects a number it moves to the next variable in the array and continues until it detects a non-number, then it moves to the next variable and repeats until the URL has been fully loaded. If the URL were delimited into parenthesis it would look like: (http://www.fakeurl.com/gallery)(001)(/picture)(001)(.jpg) This example shows how the url would split into 5 variables... seperating the numbers so that they may be manipulated. I am sure there is a cleaner way."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T01:59:42.407",
"Id": "8868",
"ParentId": "8867",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T00:02:37.090",
"Id": "8867",
"Score": "3",
"Tags": [
"javascript",
"html",
"android"
],
"Title": "Allowing simplified browsing of websites with a predictable URL structure"
}
|
8867
|
<p>I want to put some text next to its label (both of which are text blocks - which are faster than labels as I understand it). The best way I've found for doing this is a stack panel.</p>
<p>I have (repeated 3 times in a control) code like:</p>
<pre><code> <StackPanel Grid.Column="1" Grid.Row="2" Grid.ColumnSpan="2" Orientation="Horizontal">
<TextBlock Text="Start:" FontWeight="DemiBold" VerticalAlignment="Bottom" HorizontalAlignment="Left"/>
<TextBlock Text="12:00pm" VerticalAlignment="Bottom" HorizontalAlignment="Left" Margin="5,0"/>
</StackPanel>
</code></pre>
<p>Is this the cleanest way to do this, or is there a better control? I was kind of thinking about making a wrapper control around the stack panel, but then I would just end up with:</p>
<pre><code> <LabeledTextBlock Grid.Column="1" Grid.Row="2" Grid.ColumnSpan="2">
<LabledTextBlock.Label>
<TextBlock Text="Start:" FontWeight="DemiBold" VerticalAlignment="Bottom" HorizontalAlignment="Left"/>
</LabledTextBlock.Label>
<TextBlock Text="12:00pm" VerticalAlignment="Bottom" HorizontalAlignment="Left" Margin="5,0"/>
</LabeledTextBlock >
</code></pre>
<p>I guess I could refine it more:</p>
<pre><code><LabeledContent Grid.Column="1" Grid.Row="2" Grid.ColumnSpan="2" Label="Start" Content="12:00pm"/>
</code></pre>
<p>Simplicity at the cost of flexibility. Perhaps instead I should be doing it as a style?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-07T21:16:45.563",
"Id": "391906",
"Score": "0",
"body": "Should this be a stackoverflow question?"
}
] |
[
{
"body": "<p>My opinion is that for simple tasks like in your situation, you should not complicate your XAML. Wrapping a StackPanel around two TextBlock-elements is still pretty clean.</p>\n\n<p>Extracting the code and wrapping it in your own control where you would set the Label and Content surely is an option. But if this only to be done once, I think you're overdoing it. Only when you have to place the same code there a lot of times, your XAML will be cleaner using your own control.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T12:34:23.220",
"Id": "21617",
"ParentId": "8869",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "21617",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T01:59:55.493",
"Id": "8869",
"Score": "4",
"Tags": [
"wpf",
"xaml",
"gui"
],
"Title": "Putting items next to each other"
}
|
8869
|
<p>I just posted this code in SO and one person said my code sucked, and that I should post it here. So here it is (with fix I asked for included, so you don't have to worry about that).</p>
<p>The main concerns that I have with it myself is how I iterate through a sequence of objects that the object itself is in. Apparently <code>id</code> is bad, because it's like <code>id()</code>. Someone also mentioned that I shouldn't make members of a collection overly aware of their own collection.</p>
<pre><code> import random
class Car:
def __init__ (self, company, doors, id):
self.company = company
self.doors = doors
self.id = id
def printDoors(self, id):
print 'Car ' + `self.id` + ' has ' + `self.doors` + ' doors.'
def findSameDoors(self, id):
for i in self.company.cars:
if self.id != i.id and self.doors == i.doors:
print 'Car ' + `i.id` + ' does too!'
class Company:
def __init__ (self, types):
self.types = types
self.cars = []
def typesToNum(self):
result = []
for i in self.types:
if i == 'sedan':
result.append(4)
elif i == 'convertible':
result.append(2)
else:
result.append(0)
return result
porsche = Company(['sedan', 'convertible'])
honda = Company(['sedan', 'convertible', 'motorcycle'])
for i in range(10):
porsche.cars.append(Car(porsche, random.choice(porsche.typesToNum()), i))
for i in range(10):
honda.cars.append(Car(honda, random.choice(honda.typesToNum()), i))
porsche.cars[0].printDoors(0)
porsche.cars[0].findSameDoors(0)
</code></pre>
<p>Thanks for any pointers.</p>
|
[] |
[
{
"body": "<p>It is, as you say, slightly odd that a method in <code>Car</code> iterates over the container that <code>Car</code> is in. It really ought to be in <code>Company</code>, and take an argument for how many doors to match:</p>\n\n<pre><code>class Company:\n ...\n def searchByDoors(self, doors):\n ''' Get an iterator of all the cars in self that have the \n specified number of doors\n '''\n\n for car in self.cars:\n if car.doors == doors:\n yield car\n</code></pre>\n\n<p>This also brings up another point: you probably want to avoid printing from inside your class (except for debugging). Even if whatever you're writing <em>now</em> wants it printed, you should write your classes so they can be used in any program . So, a search function should give the matches back whichever part of your program called it, and it can print them if it wants to. Similarly, <code>Car.printDoors</code> can go - your program can get that information and print it. If there is a canonical way that you want represent a <code>Car</code> for human consumption, define it this way:</p>\n\n<pre><code> class Car:\n ...\n def __str__(self):\n return \"A {} {} with {} doors\".format(self.company, self.type, self.doors)\n</code></pre>\n\n<p>And your program can just <code>print(a_car)</code> to print something like <code>A porche sedan with 4 doors</code>. </p>\n\n<p>Note that, notwithstanding what the person on SO said about not making objects aware of their containers, it probably <em>does</em> make sense for a <code>Car</code> to know which <code>Company</code> made it.</p>\n\n<p>There are two issues with using <code>id</code> as an attribute name:</p>\n\n<ul>\n<li>The local variable in the constructor shadows the built-in <code>id()</code> function,</li>\n<li>More importantly, <code>car.id</code> is different to <code>id(car)</code>, even though they're named similarly and have similar purposes.</li>\n</ul>\n\n<p>Consider whether <code>id(car)</code> is good enough for what you would use <code>car.id</code> for - it identifies a unique python object, and is called for you when you do things like <code>a is b</code>. If <code>id</code> needs to reflect something external to your program, consider renaming it. <code>car_id</code> might work, but if it represents something concrete in your problem domain (eg, an official registration number), naming it after that is even better.</p>\n\n<p>There is also one issue with the way you're generating <code>id</code>s, that using Python's <code>id()</code> avoids: your <code>id</code>s are only unique within a company (and even that isn't guaranteed), but you could reasonably expect it to be unique across <em>all</em> cars. So, overall, I would drop <code>id</code> entirely.</p>\n\n<p><code>typesToNum</code> doesn't belong in <code>Company</code>, and this is really begging for a dictionary rather than a method. I'd make it a module-level private constant:</p>\n\n<pre><code> # Mapping of car type (eg, sedan) to number of doors \n _DOORS_PER_TYPE = {'sedan': 4, 'convertible': 2, 'motorcycle': 0}\n</code></pre>\n\n<p>A car should really know what type of car it is, and with this mapping it would make more sense to take this at construction than the number of doors:</p>\n\n<pre><code> class Car:\n def __init__(self, company, type):\n assert type in company.types\n self.type = type\n\n @property\n def doors(self):\n return _DOORS_PER_TYPE[self.type]\n</code></pre>\n\n<p>The <code>assert</code> makes sure that the type of car is one that that company does make. It is optional, its just a sanity check in case something impossible happens. Its a good idea, because that is more common than it sounds. Likewise, you can do:</p>\n\n<pre><code> class Company:\n def __init__(self, types):\n</code></pre>\n\n<p>The constraint that a convertible always has 2 doors, and a sedan always has 4 is a little odd. If it might make sense in your program to have a 2 or 4 door sedan, but not, say, a single-door sedan, you could do this:</p>\n\n<pre><code> _DOORS_PER_TYPE = {'sedan': (2, 4)}\n\n class Car:\n def __init__(self, company, type, doors):\n assert type in company.types\n assert doors in _DOORS_PER_TYPE[type]\n\n self.company = company\n self.type = type\n self.doors = doors\n</code></pre>\n\n<p>This also makes <code>doors</code> an attribute rather than a property since its no longer linked 1-to-1 with <code>type</code>, but the rest of your program doesn't need to care about that difference. </p>\n\n<p>You can also change the valid car types and number of doors to vary between each company, but only if that makes sense for your model. If the number of doors is <em>always</em> 1-to-1 with the type, and that is <em>always</em> going to be independent of the company who built it, then it is better to have your code say so. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T23:39:50.967",
"Id": "13928",
"Score": "0",
"body": "A lot of this is over my head, but I'm piecing it together bit-by-bit. Whether certain methods should be in the parent or child class is a bit concern to me, so thanks for talking about that. I didn't even realize that Car should inherit from Company, since you always hear inheritance in terms of \"lizard is a reptile, reptile is an animal\", and a car isn't a company, and a group of cars don't make a company. This broadens my mind. Thanks for all of the help!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T05:03:13.537",
"Id": "13939",
"Score": "0",
"body": "@KenOh `Car` shouldn't inherit from `Company`, and I didn't suggest it should. If it did, the code would look like `class Car(Company)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-13T15:10:23.790",
"Id": "14005",
"Score": "0",
"body": "@KenOh Why assert instead of throwing an exception?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-13T22:24:42.377",
"Id": "14024",
"Score": "0",
"body": "@Ominus `assert` does raise an exception (`AssertionError`) if its condition is false. But there's no particular reason you couldn't raise a more specific exception if you wanted to."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T11:41:39.603",
"Id": "8882",
"ParentId": "8871",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "8882",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T04:53:28.637",
"Id": "8871",
"Score": "4",
"Tags": [
"python"
],
"Title": "Better way to refer to common elements in a sequence of objects?"
}
|
8871
|
<p>How could this be improved style-wise (if this isn't good enough) when the need is just to have a console replacement for <code>PrintWriter.format()</code> with backwards compatibility?</p>
<pre><code>class CCConsole // not to be confused with any Java class with a similar name
{
static PrintWriter pw = new PrintWriter(System.out, true);
static void redirect(LongRunningWorker longRunningWorker) {
pw = new PrintWriter(new LongRunningWorkerWriter(longRunningWorker));
}
}
class LongRunningWorkerWriter extends Writer
{
LongRunningWorker longRunningWorker;
LongRunningWorkerWriter(LongRunningWorker longRunningWorker) {
this.longRunningWorker = longRunningWorker;
}
@Override
public void close() throws IOException { }
@Override
public void flush() throws IOException { }
@Override
public void write(char[] chars, int offset, int length) throws IOException {
this.longRunningWorker.rePublish(new String(chars, offset, length));
}
}
abstract class LongRunningWorker extends SwingWorker<Boolean, String>
{
ColorSwingConsole colorSwingConsole;
LongRunningWorker(ColorSwingConsole colorSwingConsole) {
CCConsole.redirect(this);
this.colorSwingConsole = colorSwingConsole;
}
public Boolean doInBackground() // concrete for abstract
throws Exception {
go();
return true;
}
abstract void go() throws Exception;
void rePublish(String s) {
publish(s); // protected final = inherit or same package, cannot override
}
@Override
public void process(List<String> chunks) {
for (String s : chunks)
this.colorSwingConsole.append(s);
}
}
class RealWorker extends LongRunningWorker
{
RealWorker(ColorSwingConsole css) {
super(css);
// constructor stuff
}
void go() throws Exception {
CCConsole.pw.format("%s\n", "hello world");
// application stuff
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I did not understand what exactly are you asking here. Anyway, I will review your code:</p>\n\n<p>First, make the fields private and provide getters when you need to access them. These that are set in constructors and are never re-setted, you may make them final.</p>\n\n<p>Second, the CCConsole class may break if multiple threads access the redirect method at the same time.</p>\n\n<p>Third, the CCConsole.redirect(this); in the LongRunningWorker is bad. There is no way to create a LongRunningWorker for testing purposes that does not interferes with everything else. Further if anything interferes with the CCConsole (which acts as a singleton), there is no way to remove it. I sugesting to make the CCConsole a normal object (i.e. you instantiate it and no more static fields used). In the LongRunningWorker constructor add a CCConsole parameter. In the RealWorker class, get a CCConsole from somewhere (instantiate it, get from a parameter, from a factory method, whatever).</p>\n\n<p>Forth, avoid inheritance if you can using the strategy design pattern. Instead of making LongRunningWorker abstract with the abstract go method to be overriden in the RealWorker subclass, do this:</p>\n\n<ol>\n<li><p>Create an interface with the go method (lets say LongWork).</p></li>\n<li><p>Add a parameter to the LongRunningWorker class of the type LongWork, and save it in a field.</p></li>\n<li><p>In the doInBackground() method, instead of calling the local go() method, call the one from the LongWork object.</p></li>\n<li><p>LongRunningWorker is not abstract anymore, and you may remove the go() method.</p></li>\n<li><p>RealWorker does not extends LongRunningWorker anymore, but now implements the LongWork interface.</p></li>\n<li><p>You may remove the ColorSwingConsole parameter from the RealWorker class.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T18:16:20.843",
"Id": "8888",
"ParentId": "8873",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "8888",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T05:24:28.940",
"Id": "8873",
"Score": "1",
"Tags": [
"java",
"console",
"swing"
],
"Title": "Swing / Terminal console drop-in"
}
|
8873
|
<p>I would love some thoughts on this class that a wrote to extract user information from a logfile line.</p>
<p>I'm concerned about design patterns and the complexity of the code. The extract_user method feels especially awkward.</p>
<p>The class should be used as a public interface ala:</p>
<pre><code>parser = UserExtraction(s)
data = parser.extract_user()
</code></pre>
<p>Now, the majority of the strings that I pass in will simply not be authentication strings. How do I make this available as some sort of response code / error-message to an end user? Right now I'm using self.error_message = yadayada. But I have a feeling this is not very pythonic.</p>
<p>I didn't write any documentation yet since I'm very uncertain about the general design.</p>
<p>Every detail is appreciated, I'm trying to get better at this.</p>
<pre><code>import re
import logging
import os
import ConfigParser
class UserExtraction():
def __init__(self, string):
self.string = string
def _string_identification(self):
identifiers = {
'Successfully logged in' : 'login',
'logout' : 'logout',
}
regex_patterns = {
#TODO Store regexpatterns in outside file
"login" : "(\w{3}.+?\d{1,2} \d{2}:\d{2}:\d{2}).+?Authentication: \[([0-9a-zA-Z]{2}:[0-9a-zA-Z]{2}:[0-9a-zA-Z]{2}:[0-9a-zA-Z]{2}:[0-9a-zA-Z]{2}:[0-9a-zA-Z]{2}) ## (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\] (.+?) - Successfully .+? Role: (.+?),",
"logout" : "(\w{3}.+?\d{1,2} \d{2}:\d{2}:\d{2}).+?Authentication: Unable to ping (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}), going to logout user (.+)"
}
for key, value in identifiers.iteritems():
if key in self.string:
self.event_type = value
self.regex = regex_patterns[value]
return True
return False
def _matching(self):
self.matches = re.search(self.regex, self.string)
if self.matches:
return True
else:
return False
def _match_to_dict(self):
matches = self.matches
if self.event_type == 'login':
self.userinfo = {
'date_time' : matches.group(1),
'mac_addr' : matches.group(2),
'ip_addr' : matches.group(3),
'login' : matches.group(4),
'role' : matches.group(5)
}
elif self.event_type == 'logout':
self.userinfo = {
'date_time' : matches.group(1),
'ip_addr' : matches.group(2),
'login' : matches.group(3)
}
if self.userinfo:
return True
def extract_user(self):
if self._string_identification() == True:
if self._matching() == True:
if self._match_to_dict() == True:
return self.userinfo
else:
self.error_message = "COULD NOT PARSE USERINFO INTO DICTIONARY"
else:
self.error_message = "COULD NOT MATCH AUTHENTICATION STRING"
else:
self.error_message = "NOT AN AUTHENTICATION STRING"
if __name__ == "__main__":
ROOT_PATH = os.path.dirname(__file__)
config = ConfigParser.ConfigParser()
config.readfp(open(os.path.join(ROOT_PATH + '/settings.cfg')))
filename = config.get('defaults', 'file_location')
LOG_FILENAME = config.get('defaults', 'log_location')
LOG_FORMAT = '%(asctime)s - %(levelname)s %(message)s'
LOG_LEVEL = config.get('defaults', 'logging_level')
#TODO Change datefmt to be consistent with Apache logfile
logging.basicConfig(filename=LOG_FILENAME, format=LOG_FORMAT, datefmt='%m/%d %I:%M:%S', level=eval(LOG_LEVEL))
sample_strings = []
sample_strings.append('''Jan 2 15:32:49 cam-1/10.0.0.1 Authentication: [01:26:b2:F8:39:27 ## 172.16.197.23] Anonymous - Successfully logged in, Provider: anon, L2 MAC address: 00:26:B2:F2:39:87, Role: User, OS: Mac OS 10.6''')
for s in sample_strings:
Processor = UserExtraction(s)
Processor.extract_user()
if hasattr(Processor, 'userinfo'):
print(Processor.userinfo)
else:
print(Processor.error_message)
</code></pre>
|
[] |
[
{
"body": "<pre><code>class UserExtraction():\n</code></pre>\n\n<p>Either put <code>object</code> as an explicit base class, or don't have the parens.</p>\n\n<pre><code> def __init__(self, string):\n self.string = string\n\n def _string_identification(self):\n identifiers = {\n 'Successfully logged in' : 'login', \n 'logout' : 'logout',\n }\n regex_patterns = {\n\n #TODO Store regexpatterns in outside file\n \"login\" : \"(\\w{3}.+?\\d{1,2} \\d{2}:\\d{2}:\\d{2}).+?Authentication: \\[([0-9a-zA-Z]{2}:[0-9a-zA-Z]{2}:[0-9a-zA-Z]{2}:[0-9a-zA-Z]{2}:[0-9a-zA-Z]{2}:[0-9a-zA-Z]{2}) ## (\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\] (.+?) - Successfully .+? Role: (.+?),\",\n\n \"logout\" : \"(\\w{3}.+?\\d{1,2} \\d{2}:\\d{2}:\\d{2}).+?Authentication: Unable to ping (\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}), going to logout user (.+)\"\n\n }\n</code></pre>\n\n<p>I'd combine these two dictionaries into one list of tuples. I'd also probably make a global constant. Its not clear to me that putting it into an external file would help. </p>\n\n<pre><code> for key, value in identifiers.iteritems():\n</code></pre>\n\n<p>You don't gain much using iteritems here</p>\n\n<pre><code> if key in self.string:\n self.event_type = value\n self.regex = regex_patterns[value]\n</code></pre>\n\n<p>Don't pass data between your method by storing it on the object. That just obscures what is happening. Anything the caller needs to know should be returned not stored.</p>\n\n<pre><code> return True\n return False\n\n def _matching(self):\n self.matches = re.search(self.regex, self.string)\n if self.matches: \n return True\n else:\n return False\n</code></pre>\n\n<p>Just <code>return matches</code> or <code>return bool(matches)</code> rather then introducing an if block to convert a bool into a bool.</p>\n\n<pre><code> def _match_to_dict(self):\n matches = self.matches \n if self.event_type == 'login':\n self.userinfo = { \n 'date_time' : matches.group(1),\n 'mac_addr' : matches.group(2),\n 'ip_addr' : matches.group(3),\n 'login' : matches.group(4),\n 'role' : matches.group(5)\n } \n\n elif self.event_type == 'logout':\n self.userinfo = {\n 'date_time' : matches.group(1),\n 'ip_addr' : matches.group(2),\n 'login' : matches.group(3)\n }\n</code></pre>\n\n<p>Python's regular expressions have a named group feature. You can name the groups in the regular expression and thus simplify this code.</p>\n\n<pre><code> if self.userinfo:\n return True \n\n def extract_user(self):\n if self._string_identification() == True:\n if self._matching() == True:\n if self._match_to_dict() == True:\n</code></pre>\n\n<p>Don't use <code>== True</code>. Just <code>if self._string_identification():</code></p>\n\n<pre><code> return self.userinfo\n else:\n self.error_message = \"COULD NOT PARSE USERINFO INTO DICTIONARY\"\n else:\n self.error_message = \"COULD NOT MATCH AUTHENTICATION STRING\"\n else:\n self.error_message = \"NOT AN AUTHENTICATION STRING\"\n</code></pre>\n\n<p>This is python! Throw exceptions, don't store error messages.</p>\n\n<pre><code>if __name__ == \"__main__\":\n</code></pre>\n\n<p>It's usually best to put your main code in a main function that you call from here.</p>\n\n<pre><code> ROOT_PATH = os.path.dirname(__file__)\n\n config = ConfigParser.ConfigParser()\n config.readfp(open(os.path.join(ROOT_PATH + '/settings.cfg')))\n filename = config.get('defaults', 'file_location')\n\n LOG_FILENAME = config.get('defaults', 'log_location')\n LOG_FORMAT = '%(asctime)s - %(levelname)s %(message)s' \n LOG_LEVEL = config.get('defaults', 'logging_level')\n</code></pre>\n\n<p>Convention says that ALL_CAPS is for constants. These aren't constants</p>\n\n<pre><code> #TODO Change datefmt to be consistent with Apache logfile\n logging.basicConfig(filename=LOG_FILENAME, format=LOG_FORMAT, datefmt='%m/%d %I:%M:%S', level=eval(LOG_LEVEL))\n\n sample_strings = []\n\n sample_strings.append('''Jan 2 15:32:49 cam-1/10.0.0.1 Authentication: [01:26:b2:F8:39:27 ## 172.16.197.23] Anonymous - Successfully logged in, Provider: anon, L2 MAC address: 00:26:B2:F2:39:87, Role: User, OS: Mac OS 10.6''')\n</code></pre>\n\n<p>Considering combining these two lines into a string literal. </p>\n\n<pre><code> for s in sample_strings:\n</code></pre>\n\n<p>Avoid single letter variable names, they are hard to follow</p>\n\n<pre><code> Processor = UserExtraction(s)\n Processor.extract_user()\n</code></pre>\n\n<p>By convetion Processor should be the name of a class. Local variables should undercase_with_underscores. Furthermore, should this even be a class? It looks to me more like the job for a function.</p>\n\n<pre><code> if hasattr(Processor, 'userinfo'):\n print(Processor.userinfo)\n else:\n print(Processor.error_message)\n</code></pre>\n\n<p>Here's me reworking of your code:</p>\n\n<pre><code>import re\nimport logging\nimport os\nimport ConfigParser\n\nPATTERNS = [\n ('Successfully logged in', \"(?P<date_time>\\w{3}.+?\\d{1,2} \\d{2}:\\d{2}:\\d{2}).+?Authentication: \\[(?P<mac_addr>[0-9a-zA-Z]{2}:[0-9a-zA-Z]{2}:[0-9a-zA-Z]{2}:[0-9a-zA-Z]{2}:[0-9a-zA-Z]{2}:[0-9a-zA-Z]{2}) ## (?P<ip_addr>\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\] (?P<login>.+?) - Successfully .+? Role: (?P<role>.+?),\"),\n ('logout', \"(?P<date_time>\\w{3}.+?\\d{1,2} \\d{2}:\\d{2}:\\d{2}).+?Authentication: Unable to ping (?P<ip_addr>\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}), going to logout user (?P<login>.+)\")\n]\n\n\nclass UserExtractionError(Exception):\n pass\n\ndef extract_user(string):\n for key, regex in PATTERNS:\n if key in string:\n match = re.search(regex, string)\n if match is None:\n raise UserExtractionError(\"Could not match authentication string\")\n return match.groupdict()\n else:\n raise UserExtractionError(\"Not an authenication string\")\n\n\nif __name__ == \"__main__\":\n\n\n sample_strings = [\n '''Jan 2 15:32:49 cam-1/10.0.0.1 Authentication: [01:26:b2:F8:39:27 ## 172.16.197.23] Anonymous - Successfully logged in, Provider: anon, L2 MAC address: 00:26:B2:F2:39:87, Role: User, OS: Mac OS 10.6'''\n ]\n\n for sample in sample_strings:\n try:\n print extract_user(sample)\n except UserExtractionError as error:\n print error\n</code></pre>\n\n<p>Lightly tested. I didn't keep the logging code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-13T08:35:20.043",
"Id": "14001",
"Score": "0",
"body": "Thank you Winston. What a phenomenally detailed answer. I can't come to terms with the fact that somebody would take time out off their day to teach me how to code. Thanks for the effort, your explanations are tremendously helpful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T17:50:44.680",
"Id": "8887",
"ParentId": "8878",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "8887",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T07:52:52.263",
"Id": "8878",
"Score": "4",
"Tags": [
"python"
],
"Title": "Improve on python public interface data parser"
}
|
8878
|
<p>I want to return the title of a record if one exists or the word 'invalid' if not:</p>
<pre><code> @ID int ,
@Title nvarchar(50) output
...
if exists(select * from MyTable where ID=@ID)
select @Title = (select Title from MyTable where ID=@ID);
else select @Title = 'invalid';
</code></pre>
<p>but I don't have a good feeling with this query.</p>
|
[] |
[
{
"body": "<p>Just do:</p>\n\n<pre><code>// Default value\nselect @Title = \"invalid\";\n\n// If a record is found, replace \"invalid\" by the Title value\nselect @Title = Title from MyTable where ID=@ID;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T13:27:49.487",
"Id": "8884",
"ParentId": "8879",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "8884",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T07:53:44.787",
"Id": "8879",
"Score": "4",
"Tags": [
"sql",
"sql-server",
"t-sql"
],
"Title": "Returning the title of a record"
}
|
8879
|
<p>I'm looking to speed up this method. Ideally, I would like to cut the time in 1/2 or more. At the moment I have to draw the screen line-by-line as the font is 16 pixels high, but it is being drawn with an extra blank pixel on the bottom. If I could figure out how to set the line-height to 16 pixels I would imagine that drawing 1 string over 24 strings would help speed it up. Baring that what else can I do to increase the speed?</p>
<pre><code>- (void)drawRect:(NSRect)dirtyRect
{
NSGraphicsContext *nsGraphicsContext = [NSGraphicsContext currentContext];
CGContextRef context = (CGContextRef) [nsGraphicsContext graphicsPort];
CGContextSetShouldSmoothFonts(context, false);
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@""];
for (int y=24; y >= 0; y--) {
[[string mutableString] setString:@""];;
for (int x=0; x < 80; x++) {
AnsiScreenChar *c = [self.screen objectAtIndex:(y*80)+x];
[self.fontAttributes setValue:c.fgColor forKey:NSForegroundColorAttributeName];
[self.fontAttributes setValue:c.bgColor forKey:NSBackgroundColorAttributeName];
NSAttributedString *subString = [[NSAttributedString alloc] initWithString:c.data
attributes:self.fontAttributes];
[string appendAttributedString:subString];
}
[string drawAtPoint:NSMakePoint(0, self.frame.size.height - ((y+1)*16))];
}
}
</code></pre>
<p><strong>Profile</strong></p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Running Time Self Symbol Name
3276.0ms 9.5% 3276.0 -[AnsiView drawRect:]
1726.0ms 5.0% 1726.0 -[NSLayoutManager(NSTextViewSupport) showCGGlyphs:positions:count:font:matrix:attributes:inContext:]
1540.0ms 4.4% 1540.0 -[__NSCFDictionary setObject:forKey:]
1467.0ms 4.2% 1467.0 -[NSObject dealloc]
1118.0ms 3.2% 1118.0 -[NSView _drawRect:clip:]
1108.0ms 3.2% 1108.0 -[NSConcreteHashTable getItem:]
1106.0ms 3.2% 1106.0 -[NSLayoutManager(NSPrivate) _drawBackgroundForGlyphRange:atPoint:parameters:]
901.0ms 2.6% 901.0 -[NSLayoutManager(NSPrivate) _insertionPointHelperForGlyphAtIndex:]
779.0ms 2.2% 779.0 -[NSLayoutManager(NSPrivate) _drawGlyphsForGlyphRange:atPoint:]
704.0ms 2.0% 704.0 -[__NSCFString replaceCharactersInRange:withString:]
693.0ms 2.0% 693.0 -[NSATSGlyphStorage createCTTypesetter]
619.0ms 1.8% 619.0 -[NSAttributeDictionary objectForKey:]
599.0ms 1.7% 599.0 -[NSLayoutManager(NSPrivate) _rectArrayForRange:withinSelectionRange:rangeIsCharRange:singleRectOnly:fullLineRectsOnly:inTextContainer:rectCount:rangeWithinContainer:glyphsDrawOutsideLines:]
558.0ms 1.6% 558.0 -[NSLayoutManager locationForGlyphAtIndex:]
537.0ms 1.5% 537.0 +[NSObject allocWithZone:]
</code></pre>
</blockquote>
|
[] |
[
{
"body": "<p>You want to avoid as much work inside <code>drawRect:</code> as possible. Instead of recalculating the attributed string for each line here do it whenever <code>self.screen</code> changes. That way it's done once instead of every time the some portion of the view is redrawn (which will happen a lot).</p>\n\n<p>Maybe keep a <code>self.lines</code> array with the attributed string for each line in it. Or maybe it's a dictionary with the key being the line number and you just keep adding lines and <code>drawRect</code> just draws the last <code>displayHeight</code> lines.</p>\n\n<p>Basically do everything you can to remove unnecessary work from <code>drawRect</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T17:32:03.627",
"Id": "8886",
"ParentId": "8880",
"Score": "5"
}
},
{
"body": "<p>The code has been changed according to the review and currently looks as follows:</p>\n\n<pre><code>- (void)drawRect:(NSRect)dirtyRect\n{\n NSGraphicsContext *nsGraphicsContext = [NSGraphicsContext currentContext];\n CGContextRef context = (CGContextRef) [nsGraphicsContext graphicsPort];\n CGContextSetShouldSmoothFonts(context, false); \n\n NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@\"\"];\n for (int y=24; y >= 0; y--) {\n [[string mutableString] setString:@\"\"];;\n for (int x=0; x < 80; x++) {\n AnsiScreenChar *c = [self.screen objectAtIndex:(y*80)+x];\n [string appendAttributedString:c.data];\n }\n [string drawAtPoint:NSMakePoint(0, self.frame.size.height - ((y+1)*16))];\n }\n}\n</code></pre>\n\n<p>As visible, the inner for-loop has been significantly simplified by removing the fontAttributes changes. Also the superfluous substring-creation has been removed. </p>\n\n<p>This leads to a significantly improved profile, as seen below</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Running Time Self Symbol Name\n590.0ms 6.5% 590.0 -[AnsiView drawRect:]\n561.0ms 6.2% 561.0 -[NSLayoutManager(NSPrivate) _insertionPointHelperForGlyphAtIndex:]\n417.0ms 4.6% 417.0 -[NSObject retain]\n366.0ms 4.0% 366.0 -[NSLayoutManager(NSPrivate) _drawBackgroundForGlyphRange:atPoint:parameters:]\n320.0ms 3.5% 0.0 -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:]\n318.0ms 3.5% 318.0 -[NSLayoutManager(NSTextViewSupport) showCGGlyphs:positions:count:font:matrix:attributes:inContext:]\n240.0ms 2.6% 240.0 -[NSLayoutManager glyphRangeForCharacterRange:actualCharacterRange:]\n236.0ms 2.6% 236.0 -[NSLayoutManager locationForGlyphAtIndex:]\n230.0ms 2.5% 230.0 -[__NSCFString replaceCharactersInRange:withString:]\n212.0ms 2.3% 0.0 -[NSView _drawRect:clip:]\n189.0ms 2.0% 189.0 -[NSATSGlyphStorage createCTTypesetter]\n188.0ms 2.0% 188.0 -[NSLayoutManager(NSPrivate) _rectArrayForRange:withinSelectionRange:rangeIsCharRange:singleRectOnly:fullLineRectsOnly:inTextContainer:rectCount:rangeWithinContainer:glyphsDrawOutsideLines:]\n183.0ms 2.0% 183.0 -[NSBigMutableString getCharacters:range:]\n169.0ms 1.8% 0.0 -[NSFrameView drawWindowBackgroundRect:]\n144.0ms 1.5% 144.0 -[NSConcreteGlyphGenerator generateGlyphsForGlyphStorage:desiredNumberOfCharacters:glyphIndex:characterIndex:]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-12T19:34:12.777",
"Id": "80375",
"ParentId": "8880",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "8886",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T08:09:57.640",
"Id": "8880",
"Score": "3",
"Tags": [
"performance",
"strings",
"objective-c",
"graphics"
],
"Title": "Optimizing text drawing on screen"
}
|
8880
|
<p>I'm a rather novice programmer who recently came up with a solution that works for my project, however I'm always looking for ways to improve my code. </p>
<p>So essentially, I have a settings form that pop's up and I was looking for a way to put it next to my main form but not covering it nor appearing partially off of the screen the main form is on. I came up with this but it's not very <em>dynamic</em> because it only checks 4 different locations and if none of them work it uses the default, which is center screen.</p>
<p>Here is what I have:</p>
<pre><code>private void Place_Form(Form formToPlaceNextTo, Form formToPlace)
{
Point alignRightTop = new Point(m_parent.Location.X + m_parent.Width, m_parent.Location.Y);
Point alignRightBottom = new Point(m_parent.Location.X + m_parent.Width, (m_parent.Location.Y + m_parent.Height) - this.Height);
Point alignLeftTop = new Point(m_parent.Location.X - this.Width, m_parent.Location.Y);
Point alignLeftBottom = new Point(m_parent.Location.X - this.Width, (m_parent.Location.Y + m_parent.Height) - this.Height);
if (Screen.FromControl(formToPlace).WorkingArea.Contains(new Rectangle(alignRightTop.X, alignRightTop.Y, this.Width, this.Height)))
{
this.Location = alignRightTop;
return;
}
if (Screen.FromControl(formToPlace).WorkingArea.Contains(new Rectangle(alignRightBottom.X, alignRightBottom.Y, this.Width, this.Height)))
{
this.Location = alignRightBottom;
return;
}
if (Screen.FromControl(formToPlace).WorkingArea.Contains(new Rectangle(alignLeftTop.X, alignLeftTop.Y, this.Width, this.Height)))
{
this.Location = alignLeftTop;
return;
}
if (Screen.FromControl(formToPlace).WorkingArea.Contains(new Rectangle(alignLeftBottom.X, alignLeftBottom.Y, this.Width, this.Height)))
{
this.Location = alignLeftBottom;
return;
}
}
</code></pre>
<p>Any suggestions or <em>preferred</em> coding techniques?</p>
<p>Addendum#1: I agree that it's easier and probably more <em>preferred</em> to let the framework decide where to put forms, however this settings form changes the visual look of the main form and the default position of the settings form is almost directly on top of the main form. This poses a problem in regards to user friendliness (in my eyes).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T22:40:06.723",
"Id": "13927",
"Score": "0",
"body": "@Leonid I tried to use enums but since the location of the m_parent form is *dynamic* it throws and error."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T03:11:12.753",
"Id": "13935",
"Score": "0",
"body": "@Leonid The priority was to a)keep the settings form on the monitor they are running the main form on, b)don't split the settings form over multiple monitors, c)don't cover the main form and d)don't have part of the form off screen(the abyss).\nThe 4 choices I created seemed to position the setup form so that those conditions would be met, the idea wasn't to give the program 16-32+ options on where to put the form but essentially the minimum amount of different options to get the job done."
}
] |
[
{
"body": "<p>My bad, I think see now what you wanted. I just did not feel like reading your logic fully (too many details). After I did read it, I saw that you got the details right. All you needed was to stick your points into a list or enumerate over them, as in this example. This way, if you feel like adding more options - you can. Let me know if this works, so that I can delete the other answer.</p>\n\n<pre><code>private void Place_Form(Form formToPlaceNextTo, Form formToPlace)\n{\n foreach (Point pointToTry in EnumerateFormPlacement(formToPlaceNextTo, formToPlace))\n {\n var rectToTry = new Rectangle(pointToTry.X, pointToTry.Y, formToPlace.Width, formtoPlace.Height);\n if (Screen.FromControl(formToPlace).WorkingArea.Contains(rectToTry))\n {\n formToPlace.Location = pointToTry;\n return;\n }\n }\n\n // Else no match, hence default location.\n}\n\nprivate IEnumerable<Point> EnumerateFormPlacement(Form formToPlaceNextTo, Form formToPlace)\n{\n Point alignRightTop = new Point(\n formToPlaceNextTo.Location.X + formToPlaceNextTo.Width,\n formToPlaceNextTo.Location.Y);\n yield return alignRightTop;\n\n Point alignRightBottom = new Point(\n formToPlaceNextTo.Location.X + formToPlaceNextTo.Width, \n (formToPlaceNextTo.Location.Y + formToPlaceNextTo.Height) - formToPlace.Height);\n yield return alignRightBottom;\n\n Point alignLeftTop = new Point(\n formToPlaceNextTo.Location.X - formToPlace.Width,\n formToPlaceNextTo.Location.Y);\n yield return alignLeftTop;\n\n Point alignLeftBottom = new Point(\n formToPlaceNextTo.Location.X - formToPlace.Width,\n (formToPlaceNextTo.Location.Y + formToPlaceNextTo.Height) - formToPlace.Height);\n yield return alignLeftBottom;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-15T04:36:47.043",
"Id": "14090",
"Score": "0",
"body": "This looks fantastic as well as a great implementation of IEnumerable<> which I haven't worked with (successfully) yet. I'll try this soon."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-15T04:54:39.213",
"Id": "14091",
"Score": "0",
"body": "Got to love C#. Only Clojure can be more fun."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-14T00:32:03.690",
"Id": "8950",
"ParentId": "8881",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "8950",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T10:28:27.600",
"Id": "8881",
"Score": "4",
"Tags": [
"c#",
"winforms"
],
"Title": "Is there a more elegant way of arranging my forms?"
}
|
8881
|
<p>Interested to hear any suggestions on object orientation and style for this simple spreadsheet implementation. The spreadsheet contains cells with equations in reverse polish notation and has a solver method to either determine the cell values or throw an exception if a circular reference exists.</p>
<pre><code>/**
* This class encapsulates a spreadsheet which is a collection of cells together
* with methods for solving the spreadsheet.
*/
public class SpreadSheet {
private int nRows; // number of rows in the spreadsheet
private int nCols; // number of columns, must be less than or equal to 26
private ArrayList<Cell> cells; // the cells within the spreadsheet in row by row
// order
/**
* Construct a spreadsheet from a given expression array.
*
* @param nRows
* number of rows in spreadsheet.
* @param nCols
* number of columns in spreadsheet.
* @param exprArray
* an array of Strings containing the expressions for the cells
* of the spreadsheet specified in row by row order.
*/
public SpreadSheet(int nRows, int nCols, String... exprArray) {
this.nRows = nRows;
this.nCols = nCols;
cells = new ArrayList<Cell>(exprArray.length);
for (String expressionString : exprArray) {
cells.add(new Cell(this, expressionString));
}
}
/**
* Solve a spreadsheet and return the solution of each cell.
*
* @return array of doubles containing the solution to each cell in row by
* row order.
* @throws CircularReferenceException if spreadsheet contains a circular reference.
*/
public Double[] dump() throws CircularReferenceException {
int validCells = 0; // cells with valid values
int validCellsPreviousIteration = 0; // cells with valid values in the
// previous iteration
try {
while (validCells < cells.size()) {
evaluate(); // evaluate each cell in the spreadsheet
validCells = countValidCells();
if (validCells == validCellsPreviousIteration) {
throw new CircularReferenceException(); // throw exception
// if number of
// cells that have
// valid values
// has not increased
} else {
validCellsPreviousIteration = validCells;
}
}
} catch (InvalidOperatorException e) {
System.out.println(e);
}
try {
return getValues();
} catch (InvalidValueException e) {
e.printStackTrace();
return null;
}
}
/**
* Retrieve cell from particular row and column of spreadsheet. Indexing is
* 0 based.
*
* @param row
* row of cell.
* @param column
* column of cell.
* @return cell at location (row,column).
*/
public Cell getCell(int row, int column) {
return cells.get(row * nCols + column);
}
/**
* Construct an array containing the value of each cell in the spreadsheet
* in row by row order.
*
* @return array of doubles containing values.
* @throws InvalidValueException
*/
private Double[] getValues() throws InvalidValueException {
Double[] values = new Double[cells.size()];
int i = 0;
for (Cell cell : cells) {
values[i++] = cell.getValue();
}
return values;
}
/**
* Count number of cells within the spreadsheet with valid values.
*
* @return number of cells with valid values.
*/
private int countValidCells() {
int validCells = 0;
for (Cell cell : cells) {
if (cell.isValueValid()) {
validCells++;
}
}
return validCells;
}
/**
* Evaluate the expression of every cell within the spreadsheet.
*
* @throws InvalidOperatorException
*/
private void evaluate() throws InvalidOperatorException {
for (Cell cell : cells) {
cell.evaluate();
}
}
/**
* Exception for when spreadsheet contains a circular reference.
*/
public class CircularReferenceException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
}
</code></pre>
<p>Here is the <code>Cell</code> class:</p>
<pre><code>/**
* This class encapsulates a single cell within a spreadsheet.
*/
public class Cell {
private SpreadSheet spreadsheet; // spreadsheet to which cell belongs,
// necessary for resolving cell
// references
private String expression; // expression within cell in reverse Polish
// notation
private double value; // numerical value of evaluating expression
private boolean valueValid; // whether a valid value has been found so
// far. This will change from false to true
// once all cell references have been
// resolved, provided that there are no
// circular references
/**
* Constructor for a cell belonging to a particular spreadsheet.
*
* @param spreadsheet
* SpreadSheet to which Cell belongs.
* @param expression
* expression within cell.
*/
public Cell(SpreadSheet spreadsheet, String expression) {
this.spreadsheet = spreadsheet;
this.expression = expression;
}
/**
* Evaluates expression within a cell. Expression must be in reverse Polish
* notation.
*
* @throws InvalidOperatorException
* if cell expression contains an invalid operator.
*/
public void evaluate() throws InvalidOperatorException {
if (!valueValid) { // prevent reevaluation of cells that have valid
// values
try {
// create stack containing terms in expression
Deque<String> expressionStack = new ArrayDeque<String>(
Arrays.asList(expression.split("\\s")));
value = evaluateRpn(expressionStack);
valueValid = true;
} catch (UnresolvedReferenceException e) {
// no action is necessary if a reference is unresolved, since it
// may be resolved at a later iteration during the solution of
// the spreadsheet
}
}
}
/**
* Get value of a cell. This is the numerical value resulting from
* evaluating the cell's expression.
*
* @return numerical value resulting from evaluating cell's expression.
* @throws InvalidValueException
* if a valid value is not currently available.
*/
public double getValue() throws InvalidValueException {
if (isValueValid()) {
return value;
} else {
throw new InvalidValueException();
}
}
/**
* Check if a valid numerical value has been evaluated for the cell. This
* will be true when evaluate() is called on the cell and all of the cell
* references in the cell's expression can be resolved.
*
* @return whether cell value is valid.
*/
public boolean isValueValid() {
return valueValid;
}
/**
* Evaluate an expression contained within an ExpressionStack.
*
* @param expressionStack
* an expression represented as a stack of individual terms.
* @return evaluation of expression
* @throws InvalidOperatorException
* @throws UnresolvedReferenceException
*/
private double evaluateRpn(Deque<String> expressionStack)
throws InvalidOperatorException, UnresolvedReferenceException {
String term = expressionStack.removeLast();
if (isCellReference(term)) {
// if last term in expression is a cell reference then resolve it
return resolveCellReference(term);
} else {
double x, y;
try {
// if last term in expression is double then return it
x = Double.parseDouble(term);
} catch (NumberFormatException e) {
// otherwise last term is an operator, evaluate operands and
// apply operator
y = evaluateRpn(expressionStack);
x = evaluateRpn(expressionStack);
x = applyOperator(x, y, term);
}
return x;
}
}
/**
* Apply operator to operands x and y.
*
* @param x
* first operand.
* @param y
* second operand.
* @param operator
* @return result of operation
* @throws InvalidOperatorException
*/
private double applyOperator(double x, double y, String operator)
throws InvalidOperatorException {
if (operator.equals("+"))
return x + y;
else if (operator.equals("-"))
return x - y;
else if (operator.equals("*"))
return x *= y;
else if (operator.equals("/"))
return x / y;
else
throw new InvalidOperatorException(operator);
}
/**
* Resolve a reference to another cell within the spreadsheet. If the other
* cell has a valid value, then the value will be returned, otherwise an
* UnresolvedReferenceException will be thrown.
*
* @param reference
* reference to another cell in the spreadsheet.
* @return value of referenced cell.
* @throws UnresolvedReferenceException
*/
private double resolveCellReference(String reference)
throws UnresolvedReferenceException {
int col = reference.charAt(0) - 'A';
int row = Integer.parseInt(reference.substring(1)) - 1;
Cell referencedCell = spreadsheet.getCell(row, col);
try {
return referencedCell.getValue();
} catch (InvalidValueException e) {
throw new UnresolvedReferenceException();
}
}
/**
* Determine whether a term in an expression is a reference to another cell.
*
* @param term
* @return whether term is a cell reference.
*/
private boolean isCellReference(String term) {
return Character.isLetter(term.charAt(0));
}
/**
* Thrown to indicate than an invalid operator is specified in cell
* expression.
*/
public class InvalidOperatorException extends Exception {
private static final long serialVersionUID = 1L;
private String operator;
public InvalidOperatorException(String operator) {
this.operator = operator;
}
public String toString() {
return "Invalid operator " + operator;
}
}
/**
* Thrown to indicate that a cell reference cannot be resolved. This occurs
* if a valid value is not currently available for the referenced cell.
*/
public class UnresolvedReferenceException extends Exception {
private static final long serialVersionUID = 1L;
}
/**
* Thrown to indicate that getValue() was called on a cell with a value that
* is currently invalid.
*/
public class InvalidValueException extends Exception {
private static final long serialVersionUID = 1L;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I did not go in great detail, but it looks pretty good.</p>\n\n<p>Just be careful with method names: <code>dump()</code> and <code>evaluateRpn()</code>. Usually abbreviations are avoided in Java.</p>\n\n<p>I don't know if you should have made cells a two-dimensional <code>List</code> of <code>List</code> instead. It's a bit cleaner, but it's annoying when you want to loop over all cells. I guess you thought about it before deciding on a single array. Another option would be to define some <code>Grid</code> class that stores a <code>List</code> of <code>List</code> and that implements <code>Iterable</code>.</p>\n\n<p>I would probably try to get the spreadsheet reference out of <code>Cell</code>. The evaluate methods would then need to be moved to <code>SpreadSheet</code>. I'm not sure that I really prefer that to the current implementation.</p>\n\n<p>Another suggestion would be to use an <code>Enum</code> for the 4 operations. Yet again, I'm not sure it's a good idea, but you could look into it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T20:07:56.147",
"Id": "13916",
"Score": "0",
"body": "Thanks! Actually dump() was the name required for external reasons, I don't particularly like it myself. Regarding evaluateRpn() do you think evaluateReversePolishNotation() would be better?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T20:19:55.117",
"Id": "13919",
"Score": "0",
"body": "Yes, I would use the full name. With IDE autocompletion you don't have to type the full names anyway. If you keep evaluateRpn, you'd better make it evaluateRPN."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T20:26:24.143",
"Id": "13922",
"Score": "0",
"body": "Yes, I did think quite a bit about that. You're right, it would be more elegant to use a grid, or define a row class. I ended up going with a 1D list since this was the format that the input (the expressions) and the output (the values) are in, so it seemed more natural."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-06T10:53:35.017",
"Id": "18481",
"Score": "0",
"body": "@toto2: I would use the `evaluateReversePolishNotation()` but I think `evaluateRpn` is better than `evaluateRPN`. See *Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions*: \"While uppercase may be more common, a strong argument can made in favor of capitalizing only the first letter: even if multiple acronyms occur back-to-back, you can still tell where one word starts and the next word ends. Which class name would you rather see, `HTTPURL` or `HttpUrl`?\""
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T20:05:18.083",
"Id": "8891",
"ParentId": "8889",
"Score": "3"
}
},
{
"body": "<p>Usually only a few cells of a spreadsheed are actually filled, so I'd suggest to use e.g. a <code>Map<Point, Cell></code> to save memeory and to allow to use bigger spreadsheets. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-06T10:36:47.737",
"Id": "11526",
"ParentId": "8889",
"Score": "3"
}
},
{
"body": "<ol>\n<li>\n\n<pre><code>private String expression; // expression within cell in reverse Polish\n // notation\nprivate double value; // numerical value of evaluating expression\n</code></pre>\n\n<p>I'd rename it to <code>rpnExpression</code> and <code>evaluatedValue</code> which will make the comments unnecessary. (Check <em>Clean Code</em> by Robert C. Martin, page 53-54 also.)</p></li>\n<li>\n\n<pre><code>public Cell(SpreadSheet spreadsheet, String expression) {\n this.spreadsheet = spreadsheet;\n this.expression = expression;\n}\n</code></pre>\n\n<p>I'd check <code>null</code>s here. <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Preconditions.html\" rel=\"nofollow\">checkNotNull from Guava</a> is a gread choice for that.\n(<em>Effective Java, 2nd edition, Item 38: Check parameters for validity</em>)</p></li>\n<li>\n\n<pre><code>if (!valueValid) { // prevent reevaluation of cells that have valid\n // values\n</code></pre>\n\n<p>This condition is a good candidate for guard clause.\nReferences: <em>Replace Nested Conditional with Guard Clauses</em> in <em>Refactoring: Improving the Design of Existing Code</em>; <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">Flattening Arrow Code</a></p></li>\n<li>\n\n<pre><code>throw new InvalidValueException();\n</code></pre>\n\n<p>I'd put into the message the invalid expression.</p></li>\n<li>\n\n<pre><code> * @throws InvalidOperatorException\n * @throws UnresolvedReferenceException\n</code></pre>\n\n<p>Are these lines necessary?</p></li>\n<li>\n\n<pre><code>if (isCellReference(term)) {\n // if last term in expression is a cell reference then resolve it\n return resolveCellReference(term);\n} else {\n double x, y;\n try {\n // if last term in expression is double then return it\n x = Double.parseDouble(term);\n } catch (NumberFormatException e) {\n // otherwise last term is an operator, evaluate operands and\n // apply operator\n y = evaluateRpn(expressionStack);\n x = evaluateRpn(expressionStack);\n x = applyOperator(x, y, term);\n }\n return x;\n}\n</code></pre>\n\n<p>The <code>isCellReference</code> is a guard clause, so the <code>else</code> keyword and its parentheses are unnecessary:</p>\n\n<pre><code>if (isCellReference(term)) {\n // if last term in expression is a cell reference then resolve it\n return resolveCellReference(term);\n}\ndouble x, y;\ntry {\n // if last term in expression is double then return it\n x = Double.parseDouble(term);\n} catch (NumberFormatException e) {\n // otherwise last term is an operator, evaluate operands and\n // apply operator\n y = evaluateRpn(expressionStack);\n x = evaluateRpn(expressionStack);\n x = applyOperator(x, y, term);\n}\nreturn x;\n</code></pre></li>\n<li><p>Furthermore, I'd minimize the scope of the local variables:</p>\n\n<pre><code>try {\n return Double.parseDouble(term);\n} catch (NumberFormatException e) {\n // otherwise last term is an operator, evaluate operands and\n // apply operator\n double y = evaluateRpn(expressionStack);\n double x = evaluateRpn(expressionStack);\n return applyOperator(x, y, term);\n}\nreturn x;\n</code></pre>\n\n<p>(<em>Effective Java, 2nd edition, Item 45: Minimize the scope of local variables</em>)</p></li>\n<li>\n\n<pre><code>if (operator.equals(\"+\"))\n</code></pre>\n\n<p>I prefer to invert the equals here:</p>\n\n<pre><code>if (\"+\".equals(operator))\n</code></pre>\n\n<p>It protects from <code>NullPointerException</code>s when the <code>operator</code> parameter is <code>null</code>.</p></li>\n<li>\n\n<pre><code>} catch (InvalidValueException e) {\n throw new UnresolvedReferenceException();\n}\n</code></pre>\n\n<p>Usually it's a good practice to pass the cause to constructor of the new exception:</p>\n\n<pre><code>throw new UnresolvedReferenceException(e);\n</code></pre></li>\n<li>\n\n<pre><code>public InvalidOperatorException(String operator) {\n this.operator = operator;\n}\n\npublic String toString() {\n return \"Invalid operator \" + operator;\n}\n</code></pre>\n\n<p>I'd pass the <code>\"Invalid operator \" + operator</code> string to the constructor of the superclass (as the message) and omit the <code>operator</code> field:</p>\n\n<pre><code>public InvalidOperatorException(String operator) {\n super(\"Invalid operator \" + operator);\n}\n</code></pre>\n\n<p>It's more common, and logging libraries will print the class name too, not just the string, which helps debugging.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-06T11:53:25.987",
"Id": "11527",
"ParentId": "8889",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "11527",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T19:29:41.903",
"Id": "8889",
"Score": "8",
"Tags": [
"java",
"object-oriented"
],
"Title": "Spreadsheet with reverse Polish equation solving"
}
|
8889
|
<p>This function is to return the size of the largest clique in a graph. When I run this code, I am running out of space at runtime. Also, it is insanely slow, so any speed tips would be appreciated.</p>
<pre><code>int cliqueSize(graph &g, std::vector<VertexID> nodes, std::vector<EdgeID> edges)
{
std::vector<std::vector<VertexID> > previous_cliques;
// start with all the singular nodes...
for (unsigned i = 0; i < nodes.size(); i++)
{
std::vector<VertexID> tmp;
tmp.push_back(nodes[i]);
previous_cliques.push_back(tmp);
}
for (unsigned clique_size = 1; clique_size < nodes.size(); clique_size++)
{
std::vector<std::vector<VertexID> > new_cliques;
// go through all the nodes to try to add to the clique.
for (unsigned i = 0; i < nodes.size(); i++)
{
// try to add node i to clique j.
for (unsigned j = 0; j < previous_cliques.size(); j++)
{
// make sure node j is not already in the clique.
if (std::find(previous_cliques[j].begin(), previous_cliques[j].end(), nodes[i]) == previous_cliques[j].end())
{
std::vector<VertexID> potential_clique(previous_cliques[j]);
potential_clique.push_back(nodes[i]);
// isClique has no issues, just checks if the given graph is a clique...
if (isClique(g, potential_clique, edges))
{
new_cliques.push_back(potential_clique);
}
}
}
}
// no new cliques?
if (new_cliques.size() == 0) { return clique_size; }
else { previous_cliques = new_cliques; }
}
return nodes.size();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T21:58:50.063",
"Id": "20921",
"Score": "0",
"body": "IDK if you still care about this question, but if you do: you do know that max-clique is NP problem? So it is \"normal\" that you have problems solving it. Ofc you can improve perf, but fundamentally there is nothing you can do."
}
] |
[
{
"body": "<ul>\n<li>First of all, start passing things by const reference more. You're passing both <code>nodes</code> and <code>edges</code> by value, which will make a copy.</li>\n<li>Instead of looping through the containers by index, you should use iterators.</li>\n<li>Pushing <code>tmp</code> into <code>previous_cliques</code> will make a copy.</li>\n</ul>\n\n<p>The following may be faster:</p>\n\n<pre><code>std::vector<VertexID> tmp(1);\nfor (...) {\n tmp[0] = nodes[i];\n previous_cliques.push_back(tmp);\n}\n</code></pre>\n\n<p>(If you're worried about scope, just wrap it in braces.)</p>\n\n<ul>\n<li>Checking for emptiness with <code>size()</code> may be less efficient than with <code>empty()</code>; unlikely in the case of a <code>vector</code>, though (I think <code>size()</code> must be O(1)).</li>\n<li>You're not showing us <code>isClique</code>, so it's hard to comment on that. Make sure you're passing be const reference there. Also consider not copying <code>previous_cliques</code> until you know you want to push it into <code>new_cliques</code> and instead handling <code>nodes[i]</code> as a special case (may be faster, may be slower).</li>\n<li>If you're using C++11, the <code>emplace</code> functions are your friend.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T22:02:54.117",
"Id": "13924",
"Score": "0",
"body": "Thanks for these tips. Just a question.. I just tried the code snippet you provided to speed up copying the tmp() vectors into previous_cliques, and that doesn't compile, since nodes[i] is a VertexID, and tmp is a vector of VertexIDs. Is that compiler dependent? I'm using VS2010"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T22:19:31.510",
"Id": "13925",
"Score": "0",
"body": "@notebook: Nope, that's a typo on my part, good catch. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T02:58:36.800",
"Id": "13933",
"Score": "0",
"body": "Saving the value of `end()` in a variable would make no difference speed (even if the container did not cash (or the difference is so small you could not measure it)). All the containers in modern version of the library cache a copy for re-use and the end() call returns a const reference to this cached copy. If you don't modify the value it will be just as fast and if you do modify the container it is safer. Thus prefer to always call end()."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T11:58:28.010",
"Id": "13965",
"Score": "0",
"body": "@LokiAstari: I have seen measurable differences in speed between caching the manually and calling `end`. Granted, these were in more complicated cases (the container was a class member, and there was some recursion involved). Seeing as the vectors aren't passed out of the function this may not matter, but it may still be worth trying. (By the way, the return type of `end` is `iterator`, not `iterator const&`. Not that it matters, as it is probably inlined.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T16:22:44.637",
"Id": "13975",
"Score": "0",
"body": "@AntonGolov: The return type is `iterator or const_iterator for const a` so badly worded on my part. But I would love to see an example of a situation where you can actually measure the difference in cost between calling end() every iteration and caching it once at the beginning in a situation where the actual container is not altered in the loop (ie remains const)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T19:29:54.613",
"Id": "13979",
"Score": "0",
"body": "@LokiAstari: If in the following code, the definition of `dummy` is placed in a different source file, the difference in runtime will be very significant (about 50% worse). If it is in the same source file, it seems like the optimiser handles it just fine. http://ideone.com/hDBw0 Granted, this is not very relevant in this case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-13T04:38:27.573",
"Id": "13993",
"Score": "0",
"body": "@AntonGolov: I tried putting `dummy()` in both the same and different compilation units. Seems like this shows that calling end() each time is faster. (Assuming you compile with -O3)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-13T05:13:08.993",
"Id": "13995",
"Score": "0",
"body": "@LokiAstari: Ah, -O3 versus -O2 seems to make a difference in this case. I'm still not sure why I can't reproduce the problems I had earlier, and I'll see if I can construct a more appropriate example eventually, but I doubt it'll apply in this case so I'll remove the advice."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T21:48:39.220",
"Id": "8894",
"ParentId": "8893",
"Score": "4"
}
},
{
"body": "<h3>Comments on algorithm</h3>\n\n<p>Your current algorithm is O(N^3) This can definitely be turned into <strong>O(N^2)</strong></p>\n\n<p>From reading the code you want to build a list of all sub-graphs that exist in your graph.</p>\n\n<p>I think you are doing t wrong and building several of the subsets repeatedly. </p>\n\n<p>There is a simple technique for this.<br>\nThink of each node in the graph as represented by a bit in a very large integer where the integer has one bit for every node in the graph. Node 0 is bit 0 and Node 5 is bit 5 etc. Thus the full graph is represented by the integer with all the bits set to one.</p>\n\n<p>Any sub set of the graph is then represented by an integer with some bits off and some bits on. Thus you can generate all the different sub-sets of the graph by looping through all bit patterns in the integer and this can be done simply by starting at 1 and incrementing the integer until all the bits have been set (Each increment represents a new set).</p>\n\n<p>Assuming you have more nodes than will fit into a normal integer you should probably use the boost::dynamic_bitset(If you have 64 or fewer nodes you can use a normal integer (assuming you have 64 bit integer type)).</p>\n\n<pre><code>/*\n * This function adds 1 to the bitset.\n *\n * Since the bitset does not natively support addition we do it manually. \n * If XOR a bit with 1 leaves it as one then we did not overflow so we can break out\n * otherwise the bit is zero meaning it was previously one which means we have a bit \n * overflow which must be added 1 to the next bit etc.\n */\nvoid increment(boost::dynamic_bitset<>& bitset)\n{\n for(int loop = 0;loop < bitset.count(); ++loop)\n {\n if ((bitset[loop] ^= 0x1) == 0x1)\n { break;\n }\n }\n}\n\nint cliqueSize(graph &g, std::vector<VertexID> const& nodes, std::vector<EdgeID> const& edges)\n{\n static boost::dynamic_bitset empty;\n empty.resize(nodes.size());\n\n int cliquesCount = 0;\n boost::dynamic_bitset<> set(nodes.size());\n set[0] = 1;\n\n while(set != empty()) // break when all bits are zero.\n {\n // Build the next potential clique\n // Every bit that is a 1 in set means that that nodes is in the clique.\n std::vector<VertexID> cliques;\n for(int loop = 0;loop < nodes.size(); ++loop)\n {\n if (set[loop])\n {\n cliques.push_back(nodes[loop]);\n }\n }\n\n // If this is a clique increment the count.\n if (isClique(g, cliques, edges))\n {\n ++cliquesCount;\n }\n\n // Increment the set bits by 1 each loop.\n // This effectively iterates through all different bit patterns.\n increment(set)\n }\n return cliquesCount;\n}\n</code></pre>\n\n<h3>Comment on code</h3>\n\n<p>You should prefer to pass parameters by const reference if you can.</p>\n\n<pre><code>int cliqueSize(graph &g, std::vector<VertexID> const& nodes, std::vector<EdgeID> const& edges)\n ^^^^^^^^ ^^^^^^^^\n\nstd::vector<std::vector<VertexID> > previous_cliques;\n</code></pre>\n\n<p>The following can be simplified a bit:</p>\n\n<pre><code> std::vector<VertexID> tmp;\n tmp.push_back(nodes[i]);\n previous_cliques.push_back(tmp);\n\n // Easier to read like this:\n previous_cliques.push_back(std::vector<VertexID>(1, nodes[i]));\n\n // If you have C++11 (emplace_back uses move semantics to put the object in the vector)\n previous_cliques.emplace_back(std::vector<VertexID>(1, nodes[i]));\n</code></pre>\n\n<p>Prefer to use pre-increment for loop variables. </p>\n\n<pre><code>for (unsigned clique_size = 1; clique_size < nodes.size(); ++clique_size)\n ^^\n</code></pre>\n\n<p>Though it makes no difference for POD types. It gets you in the habit of always using the pre-increment version. This will help you out when the type is not an integer type as generally speaking the pre-increment is more efficient. Also if you change the type from integer (to say iterator) it will automatically be the most efficient version.</p>\n\n<p>You are returning the wrong value:</p>\n\n<pre><code>return nodes.size();\n\n// I think you mean:\nreturn new_cliques.size();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T05:25:50.863",
"Id": "13940",
"Score": "0",
"body": "On that last point. new_cliques is out of scope. nodes.size() is the correct fall-through answer for one all-encompassing clique."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T05:39:32.933",
"Id": "13941",
"Score": "0",
"body": "@PaulMartel: You seem to have missed the point entirely. If node.size() is the answer then there seems little point in the function as it can be reduced to a single line. `int cliqueSize(graph &g, std::vector<VertexID> nodes, std::vector<EdgeID> edges) {return nodes.size();}`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T13:32:46.317",
"Id": "13967",
"Score": "0",
"body": "Too funny, 'cause I do remember feeling like I was entirely missing the point. I thought \"that function could be reduced to that one line\" and half-considered making that my answer -- but then I remembered that the function had multiple return statements, and the moment quickly passed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T16:03:35.837",
"Id": "13974",
"Score": "0",
"body": "@PaulMartel: And yet you are still missing the point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-24T15:45:30.813",
"Id": "14764",
"Score": "0",
"body": "In your proposed algorithm, isn't the while loop O(2^n)? That would make the algorithm O(n*2^n)? O(n*2^n) quickly overtakes O(n^3). Although it is cleaner, easier to read, and I suspect better on memory."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T03:46:32.103",
"Id": "8901",
"ParentId": "8893",
"Score": "2"
}
},
{
"body": "<h3>Initial conditions</h3>\n\n<p>If each element of edges always represents a clique of two elements of nodes, start by returning 0 if nodes is empty else 1 if edges is empty, else begin looping with clique_size = 2 and each element of previous_cliques initialized to each edge's VertexID pair rather than to each node's single VertexID.</p>\n\n<h3>Vector flattening</h3>\n\n<p>Since each round N produces some variable number of N-ary cliques, it may be faster,\nthough a bit trickier, to build <code>previous_cliques</code> as a flat vector of VertexID where every Nth element represents the start of a new clique.</p>\n\n<p>A variant on this idea would further capitalize on the flatness of the <code>previous_cliques</code>/<code>new_cliques</code> vectors by using a \"double buffering\" scheme\nthat limited itself to a single pair of VertexID vectors, possibly allowed to grow as\nneeded and retained for the duration of the function. The vectors would take turns\nin the roles of <code>previous_cliques</code>/<code>new_cliques</code> and each have an explicit <code>elements_used</code> high water index potentially different from its actual initialized size. The high water would get reset when it took on the role of <code>new_cliques</code> and trailing elements from past rounds simply ignored.</p>\n\n<p>All of this is somewhat second-guessing the memory manager and some of the benefits could be achieved more abstractly by packaging it as actual new/deletes with an alternative recycling-savvy Allocator strategy, if that's your idea of time well-spent.</p>\n\n<h3>Clique-first iteration</h3>\n\n<p>With or without this optimization, if the node loop is nested within the clique loop instead of vice versa, each clique in <code>previous_cliques</code> can get copied <em>once</em> into a temp vector, with its new last element simply <em>assigned into</em> by each candidate VertexID in turn (vs. using <code>push_back</code>). Then the grown vector, <em>if</em> it is a clique, can be copied into new_cliques (flattened or not). This will reap SOME of the benefits of \"only copy on success\" as suggested in the excellent answer by @Anton while still allowing passing a simple vector (<code>const &</code>) to <code>isClique</code>.</p>\n\n<h3>Optimizing for mathematical properties of cliques</h3>\n\n<p>Assuming that the clique semantics are independent of the order in which their VertexIDs are added, i.e. there is no useful distinction between clique <code>{B,A}</code> and clique <code>{A,B}</code> or between the results of <code>{A,B} + C</code> and <code>{A,C} + B</code>, culling of equivalent cliques can boost efficiency.\nAn ordering of VertexIDs -- even an arbitrary ordering that's stable for the duration of the function -- can be used to only count \"canonical form\" cliques that list their elements in order. With that restriction in place, many uninteresting duplicate cases can be eliminated just by skipping in the inner loop any VertextIDs that sort at or before the previous clique's last VertexID.</p>\n\n<p>Another optimization is possible because/assuming N-ary cliques are composed of N overlapping (N-1)-ary cliques. At a minimum, this means that when the total number of N-ary cliques is N or fewer, N can be returned as the largest clique size. </p>\n\n<h3>And there may be more, if you can stand it</h3>\n\n<p>N-1 of those N overlapping (N-1)-ary cliques will reference each of the VertexIDs in the N-ary clique. So, as a possible trade-off, track the number of times each VertexID was listed in any N-ary clique -- like in a VertexID-keyed map, preferably a sorted one for use in the range-skipping inner loop mentioned above. This allows any VertexID that was listed fewer than N times to be removed from the set of VertexIDs considered for adding in later rounds. Any N-ary clique that contained it would also be not worth building on. Either of these might be especially tricky and/or expensive to track, though.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T05:20:29.470",
"Id": "8903",
"ParentId": "8893",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T21:31:52.343",
"Id": "8893",
"Score": "4",
"Tags": [
"c++"
],
"Title": "Returning the size of the largest clique in a graph"
}
|
8893
|
<p>BFS and DFS in Java. Please give suggestions!!</p>
<pre><code>Class Main {
public void bfs()
{
// BFS uses Queue data structure
Queue queue = new LinkedList();
queue.add(this.rootNode);
printNode(this.rootNode);
rootNode.visited = true;
while(!queue.isEmpty()) {
Node node = (Node)queue.remove();
Node child=null;
while((child=getUnvisitedChildNode(node))!=null) {
child.visited=true;
printNode(child);
queue.add(child);
}
}
// Clear visited property of nodes
clearNodes();
}
public void dfs() {
// DFS uses Stack data structure
Stack stack = new Stack();
stack.push(this.rootNode);
rootNode.visited=true;
printNode(rootNode);
while(!stack.isEmpty()) {
Node node = (Node)s.peek();
Node child = getUnvisitedChildNode(n);
if(child != null) {
child.visited = true;
printNode(child);
s.push(child);
}
else {
s.pop();
}
}
// Clear visited property of nodes
clearNodes();
}
}
Class Node {
Char data;
Public Node(char c) {
this.data=c;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-31T22:12:41.480",
"Id": "33935",
"Score": "0",
"body": "Can we count the distance as well?"
}
] |
[
{
"body": "<p>There seem to be some inconsistencies here. What is <code>s</code>? I guess this is the stack? Also declaring a class Main is a little strange. You certainly want to have a main method, but a Main class?</p>\n\n<p>Also I'd suggest you not use raw collections e.g. replace</p>\n\n<pre><code>Queue queue = new LinkedList();\n</code></pre>\n\n<p>with</p>\n\n<pre><code>Queue<Node> queue = new LinkedList<Node>();\n</code></pre>\n\n<p>You may like to consider implementing DFS recursively so that you don't have to explicitly use a stack, although that's a matter of taste. Also, where is <code>getUnvisitedChildNode()</code> defined? Where are the edges of the graph actually stored? This could be e.g. an adjacency list carried around by each node, or perhaps in another object, but it should be somewhere.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-07T05:47:12.277",
"Id": "21674",
"Score": "0",
"body": "Also it make sense to replace Stack stack = new Stack(); with Deque<Node> s = new LinkedList<Node>();"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T23:21:14.860",
"Id": "8898",
"ParentId": "8896",
"Score": "8"
}
},
{
"body": "<p>It is better to name the functions as breadth-first traversal, or depth-first traversal instead, as you didn't look up any element, but travelled all the nodes.\nQuite trivial though :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T15:00:52.907",
"Id": "20209",
"ParentId": "8896",
"Score": "3"
}
},
{
"body": "<p><strong>LinkedList</strong> supports both <strong>Stack</strong> as well as <strong>Queue</strong> operations. So you can use this for both cases. Also if you are using Java 6+, better use Deque Interface instead of Queue. (Deque extends Queue).</p>\n\n<p>So your stack and queue declaration should be like below (for Java 6+ )</p>\n\n<pre><code>Deque<Node> queue = new LinkedList<Node>();\nDeque<Node> stack = new LinkedList<Node>();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T05:29:26.227",
"Id": "25643",
"ParentId": "8896",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "8898",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T22:57:20.543",
"Id": "8896",
"Score": "11",
"Tags": [
"java"
],
"Title": "Breadth and Depth First Search in Java"
}
|
8896
|
<pre><code>int X = 1;
int Y = 0;
while (X != 99 - 1 || Y != 99 - 1)
{
Y++;
if (Y > 99 - 1)
{
X += 1;
Y = 1;
}
Layer1ID[X, Y].Update(X, Y);
Layer2ID[X, Y].Update(X, Y);
}
</code></pre>
<p>This must update a total of 19602 objects each tick. Is there any way to speed this up? Threading maybe?</p>
<p>Objects(Ground and buildings) are stored in Layer1 and Layer2 ID Arrays of size 99x99. Most of them do nothing during the update method.</p>
<p>I've only recently began programming, so I apologize for the minimal information and ignorance.</p>
<p>Edit: Solved my own problem w/ help</p>
<pre><code>if (ObjectManager._r.Next(0, 5) == 3)
{
NeedUpdate = new List<Point>();
for (int x = 1; x < Layer1ID.GetLength(0); x++)
{
for (int y = 1; y < Layer2ID.GetLength(1); y++)
{
if (Layer1ID[x, y].Updates || Layer2ID[x, y].Updates)
{
NeedUpdate.Add(new Point(x, y));
}
}
}
}
foreach (Point P in NeedUpdate)
{
Layer1ID[P.X, P.Y].Update(P.X, P.Y);
Layer2ID[P.X, P.Y].Update(P.X, P.Y);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T00:33:15.563",
"Id": "13930",
"Score": "0",
"body": "Answered my own question, 1 in 60 ticks, I get a list of objects that need to be updated every tick, and update that list of objects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T01:16:32.007",
"Id": "13931",
"Score": "0",
"body": "I'm not sure if GetLength() just returns an underlying field but I would look at replacing that with a local variable to avoid the unecessary lookup on each loop iteration."
}
] |
[
{
"body": "<p>While not answering your question, I would like to point out problems with your loop conditions.</p>\n\n<p>First, the condition <code>X != 99 - 1</code> looks strange. It is the same as <code>X < 98</code> in this context. The same holds for <code>Y</code>. Since <code>Y < 98</code>, if you increment <code>Y</code> by one, <code>Y</code> is still <code>Y < 99</code> and will never be <code>Y > 98</code>!</p>\n\n<p>Arrays go from 0 to N-1. Let us assume that you have declared something like</p>\n\n<pre><code>const int N = 99;\n\nLayer[,] layer = new Layer[N, N];\n</code></pre>\n\n<p>You would make two nested loops</p>\n\n<pre><code>for (int x = 0; x < N; x++) {\n for (int y = 0; y < N; y++) {\n layer[x,y].Update(x,y);\n }\n}\n</code></pre>\n\n<hr>\n\n<p>In .NET 4.0 there is a parallel for statement, however if you are updating the UI, what your <code>Update</code> statement suggests, then a parallel processing is of little help. Only \"pure\" calculations will experience an increased calculation power when using parallel processing. Also, the single tasks must have a substantial amount of work to process; otherwise the overhead associated with parallel processing will outweigh the benefits.</p>\n\n<p>See <a href=\"http://www.dotnetcurry.com/ShowArticle.aspx?ID=608\" rel=\"nofollow\">Parallel.For Method in .NET 4.0 vs the C# For Loop</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T00:31:52.117",
"Id": "13929",
"Score": "0",
"body": "I substituted in 99 for Layer1ID.GetLength(0) & (1)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-02T11:04:05.350",
"Id": "15215",
"Score": "0",
"body": "Not only pure calculations benefit from parallel processing; for example, I maintain Castle Transactions which contains transactional file systems. It allows a lot of benefits from parallel IO, in READ COMMITTED mode."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-02T13:45:08.257",
"Id": "15227",
"Score": "0",
"body": "Yes, however your example has more to do with asynchronicity than parallel processing; i.e. one process (or task) is waiting for data from an input stream, while the other is doing something useful. My statement was more about multiplying the calculating power."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-12T00:17:08.427",
"Id": "8900",
"ParentId": "8899",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "8900",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T23:35:01.860",
"Id": "8899",
"Score": "3",
"Tags": [
"c#",
".net",
"multithreading"
],
"Title": "Quickly updating a mass of objects"
}
|
8899
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.