body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>Oftentimes people will shorten <code>System.out</code> to just <code>out</code> and make an analog called <code>in</code> (e.g. <code>Scanner in = new Scanner(System.in);</code>). I've seen two methods of doing this</p>
<h2>Method 1:</h2>
<p><code>import static java.lang.System.out;</code></p>
<h2>Method 2:</h2>
<p><code>static final PrintStream out = System.out;</code></p>
<p>Is there a coding convention or best practices for this? If so, which one is it and why is it more readable?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T05:46:34.000",
"Id": "33064",
"Score": "0",
"body": "Consider the scopes of the name `out` in each case. Method one is throughout the file and cannot be easily overridden (doing so will only add to the confusion). Method two restricts its use to the declaring class. What do you think is better?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T20:13:22.553",
"Id": "33132",
"Score": "0",
"body": "People are voting to close. Does it not seem constructive? I figured it had an appropriate level of subjectiveness when adjusting for SE CodeReview standards. Is there a way I can reword it, so that it doesn't get closed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T11:25:05.210",
"Id": "33345",
"Score": "0",
"body": "The reason they're voting to close is because this forum is dedicated to reviewing the code, e.g. you have a method that is working slowly, or you want to improve part of your code to correspond best practices, etc. This question just asks about people habits, and there is no actual code to review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T21:32:39.083",
"Id": "33373",
"Score": "0",
"body": "@almaz I want to improve my code that uses System.out to correspond to best practices. I asked if it was a matter of personal preference because I wasn't sure if a best practice exists."
}
] |
[
{
"body": "<p>With the second approach you hide that <code>out</code> refers to <code>System.out</code>, so if anytime later you want to redirect the output, you need to change only <code>static final PrintStream out = System.out;</code> since the rest of the code is only aware of the fact that it is writing to a <code>PrintStream</code>.</p>\n\n<p>The first approach is just using the shortcut offered by static imports.</p>\n\n<p>Which one to use depends on the purpose of the code. If it is a one time, throwaway code trying out something, then I'd go with the first, otherwise the second, if there are many print statements. Otherwise I would not care replacing <code>System.out</code>.</p>\n\n<p>On the other hand I would consider using a logger instead of System.out and that could be redirected to <code>System.out</code> to a <code>File</code> and to many other targets.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T05:33:39.340",
"Id": "20616",
"ParentId": "20615",
"Score": "7"
}
},
{
"body": "<blockquote>\n<p>Is one more readable than the other or is it just a matter of personal preference?</p>\n</blockquote>\n<p>Well, depends on your goals. I do not like both of them, so I would answer no to the first part.<br />\nStatic imports will confuse readers without some IDE, because it is very hard to find out the origin of the statement.\nA member or class variable could be ok if you do not modify anything about System.*, but I do not see the point to save a <code>System.</code> (Anyway, you could have the same argument as for Method1.)<br />\nNot that heavy arguments, more a matter of personal preference. This is the reason i used the word <code>like</code> in the beginning. I prefer System.out(.prinln()).<br />\nOne difference between this two methods is the effect of <code>System.setOut()</code>. Method1 is affected, Method2 does not care.</p>\n<p>To emphasize it (it was already touched by Andras):</p>\n<h2>Method 3:</h2>\n<ul>\n<li><code>static void print(Object object) { some implementation, e.g. System.out.println(o) }</code></li>\n</ul>\n<p>This is clearly shorter and more flexible. If you need more you could choose any of the available logging possibilities.</p>\n<p>(Just for completeness: This flexibility could be reached with the other methods, too. Method1: Static import of some custom class with a public class variable <code>out</code> which has the necessary methods. Method2: Modify the variable type to a custom class with the same public class variable <code>out</code> which has the necessary methods)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T21:35:16.077",
"Id": "33374",
"Score": "0",
"body": "I think the ACM library does it that way."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T18:29:16.760",
"Id": "20768",
"ParentId": "20615",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "20616",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T03:37:04.000",
"Id": "20615",
"Score": "4",
"Tags": [
"java"
],
"Title": "Shortening System.out - which is better?"
}
|
20615
|
<p>I am designing a class to store primitive types into byte buffer using predefined byte order. I am not going to use Boost.Serialization because I am working with plain types only and I need predefined binary structure without versions and things like that.</p>
<p>Here is draft of the design:</p>
<pre><code>#ifndef SERIALIZER_H_
#define SERIALIZER_H_
/**
* @file
*
* Set of byte-order independent value serializers.
* New serializers can be added with template class specialization.
*
*/
#include "types.hpp"
/**
* Serializer generic interface.
*/
template<typename ValueType>
struct serializer
{
/**
* Parses value from raw bytes.
*
* @param from byte buffer parse value from
*/
static ValueType parse(uint8_t *from);
/**
* Writes value to raw byte buffer.
*
* @param value value to write
* @param dest destination buffer
*/
static void write(ValueType value, uint8_t *dest);
};
/**
* Serializer specialization for single byte.
*/
template<>
struct serializer<uint8_t>
{
static uint8_t parse(uint8_t *from)
{
return *from;
}
static void write(const uint8_t value, uint8_t *to)
{
*to = value;
}
};
/**
* Serializer specialization for 2-byte number.
*/
template<>
struct serializer<uint16_t>
{
static uint16_t parse(uint8_t *from)
{
return (uint16_t)from[0] << 8 | from[1];
}
static void write(const uint16_t value, uint8_t *to)
{
to[0] = (value >> 8);
to[1] = value & 0xff;
}
};
/**
* Serializer specialization for 4-byte number.
*/
template<>
struct serializer<uint32_t>
{
static uint32_t parse(uint8_t *from)
{
return from[0] << 24 | from[1] << 16 | from[2] << 8 | from[3];
}
static void write(const uint32_t value, uint8_t *to)
{
serializer<uint16_t>::write(value >> 16, to);
serializer<uint16_t>::write(value & 0xffff, to + 2);
}
};
/**
* Serializer specialization for 8-byte number.
*/
template<>
struct serializer<uint64_t>
{
static uint64_t parse(uint8_t *from)
{
const uint32_t high = serializer<uint32_t>::parse(from);
const uint32_t low = serializer<uint32_t>::parse(from + 4);
return ((uint64_t) high << 32) | low;
}
static void write(const uint64_t value, uint8_t *to)
{
serializer<uint32_t>::write(value >> 32, to);
serializer<uint32_t>::write(value & 0xffffffff, to + 4);
}
};
/**
* Packet abstraction.
*
* Packet has mutable head which moves on every read or write. Packet
* overloads left/right shift operators to allow
* serialization/deserialization operations chaining:
*
* unit8_t buffer[80];
* packet p(buffer);
* p << obj.field << obj.other_field;
* // now obj fields serialized in the buffer
*
* Packet uses serializers for actual serialization/deserialization
* logic.
*
* Single packet designed to be used for reading OR writing, not for
* both operations interchaged. There is no way to move packet head
* back.
*
* @see serializer
*/
class packet
{
public:
/**
* Constructs packet from byte buffer pointer.
*
* @param buf pointer to byte buffer
*/
packet(uint8_t *buf);
/**
* Writes value to a packet.
*
* @param p packet reference
* @param value value to write
* @return reference to initial packet
*/
template<typename ValueType>
friend packet &operator<<(packet &p, ValueType value);
/**
* Reads value from a packet.
*
* @param p packet reference
* @param target value buffer reference
* @return reference to initial packet
*/
template<typename ValueType>
friend packet &operator>>(packet &p, ValueType &target);
/**
* Writes raw byte buffer to a packet.
*
* @param bytes bytes to write
* @param length buffer length
* @return reference to self
*/
packet &write_bytes(const uint8_t *bytes, std::size_t length);
/**
* Reads `length` buffers from a packet.
*
* @param dest target byte buffer
* @param length max buffer length
* @return reference to self
*/
packet &read_bytes(uint8_t *dest, std::size_t length);
/**
* Returns current head.
*
* @return current head
*/
uint8_t *get_head() const;
/**
* Skips `n` bytes in input buffer.
*/
packet &skip(std::size_t n);
/**
* Returns number of bytes written.
*
* @return number of bytes written
*/
off_t written() const;
/**
* Deallocates packet.
*/
~packet();
private:
uint8_t *_head; ///< current head
uint8_t *_start; ///< initial head
};
template<typename ValueType>
packet &operator<<(packet &p, ValueType value)
{
serializer<ValueType>::write(value, p._head);
p.skip(sizeof(ValueType));
return p;
}
template<typename ValueType>
packet &operator>>(packet &p, ValueType &target)
{
target = serializer<ValueType>::parse(p._head);
p.skip(sizeof(ValueType));
return p;
}
#endif /* SERIALIZER_H_ */
</code></pre>
<p>It looks like it does the right thing. What do you think about that?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T15:09:22.337",
"Id": "33091",
"Score": "0",
"body": "Why not use (the relatively standard) method of using htonl() and family (unfortunately for you it is network byte order (or big endian)). It is know to work and has optimal efficiency for the platform."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T12:13:54.627",
"Id": "33154",
"Score": "0",
"body": "Yep, it looks like it's much better to provide generic `native_to_network` and `network_to_native` functions for uintN_t types which delegate their work to native functions. I just googled a bit and found that there were proposal for something like that in the Boost, but it isn't currently there (and probably will never be).\nThank you!"
}
] |
[
{
"body": "<p>It just seems unnecessarily complicated. You're not doing anything to ensure binary compatibility between platforms so why not just write out the memory? Take a pointer to your data, cast it to <code>char*</code> and then read/write <code>sizeof(ValueType)</code> bytes from/to the file. There's no need to have specific template overrides for each type.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T09:14:29.767",
"Id": "33070",
"Score": "0",
"body": "Actually, I am trying to write data in a way that allow me to read file written on one platform on any other platform, that's why I use integers of known size and unifying byte order to be always little-endian."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T09:23:19.220",
"Id": "33071",
"Score": "0",
"body": "You could programmatically check whether your platform is big or little endian and then reverse the byte order as appropriate. This would allow you to use a single bit of code for all of your data rather than a set of template specialisations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T15:13:02.143",
"Id": "33092",
"Score": "0",
"body": "@roman-kashitsyn: Why little endian. The nearly d-facto standard is \"network byte order\" or big-endian."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T11:17:00.950",
"Id": "33152",
"Score": "0",
"body": "Excuse me, it's my mistake. Big-endian, of course. It's actually implemented in the example. Thank you for your correction."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T08:59:38.443",
"Id": "20625",
"ParentId": "20621",
"Score": "0"
}
},
{
"body": "<p>I ended up with something like that:</p>\n\n<pre><code>#ifndef PACKET_H_\n#define PACKET_H_\n\n#include <algorithm>\n#include \"types.hpp\"\n#include \"endian.hpp\"\n\nclass packet\n{\n public:\n\n packet(uint8_t *buf);\n\n template<typename ValueType>\n friend packet &operator<<(packet &p, ValueType value);\n\n template<typename ValueType>\n friend packet &operator>>(packet &p, ValueType &target);\n\n packet &write_bytes(const uint8_t *bytes, std::size_t length);\n\n packet &read_bytes(uint8_t *dest, std::size_t length);\n\n uint8_t *get_head() const;\n\n packet &skip(std::size_t n);\n\n off_t written() const;\n\n ~packet();\n\n private:\n friend packet &operator<<(packet &p, uint8_t value);\n friend packet &operator>>(packet &p, uint8_t &target);\n uint8_t *_head; ///< current head\n uint8_t *_start; ///< initial head\n};\n\ntemplate<typename ValueType>\npacket &operator<<(packet &p, ValueType value)\n{\n const std::size_t Size = sizeof(ValueType);\n union {\n ValueType val;\n uint8_t arr[Size];\n } Copy;\n Copy.val = native_to_network(value);\n std::copy(Copy.arr, Copy.arr + Size, p._head);\n p.skip(Size);\n return p;\n}\n\ninline packet &operator<<(packet &p, uint8_t value)\n{\n *(p._head++) = value;\n return p;\n}\n\ntemplate<typename ValueType>\npacket &operator>>(packet &p, ValueType &target)\n{\n const std::size_t Size = sizeof(ValueType);\n union {\n ValueType val;\n uint8_t arr[Size];\n } Copy;\n std::copy(p._head, p._head + Size, Copy.arr);\n p.skip(Size);\n target = network_to_native(Copy.val);\n return p;\n}\n\ninline packet &operator>>(packet &p, uint8_t &target)\n{\n target = *(p._head++);\n return p;\n}\n\n#endif /* PACKET_H_ */\n</code></pre>\n\n<p><code>native_to_network</code> and <code>network_to_native</code> functions are overloaded for uint16_t, uint32_t, uint64_t and declared in the <code>endian.hpp</code> file with a lot of preprocessor derictives. It looks like it's working for me.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T13:22:45.190",
"Id": "20678",
"ParentId": "20621",
"Score": "1"
}
},
{
"body": "<p>Here are my comments, some months later:</p>\n\n<ul>\n<li>You don't need a destructor to your <code>packet</code> class. The class does not seem to own anything.</li>\n<li>There is no mention in your <code>packet</code> class of the size (or the end) of the buffer. No check of size either. (consequently)</li>\n<li>In your <code>operator<<</code>(the one in your self-answer), <code>std::copy</code> returns the new value that <code>p.head</code> should have. No need for <code>p.skip(Size)</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-30T13:55:29.943",
"Id": "97695",
"Score": "0",
"body": "Thanks for replay ) Actually, I wrote a small C++ library based on code in the topic long time ago: https://github.com/roman-kashitsyn/encoding-binary"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-17T08:37:35.657",
"Id": "54479",
"ParentId": "20621",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T08:09:52.347",
"Id": "20621",
"Score": "3",
"Tags": [
"c++",
"template"
],
"Title": "Plain type serializer design"
}
|
20621
|
<p>I have this code in <code>LogInService</code></p>
<pre><code>public User isValid(User user) {
if(user == null)
return user;
User db_user = userDao.getUserByUsername(user.getUsername());
if (db_user != null) {
try {
if (PasswordHash.validatePassword(user.getPassword(),db_user.getPassword())) {
return db_user;
}
} catch(Exception e){ e.printStackTrace(); }
}
return null;
}
public Administrator isValid(Administrator admin){
if(admin == null)
return admin;
Administrator db_admin = adminDao.getAdminByUsername(admin.getUsername());
if(db_admin != null){
try{
if (PasswordHash.validatePassword(admin.getPassword(),db_admin.getPassword())) {
return db_admin;
}
}catch(Exception e){ e.printStackTrace(); }
}
return null;
}
</code></pre>
<p>Where we use a null to check if the user is valid.</p>
<p>My problem now is this. Users and Admins are a different entities but for them to be logged in into the system they have to login. both user and admin has the same method of logging in checking.</p>
<p>My question is there anyway I can refactor this repetitive code inside my Service layer class? or should create a different service layer for Admins to logged in? </p>
|
[] |
[
{
"body": "<p>You could use a <strong>common interface</strong> for <em>User</em> and <em>Admin</em> and a <strong>factory</strong>/service for the <em>getByUserName</em> method. So you have only a switch in the factory, and all the other duplication is gone.</p>\n\n<p>Btw. I thinks it is a better practice to return <strong>null</strong> if you know your user is null in your guard condition.\nA method with the name **<em>is</em>*Something* should return a boolean value.\nAs you will see below, I'm a friend of guard conditions, so I restructured your if.</p>\n\n<hr>\n\n<pre><code>interface Validable \n{\n String getUsername();\n String getPassword();\n}\n...\n public boolean isValid(Validable user) {\n if(user == null) return false;\n\n Validable db_user = validableFactory.getByValidable(user);\n if (db_user == null) return false\n\n try {\n return PasswordHash.validatePassword(user.getPassword(),db_user.getPassword());\n } \n catch(Exception e){\n e.printStackTrace(); return false;\n }\n }\n...\n\nclass ValidableFactory\n{\n ... \n public Validable getByValidable(Validable user)\n {\n if (user instanceOf User) return userDao.getUserByUsername(user.getUsername());\n if (user instanceOf Administrator) return dminDao.getAdminByUsername(admin.getUsername());\n return null;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>P.S.: In the case you can influence this, why is User not the base class of Administrator?\nP.P.S.: Why is the password validator throwing an Exception if it has a boolean return value?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T11:28:10.743",
"Id": "33075",
"Score": "0",
"body": "because the ValidatePassword throws an exception with regards to password decryption"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T11:29:38.857",
"Id": "33076",
"Score": "0",
"body": "btw Where would I implement the Validable interface? in the ServiceLayer ? or in the dao class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T12:03:50.620",
"Id": "33077",
"Score": "0",
"body": "Both new classes could be added to the Service as inner static. If you want to use them at an other location, you can also create standalone classes as usual."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T12:06:00.490",
"Id": "33078",
"Score": "0",
"body": "inner static? it still not clear to me on where would I implement the Validable interface"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T12:06:07.667",
"Id": "33079",
"Score": "0",
"body": "If you can't remove the exception, than you should at least catch the \"minimal\" exception (EncrytionException or so). Never catch the raw Exception as you will also catch RuntimeException and all the other stuff you might have missed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T12:07:59.613",
"Id": "33080",
"Score": "0",
"body": "User and Administrator have to implement this interface."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T10:25:10.757",
"Id": "20626",
"ParentId": "20622",
"Score": "1"
}
},
{
"body": "<ol>\n<li><p>Fix your method name <code>getUser</code>, <code>getAdmin</code> for starters. If you do not use the returned <code>User</code> object for example except for checking if it is null then consider returning <code>boolean</code>. But I suspect there are more fields in <code>User</code> and <code>Admin</code>.</p></li>\n<li><p>Fix your parameter types.\nWhy are you passing in User if you get the user from the data store. If it is only for grouping user name and password try defining a <a href=\"http://en.wikipedia.org/wiki/Value_object\" rel=\"nofollow\">value object</a>. </p></li>\n<li><p>Once you saved your User type from the burden of holding the password remove password field from the <code>User</code> object. The returned type of the authentication method should not contain the password but contain roles of the user etc. <em>Passwords</em> are an <strong>authentication</strong> concern, whereas <em>Roles</em> etc are an <strong>authorization</strong> concern.</p></li>\n<li><p>Unsuccessful authentication attempt is an exceptional case. Returning null from a service in an exceptional case burdens the user of the service with remembering the null check. In this case having a <code>NullPointerException</code> is not the worst that could happen. Not having the exception and letting unauthenticated users access your secure resources is worse.</p></li>\n<li><p>In the below code:</p>\n\n<pre><code>if(user == null)\n return user;\n</code></pre>\n\n<p>If you want to return null say so. Do not confuse the reader of your code. (Reader of the code is probably yourself in a few months.)</p>\n\n<p>Why are you returning <code>null</code>. If null is not a valid argument, as in this case, throw an <code>IllegalArgumentException</code>. I will give you an example to demonstrate the importance of this. Since you did not provide the code that uses this service it will be an imaginary usage:</p>\n\n<pre><code>User user = new User(); \nuser.setUsername(request.getParameter(\"username\"); \nuser.setPassword(request.getParameter(\"pass\"); \n\n\nUserDb = null;\nuser = loginService.isValid(user); // I'm guessing usage is as horrible as this\n\nif (userDb == null) {\n return UNSUCCESSFUL_LOGIN; \n}\n\nsaveUserToSession(userDb);\nreturn WELCOME_PAGE; \n</code></pre>\n\n<p>Programmer made a mistake but the user sees \"Login Unsuccessfull\" message for correct username and password. </p></li>\n<li><p>Do not get the real password hash out of your datastore and do not pass around the cleartext password. </p>\n\n<pre><code>User db_user = userDao.getUserByUsername(user.getUsername());\n</code></pre>\n\n<p>Instead your dao method should be something like this:</p>\n\n<pre><code>User db_user = userDao.getUserByUsername(username, passwordHash);\n</code></pre>\n\n<p>which eventually translates to some sql or ldap or hql or whatever query like this</p>\n\n<pre><code>select blah1, blah2, blah3 \n from myschema.myusertable \n where username=:username and hashedpass=:hashedpass\n</code></pre>\n\n<p>This reduces the chance of your hashed passwords to leak into logs or such, removes the need to pass around passwords in the clear makes it harder for you to let users know if a username is valid without knowing the password. I am not a security person, so I will not comment on its effect on the timing attacks. But need to know is a good Object Oriented design principle.</p></li>\n<li><p>Do a shortcut return here: </p>\n\n<pre><code> if (db_user != null) {\n //several lines of code\n }\n return null;\n</code></pre></li>\n<li><p>This should return a <code>boolean</code>. If it doesn't and you <strong>cannot</strong> change it or find one that does you can always wrap it. </p>\n\n<pre><code> PasswordHash.validatePassword(user.getPassword(),db_user.getPassword())\n</code></pre></li>\n<li><p>Do not catch <code>Exception</code> as it is too general and include unchecked exceptions such as nullpointerexception and illegalargumentexception.</p>\n\n<pre><code> } catch(Exception e){ e.printStackTrace(); }\n</code></pre></li>\n<li><code>Exception.printStackTrace();</code> is not proper exception logging. It has no use case in any production environment. </li>\n</ol>\n\n<p>My suggestion </p>\n\n<pre><code> public User getUser(UserCredential credential) throws SecurityException {\n if (credential == null) throw new IllegalArgumentException(\"credential required\");\n\n User user = userDao.getUser(credential);\n\n if (user == null) throw new InvalidCredentialException();\n\n return user;\n }\n\nstatic class UserCredential {\n //fields, all of them final\n // ..........\n UserCredential(String userName, String hashedPass) {\n //You can use org.apache.commons.lang.Validate to shorten\n //some common validations\n Validate.notNull(userName);\n Validate.notNull(hashedPass);\n this.userName = userName;\n this.hashedPass = hashedPass;\n }\n //getters no setters\n // ..........\n }\n</code></pre>\n\n<p>By validating the constructor arguments you catch some errors more easily and remove the need to check them again when used as a parameter type.</p>\n\n<pre><code>String userName = request.getParameter(\"username\");\n\n// case 1\nuser.setUsername(userName); \nUser userDb = loginService.isValid(user);\n\n// case 2\nUser user = loginService.getUserValid(new UserCredential(userName, hashedPassword));\n</code></pre>\n\n<p>Note what happens in each case if you misspell the request parameter name. In the second case you will get an illegal argument exception close to the source of the illegal argument whereas in the first case you may tell user his password wrong or you may get some unspecified error in the depths of your ORM or JDBC driver or something.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T20:07:46.763",
"Id": "33305",
"Score": "0",
"body": "You are also assuming Admin inherits from User?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T20:25:53.733",
"Id": "33306",
"Score": "0",
"body": "No. But things that need to be changed are exactly the same, so no need to repeat. UserCredential is a value object, it can be reused straightforward w/o changing the user or admin classes. isValid/getUser is reduced to 4 lines from 9. so it should be clear how getAdmin method will be implemented."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T15:34:37.197",
"Id": "20763",
"ParentId": "20622",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T08:27:43.207",
"Id": "20622",
"Score": "1",
"Tags": [
"java",
"design-patterns",
"hibernate",
"jpa"
],
"Title": "Repetitive code for different Database Entities with same implementation"
}
|
20622
|
<p>I'm building a small web application and it's starting to get a bit complex. I have reached to a point where I have to run some tests and load some libraries.</p>
<p>I made it so I can use it in this way:</p>
<pre><code>this.loadDependencies([
{
test : tests.JSON,
polyfill : self.polyfills.json
},
{
test : tests.Storage,
polyfill : self.polyfills.storage
}], self.libraries);
</code></pre>
<p>The first argument, the array, it's just a series of tests and polyfil loading, the second argument it's where I load the libraries. This is how the <code>self.libraries</code> looks:</p>
<pre><code>libraries: {
underscore: {
enabled: true,
library: [directory + 'libraries/underscore/underscore-1.4.2.js']
},
handlebars: {
enabled: true,
library: [directory + 'libraries/handlebars/handlebars-1.0.rc.1.js']
},
hammer: {
enabled: true,
library: [directory + 'libraries/hammer/hammer.js', directory + 'libraries/hammer/jquery.specialevent.hammer.js']
},
bootstrap: {
transition: {
enabled: true,
library: [directory + 'libraries/bootstrap/bootstrap-transition.js']
},
alert: {
enabled: false,
library: [directory + 'libraries/bootstrap/bootstrap-alert.js']
},
modal: {
enabled: false,
library: [directory + 'libraries/bootstrap/bootstrap-modal.js']
},
dropdown: {
enabled: false,
library: [directory + 'libraries/bootstrap/bootstrap-dropdown.js']
},
scrollspy: {
enabled: false,
library: [directory + 'libraries/bootstrap/bootstrap-scrollspy.js']
},
tab: {
enabled: false,
library: [directory + 'libraries/bootstrap/bootstrap-tab.js']
},
tooltip: {
enabled: false,
library: [directory + 'libraries/bootstrap/bootstrap-tooltip.js']
},
popover: {
enabled: false,
library: [directory + 'libraries/bootstrap/bootstrap-popover.js']
},
button: {
enabled: false,
library: [directory + 'libraries/bootstrap/bootstrap-button.js']
},
collapse: {
enabled: true,
library: [directory + 'libraries/bootstrap/bootstrap-collapse.js']
},
carousel: {
enabled: false,
library: [directory + 'libraries/bootstrap/bootstrap-carousel.js']
},
typeahead: {
enabled: false,
library: [directory + 'libraries/bootstrap/bootstrap-typeahead.js']
},
affix: {
enabled: false,
library: [directory + 'libraries/bootstrap/bootstrap-affix.js']
}
}
}
</code></pre>
<p>The <code>loadDependencies</code> function takes that object and runs on each level, checks if the enabled exists and if it's true it loads the library that is defined on the same level.</p>
<p>The function that does the above is what I want to improve a bit, so I'm looking for any advice or tips on how I could improve that code:</p>
<pre><code>Application.Dependencies.prototype.loadLibraries = function(polyfills, libraries, callback) {
var self = this,
libs = self.helpers.objectSize(libraries),
iterations = [],
loaded = [];
self.helpers.each(libraries, function(object) {
if(object.hasOwnProperty('enabled') && object.enabled === true) {
for(var i = object.library.length - 1; i >= 0; i--) {
iterations.push(object.library[i]);
};
} else if(self.helpers.objectSize(object) >= 0) {
self.helpers.each(object, function(obj) {
if(obj.hasOwnProperty('enabled') && obj.enabled === true) {
for(var i = obj.library.length - 1; i >= 0; i--) {
iterations.push(obj.library[i]);
};
};
});
};
});
return self.helpers.each(libraries, function(object) {
if(object.hasOwnProperty('enabled') && object.enabled === true) {
self.loadEngine(false, {
tests: (typeof object.enabled === 'array') ? (object.enabled.length === 1 ? false : true) : true ? object.enabled : self.helpers.reduceArray(object.enabled, function(initial, current) {
return initial && current;
}, 1),
libraries: object.library,
callback: function(url, result, key) {
loaded.push(url);
if(loaded.length === self.helpers.objectSize(iterations)) {
self.console(function() {
console.log('Libraries : ', loaded);
self.polyfillize(polyfills, function() {
return(typeof callback === 'function' && callback !== undefined) ? callback.apply(this, [this]) : console.log('Argument : Invalid [ Function Required ]');
});
});
};
}
});
} else if(self.helpers.objectSize(object) >= 0) {
self.helpers.each(object, function(obj) {
if(obj.hasOwnProperty('enabled') && obj.enabled === true) {
return self.loadEngine(false, {
tests: (typeof obj.enabled === 'array') ? (obj.enabled.length === 1 ? false : true) : true ? obj.enabled : self.helpers.reduceArray(obj.enabled, function(initial, current) {
return initial && current;
}, 1),
libraries: obj.library,
callback: function(url, result, key) {
loaded.push(url);
if(loaded.length === self.helpers.objectSize(iterations)) {
self.console(function() {
console.log('Libraries : ', loaded);
self.polyfillize(polyfills, function() {
return(typeof callback === 'function' && callback !== undefined) ? callback.apply(this, [this]) : console.log('Argument : Invalid [ Function Required ]');
});
});
};
}
});
};
});
};
});
};
</code></pre>
|
[] |
[
{
"body": "<p>One of the javascript code conventions I like to follow is to start each function with declaring all variables used in the function. Even the ones used inside For loops. The scope of these is the function body, declaring variables like this just clarify scope.</p>\n\n<p>Your code is fairly readable and clean. But you do have code duplication where you call loadEngine(), which you can eliminate. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-01T06:55:56.960",
"Id": "21160",
"ParentId": "20623",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "21160",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T08:29:17.743",
"Id": "20623",
"Score": "2",
"Tags": [
"javascript",
"object-oriented",
"jquery"
],
"Title": "Small web application"
}
|
20623
|
<p>Cyclic Words</p>
<blockquote>
<p>Problem Statement</p>
<p>We can think of a cyclic word as a word written in a circle. To
represent a cyclic word, we choose an arbitrary starting position and
read the characters in clockwise order. So, "picture" and "turepic"
are representations for the same cyclic word.</p>
<p>You are given a String[] words, each element of which is a
representation of a cyclic word. Return the number of different cyclic
words that are represented.</p>
</blockquote>
<p>I have included my attempt below, and I'm not sure whether to be pleased with it or not (because I'm new to algos). I want to solve this problem in the most efficient way, preferably in an imperative language such as Java.</p>
<p>I would appreciate criticism of my code in terms of both function and form.</p>
<pre><code>private static int countCyclicWords(String[] input) {
HashSet<String> hashSet = new HashSet<String>();
String permutation;
int count = 0;
for (String s : input) {
if (hashSet.contains(s)) {
continue;
} else {
count++;
for (int i = 0; i < s.length(); i++) {
permutation = s.substring(1) + s.substring(0, 1);
s = permutation;
hashSet.add(s);
}
}
}
return count;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T17:59:10.637",
"Id": "33289",
"Score": "1",
"body": "\"efficient\" depends on some requirements and/or further clarification. For readability and form, this solution will work. A simple and easy understandable solution is always better as a complex solution because of optimization. Only if you have to optimize, look at the requirements, profile and start optimizing. Otherwise, just do not care."
}
] |
[
{
"body": "<p>There's one trick which you can use to get a reduction in memory usage which is very worthwhile if the strings are long. <code>String.substring</code> returns a new <code>String</code> object but wrapping the same underlying <code>char[]</code> as the original. So your code:</p>\n\n<pre><code> for (int i = 0; i < s.length(); i++) {\n permutation = s.substring(1) + s.substring(0, 1);\n s = permutation;\n hashSet.add(s);\n }\n</code></pre>\n\n<p>could be replaced with</p>\n\n<pre><code> String dbl = s + s;\n for (int i = 0; i < s.length(); i++) {\n hashSet.add(dbl.substring(i, i + s.length()));\n }\n</code></pre>\n\n<p>and will contain the same strings but only store <code>2 * s.length()</code> characters rather than <code>s.length() * s.length()</code>.</p>\n\n<hr>\n\n<p>The next trick to consider using would be a <code>CharSequence</code> implementation which wraps the original string and an offset for the starting character.</p>\n\n<hr>\n\n<p>Finally, you could consider normalising each cyclic word. Given the <code>s.length()</code> possible rotations, choose the lexicographically smallest and insert only that one into the set. Whether this gives an efficiency improvement will depend on the statistics of the strings, but if they're random and of a length comparable to the size of the alphabet then a naïve algorithm for finding the smallest will be essentially linear, and you gain two things: firstly, the set becomes smaller (less memory usage, faster lookups); and secondly, you can drop <code>count</code> because the number of cyclic words will be just the size of the set.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T10:34:36.640",
"Id": "20627",
"ParentId": "20624",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "20627",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T08:34:05.400",
"Id": "20624",
"Score": "2",
"Tags": [
"java",
"optimization"
],
"Title": "Count the number of cyclic words in an input"
}
|
20624
|
<p>I'm trying to improve some code in order to get a better perfomance, I have to do a lot of pattern matching for little tags on medium large strings, for example:</p>
<pre><code>import re
STR = "0001x10x11716506872xdc23654&xd01371600031832xx10xID=000110011001010\n"
def getID(string):
result = re.search('.*ID=(\d+)', string)
if result:
print result.group(1)
else:
print "No Results"
</code></pre>
<p>Taking in mind the perfomance I rewrite it:</p>
<pre><code>def getID2(string):
result = string.find('ID=')
if result:
result += 3
print string[result:result+15]
else:
print 'No Results'
</code></pre>
<p>Are there a better way to improve these approaches?
Any comments are welcome...</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T15:17:23.493",
"Id": "33093",
"Score": "5",
"body": "Is this the actual code that you are trying to improve the performance of? As it stands, `print` will be more expensive then anything else and relative to that no other change will really matter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T15:54:33.223",
"Id": "33096",
"Score": "0",
"body": "This a getter from a class that get the string at the constructor"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T16:44:32.320",
"Id": "33104",
"Score": "1",
"body": "If its a getter you should be referencing `self` and `return`ing the answer. If you want help you need to show your actual code! As it stands this is totally useless."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-03T08:41:25.473",
"Id": "39899",
"Score": "0",
"body": "Also, what performance improvement do you need? What are possible use cases? There's not much more you can do since find(\"ID=\") is O(n), n being the length of the string. You can get performance only by not traversing the whole string, which is not possible unless we know more about your date (ID always at the end?)."
}
] |
[
{
"body": "<p>If you name your function <code>getSomething()</code>, I expect it to return a value with no side effects. I do not expect it to print anything. Therefore, your function should either return the found string, or <code>None</code> if it is not not found.</p>\n\n<p>Your original and revised code look for different things: the former wants as many digits as possible, and the latter wants 15 characters. Combining the two requirements, I take it that you want 15 digits.</p>\n\n<p><code>re.search()</code> lets the regular expression match any part of the string, rather than the entire string. Therefore, you can omit <code>.*</code> from the beginning of your regular expression.</p>\n\n<p>Here's how I would write it:</p>\n\n<pre><code>import re\nSTR = \"0001x10x11716506872xdc23654&xd01371600031832xx10xID=000110011001010\\n\"\n\ndef getID(string):\n result = re.search('ID=(\\d{15})', string)\n return result and result.group(1)\n\nprint getID(STR) or \"No Results\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T12:43:02.430",
"Id": "65214",
"Score": "0",
"body": "Out of interest, even though I prefer the look of your suggestion, do you think it will perform better than the `find(...)` option? My instinct is that RE's will be slower in general and the `\\d{15}` will do character-checking for digits which the find solution does not do..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T09:28:51.010",
"Id": "38985",
"ParentId": "20632",
"Score": "2"
}
},
{
"body": "<p>You are trying to get what's after <code>ID=</code>?<br>\nI'm not sure about performance (you'll have to benchmark on your own data) but I would do this: </p>\n\n<pre><code>def get_id(string):\n try:\n id = str.split('ID=')[1].strip()\n return id\n except IndexError:\n return None\n\nstring = \"0001x10x11716506872xdc23654&xd01371600031832xx10xID=000110011001010\\n\"\nid = get_id(string)\n</code></pre>\n\n<p>This only works if there are 0 or 1 <code>ID=</code> parts. If there are 2 or more only the first one gets returned.</p>\n\n<p>Edit:</p>\n\n<p>This is how I would do benchmarks (I might be wrong, I don't have much experience in this):</p>\n\n<pre><code>>>> #string with escaped '\\n' at the end:\n>>> string = '0001x10x11716506872xdc23654&xd01371600031832xx10xID=000110011001010\\\\n'\n>>> #original regex + getting the match object:\n>>> timeit.timeit(stmt=\"re.search(r'.*ID=(\\d+)', '{}').group(1)\".format(string), setup=\"import re\")\n3.4012476679999963\n>>> #original regex only:\n>>> timeit.timeit(stmt=\"re.search(r'.*ID=(\\d+)', '{}')\".format(string), setup=\"import re\")\n2.560870873996464\n>>> #alternative regex + match object (had to use c-style string formatting):\n>>> timeit.timeit(stmt=\"re.search(r'ID=(\\d{15})', '%s').group(1)\" % string, setup=\"import re\")\n3.0494329900029697\n>>> #alternative regex only:\n>>> timeit.timeit(stmt=\"re.search(r'ID=(\\d{15})', '%s')\" % string, setup=\"import re\")\n2.2219171980032115\n>>> #str.split:\n>>> timeit.timeit(stmt=\"'{}'.split('ID=')[1].strip()\".format(string))\n1.127366863998759\n</code></pre>\n\n<p>I think these are the benchmarks for the relevant parts. This is on a CoreDuo MacBook Pro and your results may vary. It's been my experience that using methods from the standard library usually yields the best results.\nOn the other hand, this is important only if you have a ton of data to process. Otherwise a more flexible but \"slower\" way of doing things might be better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T12:48:03.887",
"Id": "65216",
"Score": "1",
"body": "Since the actual asker of the question is using non-existant value checking in his solution, it seems fair that the assumptions of your suggestion are very restrictive too.... but I can't believe this solution will be anything near as quick as any other alternatives so far. The `str.split` has to check **every** character in the string inclusing all of those chars after the first match.... it simply does not add up. +1 though for suggesting benchmarking.... which is the obvious review question I would ask... \"What are the benchmarks?\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T17:02:46.550",
"Id": "65264",
"Score": "1",
"body": "@rolfl I added some benchmarks... I think they are ok but please correct me if I'm mistaken."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T11:38:38.813",
"Id": "38991",
"ParentId": "20632",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T13:42:52.693",
"Id": "20632",
"Score": "1",
"Tags": [
"python",
"regex"
],
"Title": "Python pattern searching using re standard lib, str.find()"
}
|
20632
|
<p>I'm just beginning my foray into iOS development and need a code review. I have a custom <code>NSManagedObject</code> that needs some smart setters. I'm new to Objective-C, iOS, and core-data development, so I don't trust myself yet. I come from a Java background, so smart setters are what I know, but might not be best when using Core Data.</p>
<pre><code>+(void)initialize
{
scoredKeys = @[@"fullSwings", @"putts", @"fairwayBunkers", @"greenBunkers", @"chipsOrPitches", @"rescue", @"wastedOrPenalty"];
}
-(id) initWithHoleNumber:(int)holeNumber
{
self = [super init];
if (self) {
[self setHoleNumber:[NSNumber numberWithInt:holeNumber]];
}
return self;
}
-(void) incrementItem:(NSString *)key
{
[self willAccessValueForKey:key];
NSNumber *value = [self primitiveValueForKey:key];
int intValue = value.intValue;
[self didAccessValueForKey:key];
[self willChangeValueForKey:key];
[self setPrimitiveValue:[NSNumber numberWithInt: intValue++] forKey:key];
[self didChangeValueForKey:key];
[self recalculateScore];
}
-(void) recalculateScore
{
NSString *key;
NSNumber *current;
int tally = 0;
for (key in scoredKeys) {
[self willAccessValueForKey:key];
current = [self primitiveValueForKey:key];
tally = tally + current.intValue;
[self didAccessValueForKey:key];
}
[self willChangeValueForKey:@"score"];
[self setPrimitiveValue:[NSNumber numberWithInt:tally] forKey:@"score"];
[self didChangeValueForKey:@"score"];
}
</code></pre>
<p>I am also seeking general comments about my approach. </p>
<ol>
<li>In the core-data docs, it says the auto generated accessors are much faster than anything a developer can write, so is this a good idea?</li>
<li>Should I not even have a <code>score</code> property, and just have a method that returns the tally?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T16:41:33.413",
"Id": "33103",
"Score": "0",
"body": "what do u mean with \"Core Data class\"? is this a subclass of NSManagedObject?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T16:46:59.200",
"Id": "33106",
"Score": "0",
"body": "@vikingosegundo yes -- edited question to reflect that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T16:49:45.763",
"Id": "33107",
"Score": "0",
"body": "Than I'd like to know how you create new model objects, as it usually is done with `initWithEntity:insertIntoManagedObjectContext:`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T16:55:45.923",
"Id": "33108",
"Score": "0",
"body": "havent gotten into that, my question is specifically about the setters and the recalculation. However, I plan to create a service class as a factory that manages the entities and their interactions with the context."
}
] |
[
{
"body": "<p>without referring to your code, I think there is one pattern, that makes core data more fun but sadly isnt supported by Xcode out-of-the-box:</p>\n\n<p>Have two classes for each model: one for automatic code generation — it will be jsut changed by Xcode — and on that inherits from the first, that can be changed and will never touched again by the machine after creation.</p>\n\n<pre><code>// for the machine\n@class _Event : NSManagedObject\n@end\n\n// for human beings\n@class Event : _Event\n// what ever you need: put it here\n@end\n</code></pre>\n\n<p>a great tool to teach Xcode this pattern is <a href=\"http://rentzsch.github.com/mogenerator/\" rel=\"nofollow\">mogenerator</a>. <a href=\"http://raptureinvenice.com/getting-started-with-mogenerator/\" rel=\"nofollow\">mogenerator + Xcode4.x</a></p>\n\n<p>Another similar approach would be to have categories on the Model class. But this is less powerful and needs more attention for importing.</p>\n\n<hr>\n\n<p>Now to your code.</p>\n\n<p>I dont see any reason to overwrite the setter. if apple says that you most likely will never be able to write as performant accessors as the provide, they probably are right. Instead you should create your own method, that will set up a object as need. you could overwrite <code>save</code> and similar methods, or access it via a wrapper class, that will set it up for you.</p>\n\n<blockquote>\n <p>I plan to create a service class as a factory that manages the entities and their interactions with the context.</p>\n</blockquote>\n\n<p>that sounds valid and could be the wrapper class mentioned above. But make sure, you create the model objects with <code>initWithEntity:insertIntoManagedObjectContext:</code>, as you want them in your context.</p>\n\n<hr>\n\n<p>Core Data is a great and powerful framework. but beware: if you shoot yourself in the foot, most likely both your legs will be gone.<br>\n2 Years ago I was working in a team where the Engineer responsible for persistency accidentally overwrote an internal method of NSManagedObject. It took him one week to find the cause and fix it by renaming his method. This line of code was probably the most expensive in the whole project. There-for another hint: prefix your custom methods.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T17:19:40.290",
"Id": "33116",
"Score": "0",
"body": "ah, so basically proxy an underlying class that only xcode touches. hmmm. interesting. hey, where are the tutorials on patterns for ios? I see lots of basic info, but nothing on patterns and best practices.... also i realize my question makes no sense. I ask about smart setters, and have no actual settings in the code. I don't think I need the `{did|will}AccessValueForKey` and probably can just use the normal setters...is that correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T17:20:01.600",
"Id": "33117",
"Score": "0",
"body": "oh, and lol for the last sentence -- I'm gonna remember that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T17:22:12.667",
"Id": "33118",
"Score": "0",
"body": "just use the setters provided by core data. everything else is for masochists. or are you masochistic?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T17:23:48.563",
"Id": "33119",
"Score": "0",
"body": "I added an eyewitness report"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T17:04:15.617",
"Id": "20650",
"ParentId": "20634",
"Score": "3"
}
},
{
"body": "<p>I would refactor your code as follows:</p>\n\n<pre><code>@implementation CodeReviewClass\n\nstatic NSArray *scoredKeys;\n\n+ (void)initialize\n{\n if (self == [CodeReviewClass class] ) {\n scoredKeys = @[@\"fullSwings\", @\"putts\", @\"fairwayBunkers\", @\"greenBunkers\", @\"chipsOrPitches\", @\"rescue\", @\"wastedOrPenalty\"];\n }\n}\n</code></pre>\n\n<p>I asked a question about +[NSObject initialize] over on <a href=\"https://stackoverflow.com/questions/13326435/nsobject-load-and-initialize-what-do-they-do\">StackOverflow</a> and got some great responses. The responses point out the canonical way to use initialize.</p>\n\n<pre><code>+ (id)codeReviewClassWithHoleNumber:(NSInteger)holeNumber insertInManagedObjectContext:(NSManagedObjectContext *)managedObjectContext\n{\n CodeReviewClass *obj = [NSEntityDescription insertNewObjectForEntityForName:@\"CodeReviewClass\" inManagedObjectContext:managedObjectContext];\n if (obj) {\n [obj setHoleNumber:@(holeNumber)];\n }\n\n return obj;\n}\n</code></pre>\n\n<p>I've seen this convenience constructor pattern more frequently with Core Data managed objects then the two-stage initialization used with NSObject. Particularly because the designated initializer (-[NSManagedObject initWithEntity: insertIntoManagedObjectContext:]) is pretty finicky. Definitely read NSManagedObject Class Reference - they give special treatment to overriding init. Obviously substitute your actual class name in for my placeholder text!</p>\n\n<pre><code>- (void)incrementItem:(NSString *)key\n{\n NSInteger value = [[self valueForKey:key] integerValue];\n\n [self setValue:@(++value) forKey:key];\n\n [self recalculateScore];\n}\n</code></pre>\n\n<p>Core Data properties are key-value coding compliant, and you don't have to use the will/did + Access/Change + ValueForKey: methods if you use the dynamically supplied accessor or mutator (KVC tries to use these methods).</p>\n\n<pre><code>-(void) recalculateScore\n{\n NSNumber *current;\n int tally = 0;\n\n for (NSString *key in scoredKeys) {\n current = [self valueForKey:key];\n tally += current.integerValue;\n }\n\n [self setScore:@(tally)];\n}\n\n@end\n</code></pre>\n\n<p>Again, I opt to use the publicly exposed properties via KVC to calculate the tally. The rest of the changes are stylistic syntax.</p>\n\n<p>Your score property could be marked as a transient property in the Core Data Managed Object Model, and calculated on-demand using the implementation of recalculateScore. This of course could get expensive if you calculate it frequently!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-12T13:09:37.630",
"Id": "315196",
"Score": "0",
"body": "\"you don't have to use the will/did + Access/Change + ValueForKey: methods if you use the dynamically supplied accessor or mutator\". True, and that is why your incrementItem: and recalculateScore methods do need the will/did + Access/Change + ValueForKey calls. So, setScore: is fine by itself, current = [self valueForKey:key]; is not."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T21:52:44.667",
"Id": "20730",
"ParentId": "20634",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T14:21:45.143",
"Id": "20634",
"Score": "3",
"Tags": [
"beginner",
"objective-c",
"ios",
"core-data"
],
"Title": "NSManagedObject in need of smart setters"
}
|
20634
|
<p>I have the following code:</p>
<pre><code> Integer cr = 3;
String y = "\"\r\n\"";
for (Integer i = 0; i < cr; i++)
{
for (Integer j = 0; j < cr; j++)
{
for (Integer k = 0; k < cr; k++)
{
for (Integer l = 0; l < cr; l++)
{
for (Integer m = 0; m < cr; m++)
{
for (Integer n = 0; n < cr; n++)
{
for (Integer o = 0; o < cr; o++)
{
for (Integer p = 0; p < cr; p++)
{
consolus.append(i.toString()+j.toString()+k.toString()+l.toString()+m.toString()+n.toString()+o.toString()+p.toString() + y);
}
}
}
}
}
}
}
}
</code></pre>
<p>Is there some way I can write this more efficiently? Essentially, the output is a number 8 chars long which contains all possible numbers containing the numbers from 0 to <code>cr</code>. This method currently works, however it doesn't seem efficient, and then writing to the <code>TextView</code> consolus, only occurs after all the <code>for</code> statements complete.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-16T02:02:05.143",
"Id": "33086",
"Score": "5",
"body": "What makes you think its inefficient?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-16T02:02:55.800",
"Id": "33087",
"Score": "2",
"body": "you don't understand what `.append()` actually does, that is your only *inefficiency* I see!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-16T03:28:50.823",
"Id": "33088",
"Score": "1",
"body": "For the record, this should really go on Code Review."
}
] |
[
{
"body": "<p>Presumably you want to avoid the 8 levels of nested loops? (This isn't an efficiency thing, merely a code cleanliness issue.)</p>\n\n<p>If so, use a length-8 array of integers, and use it to do \"counting\" in a while loop.</p>\n\n<pre><code>int[] cnt = new int[8];\n\nwhile (1) {\n\n // ... Do something ...\n\n // Update\n for (int i = 0; i < 8; i++) {\n cnt[i]++;\n if (cnt[i] != cr) break;\n cnt[i] = 0;\n }\n}\n</code></pre>\n\n<p>I'll leave termination of the while loop as an exercise for the reader...</p>\n\n<p><strong>Note:</strong> If you find this pattern occurring all over the place in your code, you could be cunning and put the update logic into a helper class. And then your outer loop could become:</p>\n\n<pre><code>for (Counter c = new Counter(8,cr); c.isActive(); c.increment()) {\n ...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-16T02:11:54.987",
"Id": "33089",
"Score": "0",
"body": "Thanks for your detailed response, is there any reason why the writing to the TextView doesn't occur until after complete iteration?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-16T02:00:57.353",
"Id": "20636",
"ParentId": "20635",
"Score": "5"
}
},
{
"body": "<p>The only inefficiency I see is this: </p>\n\n<pre><code>consolus.append(i.toString()+j.toString()+k.toString()+l.toString()+m.toString()+n.toString()+o.toString()+p.toString() + y);\n</code></pre>\n\n<p>should be this</p>\n\n<pre><code>consolus.append(i).append(j).append(k).append(l).append(m).append(n).append(o).append(p).append(y);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-16T02:07:51.370",
"Id": "20637",
"ParentId": "20635",
"Score": "2"
}
},
{
"body": "<p>Just for fun I took your code and ran it as it with timing around the loops.. <strong>on average 48 milliseconds</strong>. I then took the code and correct the usage of <code>.append</code> and gathered timing.. <strong>on average 41 milliseconds</strong>. And then I changed Integer to int in the for loops and took out the Integer.toString calls.. giving <strong>on average 21 milliseconds</strong>.</p>\n\n<p>I am not sure what your timing requirements are but both are \"fast\".</p>\n\n<p>Original code with timing</p>\n\n<pre><code>public class test\n{\n public static void main(String args[])\n {\n new test();\n }\n\n public test()\n {\n StringBuffer consolus = new StringBuffer();\n\n Integer cr = 3;\n String y = \"\\\"\\r\\n\\\"\";\n\n long start = System.currentTimeMillis();\n\n for (Integer i = 0; i < cr; i++)\n {\n for (Integer j = 0; j < cr; j++)\n {\n for (Integer k = 0; k < cr; k++)\n {\n for (Integer l = 0; l < cr; l++)\n {\n for (Integer m = 0; m < cr; m++)\n {\n for (Integer n = 0; n < cr; n++)\n {\n for (Integer o = 0; o < cr; o++)\n {\n for (Integer p = 0; p < cr; p++)\n {\n consolus.append(i.toString()+j.toString()+k.toString()+l.toString()+m.toString()+n.toString()+o.toString()+p.toString() + y);\n }\n }\n }\n }\n }\n }\n }\n }\n long stop = System.currentTimeMillis();\n\n System.out.println(stop-start);\n }\n}\n</code></pre>\n\n<p>Update code with timing</p>\n\n<pre><code>public class test\n{\n public static void main(String args[])\n {\n new test();\n }\n\n public test()\n {\n StringBuffer consolus = new StringBuffer();\n\n Integer cr = 3;\n String y = \"\\\"\\r\\n\\\"\";\n\n long start = System.currentTimeMillis();\n\n for (Integer i = 0; i < cr; i++)\n {\n for (Integer j = 0; j < cr; j++)\n {\n for (Integer k = 0; k < cr; k++)\n {\n for (Integer l = 0; l < cr; l++)\n {\n for (Integer m = 0; m < cr; m++)\n {\n for (Integer n = 0; n < cr; n++)\n {\n for (Integer o = 0; o < cr; o++)\n {\n for (Integer p = 0; p < cr; p++)\n {\n consolus.append(i.toString());\n consolus.append(j.toString());\n consolus.append(k.toString());\n consolus.append(l.toString());\n consolus.append(m.toString());\n consolus.append(n.toString());\n consolus.append(o.toString());\n consolus.append(p.toString());\n consolus.append(y);\n }\n }\n }\n }\n }\n }\n }\n }\n long stop = System.currentTimeMillis();\n\n System.out.println(stop-start);\n }\n}\n</code></pre>\n\n<p>ReUpdated code with timing</p>\n\n<pre><code>public class test\n{\n public static void main(String args[])\n {\n new test();\n }\n\n public test()\n {\n StringBuffer consolus = new StringBuffer();\n\n Integer cr = 3;\n String y = \"\\\"\\r\\n\\\"\";\n\n long start = System.currentTimeMillis();\n\n for (int i = 0; i < cr; i++)\n {\n for (int j = 0; j < cr; j++)\n {\n for (int k = 0; k < cr; k++)\n {\n for (int l = 0; l < cr; l++)\n {\n for (int m = 0; m < cr; m++)\n {\n for (int n = 0; n < cr; n++)\n {\n for (int o = 0; o < cr; o++)\n {\n for (int p = 0; p < cr; p++)\n {\n consolus.append(i);\n consolus.append(j);\n consolus.append(k);\n consolus.append(l);\n consolus.append(m);\n consolus.append(n);\n consolus.append(o);\n consolus.append(p);\n consolus.append(y);\n }\n }\n }\n }\n }\n }\n }\n }\n long stop = System.currentTimeMillis();\n\n System.out.println(stop-start);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-16T03:16:01.173",
"Id": "33090",
"Score": "0",
"body": "Apparently I can't append ints to a TextView. Any suggestions?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T15:32:55.107",
"Id": "33094",
"Score": "1",
"body": "+1 : Try with `StruigBuilder` you could gain some milliseconds (and change name to `Test` - capital letter convention for first character in classes name)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-16T02:25:16.777",
"Id": "20638",
"ParentId": "20635",
"Score": "5"
}
},
{
"body": "<p>The are perhaps some more compact ways of writing it, but you are generating CR^8 numbers, and your inner statement runs CR^8 times. However you re-arrange the loop you still need to add those CR^8 numbers...so will be roughly the same, except as noted elsewhere some call inefficiencies. </p>\n\n<p>Your <code>textView</code> is not updating because you are runnng on the UI thread, the refresh occurs after you leave your callback routine. Callbacks are atomic from the POV of the UI. If you want to see the <code>textView</code> get populated as it happens, you should run your routine on a background thread and <code>post</code> your results to the UI periodically. An <code>AsyncTask</code> would also work for this where you update your <code>TextView</code> in <code>onProgressUpdate()</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-16T02:42:29.800",
"Id": "20639",
"ParentId": "20635",
"Score": "1"
}
},
{
"body": "<p>I would suggest this approach:</p>\n\n<pre><code>public class Solution {\n public static void main(final String args[]) {\n final int upToNumberNonInclusive = 2;\n final int upToLength = 2;\n appendPermutations(upToNumberNonInclusive, upToLength, new Appendable() {\n @Override\n public void append(final CharSequence text) {\n System.out.println(text);\n }\n });\n }\n\n /**\n * Generates all Permutations from 0..upToNumberNonInclusive with a length of upToLength.<br>\n * Example: upToNumberNonInclusive=2, upToLength=2<br>\n * result: 0, 1, 10, 11 (arguments for append)\n */\n public static void appendPermutations(final int upToNumberNonInclusive, final int upToLength, final Appendable appendable) {\n for (int number = 0; number < upToNumberNonInclusive; number++)\n appendPermutationsHelper(upToNumberNonInclusive, number, upToLength - 1, appendable);\n }\n\n private static void appendPermutationsHelper(final int numberOfForks, final int currentNumber, final int depth, final Appendable appendable) {\n if (depth == 0) {\n appendable.append(Integer.toString(currentNumber, 10));\n return;\n }\n for (int number = 0; number < numberOfForks; number++)\n appendPermutationsHelper(numberOfForks, currentNumber * 10 + number, depth - 1, appendable);\n }\n\n public interface Appendable {\n public void append(CharSequence text);\n }\n}\n</code></pre>\n\n<p>The recursion makes more clarity and avoiding <code>StringBuilder</code> calls would create less object actions.</p>\n\n<p>If you need the exact same solution as in the example code, you can add a method to fill it up:</p>\n\n<pre><code> public class Solution {\n public static void main(final String args[]) {\n final int upToNumberNonInclusive = 2;\n final int upToLength = 2;\n appendPermutations(upToNumberNonInclusive, upToLength, new Appendable() {\n private final static char fillCharacter = '0';\n private static final String endOfLine = \"\\\"\\r\\n\\\"\";\n\n @Override\n public void append(final CharSequence text) {\n System.out.print(fillUpText(text) + endOfLine);\n }\n\n /** fills up the text up to upToLength with fillCharacter */\n private CharSequence fillUpText(final CharSequence text) {\n if (text.length() >= upToLength)\n return text;\n final char[] arrayChar = new char[upToLength - text.length()];\n Arrays.fill(arrayChar, fillCharacter);\n return new String(arrayChar) + text;\n }\n });\n }\n\n /**\n * Generates all Permutations from 0..upToNumberNonInclusive with a length of upToLength.<br>\n * Example: upToNumberNonInclusive=2, upToLength=2<br>\n * result: 0, 1, 10, 11 (arguments for append)\n */\n public static void appendPermutations(final int upToNumberNonInclusive, final int upToLength, final Appendable appendable) {\n for (int number = 0; number < upToNumberNonInclusive; number++)\n appendPermutationsHelper(upToNumberNonInclusive, number, upToLength - 1, appendable);\n }\n\n private static void appendPermutationsHelper(final int numberOfForks, final int currentNumber, final int depth, final Appendable appendable) {\n if (depth == 0) {\n appendable.append(Integer.toString(currentNumber, 10));\n return;\n }\n for (int number = 0; number < numberOfForks; number++)\n appendPermutationsHelper(numberOfForks, currentNumber * 10 + number, depth - 1, appendable);\n }\n\n public interface Appendable {\n public void append(CharSequence text);\n }\n }\n</code></pre>\n\n<p>Please notice, that the anonymous class is only for educational purpose, not the suggested general solution.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T17:18:33.923",
"Id": "20764",
"ParentId": "20635",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "20638",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-16T01:59:28.953",
"Id": "20635",
"Score": "2",
"Tags": [
"java",
"android"
],
"Title": "Calculating the number 8 chars long which contains all possible numbers containing the numbers from 0 to n"
}
|
20635
|
<p>I posted a question few weeks back, on making a PHP Login Script. Most of you guys told me not to use <code>global</code> variables and especially for something like MySQLi connection object as it may be insecure. I was also advised to switch to classes. I did so. And here is my code -</p>
<pre><code>class Page {
private $unauthorized_source=0;
var $signin_stat=0;
var $current_user=0;
var $incorrect=0;
protected $conn=0;
function __construct() {
$this->conn=new mysqli('127.0.0.1', 'root', 'short', 'untitled');
$this->current_user=new User(0, $this->conn);
}
function signin($u,$p) {
/*
* the username stored in $u is first escaped using htmlspecialchars() and then is passed to this function
* the password is first hashed using mkPass() [defined below] and then passed to this function
*/
$q_string="SELECT uid FROM users WHERE (emailid='$u' OR uname='$u') AND AES_DECRYPT(pass,CONCAT(uname,'$p'))='$p'";
$q=$this->conn->query($q_string);
if($q->num_rows==1) {
$c=$q->fetch_row();
$uid=$c[0]; //getting uid
$this->current_user=new User($uid, $this->conn); //creating $current_user object
$this->signin_stat=1;
$this->set_session($uid, $u, $p, $this->conn); //setting session
return true;
} else {
$this->signout(0);
$this->incorrect=1;
return 0;
}
}
function set_session($uid, $u, $p) {
$sid=sha1($uid+time()+$_SERVER['REMOTE_ADDR']);
$q_string="UPDATE users SET sid='$sid' WHERE uid=$uid";
$q=$this->conn->query($q_string);
$_SESSION['untitled']=$sid;
$_SESSION['untitled_u']=$u;
$_SESSION['untitled_p']=$p;
return $q?true:false;
}
function signout($uid) {
$sid='NULL';
$q_string="UPDATE users SET sid='$sid' WHERE uid=$uid";
$q=$this->conn->query($q_string);
$this->signin_stat=0;
$this->current_user=0;
$_SESSION['untitled']='';
unset($_SESSION['untitled']);
$_SESSION['teenoblog_first']='';
unset($_SESSION['teenoblog_first']);
unset($_POST);
session_destroy();
}
function mkPass($pass) {
$p1 = sha1($pass);
$salt = substr($p1,0,22);
$finalPass = crypt($p1,"$2a$11$".$salt."$");
return $finalPass;
}
function run() {
/*
* this function logs in the user automatically if the session is set
*/
session_start();
if(isset($_SESSION['untitled']) && isset($_SESSION['untitled_u']) && isset($_SESSION['untitled_p'])) {
$sid=$_SESSION['untitled'];
$u=$_SESSION['untitled_u'];
$p=$_SESSION['untitled_p'];
$q_string="SELECT uid FROM users WHERE sid='$sid' AND (uname='$u' OR emailid='$u') AND AES_DECRYPT(pass, CONCAT('$u', '$p'))='$p'";
$q=$this->conn->query($q_string);
if($q->num_rows==1) {
$c=$q->fetch_row();
$uid=$c[0];
$this->current_user=new User($uid, $this->conn);
$this->current_user->update_online_stat($this->conn);
$this->signin_stat=1;
return true;
} else {
signout(0);
return false;
}
}
}
}
</code></pre>
<p>Later in other webpages I'll need to access MySQLi connection object outside the <code>class Page</code> that is why I want to declare a t. Is that a security issue?</p>
|
[] |
[
{
"body": "<p>No. The <strong>visibility</strong> has little to do with security with that respect. (<a href=\"http://php.net/manual/en/language.oop5.visibility.php\" rel=\"nofollow\">PHP Document on Visibility</a>)</p>\n\n<p>In short:</p>\n\n<ul>\n<li>Public: Accessible by anything, within the object or outside.</li>\n<li>Private: Accessible only by that object.</li>\n<li>Protected: Accessible only by that object and objects that extend that object.</li>\n</ul>\n\n<p>Give a method (or property) only the scope it needs. A DB class needs to be able to send and receive information, and would need public methods (but NOT properties, they should be private or protected at most). Remember, not declaring it as public/private/protected means it will be public.</p>\n\n<p>Other tips for your code:</p>\n\n<ol>\n<li>Make your db information/setup its own class and use that class everywhere else.</li>\n<li>Use a PDO system and not the mysql* functions in PHP. This is the best thing you can do to work on increasing security.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T19:07:15.043",
"Id": "33126",
"Score": "1",
"body": "`A DB class needs to be able to send and receive information, and would need public methods (and properties)` This sentence worries me. As a rule of thumb, I don't make member variables public unless changing them at any point can't break the execution of the class, and it's very rare for that to be the case in DB classes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T19:08:23.637",
"Id": "33127",
"Score": "1",
"body": "@MrLore I agree. As soon as posted it and started thinking about it, a DB class should only need public methods for it's properties at most. It's properties should be private or protected. Updated answer with this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T11:10:12.507",
"Id": "33151",
"Score": "0",
"body": "How does declaring a variable as `global` affect security?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T15:51:40.897",
"Id": "33167",
"Score": "1",
"body": "Do some searching on global variables in php: http://stackoverflow.com/a/5166527/84162 I'm going to try an analogy: **private** is inside your body. **protected** in is your pocket. **public** is your shirt. **global** is a whiteboard you hold above your head with the information on it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T19:01:52.983",
"Id": "20655",
"ParentId": "20640",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T15:27:24.453",
"Id": "20640",
"Score": "-1",
"Tags": [
"php",
"classes",
"mysqli",
"scope"
],
"Title": "Is declaring a property as `public` insecure?"
}
|
20640
|
<p>I don't want to extend the functionality of this method to include say library objects. I'm just looking for feedback on what it currently does.</p>
<p>ES5, section 8.6.2 "exposes" these global objects. I added a few Browser or "Host" objects which I needed for my purposes.</p>
<p>If needed I can add some more Browser or Host objects but no library objects as there is too much variety here. (i.e. jQuery, Backbone, etc.).</p>
<pre><code>/*log
** dependencies - none
** browser - N/A
**
*/
$A.error = $A.report = $A.log = function (obj, note) {
var logger,
temp,
type,
ES5a = ['Arguments', 'Array', 'Object'],
ES5b = ['Boolean', 'Date', 'Error', 'Function', 'JSON', 'Math',
'Number', 'Null', 'RegExp', 'String', 'Undefined'],
kindex,
length;
note = note || '';
if (window.console) {
logger = window.console.log.bind(window.console);
} else {
return;
}
type = Object.prototype.toString.call(obj).slice(8, -1);
if (!type) {
logger("Object type not found: ");
logger(obj);
return;
}
// Language Objects
for (kindex in ES5a) {
if (type === ES5a[kindex]) {
try {
temp = JSON.stringify(obj, null, 1);
} catch (error) {
temp = false;
}
if (temp) {
logger("LOG|" + ES5a[kindex] + ">" + note + ">" + temp);
} else {
logger("LOG|" + ES5a[kindex] + ">" + note + ">");
logger(obj);
}
return;
}
}
for (kindex in ES5b) {
if (type === ES5b[kindex]) {
logger("LOG|" + ES5b[kindex] + ">" + note + ">" + obj);
return;
}
}
// Host Objects
if (type === 'Event') {
logger("LOG|B|Event>" + note + ">");
if (obj.type) {
logger("LOG|Event.type>> " + obj.type);
}
temp = obj.target || obj.srcElement;
if (temp && temp.id) {
logger("LOG|Event.target.id>> " + temp.id);
}
return;
}
if (type === 'HTMLDivElement') {
logger("LOG|B|Div>" + note + ">");
if (obj.id) {
logger("LOG|Div.id>> " + obj.id);
}
return;
}
if (type === 'Storage') {
for (kindex in obj) {
if (obj.hasOwnProperty(kindex)) {
logger("LOG|Storage>" + note + ">" + kindex + " | " + obj[kindex]);
}
}
return;
}
if (type === 'HTMLCollection') {
for (kindex = 0, length = obj.length; kindex < length; kindex++) {
logger("LOG|HTMLCollection>" + note + ">" + kindex + " | " + obj[kindex]);
}
return;
}
// Library Objects
if (win.jQuery && (obj instanceof win.jQuery)) {
logger('LOG|jQuery object>');
return;
}
// Not Found
logger("LOG|B|NotFound>" + note + "> obj: " + obj + " | str: " + type);
};
</code></pre>
|
[] |
[
{
"body": "<p><code>JSON.stringify</code> is a dangerous function. It fails, and thus your function too, on cyclic objects, on very deep or big objects, or simply on objects having some forbidden accessor deeply cached.</p>\n\n<p>This object can't be logged by your function, for example : </p>\n\n<pre><code>var a = {}; a.b=a;\n</code></pre>\n\n<p>A related problem is that you only test the type of the external object. You don't detect the problem on this one :</p>\n\n<pre><code>var a = {parent:window};\n</code></pre>\n\n<p>What I would suggest is</p>\n\n<ul>\n<li>either the addition of a try/catch (which may not be totally satisfying as some stringifications take time and memory before they fail),</li>\n<li>to use or build another stringification function (see <a href=\"https://stackoverflow.com/q/13861254/263525\">related SO question</a>)</li>\n<li>or simply to avoid the JSON format (of course it depends on your goal)</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T18:56:22.003",
"Id": "20654",
"ParentId": "20643",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T15:58:04.517",
"Id": "20643",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "NS.log (ES5 logger) - v0"
}
|
20643
|
<p>I have the below code:</p>
<pre><code>public interface IRepositoryService
{
/// <summary>
/// This will add conditions like Published = true, Deleted = false and PublisehdDate smaller than NOW
///
/// </summary>
IRavenQueryable<T> AddConditionsToQueryToLoadOnlyAvailableForFrontend<T>(IRavenQueryable<T> query) where T : BaseObject;
}
public class HomepageBannerRepository : BaseRepository<HomepageBanner>, IHomepageBannerRepository
{
public HomepageBannerRepository(IRepositoryService repositoryService)
: base(repositoryService)
{
}
public List<HomepageBanner> GetHomepageBanners()
{
var q = CreateQuery(loadOnlyItemsAvailableToFrontend: true, autoSortByPriority: true);
var list = q.ToList();
return list;
}
}
</code></pre>
<p>The method <code>IRepositoryService.AddConditionsToQueryToLoadOnlyAvailableForFrontend()</code> adds general conditions to any query like <code>Published=True</code> and <code>Deleted=False</code>, as all my objects inherit from <code>BaseObject</code> which contains fields like <code>Published</code>, <code>Deleted</code> etc.</p>
<p>This has been tested, and for the method <code>HomepageBannerRepository.GetHomepageBanners()</code>, I would only like to verify that it was called (using mocks), rather than having to check via unit-testing that only published items are returned.</p>
<p>The current unit test I created is as below (using the <code>SpecsFor</code> framework)</p>
<pre><code> [TestFixture]
public class GetHomepageBannerSpecs
{
[TestFixture]
public class when_method_is_called : SpecsForRepository<HomepageBannerRepository>
{
private HomepageBanner _bannerA;
private HomepageBanner _bannerB;
private HomepageBanner _bannerC;
private List<HomepageBanner> _results;
private HomepageBanner createHomepageBanner()
{
HomepageBanner banner = new HomepageBanner();
banner.Store();
return banner;
}
protected override void Given()
{
_bannerA = createHomepageBanner();
_bannerB = createHomepageBanner();
_bannerC = createHomepageBanner();
GetMockFor<IRepositoryService>();
base.Given();
}
protected override void When()
{
_results = SUT.GetHomepageBanners();
base.When();
}
[Test]
public void then_it_should_return_all_homepage_banners()
{
GetMockFor<IRepositoryService>().Verify(x => x.AddConditionsToQueryToLoadOnlyAvailableForFrontend(It.IsAny<IRavenQueryable<HomepageBanner>>()), Times.Once());
GetMockFor<IRepositoryService>().Verify(x => x.AddSortByPriorityToQuery(It.IsAny<IRavenQueryable<HomepageBanner>>()), Times.Once());
_results.ShouldContain(_bannerA);
_results.ShouldContain(_bannerB);
_results.ShouldContain(_bannerC);
}
}
}
</code></pre>
<p>The main problem stems from that the actual implementation of <code>HomepageBannerRepository.GetHomepageBanners()</code> requires that the implementation of the <code>IRepositoryService</code> returns a query, when <code>IRepositoryService.AddConditionsToQueryToLoadOnlyAvailableForFrontend</code> is called. Since I am using a mock, this returns NULL, and then it throws an <code>ObjectNullReference</code> exception.</p>
<p>First of all, is it possible to setup the Mock to return the same parameter passed as input parameter? Something like:</p>
<pre><code>GetMockFor(IRepositoryService).Setup(x=>x.AddConditionsToQueryToLoadOnlyAvailableForFrontend(query)).Returns(query);
</code></pre>
<p>I am using <code>Moq</code> as my mocking framework.</p>
<p>Also, I would like to receive any criticism regarding code, and where it could be structured better with regards to unit-testing / Test-Driven Development, dependency injection and any other comments are greatly welcome.</p>
|
[] |
[
{
"body": "<p>Nice thing in participating/answering in forums like this is that you learn while you answer questions. I haven't heard about SpecsFor framework. Looks a bit tricky, but will definitely have a look later. Ok, back to your question :)</p>\n\n<p>About your first question, setting up the mock - you can definitely do that, there are a number of overloaded <code>Returns</code> methods accepting delegate/lambda, depending on the number of parameters in the method being setup (here I setup the method to always return the same query regardless of the query passed:</p>\n\n<pre><code>GetMockFor(IRepositoryService)\n .Setup(x => x.AddConditionsToQueryToLoadOnlyAvailableForFrontend(It.IsAny<IRavenQueryable<HomepageBanner>>()))\n .Returns(q => q);\n</code></pre>\n\n<p>The code overally looks good except that Ayende suggests (and I completely agree with him) not to wrap RavenDB sessions into repositories. I would just create an extension method to add these filters to <code>IRavenQueryable<T> where T:BaseObject</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T16:41:09.157",
"Id": "20648",
"ParentId": "20644",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T16:01:40.917",
"Id": "20644",
"Score": "4",
"Tags": [
"c#",
"unit-testing",
"dependency-injection",
"moq"
],
"Title": "Mock/unit test for this IRepositoryService method/class"
}
|
20644
|
<p>I know the code is full of useless data and stylistic and analysis errors and I'd really love and appreciate to have a pro's idea about it so I can learn to code (and think) better.</p>
<pre><code>import os, time
from ConfigParser import SafeConfigParser
configfilename = "imhome.ini"
scriptpath = os.path.abspath(os.path.dirname(__file__))
configfile = os.path.join(scriptpath, configfilename)
parser = SafeConfigParser()
parser.read(configfile)
ip_smartphone = parser.get('imhome', 'ip_smartphone')
mac_address_pc = parser.get('imhome', 'mac_address_pc')
hometime_path = parser.get('imhome', 'hometime_path')
in_path = parser.get('imhome', 'in_path')
mp3_path = parser.get('imhome', 'mp3_path')
maximum_time_before_logout = parser.get('imhome', 'maximum_time_before_logout')
if os.path.exists(hometime_path) == False:
os.system ("touch " + str(hometime_path))
if os.path.exists(in_path) == True:
os.system ("rm " + str(in_path))
finished = 1
while finished == 1:
check_presence = os.system ("ping -w 1 " + str (ip_smartphone) + " >/dev/null")
file_modification_time = (os.path.getmtime(hometime_path))
file_delta_time = time.time() - file_modification_time
if check_presence == 0 :
os.system ("rm " + str(hometime_path))
change_arrived=("echo " + str(check_presence) + " > hometime")
os.system (change_arrived)
if os.path.exists(in_path) == False:
# You can add any custom commands to execute when home below this row
os.system ("etherwake " + str(mac_address_pc))
os.system ("mpg123 " + str(mp3_path) + " >/dev/null")
os.system ("touch " + str(in_path))
# stop adding commands
elif check_presence == 256 and file_delta_time > int(maximum_time_before_logout):
if os.path.exists(in_path) == True:
os.system ("rm " + str(in_path))
</code></pre>
|
[] |
[
{
"body": "<p>Neat idea with that script. It looks good; not bad for the first program. Just a few comments:</p>\n\n<ol>\n<li>I would improve some variable names: <code>file_modification_time</code> -> <code>phone_last_seen_time</code>, <code>file_delta_time</code> -> <code>phone_unseen_duration</code>. When I was reading the program it took me some time to figure out their purpose.</li>\n<li>Use <code>while True:</code> instead of <code>while finished == 1:</code> so it is immediately clear that it is an infinite loop.</li>\n<li>In the line <code>change_arrived=(\"echo \" + str(check_presence) + \" > hometime\")</code> you probably want <code>str(hometime_path)</code> instead of <code>\"hometime\"</code>.</li>\n<li>It would be also good to describe purpose of some variables in comments. Mainly <code>hometime_path</code> and <code>in_path</code>.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T17:53:21.570",
"Id": "20652",
"ParentId": "20646",
"Score": "6"
}
},
{
"body": "<p>I would add a <code>time.sleep(1)</code> call at the end of the loop. Without that I had to kill the program from the shell to stop it, as it was not responding to <kbd>Ctrl</kbd>-<kbd>C</kbd>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T06:39:15.013",
"Id": "20666",
"ParentId": "20646",
"Score": "1"
}
},
{
"body": "<h3>1. Comments on your code</h3>\n\n<ol>\n<li><p>You make quite a lot of use here of <a href=\"http://docs.python.org/2/library/os.html#os.system\"><code>os.system</code></a>, which runs a command in a subshell. This can be a risky function to use, because the shell can do anything. For example, you write</p>\n\n<pre><code>os.system (\"rm \" + str(hometime_path))\n</code></pre>\n\n<p>but what if <code>hometime_path</code> were <code>-rf *</code>?</p>\n\n<p>You're probably safe in this particular program because it's only for your own use and because the strings come from your own configuration file. But it's worth getting into the habit of doing this kind of thing properly, so that in situations which really <em>are</em> risky, you'll know what to do.</p>\n\n<p>In the case of <code>rm</code> you can use <a href=\"http://docs.python.org/2/library/os.html#os.unlink\"><code>os.unlink</code></a>:</p>\n\n<pre><code>os.unlink(hometime_path)\n</code></pre>\n\n<p>But in the general case, use <a href=\"http://docs.python.org/2/library/subprocess.html#subprocess.call\"><code>subprocess.call</code></a> and use the <code>--</code> argument (if necessary) to make sure that the arguments you pass cannot be misinterpreted as options. For example,</p>\n\n<pre><code>subprocess.call(['rm', '--', hometime_path])\n</code></pre>\n\n<p>In a case where you want to redirect standard output, like this:</p>\n\n<pre><code>os.system (\"ping -w 1 \" + str (ip_smartphone) + \" >/dev/null\")\n</code></pre>\n\n<p>you can use the <code>stdout</code> keyword argument to <code>subprocess.call</code>:</p>\n\n<pre><code>subprocess.call(['ping', '-w', '1', '--', ip_smartphone],\n stdout = open('/dev/null', 'w'))\n</code></pre></li>\n<li><p>Most of your calls to <code>str</code> are unnecessary: these configuration parameters ought to be strings already. (If they are not, I think it you'd prefer to get an exception so that you could fix the problem, rather than silently coercing the incorrect value to a string.)</p></li>\n<li><p>You don't need to compare booleans explicitly to <code>True</code> and <code>False</code>. So instead of:</p>\n\n<pre><code>if os.path.exists(in_path) == True:\n</code></pre>\n\n<p>just write:</p>\n\n<pre><code>if os.path.exists(in_path):\n</code></pre>\n\n<p>and instead of:</p>\n\n<pre><code>if os.path.exists(hometime_path) == False:\n</code></pre>\n\n<p>just write:</p>\n\n<pre><code>if not os.path.exists(hometime_path):\n</code></pre></li>\n<li><p>In this code you remove a file only if it exists:</p>\n\n<pre><code>if os.path.exists(in_path) == True:\n os.system (\"rm \" + str(in_path))\n</code></pre>\n\n<p>But the <code>rm</code> command already has a option for this, so you could write instead:</p>\n\n<pre><code>subprocess.call(['rm', '-f', '--', in_path])\n</code></pre>\n\n<p>Or do it in pure Python:</p>\n\n<pre><code>try:\n os.unlink(in_path)\nexcept OSError: # No such file or directory\n pass\n</code></pre>\n\n<p>(This is an example of how it is often better to ask for forgiveness than permission.)</p></li>\n<li><p>Assuming that <code>\" > hometime\"</code> is a mistake for <code>\" > \" + hometime_path</code> (as suggested in another answer), then in this bit of code:</p>\n\n<pre><code>os.system (\"rm \" + str(hometime_path))\nchange_arrived=(\"echo \" + str(check_presence) + \" > hometime\")\nos.system (change_arrived)\n</code></pre>\n\n<p>you remove a file and then overwrite it with the value of <code>check_presence</code>. There's no need to remove the file first: the second command will overwrite it if it exists.</p>\n\n<p>And in any case this is easy to do in pure Python:</p>\n\n<pre><code>with open(hometime_path, 'w') as f:\n f.write('{}\\n'.format(check_presence))\n</code></pre></li>\n<li><p>You use the modification time of the file <code>hometime_path</code> to remember the last time that your <code>ping</code> command succeeded. Why not remember this time in a variable in Python and avoid having to create and delete and examine this file?</p></li>\n<li><p>You use the existence of the file <code>in_path</code> to remember whether your smartphone is connected. Why not remember this fact in a variable in Python and avoid having to create and delete and examine this file?</p></li>\n</ol>\n\n<h3>2. Rewrite</h3>\n\n<p>Making the above improvements results in something like this (but this is untested, so beware):</p>\n\n<pre><code>import os, subprocess, time\nfrom ConfigParser import SafeConfigParser\nfrom datetime import datetime, timedelta\n\nconfigfilename = \"imhome.ini\"\nscriptpath = os.path.abspath(os.path.dirname(__file__))\nconfigfile = os.path.join(scriptpath, configfilename)\nparser = SafeConfigParser()\nparser.read(configfile)\nip_smartphone = parser.get('imhome', 'ip_smartphone')\nmac_address_pc = parser.get('imhome', 'mac_address_pc')\nmp3_path = parser.get('imhome', 'mp3_path')\ntimeout = timedelta(seconds = int(parser.get('imhome', 'maximum_time_before_logout')))\n\ndevnull = open('/dev/null', 'wb')\nconnected = False\ndisconnect_time = None\n\nwhile True:\n ping = subprocess.call(['ping', '-w', '1', '--', ip_smartphone],\n stdout = devnull)\n if ping == 0:\n disconnect_time = datetime.now() + timeout\n if not connected:\n connected = True\n subprocess.call(['etherwake', mac_address_pc])\n subprocess.call(['mpg123', mp3_path], stdout = devnull)\n elif ping == 256 and connected and datetime.now() > disconnect_time:\n connected = False\n time.sleep(1)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T13:41:06.870",
"Id": "33160",
"Score": "0",
"body": "This is seriously great fuel for my brain! I am VERY thankful also for the time you took to explain and incredibly rewrite the code! I'll hide it in my drawer and try to write it on my own to check how I do compared to you.\nIf you happen to be in central Italy you have a dinner paid! :D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-28T13:56:45.453",
"Id": "33666",
"Score": "0",
"body": "I'm finally back from my holidays and I am trying to understand better your work... I can't get how you handle time...\nIf I print the variables to understand what is going on I still can't get it.\nThe main problem is timeout.\nin timeout you get the number of seconds defined in the config file, right?\nAnd then you use this to calculate disconnect_time adding this very moment to maximum time before logout?\nWhy?\nMaybe it's just a mistake (you told me it wasn't checked) but I am a newbie so... :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-28T14:03:30.760",
"Id": "33667",
"Score": "0",
"body": "The idea is that `disconnect_time` is the clock time at which the program will consider the smartphone to be disconnected if it hasn't received any more ping responses by then. Each time a ping response is received, we update `diconnect_time` to a be a bit further in the future. But if we don't receive any ping responses, we leave it unchanged, until eventually `datetime.now() > disconnect_time`. (This is a standard idiom for timeout processing.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-28T14:29:23.403",
"Id": "33668",
"Score": "0",
"body": "Mmmh ok...\n\nBut why to you sum it with timeout (which is the value included in my config file)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-28T14:33:46.080",
"Id": "33669",
"Score": "0",
"body": "Suppose that your config file has timeout = 15 seconds. Then each time we receive a ping response, we set `disconnect_time = datetime.now() + timeout`. That is, `disconnect_time` now represents a time 15 seconds in the future. If we haven't received any more ping responses by then, we'll consider the smartphone to be disconnected."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-28T16:34:54.233",
"Id": "33684",
"Score": "0",
"body": "I am trying to debug it to understand better (putting print variables to understand what is going on) and it seems that it gets to execute commands just a single time. It never gets in connected = False again..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-28T16:38:23.287",
"Id": "33685",
"Score": "0",
"body": "If you're not getting to the line `connected = False`, that means that one of the previous conditions is not true. That is, either `ping` is not 256, or `connected` is false, or `datetime.now()` is before `disconnect_time`. Which is these is the case? (It could be that `ping == 256` is the wrong way to test for ping failure, for example. I just copied that from your original script. On my operating system, `ping` exits with status 2 if it fails to get a response from the host.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-28T16:41:00.367",
"Id": "33686",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/7285/discussion-between-pitto-and-gareth-rees)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-29T08:25:16.337",
"Id": "33742",
"Score": "0",
"body": "Copy and paste is your enemy!\n\nAll the indentation was blown away: it works perfectly and I've understood it.\n\nThanks a lot, again :)"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T12:57:08.823",
"Id": "20676",
"ParentId": "20646",
"Score": "14"
}
}
] |
{
"AcceptedAnswerId": "20676",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T16:29:00.560",
"Id": "20646",
"Score": "19",
"Tags": [
"python",
"beginner",
"child-process",
"raspberry-pi"
],
"Title": "Automatically turn on Computer from Raspberry Pi (based on user presence in home)"
}
|
20646
|
<p>I am currently programming, but I messed up my code. What is the best way to clean this?</p>
<p>buttonUitvoeren_Click_1:</p>
<pre><code>private void buttonUitvoeren_Click_1(object sender, EventArgs e)
{
buttonNoodstop.Enabled = true;
buttonPauze.Enabled = true;
buttonUitvoeren.Enabled = false;
// Orderlijst uitvoeren en meteen nieuwe status wegschrijven wanneer order klaar is
if (orderLijst.Count > 0)
{
// tussen orders kijken of er gespoeld moet worden eerste beker
for (int t = 0; t < orderLijst.Count; t++)
{
// kijk naar laatste beker in huidige en eerste in volgende om te kijken of er gespoeld moet worden
if (t > 0 && t < orderLijst.Count)
{
if (orderLijst[t].BekerList[(orderLijst[t].BekerList.Count - 1)].PercentageKleur !=
orderLijst[t + 1].BekerList[(orderLijst[t + 1].BekerList.Count - 1)].PercentageKleur)
{
orderLijst[t + 1].BekerList[(orderLijst[t + 1].BekerList.Count - 1)].Spoelen = true;
orderLijst[t + 1].Spoelingen++;
orderLijst[t + 1].Tijd += 40;
}
// refresh listview met nieuwe tijd en spoelingen
refreshList();
}
// ordernummer setten zodat deze gebruikt kan worden in pauze methode
currentorder = orderLijst[t].OrderNummer;
// zolang order nog niet klaar is
while (orderLijst[t].OrderStatus != "Klaar")
{
// ga alle bekers in de order af
for (int i = 0; i < orderLijst[t].BekerList.Count; i++)
{
// spoelen van beker
if (orderLijst[t].BekerList[i].Spoelen == true && orderLijst[t].BekerList[i].Gespoeld == false)
{
// nieuwe beker aanmaken met 0 % kleur
Beker beker = new Beker(0);
thread = new Thread(() => newAanvoerband.Beweeg(new Beker(0)));
thread.Start();
while (beker.Klaar == false && thread.IsAlive == true)
{
// Blijf acties uitvoeren in huidige thread(Form)
Application.DoEvents();
// Abort thread wanneer spoelen klaar is of wanneer noodstop actief wordt
if (noodstop == true || beker.Klaar == true)
{
// afhankelijk van welke waar is de label setten
thread.Abort();
if (noodstop == true)
{
// zorgen dat hij uit de loop springt
t = orderLijst.Count + 1;
i = orderLijst[t].BekerList.Count + 1;
addToLogListView("Noodstop is geactiveerd op order:" + orderLijst[t].OrderNummer);
}
if (beker.Klaar == true)
{
addToLogListView("Er is succesvol gespoeld");
}
}
}
}
// "normale" uitvoer van beker , met mengverhouding etc
while (orderLijst[t].BekerList[i].Klaar == false && noodstop == false)
{
thread = new Thread(() => newAanvoerband.Beweeg(orderLijst[t].BekerList[i]));
thread.Start();
while (thread.IsAlive == true && noodstop == false)
{
// Blijf acties uitvoeren in huidige thread(Form)
Application.DoEvents();
// Abort thread wanneer beker klaar is of wanneer noodstop actief wordt
if (orderLijst[t].BekerList[i].Klaar == true || noodstop == true)
{
thread.Abort();
if (noodstop == true)
{
// zorgen dat hij uit de loop springt
t = orderLijst.Count + 1;
i = orderLijst[t].BekerList.Count + 1;
addToLogListView("Order:" + orderLijst[t].OrderNummer + " is beeindigt");
}
else if (orderLijst[t].BekerList[i].Klaar == true)
{
if (orderLijst[t].BekerList[i].Gespoeld == false && orderLijst[t].BekerList[i].Klaar == true)
{
addToLogListView("Beker " + i + " is gevult");
}
}
}
else if (pauzestand == true)
{
addToLogListView("Order:" + orderLijst[t].OrderNummer + " is gepauzeerd");
}
else if (pauzestand == false && noodstop == false && orderLijst[t].BekerList[i].Klaar == false)
{
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
// Zolang de uitvoer nog bezig is en noodstop niet geactiveert is
}
}
}
// einde bekerlijst
addToLogListView("Order:" + orderLijst[t].OrderNummer + " is met succes afgerond");
orderLijst[t].OrderStatus = "Klaar";
// Als de status klaar is , schrijf nieuwe status naar textfile
if (noodstop == false && orderLijst[t].OrderStatus == "Klaar")
{
// Leeg orders.txt
try
{
File.WriteAllText(filesOrdersOrderstxt, String.Empty);
}
catch (Exception ex)
{
addToLogListView("Error while emptying:" + ex.Message);
}
// Schrijf de orders in orderLijst naar Orders.txt
try
{
StreamWriter sw = File.AppendText(filesOrdersOrderstxt);
refreshList();
foreach (ListViewItem writeorder in orderListView.Items)
{
sw.WriteLine(writeorder.SubItems[0].Text + seperator + writeorder.SubItems[1].Text);
}
sw.Close();
}
catch (Exception ex)
{
addToLogListView("Error while writing:" + ex.Message);
}
// Wanneer het programma klaar is met uitvoeren mag er weer uitgevoerd worden
buttonUitvoeren.Enabled = true;
}
}
}
// einde orderlijst
addToLogListView("Alle " + orderLijst.Count.ToString() + " orders zijn klaar.");
timer.Stop();
}
// Als er geen orders ingevoerd zijn
else
{
buttonNoodstop.Enabled = false;
buttonPauze.Enabled = false;
buttonUitvoeren.Enabled = true;
addToLogListView("Er zijn geen orders ingevoerd");
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T18:41:41.113",
"Id": "33122",
"Score": "3",
"body": "You are mixing English with ... Dutch? in comments, variable names and messages. I suppose messages must remain in the original language in the final code, but not knowing what it says would help understanding the logic better too. Could you make those changes? Also, at the end of the day you should not need so many comments."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T22:57:03.060",
"Id": "33185",
"Score": "0",
"body": "I moved your further comments back into the question as they were not an answer, just expanding on the question :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T22:58:44.337",
"Id": "33186",
"Score": "0",
"body": "As for your question, they are an improvement. The standards look good, you have removed almost all of the comments and replaced them with intuitive names for your methods. You seem to understand what methods are used for now, and separating the domain logic from your ui logic."
}
] |
[
{
"body": "<p>I would start by trying to extract methods from your code. My general rule of thumb is that a method should be small enough to fit on the screen without having to scroll up or down.</p>\n\n<p>Here is an example:</p>\n\n<pre><code>if (t > 0 && t < orderLijst.Count)\n{\n if (orderLijst[t].BekerList[(orderLijst[t].BekerList.Count - 1)].PercentageKleur !=\n orderLijst[t + 1].BekerList[(orderLijst[t + 1].BekerList.Count - 1)].PercentageKleur)\n {\n orderLijst[t + 1].BekerList[(orderLijst[t + 1].BekerList.Count - 1)].Spoelen = true;\n orderLijst[t + 1].Spoelingen++;\n orderLijst[t + 1].Tijd += 40;\n }\n\n // refresh listview met nieuwe tijd en spoelingen\n refreshList();\n}\n</code></pre>\n\n<p>Could become:</p>\n\n<pre><code>private void ProcessOrderIfInRange(int t)\n{\n if (t <= 0 || t >= orderLijst.Count)\n {\n return;\n }\n\n if (orderLijst[t].BekerList[(orderLijst[t].BekerList.Count - 1)].PercentageKleur !=\n orderLijst[t + 1].BekerList[(orderLijst[t + 1].BekerList.Count - 1)].PercentageKleur)\n {\n orderLijst[t + 1].BekerList[(orderLijst[t + 1].BekerList.Count - 1)].Spoelen = true;\n orderLijst[t + 1].Spoelingen++;\n orderLijst[t + 1].Tijd += 40;\n }\n\n refreshList();\n}\n</code></pre>\n\n<p>and in your main method:</p>\n\n<pre><code>for (int t = 0; t < orderLijst.Count; t++)\n{\n ProcessOrderIfInRange(t);\n\n // ...\n</code></pre>\n\n<p>I also find you are using too many comments (from what I can read of them). For example, when I see a method <code>refreshList()</code>, I know that is probably going to refresh a list. a comment like <code>// refresh listview met nieuwe tijd en spoelingen</code> is unnecessary. One thing though, you might want to rename <code>refreshList()</code> to something which explains it a bit better, i.e. <code>RefreshListViewWithUpdatedData()</code></p>\n\n<p>I also noticed you are not following C# standards. In C# method names start with a capital: <code>RefreshList()</code> (Pascal Case), local variable names start with a low case letter (Camel). I'd suggest you read <a href=\"http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/f75d6cb4-084f-4f2a-95c0-6d7f1b67c978\">Microsoft's Page</a> on casing.</p>\n\n<p>I also find you have WAY to many nested if statements. Things get really confusing when you start trying to figure out the code path. Using the same method extraction I mentioned above, you should be able to totally eliminate the nested ifs by pulling them out.</p>\n\n<pre><code>if (a)\n{\n if (b)\n {\n // Do something\n }\n else\n {\n // Do something\n }\n}\nelse\n{\n if (c)\n {\n // Do something\n }\n else\n {\n // Do something\n }\n}\n</code></pre>\n\n<p>Should be changed into</p>\n\n<pre><code>if (a)\n{\n ProcessB();\n}\nelse\n{\n ProcessC();\n}\n</code></pre>\n\n<p>where</p>\n\n<pre><code>private void ProcessB()\n{\n if (b)\n {\n // Do something\n }\n else\n {\n // Do something\n }\n}\n\nprivate void ProcessC()\n{\n if (c)\n {\n // Do something\n }\n else\n {\n // Do something\n }\n}\n</code></pre>\n\n<p>Of course ProcessB() and ProcessC() could be changed to return something if required.</p>\n\n<p>These suggestions are a start, try them out, see what you come up with and repost, your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T22:08:44.483",
"Id": "33143",
"Score": "2",
"body": "A good rule of thumb to add is that your event handler should do nothing more than verifying the event args and passing off to another method, preferably in another class (a controller or presenter, were you using the MVC/MVP pattern to structure your code). It also looks like you could be using LINQ to do sorting and processing your data for display in a more readable fashion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T09:51:28.947",
"Id": "33150",
"Score": "0",
"body": "Fantastic answer; in summary, more modular and less 'arrow-headed'."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T17:02:31.343",
"Id": "20649",
"ParentId": "20647",
"Score": "8"
}
},
{
"body": "<p>I see a problem in here:</p>\n\n<pre><code>for (int t = 0; t < orderLijst.Count; t++)\n {\n // kijk naar laatste beker in huidige en eerste in volgende om te kijken of er gespoeld moet worden\n if (t > 0 && t < orderLijst.Count)\n {\n if (orderLijst[t].BekerList[(orderLijst[t].BekerList.Count - 1)].PercentageKleur !=\n orderLijst[t + 1].BekerList[(orderLijst[t + 1].BekerList.Count - 1)].PercentageKleur)\n {\n orderLijst[t + 1].BekerList[(orderLijst[t + 1].BekerList.Count - 1)].Spoelen = true;\n orderLijst[t + 1].Spoelingen++;\n orderLijst[t + 1].Tijd += 40;\n }\n\n // refresh listview met nieuwe tijd en spoelingen\n refreshList();\n }\n</code></pre>\n\n<p>In this for loop you already declare that t will be less than orderLijst.Count so there is no need for checking it in if statement. Also, in this if statement you are using t>0, shich means that you will skip first element of orderLijst, and I suppose that it shouldn't be that way.\nTo sum it up, I would avoid this line:</p>\n\n<pre><code>if (t > 0 && t < orderLijst.Count)\n</code></pre>\n\n<p>And if you really need t to have value larger than 0 in this part of code, you can leave only</p>\n\n<pre><code>if(t > 0)\n</code></pre>\n\n<p>Hope this helps.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T20:17:01.820",
"Id": "20727",
"ParentId": "20647",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T16:31:08.930",
"Id": "20647",
"Score": "2",
"Tags": [
"c#",
"homework"
],
"Title": "Where to start refactoring?"
}
|
20647
|
<p>just I wan to ask how to improve my code especially contact info block </p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Compudata_ProjectManager.CodeFile.BOL;
using System.Web.Security;
namespace Compudata_ProjectManager
{
public partial class NeCustomer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// return early - nothing to do
if (Page.IsPostBack)
{
return;
}
// redirect early - no need to continue
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
Response.Redirect("~/Account/Login.aspx");
}
//get logged in user id UserID from MembershipUser
MembershipUser memberUser = Membership.GetUser();
string StrUserID = memberUser.ProviderUserKey.ToString();
Guid userID = Guid.Parse(StrUserID);
//hf_userID.Value = userID.ToString();
if ( HideGridViewsIFCIstomerIsNew())
{
int customerID = int.Parse(Request.QueryString["customerID"]);
Customer cust = Customer.GetCustomerDetail(customerID);
PopulateControls(cust);
p_contactsHTML.Visible = false;
p_locationHTML.Visible = false;
}
}
/// <summary>
/// this Function will hide the gv_Contacts & gv_location if Custoemr Has Contact and work location
/// </summary>
/// <returns></returns>
public bool HideGridViewsIFCIstomerIsNew()
{
return (gv_Contacts.Rows.Count > 0 && gv_location.Rows.Count > 0);
}
/// <summary>
/// PopulateControls
/// </summary>
/// <param name="cust"></param>
private void PopulateControls(Customer cust)
{
ddl_title.SelectedValue = cust.Title;
txtb_firstName.Text = cust.FirstName;
txtb_lastName.Text = cust.LastName;
txtb_postion.Text = cust.Postion;
ddl_gender.SelectedValue = cust.Gender.ToString();
ddl_company.SelectedValue = cust.CompanyID.ToString();
btn_add.Visible = false;
}
/// <summary>
/// Add new Contact to customer table
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btn_add_Click(object sender, EventArgs e)
{
try
{
Customer customer = new Customer();
customer.Title = ddl_title.SelectedValue.ToString();
customer.FirstName = txtb_firstName.Text;
customer.LastName = txtb_lastName.Text;
customer.Postion = txtb_postion.Text;
customer.Gender = Convert.ToChar(ddl_gender.SelectedValue.ToString());
customer.CompanyID = Convert.ToInt32(ddl_company.SelectedValue.ToString());
//Contact Info
List<Contacts> contactsList = new List<Contacts>
{
new Contacts {
ContactDetail = txtb_contact1.Text
,LabelContactTypeID = Convert.ToInt32(hf_officephone.Value)
,Status = chb_active_Contact1.Checked
,Notes = txtb_noteContact1.Text},
new Contacts {
ContactDetail = txtb_contact2.Text
,LabelContactTypeID = Convert.ToInt32(hf_cell.Value)
,Status = chb_active_Contact1.Checked
,Notes = txtb_noteContact2.Text},
new Contacts {
ContactDetail = txtb_contact3.Text
,LabelContactTypeID = Convert.ToInt32(hf_email.Value)
,Status = chb_active_Contact1.Checked
,Notes = txtb_noteContact3.Text},
new Contacts {
ContactDetail = txtb_contact4.Text
,LabelContactTypeID = Convert.ToInt32(hf_other.Value)
,Status = chb_active_Contact1.Checked
,Notes = txtb_noteContact4.Text}
};
//customer contact inforation
Location local = new Location();
local.Address = txtb_address.Text;
local.City = Convert.ToString(ddl_city.SelectedValue);
local.Province = Convert.ToString(ddl_provinces.SelectedValue);
local.PostalCode = txtb_postalCode.Text;
local.Note = noteLocation1.Value;
bool successedAddCustomer_Contacts = Customer.AddNewCustomer_Contact(customer, contactsList, local);
if (!successedAddCustomer_Contacts)
{
lb_msg.Text ="contact added";
Response.Redirect("~/CustomersManagement/NeCustomer.aspx");
}
else
lb_msg.Text = "Can't add new customer";
}
catch
{ }
}
//adding more customer contact
protected void gv_imgbtn_AddContact_Click(object sender, ImageClickEventArgs e)
{
Contacts contact = new Contacts();
DropDownList gv_ddl_ContactType = (DropDownList)gv_Contacts.FooterRow.FindControl("gv_ddl_ContactType");
TextBox gv_txtb_contactDetail = (TextBox)gv_Contacts.FooterRow.FindControl("gv_txtb_contactDetail");
CheckBox gv_ChkB_Active = (CheckBox)gv_Contacts.FooterRow.FindControl("gv_ChkB_Active");
TextBox gv_txtb_notes = (TextBox)gv_Contacts.FooterRow.FindControl("gv_txtb_notes");
contact.CustomerID = Convert.ToInt32(Request.QueryString["customerID"]);
contact.ContactDetail = gv_txtb_contactDetail.Text;
contact.LabelContactTypeID = Convert.ToInt32(gv_ddl_ContactType.SelectedValue.ToString());
contact.Status = gv_ChkB_Active.Checked;
contact.Notes = gv_txtb_notes.Text;
try
{
bool successedAddCustomer_Contacts = Contacts.AddNewCustomer_Contacts(contact);
if (!successedAddCustomer_Contacts)
{
var customerID = Convert.ToInt32(Request.QueryString["customerID"]);
Response.Redirect("~/NeCustomer.aspx?companyID=" + customerID.ToString());
}
else
lb_msg.Text = "Can't add new customer";
}
catch
{
lb_msg.Text = "Can't add new customer";
}
}
// adding more location to customer
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
//location object
TextBox gv_txtb_address = (TextBox)gv_location.FooterRow.FindControl("gv_txtb_address");
DropDownList gv_ddl_city = (DropDownList)gv_location.FooterRow.FindControl("gv_ddl_city");
DropDownList gv_ddl_province = (DropDownList)gv_location.FooterRow.FindControl("gv_ddl_province");
TextBox gv_txtb_postalCode = (TextBox)gv_location.FooterRow.FindControl("gv_txtb_postalCode");
TextBox gv_txtb_note = (TextBox)gv_location.FooterRow.FindControl("gv_txtb_note");
Location local = new Location();
local.CustomerID = Convert.ToInt32(Request.QueryString["customerID"]);
local.Address = gv_txtb_address.Text;
local.City = gv_ddl_city.SelectedValue.ToString();
local.Province = gv_ddl_province.SelectedValue.ToString();
local.PostalCode = gv_txtb_postalCode.Text;
local.Note = gv_txtb_note.Text;
try
{
bool successedAddCustomer_Contacts = Location.Add_Customer_Locations(local);
if (!successedAddCustomer_Contacts)
{
var customerID = Convert.ToInt32(Request.QueryString["customerID"]);
Response.Redirect("~/NeCustomer.aspx?customerID=" + customerID.ToString());
}
else
lb_msg.Text = "Can't add new customer";
}
catch
{
lb_msg.Text = "Can't add new customer";
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-10T20:09:13.377",
"Id": "34626",
"Score": "0",
"body": "You can use the Model View Presenter pattern to abstract away the GUI - head over to pluralsight-training.net"
}
] |
[
{
"body": "<p>A couple minor changes I would make in the loading. I didn't review the rest. I am assuming (probably correctly) that <code>memberUser.ProviderUserKey</code> is always a <code>Guid</code> at runtime.</p>\n\n<pre><code> //get logged in user id UserID from MembershipUser\n MembershipUser memberUser = Membership.GetUser();\n\n // redirect early - no need to continue\n if (memberUser == null)\n {\n Response.Redirect(\"~/Account/Login.aspx\");\n }\n\n Guid userID = (Guid) memberUser.ProviderUserKey;\n</code></pre>\n\n<p>You may want to use <code>TryParse</code> for <code>Request.QueryString[\"customerID\"]</code>, as the QueryString is user input which may not be valid.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T22:09:37.313",
"Id": "20693",
"ParentId": "20653",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20693",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T18:04:18.493",
"Id": "20653",
"Score": "1",
"Tags": [
"c#",
"asp.net"
],
"Title": "improve & review NewCustomer page?"
}
|
20653
|
<p>So I would be very grateful if you could check these four tasks - I'm a Java newbie and recently coded such things on a Introduction to CS test which I didn't score so well at and would love to know where my mistakes were, what I should do some other way and how can I get better at it to score higher again :)</p>
<blockquote>
<p>1> Write a method that takes an array of integers (you can assume the
amount is divisble by four) and decodes them in the said manner:</p>
<ul>
<li>add 15 to each integer unless it's equal to 0</li>
<li>divide the numbers in four-integer sub-words</li>
<li>let the first charater become the third, the fourth one be the first, the third - the second and the second be the last
<br><br>For example, {97,90,82,0} should output " api".</li>
</ul>
</blockquote>
<pre><code>public static String decipher(int[] specArray)
{
String finalWord = "";
for(int i=0; i<specArray.length; ++i)
{
if(specArray[i]!=0) specArray[i]+=15;
}
for(int i=0; i<specArray.length; i+=4)
{
finalWord+=(char)specArray[i+3];
finalWord+=(char)specArray[i+2];
finalWord+=(char)specArray[i];
finalWord+=(char)specArray[i+1];
}
return finalWord;
}
</code></pre>
<blockquote>
<p>2> Write a method that takes a String as an argument and also returns
a String and processes it from left to right as follows:</p>
<ul>
<li>if it finds a, it should add two a's to the result</li>
<li>if it finds two adjacent b's or one b alone, it should add one b to the result</li>
<li>if it finds two c's, it should add them both to the result. If it finds one c only, it should skip it.</li>
</ul>
<p><br>For example: "abaabbcbaccb" returns "aabaaaabbaaccb" and
"bbbbbbb" returns "bbbb".</p>
</blockquote>
<pre><code>public static String processWord(String inputWord)
{
String outputWord = "";
for(int i=0; i<inputWord.length(); ++i)
{
switch(inputWord.charAt(i)){
case 'a':
outputWord+="aa";
break;
case 'b':
if(((i+1)<inputWord.length())&&(inputWord.charAt(i+1)=='b')) // if there's at least one char left in the string and the next is b
{
i+=1;
}
outputWord += 'b';
break;
case 'c':
if(((i+1)<inputWord.length())&&(inputWord.charAt(i+1)=='c')) // if there's at least one char left in the string and the next is c
{
outputWord += "cc";
i+=1;
}
break;
}
}
return outputWord;
}
</code></pre>
<blockquote>
<p>3> Create a class MyClass with two class variables - myNumber of type
double and myString of type String. Also, add a default constructor
giving myNumber a value of 13.13 and myString value "some string" and
a constructor taking a double and String parameters, then assigning
them to myNumber and myString respectively. Add appropriate methods
for getting and setting the values of the class.</p>
</blockquote>
<pre><code>public class MyClass {
private double myNumber;
private String myString;
// CONSTRUCTORS
public MyClass(){
myNumber = 13.13;
myString = "some string";
}
public MyClass(double d, String s){
myNumber = d;
myString = s;
}
// METHODS
public double getNumber()
{
return myNumber;
}
public void setNumber(double newN)
{
myNumber = newN;
}
public String getString()
{
return myString;
}
public void setString(String newS)
{
myString = newS;
}
}
</code></pre>
<blockquote>
<p>4> Create a method working similarly to String.indexOf() but taking as
parameters a source String in which it should look and String
containing the word it should look for in the source. It should return
an integer array containing all the occurrences of said sub-word in a
word denoted by indexes of the first letters.</p>
<p>For example, ("ThiDFUs iDFs a DF D DFU sample.", "DFU") should return
an array containing 3 and 20.</p>
</blockquote>
<pre><code>public static int[] differentIndexOf(String source, String divisor)
{
ArrayList<Integer> occurrenceFound = new ArrayList<Integer>();
int suspectedStart=-1;
for(int i=0; i<source.length(); ++i) // check the whole word letter-by-letter
{
if(source.charAt(i)==divisor.charAt(0)) // if one of the letters corresponds the first one of the separator:
{
suspectedStart = i;
for(int j=1; j<divisor.length(); ++j) // check the ones after it until the separator is fully used
{
if(source.charAt(i+j) != divisor.charAt(j)) suspectedStart = -1; // (^) or until you find a difference
}
}
if(suspectedStart != -1) {occurrenceFound.add(suspectedStart);} // if no differences found in (^) => occurrence found
suspectedStart = -1;
}
int[] finalArray = new int[occurrenceFound.size()];
for(int i=0; i<finalArray.length; ++i)
{
finalArray[i] = occurrenceFound.get(i);
}
return finalArray;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-09T04:00:59.100",
"Id": "169139",
"Score": "1",
"body": "It's best to just have one exercise per question, especially if they're unrelated."
}
] |
[
{
"body": "<p>Hmmmm...</p>\n\n<p>1> This looks mostly okay. Probably the biggest help for you would be to extract adding the offset (15) to another method. This should change your algorithm from O(2n) to O(n); that is, you only have to loop through the array once, instead of twice:</p>\n\n<pre><code>private static final int OFFSET = 15;\n\nprivate static char offsetCharacter(final int character) {\n return (char) (character == 0 ? character : character + OFFSET);\n}\n</code></pre>\n\n<p>Also, string concatenation is not really that efficient; you should probably use a <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/StringBuilder.html\" rel=\"nofollow\">StringBuilder</a>, which will allow for the fastest writes (well, probably). And a little error checking never hurt, even in cases where you are allowed 'assumptions. Oh, and some of your names could use a little work.</p>\n\n<pre><code>private static final int WORD_LENGTH = 4;\n\npublic static String decipher(final int[] encodedCharacters) {\n\n if (encodedCharacters == null || encodedCharacters.length == 0 || encodedCharacters.length % WORD_LENGTH != 0) {\n throw new IllegalArgumentException(\"Requires input array sized as multiple of \" + WORD_LENGTH);\n }\n\n final StringBuilder decoded = new StringBuilder(encodedCharacters.length);\n\n for(final int i = 0; i < encodedCharacters.length; i += WORD_LENGTH) {\n\n decoded.append(offsetCharacter(encodedCharacters[i + 3]));\n decoded.append(offsetCharacter(encodedCharacters[i + 2]));\n decoded.append(offsetCharacter(encodedCharacters[i + 0]));\n decoded.append(offsetCharacter(encodedCharacters[i + 1]));\n\n }\n\n return decoded.toString();\n}\n</code></pre>\n\n<p>Unfortunately, I couldn't figure out a good way to deal with the swapping...</p>\n\n<hr />\n\n<p>2> You're using String concatenation again, when you should be using a StringBuilder. Things are a little convoluted here, probably due to the requirements for b/c (actually, I'm pretty sure that was the point). Ideally, you'd be able to use <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html\" rel=\"nofollow\">Regex</a>. Unfortunately, I'm not that great with it at the moment.<br>\nI'm assuming that all other characters are ignored (like you do). Oh, even if there isn't anything to actually process, it's usually best to put a 'default' case in switch statements, as a deliberate declaration of expectation. Somehow, it seems a little clumsy right now, but I haven't been able to come up with anything better...</p>\n\n<hr />\n\n<p>3> Nothing much to go wrong with here. You avoided the easy trap of making <code>myString</code> or <code>myNumber</code> non-private. Some general stuff:</p>\n\n<p>Usually, when you have constructors that set defaults, and one that requires all parameters, make the 'defaulting' ones use the other:</p>\n\n<pre><code>public MyClass() {\n this(13.13, \"some string\");\n}\n\npublic MyClass(double d, String s) {\n myNumber = d;\n myString = s;\n}\n</code></pre>\n\n<p>Also, getters/setters tend to have the <em>entire</em> name of the variable, instead of just part of it (so, <code>getMyNumber()</code>). Note that this will depend on local coding styles to an extent; actually here, I'd probably prefer your choice, given the awkward names chosen by your professor. Also, for setters, the name of the passed in parameter is often the same as the parameter it's setting, and the <code>this</code> reference is used to differentiate them: </p>\n\n<pre><code>public void setNumber(double myNumber) {\n this.myNumber = myNumber;\n}\n</code></pre>\n\n<p>Oh, and the requirements didn't list them, but it's a good idea to put Javadoc on every exposed member (class, variable, and method). Getters and Setters are usually pretty boring, though.</p>\n\n<hr />\n\n<p>4> The requirements are a little sparse on this one. I mean, it doesn't restrict me from using something like the <a href=\"http://commons.apache.org/lang/api/index.html\" rel=\"nofollow\">Apache Commons Utils</a>. Heck, it doesn't say you aren't allowed to use <code>String.indexOf()</code> <em>inside</em> your method - although that obviously isn't the intent of the problem. I'm going to assume that you're limited to the 'standard' JDK libraries. And that you aren't allowed to use Regex here.<br>\nOh, never use end-of-line comments. </p>\n\n<pre><code>ArrayList<Integer> occurrenceFound = new ArrayList<Integer>();\n</code></pre>\n\n<p>Whenever possible, use the <em>least specific</em> (most generic) object possible:</p>\n\n<pre><code>List<Integer> occurrenceFound = new ArrayList<Integer>();\n</code></pre>\n\n<p>Oh, you don't actually need to check <em>every</em> character in the string:</p>\n\n<pre><code>for(int i = 0; i < source.length(); ++i) {\n ....\n}\n</code></pre>\n\n<p>After all, if you find the starting character as the <em>last</em> character, it's going to be a given it's not going to match, right? What's the <em>actual</em> last character you need to check?</p>\n\n<pre><code>int[] finalArray = new int[occurrenceFound.size()];\n</code></pre>\n\n<p>Learn your libraries - the interface <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html#toArray%28%29\" rel=\"nofollow\">Collection</a> defines a couple of methods that would probably be helpful.</p>\n\n<p>Breaking things up a little (and just using arrays) makes it a bit cleaner. I'd really prefer some sort of 'Collections' based approach (ie something that <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/List.html\" rel=\"nofollow\">List.subList()</a> would work with), but that's probably too 'heavy'. </p>\n\n<pre><code>public static int[] differentIndexOf(String source, String divisor) {\n\n final char[] characters = source.toCharArray();\n final char[] search = divisor.toCharArray();\n\n final int[] occurrences = new int[characters.length - search.length + 1];\n int occurrenceCount = 0;\n\n for (int i = 0; i < characters.length - search.length; i++) {\n if (stringMatches(characters, i, search)) {\n occurrences[occurrenceCount] = i;\n occurrenceCount++;\n }\n }\n\n return Arrays.copyOf(occurrences, occurrenceCount);\n}\n\nprivate static boolean stringMatches(char[] characters, int index, char[] search) {\n for (int i = 0; i + index < characters.length && i < search.length; i++) {\n if (characters[i + index] != search[i]) {\n return false;\n }\n }\n\n return true;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T20:33:32.133",
"Id": "33135",
"Score": "1",
"body": "Your big-O claim is confused. Technically, `O(n) = O(2n)`, there is no difference between the two classes. In terms of efficiency there is no reason to believe that combining the two loops will help at all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T20:48:29.600",
"Id": "33137",
"Score": "0",
"body": "@WinstonEwert - You're right, when compared to other progressions, there is no difference. And the array access are likely to be fast regardless. Still, it's usually best to attempt to reduce multiple iterations to one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T20:51:05.843",
"Id": "33139",
"Score": "1",
"body": "Why is it best to attempt to reduce the multiple iterations?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T16:45:11.033",
"Id": "33170",
"Score": "0",
"body": "@WinstonEwert - Assuming that array access has a non-zero cost (and all operations will still otherwise be performed), the 'cost' of the function has been reduced by the length of the input. 2bn array access rather than 4bn sounds better to me. While not as applicable to this situation, there are some languages that provide built-in mechanisms for operating on an array in parallel - however, they really only work for a single iteration. With chained function steps (and preferably more than here), programs can really fly over data processing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T18:25:47.210",
"Id": "33172",
"Score": "0",
"body": "Thank you very much for the thorough explanation of my mistakes! :) The only thing I have a question about: in 4>, shouldn't _final int[] occurrences = new int[characters.length - search.length];_ be _final int[] occurrences = new int[characters.length/search.length+1];_? In the first case, it would create a 0-element array in case the search word is of even length to the source while it still can contain one instance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T18:45:44.363",
"Id": "33177",
"Score": "1",
"body": "Ack! You're right about the `+ 1` bit. However, given current requirements, you can't use `characters.length / search.length` - if you have a string of repeating characters, and a search string of the same characters (but shorter), there will be a 'starting' occurrence for every character (until `search.length` before the end). I'd wanted to use the divided version too, originally."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T19:03:45.247",
"Id": "33179",
"Score": "0",
"body": "You're right, it would crash on (\"bbbbb\", \"bb\"), for example. Also, we'd have to add an additional if in case of search.length being 0 (empty string as the search word). Thanks a lot once again :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T19:21:15.930",
"Id": "33180",
"Score": "0",
"body": "Yeah, I didn't test stuff well enough. This is why, whenever you do any sort of coding, get a whole bunch of expected inputs/outputs you can run through it. Any decent set of test inputs for 4 would have revealed the deficiencies right off."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T21:18:26.373",
"Id": "33182",
"Score": "0",
"body": "I do not agree when you say \"it's a good idea to put Javadoc on every exposed member (class, variable, and method)\". This just bloats the code. I really believe that if you choose proper names for variables and methods, no comments are needed. Of course, if we're writing an API or so, Javadoc is a must. For the rest +1."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T20:21:43.427",
"Id": "20659",
"ParentId": "20656",
"Score": "2"
}
},
{
"body": "<p>In (3), its bad practice to update the counter of the for loop inside the body of the for loop.</p>\n\n<p>It's better to use a while() loop here, since each iteration of the loop may consume multiple tokens from the input string.</p>\n\n<p>For (4), this may be not be in the spririt of the question, but there already is an indexOf(substring, startIndex) method in Java which would be much more appropriate here. Not sure if you are restricted from using that though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T18:26:48.130",
"Id": "33173",
"Score": "0",
"body": "Thank you a lot :) Yep, I was restricted from using indexOf, forgot to mention it as it was only verbally stated, not mentioned in the specs ;)\n\nAlso, why is additional incrementing of the counter inside for loop bad whilst being acceptable for while loop?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T18:42:18.730",
"Id": "33175",
"Score": "1",
"body": "Its mostly about clarity. If we see for (int i=0; i < 100; i++), most developers automatically assume it will get executed 100 times. If we see a while or a do loop, we expect the number of iterations to be variable."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T22:08:45.040",
"Id": "20661",
"ParentId": "20656",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "20659",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T19:10:22.107",
"Id": "20656",
"Score": "2",
"Tags": [
"java"
],
"Title": "Four basic Java exercises - what should have been done better?"
}
|
20656
|
<p>I'm building an authentication system using a combination of PHP, MySQL, jQuery, and AJAX. The way I'm doing it right now is I have a form that takes in a username and password. When the user clicks on the login button I pass the value of those two values along with an action to a controller file. That controller file will use an Authentication object (I wrote my own Authentication class) to determine if the user is authenticated or not. If so, it will return a string that says "authenticated" or something similar. I check for that value in the response of the AJAX request and go from there based on the response. Of course I do all sorts of server side checks so someone can't just navigate to a certain section or tamper with my jQuery to trick the system. It's all enforced behind the scenes.</p>
<p>Is this acceptable? Is there any major problem with doing this the way I am? Here are some snippets of my code that is responsible for handling all this:</p>
<p>Login section:</p>
<pre><code><div data-role="content">
<div class="center" id="loginContainer" data-role="fieldcontain">
<input id="username" type="text" placeholder="Username" />
<input id="password" type="password" placeholder="Password" />
<br />
<a id="loginButton" href="#" data-role="button" data-inline="true">Login</a>
</div>
</div>
</code></pre>
<p>jQuery:</p>
<pre><code>$(document).on("click", "#loginButton", function() {
var user = $("#username").val();
var pass = $("#password").val();
$.post("controllers/auth.php", {"action": "authenticate", "user": user, "pass": pass}, function(data) {
if(data == "authenticated") {
//stuff
}
});
});
</code></pre>
<p>Controller:</p>
<pre><code>if(isset($_POST['action']) && $_POST['action'] == "authenticate") {
$credentials = array("user" => $_POST['user'], "pass" => $_POST['pass']);
$auth = new Auth($dbh, $ldaps, $credentials);
if($auth->authenticate()) {
echo "authenticated";
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Do all URLs on your site use SSL? If not you'll need to setup your site to at least support the authenticate URL over HTTPS.<br>\nCurrently your passing a plain text Username and Password - anyone can grab them.</p>\n\n<p>On requests after the login, how are you determining whether or not the user is authenticated?\nIt does not look like you are persisting the login in any way, unless Auth class is doing it behind the scenes. Typically this is done with a session variable or cookie.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T20:36:51.503",
"Id": "33136",
"Score": "0",
"body": "I don't have SSL enabled at the moment but I will eventually. Since it's not finished yet I am really more concerned with my implementation since I haven't done too many authentication systems with AJAX.\n\nThe way I'm checking to see if they're authenticated is by checking a certain session variable on pages that are in an administration folder. I didn't post all of the checking, sanitization, and persistence code because everything is working the way it should; I just want to make sure that the way I'm handling the initial login with AJAX was okay."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T20:49:03.377",
"Id": "33138",
"Score": "0",
"body": "Will people be logging in from a non-SSL page? If so, it will quickly become a large concern and you'll want to start looking at how that will affect your login function now, because of the 'same domain origin policy'."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T20:51:15.827",
"Id": "33140",
"Score": "1",
"body": "Separate from SSL and any security issues, everything else looks typical."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T20:52:55.200",
"Id": "33141",
"Score": "0",
"body": "Nope, the login and all pages following will be over SSL. Thank you for your feedback!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T20:21:15.023",
"Id": "20658",
"ParentId": "20657",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "20658",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T20:12:37.030",
"Id": "20657",
"Score": "0",
"Tags": [
"php",
"jquery",
"mysql",
"security",
"ajax"
],
"Title": "Authentication system using AJAX"
}
|
20657
|
<p>I use this simple time method to time intervals. It basically just consolidates some simple math.</p>
<pre><code>/*time
** dependencies - none
** browser - unknown
**
*/
NS.time = (function () {
var measurements = [];
return function (control) {
var index,
intervals = [],
time_current = new Date().getTime();
if (control === 'start') {
measurements = [];
measurements.push(time_current);
return;
}
if (control !== 'finish') {
measurements.push(time_current);
return;
}
if (control === 'finish') {
measurements.push(time_current);
index = measurements.length;
while (index) {
index--;
intervals[index - 1] = (measurements[index] - measurements[index - 1]) + 'ms';
}
return intervals;
}
};
}());
</code></pre>
|
[] |
[
{
"body": "<p>Since <code>start</code>, <code>middle</code> and <code>finish</code> are pretty much \"verbs\", why not make them actions of the object <code>time</code>? With that, an API like this would do:</p>\n\n<pre><code>$.time.start();\n$.time.middle();\n$.time.finish();\n</code></pre>\n\n<p>Further, a developer might run multiple instances of a timer to track more than just one something. Maybe a developer would like to run one timer for a page load while another set of timers for image loading. Thus, it would be better if we created instances:</p>\n\n<pre><code>//returns an instance id'ed by \"pageload\"\n//passing blank creates only one anonymous timer\nvar pageLoadTimer = $.time('pageload');\n\n//methods\npageLoadTimer.start();\npageLoadTimer.middle();\npageLoadTimer.finish();\n\n//or simply chain\n$.time('pageload').start();\n\n//if you lose reference because you are not on the same scope\n//or forgot to make one \n//or didn't make one at all and relied on the globality of jQuery\n//calling a timer of the same name returns an existing timer\n$.time('pageload').middle();\n</code></pre>\n\n<p>Anyways, with that adapted code, a result would be (as verbose as I can):</p>\n\n<pre><code>$.time = (function () {\n\n //our timer cache\n var timers = {};\n\n //extract common code\n function getCurrentTimestamp() {\n return new Date().getTime();\n }\n\n //constructor to our instances\n //each with a name, time collection and difference collection\n function Timer(timerName) {\n this.name = timerName;\n this.times = [];\n this.perf = [];\n this.lastPerfIndex = 0;\n }\n\n //since the initialization has been done in the constructor\n //we remove it from start. but since start and middle does\n //the same thing, we merge it as \"ping\"\n Timer.prototype.ping = function () {\n this.times.push(getCurrentTimestamp());\n return this;\n };\n\n //calculate\n //a developer might want to get performance data\n //before actually finishing, thus the rename\n Timer.prototype.calculate = function () {\n\n //caching a few variables from the instance\n var perf = this.perf,\n times = this.times,\n timesLength = times.length, //getting n-1 length\n i = this.lastPerfIndex; //perfIndex explained further down\n\n //ping our last time check\n this.ping();\n\n //now a reverse loop would only make the code longer\n //a forward loop would make it much simpler\n while (i <= timesLength) {\n\n //now a developer might want to get performance data\n //but you would not want to calculate the entire set again\n //thus we store a last index, so the next call starts from here\n this.lastPerfIndex = i;\n\n //now since we are in order, use push instead\n //of manually jotting down the index\n perf.push(times[i + 1] - times[i]);\n }\n return perf;\n };\n\n //lets implement finish as a destroy function instead\n Timer.prototype.finish = function(){\n //remove this timer from cache\n delete timers[this.name];\n //return performance data\n return this.calculate;\n }\n\n\n return function (timerName) {\n if (timers[timerName]) {\n //if timer with name exists, return existing\n return timers[timerName];\n } else {\n //or cache and return a new one\n //creating a new one does not start it immediately\n //useful for stuff like preloading stuff or something\n return timers[timerName] = new Timer(timerName);\n }\n };\n}());\n</code></pre>\n\n<p>In the end, usage might look like this:</p>\n\n<pre><code>//create a timer\n$.timer('foo');\n\n//aw snap! i forgot to reference, we can retrieve it\nvar foo = $.timer('foo').ping(); //lets start!\n\n//some lines later, let's mark this period\n$.timer('foo').ping(); //by retrieval\nfoo.ping(); //by reference \"foo\"\n\n//let's get the performance array without killing this timer\nvar perfAfterTenKlines = foo.calculaate();\n\n//let's get the performance array gain after 20 lines\n//this time it calculates only data since last calculate\nvar perfAfterTwentyKlines = foo.calculate();\n\n//ok we're done. lets get the final data and call it a day\nvar perfAfterOneMlines = foo.finish();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T02:42:24.820",
"Id": "20663",
"ParentId": "20662",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "20663",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T01:13:32.803",
"Id": "20662",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Release - NS.time"
}
|
20662
|
<p>Just curious if this is a reasonable idea. I wouldn't do it all the time. The example I'm in now is that of the data context and repository that uses it.</p>
<p>I kind of like this because, compared to calling <code>new</code> in <code>AssignButtonClicked</code>, it gives my code the same quality of feeling independent of resource allocation as when using constructor injection (which I can't do for short lived resources).</p>
<pre><code>void AssignButtonClicked(object sender, EventArgs e)
{
WithPaymentBatchRepository((context, repository) =>
{
foreach (var itemIDs in this.SelectedItemIdsAsInts)
{
repository.SetPaymentBatchId(itemIDs, this.SelectedPaymentBatchId);
}
context.SaveChanges();
});
Refill();
}
static void WithPaymentBatchRepository(Action<EomTool.Domain.Entities.EomEntities, EomTool.Domain.Concrete.PaymentBatchRepository> action)
{
using (var context = new EomTool.Domain.Entities.EomEntities(EomAppCommon.EomAppSettings.ConnStr, false))
{
var repository = new EomTool.Domain.Concrete.PaymentBatchRepository(context);
action(context, repository);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T11:24:23.413",
"Id": "33153",
"Score": "1",
"body": "Is `WithPaymentBatchRepository` going to be called elsewhere or only from `AssignButtonClicked`? Or there gonna be other helper methods of the same style for other user actions?"
}
] |
[
{
"body": "<blockquote>\n <p>it gives my code the same quality of feeling independent of resource allocation as when using constructor injection</p>\n</blockquote>\n\n<p>But it's not. With constructor injection, the caller can easily use another implementation or create the resource with different parameters. With your helper method, that is gone. And you <em>can</em> use constructor injection with short lived resources: inject a factory for that resource (that could be a simple <code>Func<Resource></code> delegate or an interface) instead of the resource itself.</p>\n\n<p>All in all, your helper method might be useful to avoid repeating common code, but not much else. And even with that, it doesn't help much.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T19:47:27.917",
"Id": "33181",
"Score": "0",
"body": "that's a good idea to inject a factory. thanks for the tip!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T13:07:15.740",
"Id": "20677",
"ParentId": "20664",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "20677",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T03:23:28.437",
"Id": "20664",
"Score": "3",
"Tags": [
"c#"
],
"Title": "Do you like this kind of helper, which creates short lived helper objects through a delegate?"
}
|
20664
|
<p>I've created this scheme to preserve function calls until all the arguments are available. The <code>stub_op</code> classes will be replaced with classes that implement a <code>forward</code>-like mechanism that receives notifications when a forward is finished.</p>
<p>I wanted to have a way to set up a function call that turned into a forward that was complete as soon as the function's arguments were available.</p>
<p>So I came up with this. Could this be done more simply?</p>
<pre><code>#include <functional>
#include <memory>
#include <type_traits>
#include <tuple>
struct base_stub_op {
typedef ::std::shared_ptr<base_stub_op> ptr_t;
virtual ~base_stub_op() noexcept(true) = default;
};
template <typename ResultType>
struct stub_op : public base_stub_op {
typedef base_stub_op::ptr_t base_ptr_t;
typedef ::std::shared_ptr<stub_op<ResultType> > ptr_t;
typedef ResultType result_type;
virtual ResultType result() const { return ResultType(); }
static ptr_t create() {
return ::std::make_shared<stub_op<ResultType>>();
}
};
template <typename ResultType>
struct stub_const_op : public stub_op<ResultType> {
typedef ::std::shared_ptr<stub_const_op<ResultType> > ptr_t;
typedef ResultType result_type;
explicit stub_const_op(ResultType &&val)
: val_(::std::move(val))
{ }
explicit stub_const_op(const ResultType &val)
: val_(val)
{ }
ResultType result() const { return val_; }
static ptr_t create(ResultType &&val) {
return ::std::make_shared<stub_const_op<ResultType>>(::std::move(val));
}
static ptr_t create(const ResultType &val) {
return ::std::make_shared<stub_const_op<ResultType>>(val);
}
private:
const ResultType val_;
};
template <typename ResultType>
struct stub_func_op : public stub_op<ResultType> {
typedef ::std::shared_ptr<stub_func_op<ResultType> > ptr_t;
typedef ResultType result_type;
typedef ::std::function<ResultType()> func_t;
explicit stub_func_op(func_t &&func)
: func_(::std::move(func))
{ }
explicit stub_func_op(const func_t &func)
: func_(func)
{ }
virtual ~stub_func_op() noexcept(true) { }
ResultType result() const { return func_(); }
static ptr_t create(func_t &&func) {
return ::std::make_shared<stub_func_op<ResultType>>(::std::move(func));
}
static ptr_t create(const func_t &func) {
return ::std::make_shared<stub_func_op<ResultType>>(func);
}
private:
const func_t func_;
};
template <typename T>
struct is_op_ptr {
private:
// Returns false_type, which has a ::value that is false.
template <class AT>
static constexpr std::false_type is_it_a_ptr(...);
// Returns true_type (if enable_if allows it to exist).
template <class AT>
static constexpr typename ::std::enable_if<
::std::is_same<
AT,
typename stub_op<typename AT::element_type::result_type>::ptr_t>::value,
std::true_type>::type // note the true_type return
is_it_a_ptr(int); // no definition needed
public:
// do everything unevaluated
static constexpr bool value = decltype(is_it_a_ptr<T>(0))::value;
};
template <typename T>
class transform_type
{
public:
static constexpr bool passthrough = is_op_ptr<T>::value;
typedef typename ::std::conditional< passthrough,
T,
typename stub_op<T>::ptr_t>::type type;
typedef T orig_type;
typedef decltype(::std::declval<type>()->result()) base_type;
transform_type(const type &o) : wrapped_(o) { }
transform_type(type &&o) : wrapped_(o) { }
template <typename U = T>
typename ::std::enable_if< ::std::is_same<U, T>::value && passthrough,
orig_type>::type
result() {
return wrapped_;
}
template <typename U = T>
typename ::std::enable_if< ::std::is_same<U, T>::value && !passthrough,
orig_type>::type
result() {
return wrapped_->result();
}
private:
type wrapped_;
};
template <typename ResultType, typename FuncT, typename TupleT>
class suspended_call {
public:
explicit suspended_call(FuncT func, TupleT args)
: func_(::std::move(func)), args_(::std::move(args))
{
}
// This can only be called once and will alter the state of the object so it
// cannot be called again.
ResultType operator()() {
typedef call_helper< ::std::tuple_size<TupleT>::value> helper_t;
return ::std::move(helper_t::engage(func_, args_));
}
private:
FuncT func_;
TupleT args_;
template <unsigned int N, unsigned int... I>
struct call_helper {
static ResultType engage(FuncT &func, TupleT &args) {
return ::std::move(call_helper<N - 1, N - 1, I...>::engage(func, args));
}
};
template <unsigned int... I>
struct call_helper<0, I...> {
static ResultType engage(FuncT &func, TupleT &args) {
return ::std::move(func(::std::get<I>(args).result()...));
}
};
};
template <typename ResultType, typename... ArgTypes>
class deferred {
public:
typedef typename stub_op<ResultType>::ptr_t deferred_t;
typedef ::std::function<ResultType(ArgTypes...)> wrapped_func_t;
explicit deferred(const wrapped_func_t &func)
: func_(func)
{
}
deferred_t until(const typename transform_type<ArgTypes>::type &... args) {
typedef ::std::tuple<transform_type<ArgTypes>...> argtuple_t;
argtuple_t saved_args = ::std::make_tuple(args...);
::std::function<ResultType()> f{suspended_call<ResultType, wrapped_func_t, argtuple_t>(func_, ::std::move(saved_args))};
return stub_func_op<ResultType>::create(f);
}
private:
const wrapped_func_t func_;
};
template <typename ResultType, typename... ArgTypes>
deferred<ResultType, ArgTypes...>
defer(::std::function<ResultType(ArgTypes...)> func)
{
return deferred<ResultType, ArgTypes...>(func);
}
template <typename ResultType, typename... ArgTypes>
deferred<ResultType, ArgTypes...>
defer(ResultType (*func)(ArgTypes...))
{
::std::function<ResultType(ArgTypes...)> f = func;
return deferred<ResultType, ArgTypes...>(::std::move(f));
}
</code></pre>
<hr>
<p>Example use:</p>
<pre><code>#include <sparkles/make_operation.hpp>
#include <iostream>
using ::std::cerr;
int a_function()
{
cerr << "In a_function.\n";
return 5;
}
int a_function2(int arg)
{
cerr << "In a_function(" << arg << ").\n";
return arg;
}
int main()
{
cerr << "Here 1\n";
auto func1 = defer(a_function).until();
cerr << "Here 2\n";
auto func2 = defer(a_function2).until(func1);
cerr << "Here 3\n";
cerr << "func2->result() == " << func2->result() << '\n';
}
</code></pre>
<p>The thing that this is actually eventually going to become a part of is called <a href="https://bitbucket.org/omnifarious/sparkles/overview" rel="nofollow">Sparkles</a>, and it's GPLv3, so the source code is there.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T15:43:43.750",
"Id": "33238",
"Score": "0",
"body": "Why out of my league. There are not that many C++ reviewers here (and fewer that I have seen have this kind of knowledge). You may want to try pinging somebody from this list to give you some help: http://stackoverflow.com/tags/c%2b%2b/topusers"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T18:17:51.310",
"Id": "33241",
"Score": "0",
"body": "@LokiAstari: I've done a bit of that, mostly by poking <Lounge C++>, but I'll try some more. Thanks!"
}
] |
[
{
"body": "<p>the very first and important question: <strong>what problem you are trying to solve with this code?</strong> Why do you think it's better than simple:</p>\n\n<pre><code>auto call_chain = []()\n{\n return a_function2(a_function());\n};\nstd::cerr << \"result == \" << call_chain() << std::endl;\n</code></pre>\n\n<p>your code doesn't allow to do smth in the middle of function calls -- i.e. smth like this:</p>\n\n<ul>\n<li>call <code>a_function()</code></li>\n<li>do smth while results available</li>\n<li>when result ready, pass it to <code>a_function2()</code></li>\n<li>do smth else</li>\n<li>wait/check for final result</li>\n</ul>\n\n<p>so, personally I see no reason to use your code (at least in it's current state)...</p>\n\n<p>anyway, some (not/less important) notes about your code:</p>\n\n<ul>\n<li>do not use <code>::std::smth</code> everywhere, <code>std::smth</code> quite enough</li>\n<li>put your code into your own namespace. put everything what is not a public API into <code>your_ns::details</code> namespace</li>\n<li>use <code>inline</code> for your template functions in a header to avoid 'function redeclaration' errors</li>\n<li>use <code>override</code> for <code>result()</code> in <code>stub_op</code> child classes</li>\n<li>why to use <code>shared_ptr</code>, why not <code>unique_ptr</code>?</li>\n<li>rethink semantic of your service classes and disable all not required (undesirable) ctors/assign operators for them to avoid use cases that shouldn't work</li>\n<li>currently <code>defer()</code> function won't work w/ labmdas and any user provided functors. to implement it in a better way, define it as <code>template <typename Func></code> and then you have to analyze that <code>Func</code> is a callable type (using <code>boost::function_types</code> or smth similar). cuz C++11 have no concepts, you may use <code>static_assert</code> with human readable message sayin that <code>defer</code> should be instantiated w/ callable types only...</li>\n<li>no need to override a function w/ <code>T&&</code>+<code>std::move</code> and <code>const T&</code> parameters. use <code>T&&</code> and <code>std::forward</code> instead.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T21:02:42.897",
"Id": "33558",
"Score": "0",
"body": "The library this will be incorporated in has something called a `remote_operation` which puts a notification on an inter-thread queue when it's done. A `remote_operation` is a type of `operation`. The `stub_op` class in the code above is a stand-in for the more complex `operation` class. While I was working on this, I didn't want to have to deal with the complexity of that class. Also, see this SO question to explain my stylistic use of `::std` everywhere: http://stackoverflow.com/questions/1661912/why-does-everybody-use-unanchored-namespace-declarations-i-e-std-not-std"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T21:04:37.013",
"Id": "33559",
"Score": "0",
"body": "+1 for the `inline` suggestion. Though most compilers nowadays emit 'weak' bindings for template expansions so there can be multiples with no complaints."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T21:05:36.437",
"Id": "33560",
"Score": "0",
"body": "And I would like `defer` to work with any callable. My overload for `function<ResultType(ArgT...)>` is a poor attempt at making that happen."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T21:08:14.703",
"Id": "33561",
"Score": "1",
"body": "I used `shared_ptr` because you might say something like `x = defer(...).until(foo); y = defer(...).until(foo);`. Poof, now you have two things depending on the same object's results. That object can't go away until both dependencies have fetched their results."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T21:16:40.373",
"Id": "33563",
"Score": "0",
"body": "@Omnifarious what kind of notifications do you use? I think (strognly believe) that using `boost::signals2` or (possible queue of shared) future/promises (`std` or `boost`) it would be possible to do the job simple than your approach. btw, `boost` allows to wait on multiple futures, in contrast to `std`. anyway if you are talking about _notifications_ `boost::signals2` is a first thing cames into my mind..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T21:18:55.237",
"Id": "33564",
"Score": "0",
"body": "@Omnifarious about `::std` vs `std` -- some ppl are just crazy: they do things that they shouldn't do, then they starts to fight w/ consequences of wrong decisions..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T21:37:52.833",
"Id": "33567",
"Score": "0",
"body": "Well, yes, they do stupid things. But I liken using `::std` to a good habit that you should be following with all the namespaces you use. If you give special treatment to `::std` you will forget to do it with a namespace for which it really matters. But anyway, I don't want to argue over that. If you want to, feel free to comment on my SO question. :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T21:40:43.363",
"Id": "33568",
"Score": "0",
"body": "@zuafi: Threads are expected to have a loop that works like this: `while (true) { wq.dequeue()(); }`. The notifications are functors that are executed in the context of the receiving thread."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-03-14T05:48:57.933",
"Id": "298531",
"Score": "0",
"body": "Thank you for pointing me at boost. I will take a look at the libraries you suggest to see if they do what I was looking to do."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T20:21:58.797",
"Id": "20942",
"ParentId": "20665",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T04:48:16.463",
"Id": "20665",
"Score": "3",
"Tags": [
"c++",
"c++11",
"template-meta-programming"
],
"Title": "Could this deferred execution scheme be any simpler?"
}
|
20665
|
<p>I'm writing a simple disassembler in C for learning. It is supposed to take a ELF file read in the contents of the ELF header then the individual program headers (potentially multiple) and print out various information on the file and then print each ARM code out.</p>
<p><strong>main.c</strong></p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include "elf.h"
void Disassemble(unsigned int *armI, int count, unsigned int startAddress);
void DecodeInstruction(unsigned int instr, unsigned int Address);
void HexToBinary(int *bits, unsigned int hex);
int SignExtend(unsigned int x, int bits);
int Rotate(unsigned int rotatee, int amount);
void PrintASCII(unsigned int instr);
void ProcessSWI(int *bits, unsigned int instr, char *instructionPtr);
void ProcessBranch(int *bits, unsigned int instr, unsigned int currentAddress, char *instructionPtr);
void ProcessDP(int *bits, unsigned int instr, char *instructionPtr);
void ProcessLDR(int *bits, unsigned int instr, char *instructionPtr);
void ProcessMUL (int *bits, unsigned int instr, char *instructionPtr);
void ProcessLDM(int *bits, unsigned int instr, char *instructionPtr);
int main(int argc, const char * argv[])
{
FILE *fp;
ELFHEADER elfhead;
int i;
unsigned int *armInstructions = NULL;
if(argc < 2)
{
fprintf(stderr, "Usage: DisARM <filename>\n");
return 1;
}
/* Open ELF file for binary reading */
if((fp = fopen(argv[1], "rb")) == NULL)
{
fprintf(stderr, "%s\n", argv[1]);
exit(EXIT_FAILURE);
}
/* Read in the header */
fread(&elfhead, 1, sizeof(ELFHEADER), fp);
if(!(elfhead.magic[0] == 0177 && elfhead.magic[1] == 'E' && elfhead.magic[2] == 'L' && elfhead.magic[3] == 'F'))
{
fprintf(stderr, "%s is not an ELF file\n", argv[1]);
return 2;
}
printf("\nFile-type: %d\n",elfhead.filetype);
printf("Arch-type: %d\n",elfhead.archtype);
printf("Entry: %x\n", elfhead.entry);
printf("Prog-Header: %x\n", elfhead.phdrpos);
printf("Prog-Header-count: %d\n", elfhead.phdrcnt);
printf("Section-Header: %x\n", elfhead.shdrpos);
/* Find and read program headers */
ELFPROGHDR *prgHdr;
fseek(fp, elfhead.phdrpos, SEEK_SET);
prgHdr = (ELFPROGHDR *)malloc(elfhead.phdrcnt * sizeof(ELFPROGHDR));
if(!prgHdr)
{
fprintf(fp, "Out of Memory\n");
fclose(fp);
return 3;
}
fread(prgHdr, 1, sizeof(ELFPROGHDR)*elfhead.phdrcnt, fp);
/* allocate memory and read in ARM instructions */
for(i = 0; i < elfhead.phdrcnt; i++)
{
printf("Segment-Offset: %x\n", prgHdr[i].offset);
printf("File-size: %d\n", prgHdr[i].filesize);
printf("Align: %d\n", prgHdr[i].align);
armInstructions = (unsigned int *)malloc(prgHdr[i].filesize + 3 & ~3);
if(armInstructions == NULL)
{
fclose(fp);
free(prgHdr);
fprintf(stderr, "Out of Memory\n");
return 3;
}
fseek(fp, prgHdr[i].offset, SEEK_SET);
fread(armInstructions, 1, prgHdr[i].filesize, fp);
/* Disassemble */
printf("\nInstructions\n\n");
Disassemble(armInstructions, (prgHdr[i].filesize + 3 & ~3) /4, prgHdr[i].virtaddr);
printf("\n");
free(armInstructions);
}
free(prgHdr);
fclose(fp);
return 0;
}
void Disassemble(unsigned int *armI, int count, unsigned int startAddress)
{
int i;
printf("Address Hex ASCII\tDisassembly\n");
printf("=============================================\n");
for(i = 0; i < count; i++)
{
printf("%08X %08X", startAddress + i*4, armI[i]);
DecodeInstruction(armI[i], startAddress + i*4);
printf("\n");
}
}
void DecodeInstruction(unsigned int instr, unsigned int Address)
{
int bits[32];
char instruction[100];
sprintf(instruction, "\0");
HexToBinary(bits, instr);
printf(" ");
PrintASCII(instr);
printf("\t");
if (instr == 0)
strcat(instruction, "NOP");
else if (bits[27] && bits[26] && bits[25] && bits[24])
ProcessSWI(bits, instr, instruction);
else if (bits[27] && !bits[26] && bits[25])
ProcessBranch(bits, instr, Address, instruction);
else if (!bits[27] && bits[26])
{
if (!bits[25])
ProcessLDR(bits, instr, instruction);
else if (bits[4])
strcat(instruction, "Undefined Instruction.");
else if (!bits[4])
ProcessLDR(bits, instr, instruction);
}
else if (bits[27] && !bits[26] && !bits[25])
ProcessLDM(bits, instr, instruction);
else if (!(bits[27] || bits[26] || bits[25] || bits[24] || bits[23] || bits[22]) && (bits[7] && !bits[6] && !bits[5] && bits[4]))
ProcessMUL(bits, instr, instruction);
else if (!bits[27] && !bits[26])
ProcessDP(bits, instr, instruction);
else
strcat(instruction, "Undefined Instruction.");
printf("%s", instruction);
/* DEBUG PRINT BINARY */
/*printf("\t\t");
for(int i=31;i>=0;i--)
{
printf("%d", bits[i]);
}*/
}
int SignExtend(unsigned int x, int bits)
{
int r;
int m = 1U << (bits - 1);
x = x & ((1U << bits) - 1);
r = (x ^ m) - m;
return r;
}
int Rotate(unsigned int rotatee, int amount)
{
unsigned int mask, lo, hi;
mask = (1 << amount) - 1;
lo = rotatee & mask;
hi = rotatee >> amount;
rotatee = (lo << (32 - amount)) | hi;
return rotatee;
}
void HexToBinary(int *bits, unsigned int hex)
{
int i;
for (i = 0; i < 32; i++)
{
bits[i] = (hex >> i) & 1;
}
}
void PrintCCode(unsigned int instr, char *instructionPtr)
{
switch((instr & 0xF0000000) >> 28)
{
case(13): strcat(instructionPtr, "LE"); break;
case(12): strcat(instructionPtr, "GT"); break;
case(11): strcat(instructionPtr, "LT"); break;
case(10): strcat(instructionPtr, "GE"); break;
case(9): strcat(instructionPtr, "LS"); break;
case(8): strcat(instructionPtr, "HI"); break;
case(7): strcat(instructionPtr, "VC"); break;
case(6): strcat(instructionPtr, "VS"); break;
case(5): strcat(instructionPtr, "PL"); break;
case(4): strcat(instructionPtr, "MI"); break;
case(3): strcat(instructionPtr, "CC/LO"); break;
case(2): strcat(instructionPtr, "CS/HS"); break;
case(1): strcat(instructionPtr, "NE"); break;
case(0): strcat(instructionPtr, "EQ"); break;
}
}
void PrintASCII(unsigned int instr)
{
char c[5];
int i;
c[0] = (instr & 0x000000FF);
c[1] = (instr & 0x0000FF00) >> 8;
c[2] = (instr & 0x00FF0000) >> 16;
c[3] = (instr & 0xFF000000) >> 24;
for(i = 0; i < 4; i++)
{
if(isalpha(c[i]) || ispunct(c[i]))
printf("%c", c[i]);
else
printf("*");
}
}
void ProcessSWI(int *bits, unsigned int instr, char *instructionPtr)
{
strcat(instructionPtr, "SWI");
PrintCCode(instr, instructionPtr);
sprintf(instructionPtr + strlen(instructionPtr), "\t%X", instr & 0x00FFFFFF);
}
void ProcessBranch(int *bits, unsigned int instr, unsigned int currentAddress, char *instructionPtr)
{
if ( bits[24] )
strcat(instructionPtr, "BL");
else
strcat(instructionPtr, "B");
PrintCCode(instr, instructionPtr);
sprintf(instructionPtr + strlen(instructionPtr), "\t&%X", (SignExtend((instr & 0x00FFFFFF) << 2, 26)) + currentAddress + 8);
}
void ProcessDP(int *bits, unsigned int instr, char *instructionPtr)
{
int DP = (instr & 0x01E00000) >> 21;
int Rd = (instr & 0x0000F000) >> 12;
int Rn = (instr & 0x000F0000) >> 16;
int Rot = (instr & 0x00000F00) >> 8;
int Op = (instr & 0x000000FF);
int Rm = (instr & 0x0000000F);
int Sh = (instr & 0x00000060) >> 5;
int Shift;
switch(DP)
{
case(15): strcat(instructionPtr, "MVN"); break;
case(14): strcat(instructionPtr, "BIC"); break;
case(13): strcat(instructionPtr, "MOV"); break;
case(12): strcat(instructionPtr, "ORR"); break;
case(11): strcat(instructionPtr, "CMN"); break;
case(10): strcat(instructionPtr, "CMP"); break;
case(9): strcat(instructionPtr, "TEQ"); break;
case(8): strcat(instructionPtr, "TST"); break;
case(7): strcat(instructionPtr, "RSC"); break;
case(6): strcat(instructionPtr, "SBC"); break;
case(5): strcat(instructionPtr, "ADC"); break;
case(4): strcat(instructionPtr, "ADD"); break;
case(3): strcat(instructionPtr, "RSB"); break;
case(2): strcat(instructionPtr, "SUB"); break;
case(1): strcat(instructionPtr, "EOR"); break;
case(0): strcat(instructionPtr, "AND"); break;
}
PrintCCode(instr, instructionPtr);
if (bits[20] && DP != 10 && DP != 11)
strcat(instructionPtr, "S");
if (DP != 11 && DP != 10)
sprintf(instructionPtr + strlen(instructionPtr), "\tR%d, ", Rd);
else
strcat(instructionPtr, "\t");
if (DP != 13 && DP != 15)
sprintf(instructionPtr + strlen(instructionPtr), "R%d, ", Rn);
if (bits[25])
{
if (!(bits[11] || bits[10] || bits[9] || bits[8]))
sprintf(instructionPtr + strlen(instructionPtr), "#&%X", Op);
else
sprintf(instructionPtr + strlen(instructionPtr), "#&%X", Rotate(Op, Rot*2));
}
else
{
if (bits[4])
Shift = (instr & 0x00000F00) >> 8;
else
Shift = (instr & 0x00000F80) >> 7;
sprintf(instructionPtr + strlen(instructionPtr), "R%d", Rm);
if (Shift > 0)
{
switch(Sh)
{
case(3): if(Shift == 0) strcat(instructionPtr, ", RRX"); else strcat(instructionPtr, ", ROR "); break;
case(2): strcat(instructionPtr, ", ASR "); break;
case(1): strcat(instructionPtr, ", LSR "); break;
case(0): strcat(instructionPtr, ", LSL "); break;
}
sprintf(instructionPtr + strlen(instructionPtr), "#&%X", Shift);
}
}
}
void ProcessLDR(int *bits, unsigned int instr, char *instructionPtr)
{
int sourceReg = (instr & 0x0000F000) >> 12;
int baseReg = (instr & 0x000F0000) >> 16;
int Rm = (instr & 0x0000000F);
int immediate = (instr & 0x00000FFF);
int Shift = (instr & 0x00000F80) >> 7;
int Sh = (instr & 0x00000060) >> 5;
if (bits[20])
strcat(instructionPtr, "LDR");
else
strcat(instructionPtr, "STR");
PrintCCode(instr, instructionPtr);
if (bits[22])
strcat(instructionPtr, "B");
sprintf(instructionPtr + strlen(instructionPtr), "\tR%d", sourceReg);
if (bits[24]) // Pre incremented
{
sprintf(instructionPtr + strlen(instructionPtr), ", [R%d", baseReg);
if (bits[25])
sprintf(instructionPtr + strlen(instructionPtr), ", R%d]", Rm);
else
{
if (immediate > 0)
sprintf(instructionPtr + strlen(instructionPtr), ", #%d]", immediate);
else
strcat(instructionPtr, "]");
}
if (bits[21])
strcat(instructionPtr, "!");
}
else // Post incremented
{
if (bits[21])
strcat(instructionPtr, "!");
sprintf(instructionPtr + strlen(instructionPtr), ", [R%d]", baseReg);
if (bits[25])
{
if(bits[23])
sprintf(instructionPtr + strlen(instructionPtr), ", R%d", Rm);
else
sprintf(instructionPtr + strlen(instructionPtr), ", -R%x", Rm);
if (Shift > 0)
{
switch(Sh)
{
case(3): if(Shift == 0) strcat(instructionPtr, ", RRX"); else strcat(instructionPtr, ", ROR "); break;
case(2): strcat(instructionPtr, ", ASR "); break;
case(1): strcat(instructionPtr, ", LSR "); break;
case(0): strcat(instructionPtr, ", LSL "); break;
}
sprintf(instructionPtr + strlen(instructionPtr), "#&%X", Shift*2); //DOUBLED..
}
}
else
{
if (bits[23])
sprintf(instructionPtr + strlen(instructionPtr), ", #&%x", immediate);
else
sprintf(instructionPtr + strlen(instructionPtr), ", #-&%x", immediate);
}
}
}
void ProcessMUL (int *bits, unsigned int instr, char *instructionPtr)
{
int Rd = (instr & 0x000F0000) >> 16;
int Rm = instr & 0x0000000F;
int Rs = (instr & 0x00000F00) >> 8;
int Rn = (instr & 0x0000F000) >> 12;
if (bits[21])
strcat(instructionPtr, "MLA");
else
strcat(instructionPtr, "MUL");
PrintCCode(instr, instructionPtr);
if(bits[20])
strcat(instructionPtr, "S");
sprintf(instructionPtr + strlen(instructionPtr), "\tR%d, R%d, R%d", Rd, Rm, Rs);
if(bits[21])
printf(", R%d", Rn);
}
void ProcessLDM(int *bits, unsigned int instr, char *instructionPtr)
{
char regList[256] = { 0 };
int listState = 0;
int Rn = (instr & 0x000F0000) >> 16;
int i;
if (bits[20])
strcat(instructionPtr, "LDM");
else
strcat(instructionPtr, "STM");
PrintCCode(instr, instructionPtr);
sprintf(instructionPtr + strlen(instructionPtr), "\tR%d", Rn);
if (bits[21])
strcat(instructionPtr, "!");
strcat(instructionPtr, ", ");
strcat(regList, "{");
for (i = 0; i<16; i++)
{
if (bits[i] && !bits[i+1])
{
sprintf(regList + strlen(regList), "R%d, ", i);
listState = 0;
}
else if (bits[i] && bits[i+1] && !listState)
{
sprintf(regList + strlen(regList), "R%d-", i);
listState = 1;
}
}
strcat(regList, "\b\b}");
strcat(instructionPtr, regList);
if(bits[22])
strcat(instructionPtr, "^");
}
</code></pre>
<p><strong>elf.h</strong></p>
<pre><code>#ifndef DisARM_elf_h
#define DisARM_elf_h
typedef struct _elfHeader
{
char magic[4];
char class;
char byteorder;
char hversion;
char pad[9];
short filetype;
short archtype;
int fversion;
int entry;
int phdrpos;
int shdrpos;
int flags;
short hdrsize;
short phdrent;
short phdrcnt;
short shdrent;
short shdrcnt;
short strsec;
} ELFHEADER;
typedef struct _elfProgHeader
{
int type;
int offset;
int virtaddr;
int physaddr;
int filesize;
int memsize;
int flags;
int align;
} ELFPROGHDR;
#endif
</code></pre>
<p>Advice on best practices, syntax and any errors you can see is greatly appreciated.</p>
|
[] |
[
{
"body": "<p>As a first thought, how portable is this? You use standard types (int, short, unsigned int etc) everywhere, but the sizes of these vary with platform. You might be better using types from stdint.h, such as int32_t, int16_t etc, which guarantee size.</p>\n\n<p>I'll comment more thoroughly later...</p>\n\n<p>.. Later ... in addition the the above:</p>\n\n<ul>\n<li>You have assumed the constant 4 in various places. Better as a define, as a const int or as a sizeof().</li>\n<li>You also have many embedded constants sprinkled around. These are better #defined and/or in inline functions. </li>\n<li>Type names are not normally all uppercase (which is used for defines).</li>\n<li>Define functions in reverse order of use to avoid the need for prototypes. So <code>main</code> comes last. Also all functions except main should be static.</li>\n<li>I prefer to see keywords like <code>if</code>, <code>for</code> etc followed by a space, as in <code>if (argc < 2)</code></li>\n<li>On errors in system and library calls where <code>errno</code> is set, prefer <code>perror</code> to your own fprintf message. People are used to seeing the system error messages.</li>\n<li>Inconsistent used of <code>exit(EXIT_FAILURE)</code> and <code>return 1</code> (or 2, 3 etc)</li>\n<li><code>main</code> is much too big for my taste - extract some code into suitable functions.\nFor example, the reading of the file header and checking its prefix might be a suitable function. Similarly, printing header info might be suitable as a function. </li>\n<li>don't cast the return from <code>malloc</code> if this is meant to be C (seems to be).</li>\n<li>system calls should be checked for failure (eg fseek, fread etc). Note that you'll end up with more calls to <code>fclose(fp)</code> and <code>free(prgHdr)</code> scattered around if you add failure checks. It is often better to allocate a resource and then pass it into a function that uses it; then free the resource when that function returns, whether on success or failure.</li>\n<li>your <code>+ 3 & 3</code> terms should be coded in terms of the types you are using - eg <code>(... + sizeof(int)-1) & (sizeof(int)-1)</code>. This gets messy so an inline function to do the math would be better.</li>\n</ul>\n\n<p>In <code>Disassemble</code>:</p>\n\n<ul>\n<li>Parameter <code>armI</code> should be const</li>\n<li><code>startAddress + i*4</code> is duplicated</li>\n</ul>\n\n<p>In <code>DecodeInstruction</code>:</p>\n\n<ul>\n<li>use <code>char instruction[100] = \"\";</code> instead of <code>sprintf(...,\"\\0\");</code></li>\n<li>you have an combination of printing into <code>instruction</code> and printing directly to <code>stdout</code> (from PrintASCII)</li>\n<li><p>your decomposition of the instruction into the <code>bits</code> array is really unnecessary and is rather ugly. Instead of saying <code>if (bits[27] && bits[26] && bits[25] && bits[24])</code> etc, it would be better to do:</p>\n\n<pre><code>if (isXXX(instr)) {\n processXXX(...);\n} else if (isYYY(instr) {\n processYYY(...);\n} else ...\n</code></pre>\n\n<p>where <code>isXXX</code> is defined along the lines of:</p>\n\n<pre><code>#define XXX_BITS 0xf000000 \n#define XXX_BITCODE 0xe000000 \nstatic inline int isXXX(unsigned int instr) \n{\n return (instr & XXX_BITS) == XXX_BITCODE;\n}\n</code></pre></li>\n</ul>\n\n<p>In <code>PrintCCode</code>, the switch is missing a <code>default</code> case.</p>\n\n<p>In <code>PrintASCII</code>, the array in not needed. Also, printing one char is better done with <code>putchar</code></p>\n\n<p>... I got this far and no further. After this it gets rather messy and difficult to read. It would also be difficult to test and maintain. I imagine there are cleaner ways of doing this. </p>\n\n<p>Note that <code>sprintf</code> and <code>strcat</code> are in general frowned upon as they often result in buffer overflows.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T18:08:32.997",
"Id": "20686",
"ParentId": "20671",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T11:04:31.673",
"Id": "20671",
"Score": "2",
"Tags": [
"optimization",
"c"
],
"Title": "ARM disassembler from ELF file in C"
}
|
20671
|
<p>While I'm aware that code with callbacks tends to be complex, I'm wondering if there are any patterns or something to improve my situation.</p>
<p>All I do here is check if a file exists and then print its name if it's not a directory:</p>
<pre><code>var fs = require('fs'),
filename = process.args[2];
fs.exists(filename, function(exists) {
if (exists) {
fs.stat(filename, function(err, stats) {
if (stats.isDirectory()) {
console.log(filename + ": is a directory");
} else {
// do something with file
console.log(filename);
}
});
} else {
console.log(filename + ": no such file");
}
});
</code></pre>
|
[] |
[
{
"body": "<p>You can actually omit <code>fs.exists()</code>. The <code>fs.stat()</code> will return an error when the item you are testing is not there. You can scavenge through the <code>err</code> object that <code>fs.stat()</code> returns to see what error caused it. As I remember, when <code>fs.stat()</code> stats a non-existing entry, it returns an <code>ENOENT, no such file or directory</code> error.</p>\n\n<p>And so:</p>\n\n<pre><code>var fs = require('fs')\n , filename = process.args[2]\n ;\n\nfs.stat(filename, function(err, stats) { \n if(err){\n //doing what I call \"early return\" pattern or basically \"blacklisting\"\n //we stop errors at this block and prevent further execution of code\n\n //in here, do something like check what error was returned\n switch(err.code){\n case 'ENOENT':\n console.log(filename + ' does not exist');\n break;\n ...\n }\n //of course you should not proceed so you should return\n return;\n }\n\n //back there, we handled the error and blocked execution\n //beyond this line, we assume there's no error and proceed\n\n if (stats.isDirectory()) {\n console.log(filename + \": is a directory\");\n } else {\n console.log(filename);\n }\n});\n</code></pre>\n\n<p>So essentially, we reduced the number of indents caused by callbacks and also reduced it by restructuring <code>if-else</code> statements</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T12:08:24.073",
"Id": "20675",
"ParentId": "20674",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "20675",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T11:47:31.293",
"Id": "20674",
"Score": "4",
"Tags": [
"javascript",
"node.js",
"file-system"
],
"Title": "Checking if a file exists then do something if it's not a directory"
}
|
20674
|
<p>I know that is generally expected that <a href="http://blog.mohammadjalloul.com/blogs/mo/archive/2009/12/13/evil-practices-swallowing-exceptions.aspx" rel="nofollow">you should not swallow exceptions</a>. In this code, an <a href="http://help.infragistics.com/Help/NetAdvantage/WinForms/2011.2/CLR2.0/html/Infragistics2.Win.UltraWinGrid.v11.2~Infragistics.Win.UltraWinGrid.UltraGridBase.html" rel="nofollow">Infragistic's UltraWinGrid</a> is being configured. Is there a better way to handle the failed <code>catch</code>es? Is this an exception to the rule?</p>
<pre><code>private void HideExcludedColumns(UltraGridBase grid)
{
if (_scExclusions == null) return;
foreach (var strKey in _scExclusions)
{
//Set the appropriate column of the grid to hidden.
foreach (var band in grid.DisplayLayout.Bands)
{
try
{
band.Columns[strKey].Hidden = true;
break;
}
catch { } //go to the next band.
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T14:49:34.140",
"Id": "33162",
"Score": "1",
"body": "Why do you think it should be an exception to the rule? What kind of exceptions can be thrown here, and in which cases?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T14:59:24.123",
"Id": "33163",
"Score": "0",
"body": "I'm not sure what exceptions my be possible, other the column may not exist. But it did not write this code myself, and I'm not fully sure about how this control works."
}
] |
[
{
"body": "<p>I agree with <a href=\"https://codereview.stackexchange.com/users/19473/almaz\">almaz</a> - a blanket <code>catch</code> is bad juju in just about every case. Need to know what exception(s) wind up being there. If the column doesn't exist, there should be a better, non-exceptional way of doing that:</p>\n\n<pre><code> private void HideExcludedColumns(UltraGridBase grid)\n {\n if (_scExclusions == null) return;\n foreach (var strKey in _scExclusions)\n {\n //Set the appropriate column of the grid to hidden.\n foreach (var band in grid.DisplayLayout.Bands)\n {\n var columnIndex = band.Columns.IndexOf(strKey);\n if (columnIndex > -1)\n {\n band.Columns[columnIndex].Hidden = true;\n break;\n }\n }\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T15:49:19.070",
"Id": "33166",
"Score": "0",
"body": "Thanks, that looks great assuming that the only possible exception."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T04:16:52.060",
"Id": "33388",
"Score": "0",
"body": "To expand: I am currently in the process of auditing all of the \"catch-all\"'s in a legacy code base at my work. It is one of the most painful things I have ever had to do. Catch-alls are badbadbad."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T21:35:56.777",
"Id": "33425",
"Score": "1",
"body": "As a general rule, your code should only catch what it can handle and either resolve or report appropriately."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T04:32:25.053",
"Id": "62602",
"Score": "0",
"body": "@RyanGates Do you think there are cases where a catch-rethrow is valid and not bad practice? Eg: `catch { logOrDoSomething(); throw; }`. I find that some state information on logged on a debug level can be infinitely useful like this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T14:30:26.843",
"Id": "62643",
"Score": "1",
"body": "@Kyle I think there are certain cases where it makes sense, but I would argue that they are few and far between. I have found that it holds pretty well as a general rule."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T15:32:39.073",
"Id": "20681",
"ParentId": "20680",
"Score": "12"
}
},
{
"body": "<p>I'd introduce an assert in that catch block. That way whenever it gets entered during debug, the program will die and you can see what exception is being thrown. In production, the assert will not apply and the current behavior will remain. Then as you find exceptions being caught there, add code to handle them properly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T09:41:00.727",
"Id": "89928",
"Score": "0",
"body": "It is a good suggestion but it doesn't cover all scenarios. Murphy's law states exactly that. In production you may run into exceptions that you didn't encounter during development. It is better to have a fallback mechanism to deal with such cases."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T15:03:34.070",
"Id": "89998",
"Score": "0",
"body": "@Sandeep, and what fallback mechanism would you add here?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-30T06:41:23.460",
"Id": "90136",
"Score": "0",
"body": "Fallback mechanism might be a wrong choice of word. But after one has changed his code to handle all the possible exceptions, the rest of the code should be written as given in the previous answers, which is do not handle the error (in case of an library) or have global handlers for unhandled exception or thread exceptions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-31T20:16:42.063",
"Id": "91329",
"Score": "0",
"body": "@Sandeep, fair enough. I only suggested this approach as a transitional step to keep the current behavior until you're sure that you've identified all the cases it was detecting."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T15:34:47.557",
"Id": "20682",
"ParentId": "20680",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "20681",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T14:44:18.907",
"Id": "20680",
"Score": "6",
"Tags": [
"c#",
"exception-handling"
],
"Title": "Handling failed catches"
}
|
20680
|
<p>How could this code become cleaner? I think that the way I handle the interfaces and binary search could be improved. I am trying to understand how to structure such a code (and usage of APIs) in a cleaner and more efficient manner. </p>
<p>This code solves the problem of finding the max subset of non-overlapping intervals. I especially believe the way I handle the binary search result is error-prone. </p>
<pre><code>private boolean nonOverlapping(Pair interval, SortedSet<Pair> selectedIntervals) {
if(selectedIntervals.isEmpty())
return true;
if(selectedIntervals.contains(interval)){
return true;
}
Pair[] sortedSelections = selectedIntervals.toArray(new Pair[0]);
int pos = Arrays.binarySearch(sortedSelections, interval, new Comparator<Pair>() {
@Override
public int compare(Pair o1, Pair o2) {
return o1.getStart() - o2.getEnd();
}
});
pos = (-pos) -1;
if(pos == sortedSelections.length){
if(sortedSelections[pos - 1].getEnd() < interval.getStart()){
return true;
}
}
else if(sortedSelections[pos].getEnd() > interval.getStart()){
if(pos + 1 < sortedSelections.length){
if(sortedSelections[pos + 1].getEnd() < interval.getStart()){
return false;
}
}
if(pos - 1 >= 0){
if(sortedSelections[pos - 1].getEnd() < interval.getStart()){
return false;
}
}
return true;
}
return false;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T09:38:48.903",
"Id": "33265",
"Score": "1",
"body": "http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html#compare%28T,%20T%29 \"The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y. (This implies that compare(x, y) must throw an exception if and only if compare(y, x) throws an exception.)\nThe implementor must also ensure that the relation is transitive: ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T15:41:51.827",
"Id": "33284",
"Score": "0",
"body": "One small simplification is assigning `interval.getStart()` to a variable: `int intervalStart = interval.getStart()`, so you aren't calling the method every time and its easier to read."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T15:56:53.007",
"Id": "33286",
"Score": "2",
"body": "If you can, I'd also put this method under `Pair` class, so you have `interval.overlaps( selectedIntervals );`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T08:00:15.000",
"Id": "63601",
"Score": "0",
"body": "Write tests covering all branches and all border cases. Afterwards you can happily try to merge your `if` branches and start other optimizations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T09:33:31.637",
"Id": "63602",
"Score": "0",
"body": "This is my attempt to code a solution to a classic algorithmic problem. I understand how I can write cleaner code. So I don't see how this helps me here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T09:58:30.127",
"Id": "63603",
"Score": "0",
"body": "Right from looking at the code I had the feeling that there might be some if branches able to be merged to one. I have no time to write some tests and check this. You could also try to minimize your logic with a [Karnaugh map](http://en.wikipedia.org/wiki/Karnaugh_map). If this is already the minimum amount of conditions, then there is nothing you can do (beside extracting a method or create temporary variable for your conditions to improve the readability.)"
}
] |
[
{
"body": "<p>I see three points of improvement:</p>\n\n<ol>\n<li>The isEmpty check is redundant can be removed. The contains will handle the scenario your are checking for.</li>\n<li>The Comparator really clutters things up, and since you already have a SortedSet coming in, I know you have another compareTo method somewhere else. If Pair is one of your classes, go ahead and make it implement Comparable so you don't have to worry about rewriting comparison logic everywhere.</li>\n<li>Your conditional block could be simplified if you only look for your failure cases. In cases like this, I usually step back and start by writing our pseudo code for these complex boolean constructs and let loose with DeMorgan's law.</li>\n</ol>\n\n<p>Here's a pastebin with my changes. It takes you down from 35 loc to 19 loc. <a href=\"http://pastebin.com/NpSHemqP\" rel=\"nofollow\">http://pastebin.com/NpSHemqP</a></p>\n\n<p>--edit-- Wrong sleep deprived academic reference.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T17:18:28.907",
"Id": "33287",
"Score": "0",
"body": "Good use of comments. Minor mistake (`getStart` should be `getStart()`). And could the last inner `if` statement be rewritten as `return sortedSelections[pos].getStart <= interval.getEnd()`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T17:48:55.150",
"Id": "33288",
"Score": "1",
"body": "As for that '<=', OP is going to have to weigh in on what actually constitutes an overlap. Actually, I like the Pair.overlaps() proposal @Knownasilya made above. Then one could get free this code from that complexity."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T09:07:01.083",
"Id": "20754",
"ParentId": "20683",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "20754",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T15:49:04.923",
"Id": "20683",
"Score": "2",
"Tags": [
"java",
"algorithm",
"api",
"binary-search",
"interval"
],
"Title": "Finding the max subset of non-overlapping intervals"
}
|
20683
|
<p>Thanks for taking the time to read this first off. I want to say that I have always been very interested in generating random terrain and since I'm new to any sort of graphical programming, I decided to start as simple as I could get.</p>
<p>I am trying to implement the midpoint displacement algorithm to make fractal type mountains. I've read the most common resources on it and understand the concept but that hasn't made it any easier. I suppose I have some more general questions about how I would store data effectively, but this is the code I have come up with. The code is pretty awful but it produces numbers and I've tried to make lines with the different points in openGL but I'm getting some pretty crazy results. I'm using the idea discussed on the start of this page. <a href="http://www.gameprogrammer.com/fractal.html" rel="nofollow">http://www.gameprogrammer.com/fractal.html</a> </p>
<pre><code>import java.util.Random;
public class MidPointGenerator {
private static double[] heightmap;
private static double randrange;
private static int iterations;
private static double roughness;
private static int n;
public MidPointGenerator(double s, int i, double h){
n = (int)(Math.pow(2, i) + 1); // size of the array
heightmap = new double[(int)n];
randrange = s;
iterations = i;
roughness = Math.pow(2,-h);
midPoint(0, n-1, randrange,0,i);
}
public static void midPoint(int left, int right, double range, int i, int goal){
if(i == goal){
return;
}
int mp = (left + right) / 2;
double mpheight;
if(heightmap[left] < heightmap[right]){
mpheight = ((heightmap[right] - heightmap[left]) / 2.0) + heightmap[left];
heightmap[mp] = mpheight + random(range);
}
if(heightmap[right] < heightmap[left]){
mpheight = ((heightmap[left] - heightmap[right]) / 2.0) + heightmap[right];
heightmap[mp] = mpheight + random(range);
}
if(heightmap[right] == heightmap[left]){
heightmap[mp] += random(range);
midPoint(left, mp, range * roughness, i+1, goal);
midPoint(mp, right, range * roughness, i+1, goal);
}
public static double random(double range){
//Returns a random number from -s to s.
Random random = new Random();
double randNum = range - ((2*range) * random.nextDouble());
return randNum;
}
public static void displayHeights(){
for(int i = 0; i < heightmap.length; i++){
System.out.println(heightmap[i]);
}
}
public double getHeightValue(int index){
if(index == n ){
return 0;
}
return heightmap[index];
}
public int getIterations(){
return n;
}
}
</code></pre>
<p>So this at least runs, stores the height values in a 1D array thats size depends on the number of iterations I want to do. How can I make my code much more logical and perhaps there is a much better way of implementing this. I was more concerned about just getting something that compiled and ran successfully. I'm convinced the way I'm approaching this is flawed and there is a much better way.</p>
<p>Any criticism is welcomed!
Thanks,
Ryan</p>
|
[] |
[
{
"body": "<p>.... Hrm...</p>\n\n<pre><code>import java.util.Random;\n</code></pre>\n\n<p>I'm assuming this is sufficient for your needs. In the future, it may be preferable to create your own interface, that you can supply different implementations for.</p>\n\n<pre><code>public class MidPointGenerator {\n\n private static double[] heightmap;\n private static double randrange;\n private static int iterations;\n private static double roughness;\n private static int n;\n</code></pre>\n\n<p>What does <code>n</code> represent? Most of the other variables are named okay (although <code>randrange</code> should probably be <code>deviation</code>, or similar).<br>\nMutable class-level variables should (almost always) die. Especially since:</p>\n\n<pre><code>public MidPointGenerator(double s, int i, double h){\n n = (int)(Math.pow(2, i) + 1); // size of the array\n heightmap = new double[(int)n];\n randrange = s;\n iterations = i;\n roughness = Math.pow(2,-h);\n midPoint(0, n-1, randrange,0,i); \n}\n</code></pre>\n\n<p>You set them in the instance constructor! So, they're really <em>instance</em> variables! If I were attempting to use your class, I might end up mighty confused as to behavior, when attempting to use two different instances. Also, your parameter names are <em>terrible</em> - they don't tell me at all what they're used for. And don't use end-of-line comments.</p>\n\n<pre><code>public static void midPoint(int left, int right, double range, int i, int goal){\n\n if(i == goal){\n return;\n }\n</code></pre>\n\n<p>What does <code>i</code> represent? The only time such short variables are ever really acceptable is as indices during iterators (maybe). This method is <code>static</code> because it's operating on class-level variables (which should be instance-level), but there's no good reason for it to be flagged <code>public</code> as well.</p>\n\n<pre><code> int mp = (left + right) / 2;\n double mpheight;\n\n if(heightmap[left] < heightmap[right]){\n mpheight = ((heightmap[right] - heightmap[left]) / 2.0) + heightmap[left];\n heightmap[mp] = mpheight + random(range);\n } \n if(heightmap[right] < heightmap[left]){\n mpheight = ((heightmap[left] - heightmap[right]) / 2.0) + heightmap[right];\n heightmap[mp] = mpheight + random(range);\n }\n if(heightmap[right] == heightmap[left]){\n heightmap[mp] += random(range);\n\n } // <- Missing?\n</code></pre>\n\n<p>I'm assuming, given other indentation, that the brace (<code>}</code>) belongs here. Compiler error otherwise.</p>\n\n<pre><code> midPoint(left, mp, range * roughness, i+1, goal);\n midPoint(mp, right, range * roughness, i+1, goal);\n\n}\n\npublic static double random(double range){\n //Returns a random number from -s to s.\n Random random = new Random();\n</code></pre>\n\n<p>You're creating a new <code>Random</code> object each time you enter this object (and not using the variable you created earlier...). Depending on how your program runs, you may have multiple instances of <code>Random</code> with the <em>same</em> seed value, causing them to generate the same output; while occasionally random generators should return the same output, getting them in this fashion is undesirable. Same comments about <code>public</code> and <code>static</code>.</p>\n\n<pre><code> double randNum = range - ((2*range) * random.nextDouble());\n return randNum;\n}\n</code></pre>\n\n<p><code>random.nextDouble()</code> returns an evenly distributed value in the range [0, 1). The result of the math, though, is <em>not</em> evenly distributed along (-range, range); at least, I don't think so (anybody else know better? help?). You can generate double-ended <em>integer</em> ranges (with <code>Random.nextInteger(upper)</code>), which doesn't really help here. You may need a new random generator, if you're going to get 'correct' results - what you have may be good enough for your current purposes.</p>\n\n<pre><code>public static void displayHeights(){\n for(int i = 0; i < heightmap.length; i++){\n System.out.println(heightmap[i]);\n }\n}\n</code></pre>\n\n<p>Same comments about <code>public</code> and <code>static</code>. Really, you should be using a <a href=\"http://www.java2s.com/Code/Java/Language-Basics/ForeachArray.htm\" rel=\"nofollow\">for-each loop</a>. Oh, and not printing out to the console directly, but that's probably forgivable here.</p>\n\n<pre><code>public double getHeightValue(int index){\n if(index == n ){\n return 0;\n }\n return heightmap[index];\n}\n\npublic int getIterations(){\n return n;\n}\n</code></pre>\n\n<p>I'm assuming that these methods are for whatever needs to inspect the state of the map after you're done constructing it (hence the <code>public</code>), given it's not used anywhere in your code. You really ought to be returning some sort of array/collection, though (probably a copy of <code>heightmap</code>), which should be easier to work with.</p>\n\n<hr />\n\n<p>Ah, I think this is more along the lines of how I would have done it:</p>\n\n<pre><code>public class MidPoint {\n\n private static final Random RANDOM = new Random();\n\n private final double[] heightmap;\n\n private MidPoint(double[] heightmap) {\n this.heightmap = heightmap;\n }\n\n private double[] getHeightmap() {\n return Arrays.copyOf(heightmap, heightmap.length);\n }\n}\n</code></pre>\n\n<p>This is the basic class definition (static creation methods in a second). Because the class now represents the end state, I felt it was appropriate to change the name. The constructor is private, because it doesn't make much sense for it to be <em>manually</em> created. And the end heightmap should be accessed as a copy, so that the result can be safely shared. It's also being output as the array, not as by-index, which you may find easier to work with.</p>\n\n<pre><code>private static double random(double range) {\n return range - ((2 * range) * RANDOM.nextDouble());\n}\n</code></pre>\n\n<p>I just tightened this up a little, was all. It might not be 'perfect', but I personally don't know of a better way to set this up, if the variation is an issue. Actually, this method makes (temporary) testing really easy - just have it return a constant value!</p>\n\n<pre><code>private static double getMidpoint(double a, double b) {\n return ((a - b) / 2) + b;\n}\n</code></pre>\n\n<p>Helper method, to remove code duplication.</p>\n\n<pre><code>private static double getOffset(double current, double left, double right) {\n final int comparison = Double.compare(left, right);\n\n if (comparison < 0) {\n return getMidpoint(left, right);\n } else if (comparison > 0) {\n return getMidpoint(right, left);\n } else {\n return current;\n }\n}\n</code></pre>\n\n<p>... Mathematically speaking, the greater/less than shouldn't be necessary (because the midpoint calculation gives correct results either way). The problem comes in that the way doubles (and limited-precision numbers of all types) are represented won't necessarily always give the same results. </p>\n\n<pre><code>private static void midPoint(double[] heightmap, int iteration, int limit, int left, int right, double range, double deviation) {\n if (iteration == limit) {\n return;\n }\n\n final int midpoint = ((right - left) / 2) + left;\n\n heightmap[midpoint] = (getOffset(heightmap[midpoint], heightmap[left], heightmap[right]) + random(range));\n\n final double adjusted = range * deviation;\n\n midPoint(heightmap, iteration + 1, limit, left, midpoint, adjusted, deviation);\n midPoint(heightmap, iteration + 1, limit, midpoint, right, adjusted, deviation);\n}\n</code></pre>\n\n<p>Recursive method. Things have mostly just been extracted to helper methods. The only big difference is the way the midpoint is retrieved, which was changed so that with larger iterations (because of the squaring from <code>iterations</code>) they won't overflow.</p>\n\n<pre><code>private static double[] getMidPoints(final int iterations, final double range, final double roughness) {\n final double[] heightmap = new double[(int) Math.pow(2, iterations) + 1];\n final double deviation = Math.pow(2.0, roughness);\n\n midPoint(heightmap, 0, iterations, 0, heightmap.length - 1, range, deviation);\n\n return heightmap;\n}\n</code></pre>\n\n<p>Setup for entire process, returning the finished array.</p>\n\n<pre><code>public static MidPoint generate(final int iterations, final double range, final double roughness) {\n\n if (iterations >= 31) {\n throw new IllegalArgumentException(\"Too many iterations, must be 30 or less\");\n }\n\n if (Double.isNaN(range) || Double.isInfinite(range) || !(range > 0.0)) {\n throw new IllegalArgumentException(\"Range must be a positive value greater than 0\");\n }\n\n if (Double.isNaN(roughness) || Double.isInfinite(roughness) || !(roughness > 0.0)) {\n throw new IllegalArgumentException(\"Roughness must be a positive value greater than 0\");\n }\n\n return new MidPoint(getMidPoints(iterations, range, roughness));\n}\n</code></pre>\n\n<p>And... The static generator method, returning the final value object. The biggest thing here was the error checking.</p>\n\n<p>Oh, the results always have 0.0 at the start and end of the set of midpoints, which makes me think something is up, but I have no idea what. Unfortunately, I don't know what you're trying to implement, so I can't tell <em>if</em> something is wrong. And no, it's not something I introduced - yours gets that too (constant values for the random get the same results).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T20:37:15.730",
"Id": "20690",
"ParentId": "20684",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20690",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T16:47:19.680",
"Id": "20684",
"Score": "1",
"Tags": [
"java"
],
"Title": "Implementing the midpoint displacement algorithm in Java"
}
|
20684
|
<p>I'm currently writing a class:</p>
<pre><code>final class MyTestClass {
const URL = 'http://www.example.org';
private static $MY_ARRAY = array('...');
// since this is not allowed
// const MY_ARRAY = array('...');
}
</code></pre>
<p>So my question is whether I should make <em>URL</em> a <code>private static</code> variable, too?
These values are constant and are only used in the class itself.</p>
|
[] |
[
{
"body": "<p>I'm not quite sure that this question is on topic, however:</p>\n\n<p>You have to understand what each variable definition is and what it means for the accesibility of that variable.</p>\n\n<p>Say your class definition is as follows:</p>\n\n<pre><code>class MyTestClass {\n const URL = 'http://www.example.org';\n private static $MY_ARRAY = array('...');\n}\n</code></pre>\n\n<p>And in the future you write another class that extends that class and it wants to update URL as below:</p>\n\n<pre><code>class SomeOtherClass extends MyTestClass {\n public __construct(){\n $this->URL = \"http://www.someothersite.com\";\n }\n}\n</code></pre>\n\n<p>Now, if you never want URL to change, then that's fine. A better way to write <code>MyTestClass</code> however, would be:</p>\n\n<pre><code>class MyTestClass {\n private $URL = 'http://www.example.org';\n private $myArray = array();\n}\n</code></pre>\n\n<p>Again however, if some class extends it, they won't be able to access the <code>$URL</code> var. Also, stay away from static. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T18:43:42.493",
"Id": "33176",
"Score": "0",
"body": "This class will never be *extended* (now declared as `final` in the question). I just want to store a constant variable thus I took `const URL`, but PHP doesn't let me store arrays in there so my array variable will be declared as `private static`. Therefore I have to write both `MyTestClass::URL` and `self::$myArray` in the code. That's inconsitent in my opinion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T17:25:34.897",
"Id": "33364",
"Score": "0",
"body": "Ah! I misunderstood, sorry."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T17:30:36.340",
"Id": "33365",
"Score": "1",
"body": "No problem! Thanks for taking time to write the answer anyway ;)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T18:29:23.070",
"Id": "20687",
"ParentId": "20685",
"Score": "1"
}
},
{
"body": "<p>See <a href=\"https://stackoverflow.com/questions/1290318/php-constants-containing-arrays\">PHP Constants Containing Arrays?</a> . I think both are valid and also your current approach is fine. It's only important that you stick with one solution in your whole project.</p>\n\n<p>Personally I think I would stay with your current solution.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T10:27:23.640",
"Id": "20705",
"ParentId": "20685",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "20705",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T17:20:34.410",
"Id": "20685",
"Score": "2",
"Tags": [
"php",
"object-oriented",
"classes"
],
"Title": "Consistent implementation of PHP class constants (arrays not allowed)"
}
|
20685
|
<p>I have a few custom exception classes that I created simply for the sake of having my own exception message:</p>
<pre><code>public class DivideByZeroException extends Exception
{
@Override
public String toString()
{
return "ERROR: Expression cannot divide by 0";
}
}
</code></pre>
<p>I realize that this can be done by throwing an exception like: </p>
<pre><code>throw new Exception("ERROR: Expression cannot divide by 0");
</code></pre>
<p>but this contains a prefix of <code>java.lang.Exception:</code> in the string.</p>
<p>I think it's a bit ugly to remove the unwanted prefix from the string, but creating a class just for the exception message seems a bit excessive to me. Is there a different way to do this?</p>
|
[] |
[
{
"body": "<p>If you want all your exceptions to follow this style, then you could have one parent Exception class, then make your application exceptions extend it, like so:</p>\n\n<pre><code>class MyException extends Exception\n{\n MyException(String message)\n {\n super(message);\n }\n\n @Override\n public String toString()\n {\n return \"ERROR: \" + this.getMessage();\n }\n}\n\nclass DivideByZeroException extends MyException\n{\n DivideByZeroException()\n {\n super(\"Expression cannot divide by 0\");\n }\n}\n</code></pre>\n\n<p>This way, you don't have to override <code>toString()</code> every time, and you also don't have to put \"ERROR\" into the actual text of the exception.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T19:09:46.753",
"Id": "20689",
"ParentId": "20688",
"Score": "2"
}
},
{
"body": "<p><strong>Don't throw raw Exceptions</strong>, use always a subclass (as explained by MrLore). If you are throwing raw exceptions you also have to catch them, which might mask other exception or runtime exceptions. You would add a instanceof to any of your catch blocks.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T07:54:29.893",
"Id": "20701",
"ParentId": "20688",
"Score": "5"
}
},
{
"body": "<p>Even if it is already cleared by RHS, I am not quite sure what the original idea behind this question is.</p>\n\n<blockquote>\n <p>I think it's a bit ugly to remove the unwanted prefix from the string, but creating a class just for the exception message seems a bit excessive to me. Is there a different way to do this?</p>\n</blockquote>\n\n<p>Well, you do not have to remove the prefix? This is just some formating from Java. You could catch an Exception <code>e</code> and use <code>e.getMessage()</code> to see the message and do whatever you want with it.</p>\n\n<p>Nevertheless, you should avoid implementing your own Exception class. And you should not throw a generic \"Exception\" (See for example Effective Java Programming Language Guide). Just use the current available exceptions from Java, most likely IllegalArgumentException or IllegalStateExceptions. This covers about 90% of all valid cases in typical code (own experience).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T05:54:28.573",
"Id": "33327",
"Score": "0",
"body": "java.lang.ArithmeticException :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T14:16:44.157",
"Id": "33404",
"Score": "0",
"body": "@mnhg example for an use case? I think, this could be handled most of the time by Argument/State, too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T19:24:22.253",
"Id": "33525",
"Score": "0",
"body": "I only wanted to state, that this is also a standard exception, and actually it is designed for exactly this scenario. (Ex.: dividing by zero, dividing and loosing scale information, overflows in multiplication, ...)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T17:40:48.837",
"Id": "20766",
"ParentId": "20688",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "20689",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T19:00:09.393",
"Id": "20688",
"Score": "1",
"Tags": [
"java",
"exception"
],
"Title": "Java Exception Message"
}
|
20688
|
<p>I wrote the following in Javascript and jQuery, and I'm wondering if there are any ways to improve the code, organize it better, and increase speed:</p>
<pre><code>function calendar(d) {
$("#calendar").remove();
$("#calendar_container").append("<table border='1' id='calendar'></table>");
t = new Date(d); // Today [Wed Jan 16 2013 00:00:00 GMT-0500 (EST)]
var d = t.getDate(); // Today's date (1-31) [16]
var y = t.getFullYear(); // Full year [2013]
var m = t.getMonth(); // Month (0-11) [0]
var mN = ["January", // Month name array (0-11)
"February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var fM = mN[m]; // Full month name [January]
var dIM = new Date(y, m + 1, 0).getDate(); // Number of days in current month (1-31) [31]
var dILM = new Date(y, m, 0).getDate(); // Number of days in last month (1-31) [31]
var dOW = new Date(y, m, 1).getDay(); // Day of the first day of the month (0-6) [2]
var nOW = Math.ceil((dIM + dOW) / 7); // Number of weeks in the month, including space [5]
var w = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
function datDate(m, day, y) {
date = new Date(" " + mN[m] + " " + day + " " + y);
return date;
}
$("#calendar").append("<tr><td class='month' colspan='7'>" + mN[m] + " - " + y + "</td></tr>");
$("#calendar").append("<tr class='day'></tr>");
for (var i = 0; i < 7; i++) $(".day").append("<td>" + w[i][0] + "</td>");
if (m === 0) {
n_m = 12;
} else {
n_m = m - 1;
}
var pre = new Date(y - 1, n_m + 1, 0).getDate();
var daysInLastMonth = new Date(y, n_m + 1, 0).getDate();
var after = (7 * (nOW)) - (dOW + dIM);
var count = 0,
$row;
for (var i = 0 - dOW; i < dIM; i++) {
var day = i + 1;
if (count % 7 === 0) {
$row = $("<tr class='row'>").appendTo("#calendar");
}
if (day > 0) {
date = datDate(m, day, y);
if (day === d) {
$row.append("<td class='calendar_date current_date watch' data-date='" + date + "'>" + day + "</td>");
} else {
$row.append("<td class='calendar_date watch' data-date='" + date + "'>" + day + "</td>");
}
} else {
var day = daysInLastMonth--;
if (m === 0) {
var n_y = y - 1;
var n_m = 11
} else {
var n_m = m - 1;
var n_y = y;
}
var n_date = new Date(n_y, n_m, day);
$row.prepend("<td class='calendar_back watch' data-date='" + n_date + "'>" + day + "</td>");
}
count++;
}
for (var i = 0; i < after; i++) {
var day = (i + 1);
if (m === 12) {
var n_y = y + 1;
var n_m = 0
} else {
var n_m = m + 1;
var n_y = y;
}
var n_date = new Date(n_y, n_m, day);
$("td:last").after("<td class='calendar_next watch' data-date='" + n_date + "'>" + day + "</td>");
}
}
function calendarSetup() {
function changed(c) {
$(".current").text(c);
localStorage.setItem("date", c);
b_current = new Date(c);
b_year = b_current.getFullYear();
b_month = b_current.getMonth();
b_date = b_current.getDate();
b_daysInLastMonth = new Date(b_year, b_month, 1).getDate();
}
if (localStorage.getItem("date")) {
var now = localStorage.getItem("date");
} else {
var now = new Date(); // "1 March 2013"
}
calendar(now);
changed(localStorage.getItem("date"));
b_current = new Date(now);
b_year = b_current.getFullYear();
b_month = b_current.getMonth();
b_date = b_current.getDate();
b_daysInLastMonth = new Date(b_year, b_month, 1).getDate();
b_monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
function move(a, b, c) {
if (b_month === a) {
var year = b_year + b;
var month = c;
a === 11 ? day = 1 : day = new Date(year, month + 1, 0).getDate();
} else {
var year = b_year;
var month = b_month + b;
a === 11 ? day = 1 : day = new Date(year, month + 1, 0).getDate();
}
var now = new Date(year, month, day);
calendar(now);
changed(now);
}
function step(a, b, c) {
var year = b_year;
var day = b_date + b;
var month = b_month;
var now = new Date(year, month, day);
calendar(now);
changed(now);
}
$(".watch").live("click", function () {
if ($(this).hasClass("back")) {
move(0, -1, 11);
}
if ($(this).hasClass("next")) {
move(11, 1, 0);
}
if ($(this).hasClass("calendar_back")) {
var now = $(this).data("date");
calendar(now);
changed(now);
}
if ($(this).hasClass("calendar_next")) {
var b_now = $(this).data("date");
calendar(b_now);
changed(b_now);
}
if ($(this).hasClass("calendar_date")) {
var b_now = $(this).data("date");
calendar(b_now);
changed(b_now);
}
if ($(this).hasClass("today")) {
var b_now = new Date();
calendar(b_now);
changed(b_now);
}
});
$(document).keydown(function (e) {
if (e.keyCode == 37) {
step(0, -1, 11);
}
if (e.keyCode == 39) {
step(11, 1, 1);
}
});
}
// Onload
calendarSetup();
</code></pre>
<p>Demo: <a href="http://jsfiddle.net/charlescarver/XZE3x/" rel="nofollow">http://jsfiddle.net/charlescarver/XZE3x/</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T21:20:19.150",
"Id": "33183",
"Score": "2",
"body": "You should cache var `$this = $(this)` to avoid re querying."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T22:02:44.660",
"Id": "33184",
"Score": "0",
"body": "Done. That can't be all, though ;D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T16:15:33.857",
"Id": "39677",
"Score": "0",
"body": "You should move your `var` and `function` lines up above your code to more accurately reflect how the code will actually execute. They'll be hoisted above the rest of the function body."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T13:51:18.790",
"Id": "73675",
"Score": "0",
"body": "As mentioned by @jonny-sauter,use meaningful names. It's always the first step."
}
] |
[
{
"body": "<p>The code you posted is quite big so I believe that's why no one has answered this question yet. For a better and more specific answer I would suggest you ask several questions with isolated sections you want to improve.</p>\n\n<p>Anyways, here are some basic improvements you could use:</p>\n\n<ul>\n<li>Removing <code>$(\"#calendar\").remove();</code> that's not in your HTML? Then you call this later?</li>\n<li>You only need to say \"var\" once. After that just use a \",\" and bumb onto the next one.</li>\n<li>Use variable names that actually tell us what they are. Keeping this in mind will help you in the future if you have to update or make changes to your code. If you're worried about size, don't. You should be using a minifier anyways and that would replace your variable names later.</li>\n</ul>\n\n<p>Ex:</p>\n\n<pre><code> var d = t.getDate(), // Use the coma instead of saying var each time.\n y = t.getFullYear(), // Name your var \"year\" instead of just \"y\".\n m = t.getMonth(),\n mN = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"],\n fM = mN[m],\n dIM = new Date(y, m + 1, 0).getDate(),\n dILM = new Date(y, m, 0).getDate(),\n dOW = new Date(y, m, 1).getDay(),\n nOW = Math.ceil((dIM + dOW) / 7),\n w = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"];\n</code></pre>\n\n<ul>\n<li>As a rule of thumb, if you use a selection more than once you should cache its value:</li>\n</ul>\n\n<p>Ex:</p>\n\n<pre><code>var calendar = $(\"#calendar\");\n\ncalendar.append(\"<tr><td class='month' colspan='7'>\" + mN[m] + \" - \" + y + \"</td></tr>\");\ncalendar.append(\"<tr class='day'></tr>\");\n</code></pre>\n\n<ul>\n<li>Why do you declare the month names twice? Use the previously declared array instead.</li>\n</ul>\n\n<p>This:</p>\n\n<pre><code>mN = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"]\nb_monthNames = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"];\n//Just use the mN again instead of making a whole new variable.\n</code></pre>\n\n<ul>\n<li>Use a IIFE instead of this <code>calendarSetup();</code></li>\n</ul>\n\n<p>Ex:</p>\n\n<pre><code>(function($) {\n//Wrap your code with this.\n//This gets immediatly invoked and runs your code.\n//We pass \"$\" to the function as jQuery.\n//By doing this you protect yourself from other libraries that might use the \"$\", thus, preventing conflicting code.\n})(jQuery);\n</code></pre>\n\n<ul>\n<li>Lastly, you should consider using a design pattern. You can do some research to find which might fit your situation the best. This <a href=\"http://addyosmani.com/resources/essentialjsdesignpatterns/book/\" rel=\"nofollow\">book</a> describes them well and provides examples etc. From what I can tell from your code I would recomend the Module Design Pattern. Chris Coyer does a good job explaining this concept in <a href=\"http://css-tricks.com/how-do-you-structure-javascript-the-module-pattern-edition/\" rel=\"nofollow\">this article</a>. I also highly recommend <a href=\"https://tutsplus.com/course/30-days-to-learn-jquery/\" rel=\"nofollow\">this course by Jeffery Way</a>. He explains a lot of the core concepts in jQuery as well as some more advanced techniques.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T16:48:10.973",
"Id": "23224",
"ParentId": "20691",
"Score": "2"
}
},
{
"body": "<p>You shouldn't hard-code any IDs or use global variables, because either could collide with other HTML, JavaScript, etc. on the page.</p>\n\n<p>Instead of hard-coding <code>#calendar_container</code>, pass the id of the target element as a parameter, and instead of giving your table the hard-coded id <code>calendar</code>, you could get a reference from jQuery when creating it:</p>\n\n<pre><code>function calendar(container, date) {\n var container = $(container);\n container.empty(); // Instead of removeing the table \"#calender\"\n var calender = $('<table></table>').appendTo(container); // Drop 'border=1'. Style the table in CSS.\n // From here on you can use the variable calendar intstead of $('#calendar') to refer to your table:\n // ...\n calendar.append('...');\n // ...\n}\n</code></pre>\n\n<p>Similar here:</p>\n\n<pre><code>$(\"#calendar\").append(\"<tr class='day'></tr>\");\nfor (var i = 0; i < 7; i++) $(\".day\").append(\"<td>\" + w[i][0] + \"</td>\");\n</code></pre>\n\n<p>Instead do:</p>\n\n<pre><code>var day = jQuery(\"<tr></tr>\").appendTo(calender);\nfor (var i = 0; i < 7; i++) day.append(\"<td>\" + w[i][0] + \"</td>\");\n</code></pre>\n\n<p>(Maybe more later).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T14:33:04.120",
"Id": "23269",
"ParentId": "20691",
"Score": "3"
}
},
{
"body": "<p>You are storing loads of information in the class names and as data in the DOM which is ultimately making everything a lot more complicated. A better approach would be to store it in an object. But also note that there is only one small piece of information you need to know to display the calendar correctly: the date it is supposed to be showing. Most of the other variables you create are superfluous.</p>\n\n<p>Splitting the logic between <code>calendar</code> and <code>calendarSetup</code> is particularly problematic because you end up recalculating and storing some of the same data in both (like the names of the months), and unnecessarily rebuilding the entire calendar HTML each time you change the date.</p>\n\n<p>You could also make better use of javascript's date methods, for instance:</p>\n\n<pre><code>date.setMonth(date.getMonth() - 1)\n</code></pre>\n\n<p>subtracts a month from <code>date</code> (and works even if the month is January).</p>\n\n<p>Here is a version that constructs an object for the calendar. (I used plain js, but it should be easy enough to add jquery.) (<a href=\"http://jsfiddle.net/kxPZb/11/\" rel=\"nofollow\">jsfiddle</a>)</p>\n\n<pre><code>function nel(type, parent) {\n // helper to make or clone a new element and append it to parent\n var el = document.createElement(type);\n if (parent) parent.appendChild(el);\n return el;\n}\n\nfunction Calendar(elements) {\n var startDate, date = new Date(),\n table = nel('table', elements.container),\n headerCell = nel('th', nel('tr', table)),\n months = ['January', 'February', 'March', 'April', 'May', 'June',\n 'July', 'August', 'September', 'October', 'November', 'December'],\n days = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];\n\n function buildHtml() {\n var i, j, row, cell;\n headerCell.colSpan = 7;\n\n // Add days of week in first row\n row = nel('tr', table);\n for (i = 0; i < 7; i++) {\n nel('td', row).innerHTML = days[i];\n }\n\n // Add the remaining cells and give them event handlers \n for (j = 0; j < 5; j++) {\n row = nel('tr', table);\n for (i = 0; i < 7; i++) {\n nel('td', row).onclick = getCellResponse(i, j);\n }\n }\n }\n\n function getCellResponse(col, row) {\n return function () {\n date = new Date(startDate);\n date.setDate(date.getDate() + row * 7 + col);\n refresh();\n };\n }\n\n function refresh() {\n var cell, row, col, d;\n startDate = new Date(date);\n startDate.setDate(1); // set to first of month\n startDate.setDate(1 - startDate.getDay()); // set to preceding Sunday\n for (row = 2, d = new Date(startDate); row < 7; row++) {\n for (col = 0; col < 7; col++) {\n cell = table.children[row].children[col];\n cell.innerHTML = d.getDate();\n cell.className = '';\n if (d.getMonth() !== date.getMonth()) {\n cell.className = 'feint';\n } else if (d.getDate() === date.getDate()) {\n cell.className = 'selected';\n } \n d.setDate(d.getDate() + 1);\n }\n }\n headerCell.innerHTML = months[date.getMonth()] + '-' + date.getFullYear();\n }\n buildHtml();\n refresh();\n elements.today.onclick = function () {\n date = new Date();\n refresh();\n };\n elements.forward.onclick = function () {\n date.setMonth(date.getMonth() + 1);\n refresh();\n };\n elements.back.onclick = function () {\n date.setMonth(date.getMonth() - 1);\n refresh();\n };\n}\n\nvar calendar = new Calendar({\n current: document.getElementsByClassName('current')[0],\n container: document.getElementById('calendarContainer'),\n today: document.getElementsByClassName('today watch')[0],\n back: document.getElementsByClassName('back watch')[0],\n forward: document.getElementsByClassName('next watch')[0]\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-28T01:11:33.537",
"Id": "30338",
"ParentId": "20691",
"Score": "0"
}
},
{
"body": "<p><strong>Some time ago i wrote a multilanguage calendar</strong> for modern browsers.</p>\n\n<p>this function returns an array of the <strong>months</strong> and <strong>days</strong> in <em>narrow,short & long</em></p>\n\n<pre><code>var months,weekdays;\nfunction setlng(l){\n var wd={narrow:[],short:[],long:[]},b=7,d=new Date(),l=l||navigator.language;\n while(d.getDay()>0){d.setDate(d.getDate()+1);}\n while(b--){\n d.setDate(d.getDate()-1);\n wd.narrow[b]=d.toLocaleDateString(l,{weekday:'narrow'});\n wd.short[b]=d.toLocaleDateString(l,{weekday:'short'});\n wd.long[b]=d.toLocaleDateString(l,{weekday:'long'});\n } \n var m={narrow:[],short:[],long:[]},b=12,d=new Date(),l=l||navigator.language;\n while(d.getMonth()>0){d.setMonth(d.getMonth()+1)};\n while(b--){\n d.setMonth(d.getMonth()-1);\n m.narrow[b]=d.toLocaleDateString(l,{month:'narrow'});\n m.short[b]=d.toLocaleDateString(l,{month:'short'});\n m.long[b]=d.toLocaleDateString(l,{month:'long'});\n }\n months=m;weekdays=wd;\n}\nsetlng();//en,ru,it ... whatever language\n</code></pre>\n\n<p>setlng() returns the current browser language else you can manually specify a language</p>\n\n<p>like en,it,ru... so setlng('ru') creates an array of russian month and day names.</p>\n\n<p>then (i don't remember why) used the protorype to create some functions to get these monthname,the days in the current month and the calendar itself.</p>\n\n<pre><code>Date.prototype.getMonthName=function(){return months.long[this.getMonth()];};\nDate.prototype.daysInMonth=function(){\n return new Date(this.getFullYear(),this.getMonth()+1,0).getDate();\n};\n\nDate.prototype.calendar=function(){\n var numDays=this.daysInMonth();\n var startDay=new Date(this.getFullYear(),this.getMonth(),1).getDay();\n var buildStr ='<table>';\n buildStr+='<tr><td colspan=7>'+this.getMonthName()+' '+this.getFullYear()+'</td></tr>';\n buildStr+='<tr><td>'+weekdays.short.join('</td><td>')+'</td></tr>';\n buildStr+='<tr>';\n buildStr+=new Array(startDay+1).join('<td>&nbsp;</td>');\n var border=startDay;\n for(i=1;i<=numDays;i++){\n buildStr+='<td>'+i+'</td>';\n border++;\n if(((border%7)==0)&&(i<numDays)){\n buildStr+='</tr><tr>';\n }\n }\n while((border++%7)!=0) {\n buildStr+='<td>&nbsp;</td>';\n }\n buildStr+='</tr>';\n buildStr+='</table>';\n return buildStr;\n}\n</code></pre>\n\n<p>as you can see the calendar function is really short and also relatively fast.</p>\n\n<p>all you have to set the language & pass a date to the calendar function</p>\n\n<pre><code>document.body.innerHTML=(setlng('it'),new Date()).calendar();//italian calendar\n</code></pre>\n\n<p>or</p>\n\n<pre><code>element.appendChild(document.createElement('div')).innerHTML=(new Date()).calendar()\n</code></pre>\n\n<p>now to create a navigation (for example to jump to the next month) you can do something like this.</p>\n\n<pre><code>element.innerHTML=(new Date(now.getFullYear(), now.getMonth() + 1, 1)).calendar();\n</code></pre>\n\n<p>and so on...</p>\n\n<p>style with css by adding a class to the table inside the function</p>\n\n<p>and i leaved the arguments free so you can add custom ones for different types of calendars.</p>\n\n<p>ps.: i used to return a simple string vs dom manipulation because the code is much shorter.and the code it self is just a test i made some time ago .. and it needs alot of modifications to ptoperly work.i posted only cause maybe you find something useful inside this functions.</p>\n\n<p><strong>Example</strong></p>\n\n<p><a href=\"http://jsfiddle.net/TgdT7/1/\" rel=\"nofollow\">http://jsfiddle.net/TgdT7/1/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T01:43:33.470",
"Id": "37274",
"ParentId": "20691",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-18T21:11:56.667",
"Id": "20691",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"performance",
"datetime"
],
"Title": "Calendar code review"
}
|
20691
|
<p>I'm trying to solve <a href="http://www.spoj.com/problems/PRIME1/" rel="nofollow">this</a> problem. After a couple of tries, this is what I pulled off:</p>
<pre><code> #include<stdio.h>
#define primeLimit 100000
int prime (long int Start2, long int Stop2 )
{
long int a[primeLimit+1];
long int i,j,k,l;
for (i=Start2;i<=Stop2;i++)
{
a[i-Start2] = 1;
}
for (i=Start2;i<=Stop2;i++)
{
if (a[i-Start2]!= 0 && i!=1)
{
for (j=3; j*j< i;j=j+2)
{
if(i%j==0)
break;
}
if(j*j > i)
{
printf(" \n %ld",i);
l = i;
if (i<=46340)
{
for (k = i*i; k< Stop2;)
{
while (k<46340 && (k-Start2 <100000))
a[k-Start2] = 0;
k = k+l;
}
}
}
else
{
a[i-Start2] = 0;
}
}
}
return 0;
}
int main (void)
{
long int start,stop,a,look;
scanf("%ld", &look);
for (a=1;a<=look;a++)
{
scanf("%ld %ld", &start,&stop);
prime (start,stop);
}
return 0;
}
</code></pre>
<p>Here I used <code>if (i<=46340)</code> because the 46340*46340 exceeds the limit of a <code>long int</code> on a 32-bit machine (2,147,483,647). For the same purpose, I used <code>while (k<46340 && (k-Start2 <100000))</code>.</p>
<p>This code exceeds the time limit (6 seconds) of the SPOJ problem rule.</p>
<p>How can this be faster?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T15:19:58.197",
"Id": "126811",
"Score": "0",
"body": "You should use the 'Segmented Sieve' algorithm. If you need the complete explanation of the problem look here: http://zobayer.blogspot.de/2009/09/segmented-sieve.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-11T16:55:32.813",
"Id": "126943",
"Score": "0",
"body": "cat_baxter, why should anyone look at that horrible code? Post it for review to find out all the things that are wrong with it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-11T16:58:00.347",
"Id": "126944",
"Score": "1",
"body": "@DarthGizka: That wouldn't be recommended as it's someone else's code."
}
] |
[
{
"body": "<p>The short answer: restrict your sieving to what is necessary (sieve potential factors up to the square root of the upper end of the range, sieve the range itself). The runtime for that is a few milliseconds, compared to several seconds (or even minutes) for sieving <strong>all</strong> numbers up to the upper end of the range. </p>\n\n<p>An extensive answer with all the bells and whistles is at StackOverflow, where the SPOJ PRIME1 question has already been asked and answered:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/14003876/how-do-i-efficiently-sieve-through-a-selected-range-for-prime-numbers/26840156#26840156\">How do I efficiently sieve through a selected range for prime numbers?</a></p>\n\n<p>In addition to what is said there: trial division is the slowest form of primality test ever. The <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">Sieve of Eratosthenes</a> is equally simple but it is the fastest of them all, for small numbers up to 2^64 or thereabouts. Special requirements like that of SPOJ PRIME1 require small complications - e.g. windowed/segmented operation - and there are many complications that can be added to make it even faster if that is desired. See the linked article. However, for SPOJ I would keep things sweet and simple.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-11T16:40:05.977",
"Id": "69505",
"ParentId": "20694",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T04:13:26.887",
"Id": "20694",
"Score": "1",
"Tags": [
"c",
"programming-challenge",
"primes",
"time-limit-exceeded"
],
"Title": "SPOJ Problem 2 - Prime Generator"
}
|
20694
|
<p>I have the following code below I was wondering if there is a way to clean it up/improve it especially near the if statements. I am new to programming and this is what I came up with and its working fine I just think there might be a better way to accomplish it.</p>
<pre><code> <?php
require 'DB.php';
try {
$stmt = $conn->prepare('SELECT * FROM equipment');
$stmt->execute();
} catch(PDOException $e){
echo'ERROR: ' . $e->getMessage();
}
echo "<table class='tableTwo'>
<tr>
<th>Equipment Type</th>
<th>Unit Number</th>
<th>Last Updated</th>
<th>Current Hours</th>
<th>Scheduled PM</th>
</tr>";
while($row = $stmt->fetch())
{
echo "<tr>";
echo "<td>" . $row['equipType'] . "</td>";
echo "<td>" . $row['unitNumber'] . "</td>";
echo "<td>" . $row['lastUpdate'] . "</td>";
if ($row['nextPM'] - $row['currentHours'] > 100) {
echo "<td class='good'>" . $row['currentHours'] . "</td>";
echo "<td class='good'>" . $row['nextPM'] . "</td>";
} else if ($row['nextPM'] - $row['currentHours'] < 100 && $row['nextPM'] - $row['currentHours'] > 50){
echo "<td class='soon'>" . $row['currentHours'] . "</td>";
echo "<td class='soon'>" . $row['nextPM'] . "</td>";
}
else {
echo "<td class='bad'>" . $row['currentHours'] . "</td>";
echo "<td class='bad'>" . $row['nextPM'] . "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
</code></pre>
|
[] |
[
{
"body": "<p>My own personal preference when outputting things like this is to put the portion where data is actually retrieved in a separate file and then use the alternate PHP structure syntax. While this probably isn't everyone's preferred coding style, in my opinion it makes it easier to structure HTML so that its readable among the PHP. From what I have seen, this appears to be relatively common in templates.</p>\n\n<p>Just a quick once-over your file to show you what I mean:</p>\n\n<pre><code><?php\nrequire 'DB.php'\n\ntry {\n $stmt = $conn->query('SELECT * FROM equipment');\n} \ncatch(PDOException $e){\n echo'ERROR: ' . $e->getMessage();\n die();\n}\n\n?>\n<table class='tableTwo'>\n <tr>\n <th>Equipment Type</th>\n <th>Unit Number</th>\n <th>Last Updated</th>\n <th>CurrentHours</th>\n <th>Scheduled PM</th>\n </tr>\n<?php while($row = $stmt->fetch()): ?>\n <tr>\n <td><?php echo htmlspecialchars($row['equipType']); ?></td>\n <td><?php echo htmlspecialchars($row['unitNumber']); ?></td>\n <td><?php echo htmlspecialchars($row['lastUpdate']); ?></td>\n<?php if ($row['nextPM'] - $row['currentHours'] > 100): ?>\n <td class='good'><?php echo htmlspecialchars($row['currentHours']); ?></td>\n <td class='good'><?php echo htmlspecialchars($row['nextPM']); ?></td>\n<?php elseif ($row['nextPM'] - $row['currentHours'] < 100 && $row['nextPM'] - $row['currentHours'] > 50): ?>\n <td class='soon'><?php echo htmlspecialchars($row['currentHours']); ?></td>\n <td class='soon'><?php echo htmlspecialchars($row['nextPM']); ?></td>\n<?php else: ?>\n <td class='bad'><?php echo htmlspecialchars($row['currentHours']); ?></td>\n <td class='bad'><?php echo htmlspecialchars($row['nextPM']); ?></td>\n<?php endif; ?>\n </tr>\n<?php endwhile; ?>\n</table>\n</code></pre>\n\n<p>Again, if I were doing this I would separate that top half into another file and have that file include your \"template\" which would output the actual HTML. You could also use a template engine like <a href=\"http://phpsavant.com/\" rel=\"nofollow\">Savant3</a> to make the separation a little cleaner and the templating better.</p>\n\n<p>Demonstration with savant3:</p>\n\n<p>Your main file (index.php perhaps?):</p>\n\n<pre><code><?php\nrequire 'DB.php'\nrequire_once 'Savant3.php'\n$tpl = new Savant3();\n\ntry {\n\n $stmt = $conn->query('SELECT * FROM equipment');\n $tpl->data = $stmt; \n} \ncatch(PDOException $e){\n echo'ERROR: ' . $e->getMessage();\n die();\n}\n\n$tpl->display('table.tpl.php');\n\n?>\n</code></pre>\n\n<p>Then in your template file (table.tpl.php in this example):</p>\n\n<pre><code><table class='tableTwo'>\n <tr>\n <th>Equipment Type</th>\n <th>Unit Number</th>\n <th>Last Updated</th>\n <th>CurrentHours</th>\n <th>Scheduled PM</th>\n </tr>\n<?php foreach($this->data as $row): ?>\n <?php $class = \"bad\";\n if ($row['nextPM'] - $row['currentHours'] > 100) {\n $class = \"good\";\n }\n elseif ($row['nextPM'] - $row['currentHours'] < 100 && $row['nextPM'] - $row['currentHours'] > 50) {\n $class = \"soon\";\n }\n ?>\n <tr>\n <td><?php echo htmlspecialchars($row['equipType']); ?></td>\n <td><?php echo htmlspecialchars($row['unitNumber']); ?></td>\n <td><?php echo htmlspecialchars($row['lastUpdate']); ?></td>\n <td class='<?php echo $class; ?>'><?php echo htmlspecialchars($row['currentHours']); ?></td>\n <td class='<?php echo $class; ?>'><?php echo htmlspecialchars($row['nextPM']); ?></td>\n </tr>\n<?php endforeach; ?>\n</table>\n</code></pre>\n\n<p>Note that I changed the while into a foreach because I personally don't like doing an assignment and comparison in the same statement. You can foreach over a PDOStatement (as far as I know) just as well as you can fetch from it.</p>\n\n<p>EDIT: Also, you don't necessarily need to prepare the statment with the PDOs if there are no arguments. Of course, that's all up to preference again. If you have arguments, though, definitely use the prepared statements.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T03:30:00.420",
"Id": "33491",
"Score": "0",
"body": "I feel it is important to demonstrate proper security when posting example code. Can you please update your example to include XSS protection?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T17:23:38.343",
"Id": "33552",
"Score": "0",
"body": "That should do it...it's pretty basic since its just htmlspecialchars, but it should work so long as they don't actually need html to be displayed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T04:39:00.510",
"Id": "20696",
"ParentId": "20695",
"Score": "3"
}
},
{
"body": "<p>First of all read Los Frijoles post, he is right :)</p>\n\n<p>In addition to that you should extract large (not fitting on the screen/iframe) conditions in a variable (readability over performance) and move the common parts of your if branches out of your if. (I also use the short tag in templates, but this is an other discussion :P)</p>\n\n<pre><code><?php foreach($this->data as $row): ?>\n <?php \n $isGood=$row['nextPM'] - $row['currentHours'] > 100;\n $isSoon=$row['nextPM'] - $row['currentHours'] < 100 && \n $row['nextPM'] - $row['currentHours'] > 50;\n if ($isGood) $class=\"good\";\n else if ($isSoon) $class=\"soon\";\n else $class=\"bad\";\n ?>\n <tr>\n <td><?=$row['equipType'] ?></td>\n <td><?=$row['unitNumber'] ?></td>\n <td><?=$row['lastUpdate'] ?></td>\n <td class='<?=$class ?>'><?=$row['currentHours'] ?></td>\n <td class='<?=$class ?>'><?=$row['nextPM'] ?></td>\n </tr>\n<?php endforeach; ?>\n</code></pre>\n\n<p>Of course you should move this logic into your other php file, but for demonstration this is fine.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T07:43:02.147",
"Id": "20700",
"ParentId": "20695",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T04:32:53.567",
"Id": "20695",
"Score": "1",
"Tags": [
"php"
],
"Title": "echoing html tags in php"
}
|
20695
|
<p>I've made a small breakout game, so far with one level. My plan is to expand it so that it has a level editor, but for now I wanted to make sure that everything is currently looking well-designed. I don't use js a lot so I'm not always very sure where to put things.</p>
<p>Just a heads up, the collision doesn't work entirely, but that's a side issue that can be fixed in it's own function. If you'd like to give it a try, go for it, but mainly I want to see what you think of the rest of the code and the structure.</p>
<p>The game is already hosted on my website, but since I don't have all the features I want it isn't linked to anywhere but <a href="http://www.tomprats.com/games/game.html" rel="nofollow">here</a> now.</p>
<p>Since I assume people want the actual code here and not having to inspect for it, here ya go.</p>
<pre><code>var then;
var text;
var canvasW = 600;
var canvasH = 400;
var numX = 30;
var numY = 20;
var blockW = 20;
var blockH = 15;
var paddleW = 50;
var paddleH = 5;
var paddleX = canvasW/2-paddleW/2;
var paddleY = canvasH - 10;
var ballX = paddleX+paddleW/2;
var ballY = paddleY-2.5;
var ballS = 5;
var maxSpeed = paddleW*5;
var ballSpeedX = 0;
var ballSpeedY = maxSpeed;
var ballDirX = 1;
var ballDirY = -1;
var ballAlive = true;
var ballReleased = false;
var gameBoard = new Array(numX);
for(var i = 0; i < numX; i++) {
gameBoard[i] = new Array(numY);
for(var j = 0; j < numY; j++) {
gameBoard[i][j] = 'black';
}
}
var ctx;
var canvas;
var keysDown = {};
$(document).ready(function() {
if (Modernizr.canvas) {
$('#broken').hide();
initialize();
then = Date.now();
setInterval(main, 1);
}
});
addEventListener("keydown", function (e) {
keysDown[e.keyCode] = true;
}, false);
addEventListener("keyup", function (e) {
delete keysDown[e.keyCode];
}, false);
function initialize(){
$('#game').removeClass();
canvas = $('<canvas>');
canvas.attr('id', 'canvas');
canvas.attr('width', $('#game').width());
canvas.attr('height', $('#game').height());
canvas.appendTo('#game');
ctx = $('#canvas')[0].getContext("2d");
levelSelect(1);
}
function main() {
var now = Date.now();
var delta = now - then;
update(delta / 1000);
draw();
then = now;
};
function levelSelect(i){
switch(i) {
case 1:
level1();
break;
case 2:
level2();
break;
}
}
function level1() {
for(var i = 0; i < numX; i++) {
gameBoard[i][0] = 'gray';
if(i<numY) {
gameBoard[0][i] = 'gray';
gameBoard[numX-1][i] = 'gray';
}
}
for(var i = 4; i < numX; i++) {
for(var j = 2; j < numY; j++) {
gameBoard[i-2][j] = 'green';
}
}
}
function update(time) {
keys(time);
ball(time);
}
function keys(time) {
if ((37 in keysDown)&&(paddleX > 0)) { // Player holding left
paddleX -= 256*time;
}
if ((39 in keysDown)&&(paddleX < canvasW-paddleW)) { // Player holding right
paddleX += 256*time;
}
if (32 in keysDown) {
ballReleased = true;
}
if (32 in keysDown) {
text = "";
}
}
function ball(time) {
if(ballAlive)
{
if(ballReleased) {
moveBallY(time);
moveBallX(time);
checkBlocks();
}
else {
ballX = paddleX+paddleW/2;
ballY = paddleY-2.5;
}
} else {
resetBall();
}
}
function resetBall() {
ballSpeedX = 0;
ballSpeedY = maxSpeed;
ballDirX = 1;
ballDirY = -1;
ballAlive = true;
ballReleased = false;
}
function moveBallX(time) {
if(checkXWalls(time)) {
ballDirX = -ballDirX;
}
ballX = ballX + ballSpeedX*ballDirX*time;
}
function moveBallY(time) {
if(checkYWalls(time)||checkPaddle(time))
{
ballDirY = -ballDirY;
}
ballY = ballY + ballSpeedY*ballDirY*time;
}
function checkBlocks(time) {
if(contains(ballX, ballY)) {
var ballXC = ballX + ballS/2;
var ballYC = ballY + ballS/2;
var ballLeft = ballXC - ballS/2 - 1;
var ballRight = ballXC + ballS/2 + 1;
var ballTop = ballYC - ballS/2 - 1;
var ballBottom = ballYC + ballS/2 + 1;
text = "";
if(contains(ballLeft, ballYC)) {
hit(ballLeft, ballYC);
text = text + "left";
ballDirX = 1;
} if (contains(ballRight, ballYC)) {
text = text + "right";
hit(ballRight, ballYC);
ballDirX = -1;
} if(contains(ballXC, ballTop)) {
text = text + "top";
hit(ballXC, ballTop);
ballDirY = 1;
} else if (contains(ballXC, ballBottom)) {
text = text + "bottom";
hit(ballXC, ballBottom);
ballDirY = -1;
}
}
}
function contains(i, j) {
var x = Math.floor(i/blockW);
var y = Math.floor(j/blockH);
var block = gameBoard[x][y];
return intersects(block);
}
function intersects(block) {
if((block != 'black')&&(typeof block != 'undefined')) {
return true;
} else {
return false;
}
}
function hit(i, j) {
var x = Math.floor(i/blockW);
var y = Math.floor(j/blockH);
if(gameBoard[x][y] != 'gray') {
gameBoard[x][y] = 'black';
}
}
function checkXWalls(time) {
var newBallX = ballX + ballSpeedX*ballDirX*time;
if((newBallX <= 0)||(newBallX >= canvasW)) {
return true;
} else {
return false;
}
}
function checkYWalls(time) {
var newBallY = ballY + ballSpeedY*ballDirY*time;
if(newBallY <= 0) {
return true;
} else if (newBallY >= canvasH) {
ballAlive = false;
return false;
}
return false;
}
function checkPaddle(time) {
var newBallX = ballX + ballSpeedX*ballDirX*time;
var newBallY = ballY + ballSpeedY*ballDirY*time;
if((newBallX >= paddleX) && (newBallX <= paddleX + paddleW)
&& (newBallY >= paddleY)
&& (newBallY <= paddleY + paddleH)) {
ballSpeedX = (ballX - (paddleX + paddleW/2))*10;
if(ballSpeedX<0) {
ballSpeedX = -ballSpeedX;
ballDirX = -1;
} else {
ballDirX = 1;
}
ballSpeedY = maxSpeed - ballSpeedX;
return true;
}
return false;
}
function draw() {
if(ctx) {
drawBackground();
drawBoard();
if(ballAlive) {
drawBall();
}
drawPaddle();
ctx.fillStyle = "blue";
ctx.font = "bold 16px Arial";
ctx.fillText(text, 100, 100);
}
}
function drawBackground() {
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, canvasW, 400);
}
function drawBoard() {
for(var i = 0; i < numX; i++) {
for(var j = 0; j < numY; j++) {
if(gameBoard[i][j] != 'black') {
ctx.fillStyle = gameBoard[i][j];
ctx.strokeStyle = 'blue';
ctx.fillRect(i*blockW,j*blockH, blockW, blockH);
ctx.strokeRect(i*blockW,j*blockH, blockW, blockH);
}
}
}
}
function drawPaddle() {
ctx.fillStyle = 'blue';
ctx.fillRect(paddleX, paddleY, paddleW, paddleH);
}
function drawBall() {
ctx.beginPath();
ctx.arc(ballX, ballY, ballS/2, 0, 2 * Math.PI, false);
ctx.fillStyle = 'white';
ctx.fill();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T19:57:27.400",
"Id": "33210",
"Score": "0",
"body": "Do you know about [requestAnimationFrame](http://creativejs.com/resources/requestanimationframe/)? I haven't used it yet but would probably try it if I was making a new game. That link also notes that max frame rate is usually 60, so `setInterval` with an interval of less than 17 might not make sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T02:06:24.360",
"Id": "33222",
"Score": "0",
"body": "by setting it to 1 it just does it as fast as possible, the time variable keeps track of how fast it happens and the code works off of that. it probably wouldnt be good to do in a more complex game, but since it's 1P breakout it doesnt really matter. requestAnimationFrame actually looks pretty cool, I'll probably use that and polyfill for the next project i do"
}
] |
[
{
"body": "<p>You might want to put all the canvas stuff into an object or class.</p>\n\n<pre><code>function Canvas() {\n var el = $('<canvas>'),\n ctx;\n this.width = 600;\n this.height = 400;\n el.attr('id', 'canvas');\n el.attr('width', $('#game').width());\n el.attr('height', $('#game').height());\n el.appendTo('#game');\n ctx = $('#canvas')[0].getContext(\"2d\");\n this.draw = function () {\n if (ctx) {\n drawBackground();\n drawBoard();\n if (ballAlive) {\n drawBall();\n }\n drawPaddle();\n ctx.fillStyle = \"blue\";\n ctx.font = \"bold 16px Arial\";\n ctx.fillText(text, 100, 100);\n }\n }\n\n function drawBackground() {\n ctx.fillStyle = 'black';\n ctx.fillRect(0, 0, canvasW, 400);\n }\n\n function drawBoard() {\n for (var i = 0; i < numX; i++) {\n for (var j = 0; j < numY; j++) {\n if (gameBoard[i][j] != 'black') {\n ctx.fillStyle = gameBoard[i][j];\n ctx.strokeStyle = 'blue';\n ctx.fillRect(i * blockW, j * blockH, blockW, blockH);\n ctx.strokeRect(i * blockW, j * blockH, blockW, blockH);\n }\n }\n }\n }\n\n function drawPaddle() {\n ctx.fillStyle = 'blue';\n ctx.fillRect(paddleX, paddleY, paddleW, paddleH);\n }\n\n function drawBall() {\n ctx.beginPath();\n ctx.arc(ballX, ballY, ballS / 2, 0, 2 * Math.PI, false);\n ctx.fillStyle = 'white';\n ctx.fill();\n }\n}\n</code></pre>\n\n<p>This keeps all the drawing code separate from the game logic, which will simplify the other functions, and allows you to have variables storing state of the drawn objects if necessary, without having to make more global variables.</p>\n\n<p>In the <code>initialize</code> function you then just need <code>canvas = new Canvas()</code>, and you can access <code>canvas.width</code>, <code>canvas.height</code> and <code>canvas.draw()</code> as needed.</p>\n\n<p>In general as the game increases in complexity it is likely to be useful to group functions and variables that are currently all in the global scope, into objects. Ball and paddle are obvious candidates. e.g. <code>paddleX -= 256*time</code> could get replaced with <code>paddle.move('left', time)</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T02:11:48.047",
"Id": "33225",
"Score": "0",
"body": "thanks, I like how you organized the canvas a lot. I at first tried to use them as separate functions because I didn't want to pass them around, but this solves that problem. thanks for all the help"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T20:21:36.477",
"Id": "20728",
"ParentId": "20704",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "20728",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T10:10:30.160",
"Id": "20704",
"Score": "1",
"Tags": [
"javascript",
"collision"
],
"Title": "Breakout-like game in JS"
}
|
20704
|
<p>My son (9) is learning Python and wrote this temperature conversion program. He can see that there is a lot of repetition in it and would like to get feedback on ways to make it shorter.</p>
<pre><code>def get_temperature():
print "What is your temperature?"
while True:
temperature = raw_input()
try:
return float(temperature)
except ValueError:
print "Not a valid temperature. Could you please do this again?"
print "This program tells you the different temperatures."
temperature = get_temperature()
print "This is what it would be if it was Fahrenheit:"
Celsius = (temperature - 32)/1.8
print Celsius, "degrees Celsius"
Kelvin = Celsius + 273.15
print Kelvin, "Kelvin"
print "This is what it would be if it was Celsius."
Fahrenheit = temperature * 9 / 5 + 32
print Fahrenheit, "degrees Fahrenheit"
Kelvin = temperature + 273.15
print Kelvin, "Kelvin"
print "This is what it would be if it was Kelvin"
Celsius = temperature - 273.15
print Celsius, "degrees Celsius"
Fahrenheit = Celsius * 9 / 5 + 32
print Fahrenheit, "degrees Fahrenheit"
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T12:56:32.623",
"Id": "33194",
"Score": "0",
"body": "Out of curiosity: why didn't your son ask here himself?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T12:59:52.990",
"Id": "33195",
"Score": "5",
"body": "[`Subscriber certifies to Stack Exchange that if Subscriber is an individual (i.e., not a corporate entity), Subscriber is at least 13 years of age`](http://stackexchange.com/legal#1AccesstotheServices)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T13:12:23.787",
"Id": "33197",
"Score": "0",
"body": "@vikingosegundo I did not know that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T13:20:42.360",
"Id": "33198",
"Score": "2",
"body": "@svick I think it is quite common to exclude kids younger than 13. So maybe this 9-yo is very clever and poses as his father :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T19:04:41.963",
"Id": "33208",
"Score": "0",
"body": "Although the answers already given below are useful, I would say the first thing is to consider whether he really wants to print all possible conversions, or instead allow the user to specify a unit (which as it happens would avoid the need for most of the repetition). I.e. think about the aim of the programme before implementation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T02:09:36.030",
"Id": "33224",
"Score": "3",
"body": "I just realized the delightful detail of not adding 'degrees' in front of 'Kelvin'! I've had professors in college doing it wrong all the time..."
}
] |
[
{
"body": "<p>He should define functions that he can re-use:</p>\n\n<pre><code>def fahrenheit_from_celsius(temprature):\n return temperature * 9 / 5 + 32\n\n\nprint fahrenheit_from_celsius(get_temperature())\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T12:24:57.323",
"Id": "20709",
"ParentId": "20708",
"Score": "1"
}
},
{
"body": "<p>The most repetition in that program comes from printing the converted temperatures. When a program contains repeated code, the most common solution is to <a href=\"http://en.wikipedia.org/wiki/Code_refactoring\" rel=\"nofollow\">refactor</a> the code by extracting a function. The new function would contain the common parts, and use its parameters for the differing parts.</p>\n\n<p>In your case, the function could look like this:</p>\n\n<pre><code>def print_temperatures(original_unit, first_value, first_unit, second_value, second_unit):\n print \"This is what it would be if it was\", original_unit\n print first_value, first_unit\n print second_value, second_unit\n</code></pre>\n\n<p>The code to print the temperatures (assuming the differences in punctuation are not intentional):</p>\n\n<pre><code>print \"This program tells you the different temperatures.\"\ntemperature = get_temperature()\n\nCelsius = (temperature - 32)/1.8\nKelvin = Celsius + 273.15\nprint_temperatures(\"Fahrenheit\", Celsius, \"degrees Celsius\", Kelvin, \"Kelvin\")\n\nFahrenheit = temperature * 9 / 5 + 32\nKelvin = temperature + 273.15\nprint_temperatures(\"Celsius\", Fahrenheit, \"degrees Fahrenheit\", Kelvin, \"Kelvin\")\n\nCelsius = temperature - 273.15\nFahrenheit = Celsius * 9 / 5 + 32\nprint_temperatures(\"Kelvin\", Celsius, \"degrees Celsius\", Fahrenheit, \"degrees Fahrenheit\")\n</code></pre>\n\n<p>This still leaves some repetition in the temperature conversions themselves. This could be again solved by extracting a function for each conversion. Another solution would be to <a href=\"http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29\" rel=\"nofollow\">encapsulate</a> all the conversions into a class. That way, your code could look something like:</p>\n\n<pre><code>temperature_value = get_temperature()\n\ntemperature = Temperature.from_fahrenheit(temperature_value)\nprint_temperatures(\"Fahrenheit\", temperature.Celsius, \"degrees Celsius\", temperature.Kelvin, \"Kelvin\")\n</code></pre>\n\n<p>But creating a class would make more sense if conversions were used more, it probably isn't worth it for this short program.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T13:55:35.467",
"Id": "20713",
"ParentId": "20708",
"Score": "1"
}
},
{
"body": "<p>Some of what I am going to write may be a little too much for a 9 year old, but if he was able to produce such neat, structured code on his own, he should be ready for some further challenge.</p>\n\n<p>So to make things less repetitive, all you have to do is figure out how to make what appears different to share a common framework. For the temperature conversions, they are all of the form:</p>\n\n<pre><code>return_value = (input_value + a) * b + c\n</code></pre>\n\n<p>Lazy programmers are better programmers, so you don´t want to figure out all six possible transformations by hand, so note that the reverse transformation has the form:</p>\n\n<pre><code>input_value = (return_value - c) / b - a\n</code></pre>\n\n<p>Furthermore, even specifying three of six transformations is too many, since you can always convert, e.g. from Celsius to Kelvin and then to Fahrenheit. So we just need to choose a <code>BASE_UNIT</code> and encode a transformation to or from it to all other. This will also make it a breeze to include <a href=\"http://en.wikipedia.org/wiki/Rankine_scale\" rel=\"nofollow\">Rankine degrees</a> or any other of the weird scales if you would so desire in the future.</p>\n\n<p>So the code below is probably going to end up being longer than what you posted, but the main program is just four lines of code, there's quite a lot of error checking, and it would be a breeze to update to new units:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>UNITS = 'fck'\nBASE_UNIT = 'k'\nUNIT_NAMES = {'f' : 'Fahrenheit', 'c' : 'Celsius', 'k' : 'Kelvin'}\nCONVERSION_FACTORS = {'fk' : (-32., 5. / 9., 273.16),\n 'ck' : (273.16, 1., 0.)}\n\ndef get_temperature():\n print \"What is your temperature?\"\n while True:\n temperature = raw_input()\n try:\n return float(temperature)\n except ValueError:\n print \"Not a valid temperature. Could you please do this again?\"\n\ndef convert_temp(temp, unit_from, unit_to) :\n if unit_from != BASE_UNIT and unit_to != BASE_UNIT :\n return convert_temp(convert_temp(temp, unit_from, BASE_UNIT),\n BASE_UNIT, unit_to)\n else :\n if unit_from + unit_to in CONVERSION_FACTORS :\n a, b, c = CONVERSION_FACTORS[unit_from + unit_to]\n return (temp + a) * b + c\n elif unit_to + unit_from in CONVERSION_FACTORS :\n a, b, c = CONVERSION_FACTORS[unit_to + unit_from]\n return (temp - c) / b - a \n else :\n msg = 'Unknown conversion key \\'{0}\\''.format(unit_from + unit_to)\n raise KeyError(msg)\n\ndef pretty_print_temp(temp, unit_from) :\n if unit_from not in UNITS :\n msg = 'Unknown unit key \\'{0}\\''.format(unit_from)\n raise KeyError(msg)\n txt = 'This is what it would be if it was {0}'\n print txt.format(UNIT_NAMES[unit_from])\n for unit_to in UNITS.replace(unit_from, '') :\n print '{0:.1f} degrees {1}'.format(convert_temp(temp, unit_from,\n unit_to),\n UNIT_NAMES[unit_to])\n\nif __name__ == '__main__' :\n\n print \"This program tells you the different temperatures.\"\n temperature = get_temperature()\n\n for unit_from in UNITS :\n pretty_print_temp(temperature, unit_from)\n</code></pre>\n\n<hr>\n\n<p><strong>EDIT</strong> As an aside, for minimal length without modifying the logic of the original code, the following would work:</p>\n\n<pre><code>print \"This program tells you the different temperatures.\"\ntemperature = get_temperature()\ntext = ('This is what it would be if it was {0}:\\n'\n '{1:.1f} {2}\\n{3:.1f} {4}')\nprint \nCelsius = (temperature - 32) / 1.8\nKelvin = Celsius + 273.15\nprint text.format('Fahrenheit', Celsius, 'degrees Celsius', Kelvin, 'Kelvin')\nFahrenheit = temperature * 9 / 5 + 32\nKelvin = temperature + 273.15\nprint text.format('Celsius', Fahrenheit, 'degrees Fahrenheit', Kelvin,\n 'Kelvin')\nCelsius = temperature - 273.15\nFahrenheit = Celsius * 9 / 5 + 32\nprint text.format('Kelvin', Celsius, 'degrees Celsius', Fahrenheit,\n 'Fahrenheit')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T20:17:20.233",
"Id": "33212",
"Score": "2",
"body": "A solution like this might make sense if you wanted to convert between many different units. But if you expect that you won't need any unusual units, this code is way too overengineered. Besides the question is how to make the program shorter, you made it longer and much more complicated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T23:10:58.537",
"Id": "33216",
"Score": "0",
"body": "Your temperature conversions could get lazier still, since they are actually all of the form `return_value = input_value * a + c`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T23:31:18.463",
"Id": "33217",
"Score": "0",
"body": "@svick I'd argue that the program is actually much, much shorter: 4 lines of code. It's the temperature conversion library functions that take up more space... In any real production environment in which you had to do all six possible conversions, I really don't see coding six different functions as a good design practice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T23:32:01.910",
"Id": "33218",
"Score": "0",
"body": "@Stuart But that would actually require me to do some of the math that I can have the computer do!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T00:19:34.130",
"Id": "33219",
"Score": "1",
"body": "@Jaime For me “a program” is all code I have to develop and maintain for it. And that's not 4 lines in your case. And I really do think that 6 one-line functions are better than one big, that is hard to understand."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T01:28:55.667",
"Id": "33220",
"Score": "0",
"body": "@svick I really don´t want to get into an argument about coding styles, but I see my code as easier to maintain, because all the logic is in one place. And given the very descriptive nature of the variable names, I do not find it that hard to understand. For the purpose of this particular program, there is no point in writing **any** function, because each conversion is done only once! Yet we both agree that encapsulating that logic is a good thing, right? I like to take things a little further. You don't. Can we agree to disagree?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T01:47:51.623",
"Id": "33221",
"Score": "1",
"body": "I would say the problem is more that `convert_temp` is needlessly complicated and could be reduced to a few lines and made easier to read at the same time http://pastebin.com/jQkmR8Rz"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T02:08:15.077",
"Id": "33223",
"Score": "0",
"body": "@Stuart Very nice approach, indeed!"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T16:07:52.717",
"Id": "20717",
"ParentId": "20708",
"Score": "2"
}
},
{
"body": "<p>The easiest way to remove repetition here is with nested <code>for</code> loops, going through all the combinations of units. In the code below I also use the fact that you can convert between any two scales in the following way:</p>\n\n<ol>\n<li>subtract something then divide by something to get back to Celsius, then</li>\n<li>multiply by something then add something to get to the desired unit</li>\n</ol>\n\n<p>The \"something\"s can be stored in a single tuple (list of values), making the conversions simpler.</p>\n\n<pre><code>scales = ('Celsius', 'degrees ', 1, 0), ('Farenheit', 'degrees ', 1.8, 32), ('Kelvin', '', 1, 273.15)\nvalue = get_temperature()\nfor from_unit, _, slope1, intercept1 in scales:\n print \"This is what it would be if it was\", from_unit\n celsius = (value - intercept1) / slope1\n for to_unit, prefix, slope2, intercept2 in scales:\n if to_unit != from_unit:\n print '{0} {1}{2}'.format(intercept2 + slope2 * celsius, degrees, to_unit)\n</code></pre>\n\n<p>Dividing code into functions is of course a good idea in general, but not that useful in this case. If he's interested in performing other operations on temperatures it might be interesting to go a step further and make a simple class like the following.</p>\n\n<pre><code>scales = {\n 'Celsius': ('degrees ', 1, 0),\n 'Farenheit': ('degrees ', 1.8, 32),\n 'Kelvin': ('', 1, 273.15)\n }\nclass Temperature: \n def __init__(self, value, unit = 'Celsius'):\n self.original_unit = unit\n _, slope, intercept = scales[unit]\n self.celsius = (value - intercept) / slope\n def to_unit(self, unit):\n _, slope, intercept = scales[unit]\n return slope * self.celsius + intercept\n def print_hypothetical(self):\n print \"This is what it would be if it was\", self.original_unit\n for unit, (prefix, _, _) in scales.iteritems():\n if unit != self.original_unit:\n print \"{0} {1}{2}\".format(self.to_unit(unit), prefix, unit)\nvalue = get_temperature()\nfor unit in scales:\n m = Temperature(value, unit)\n m.print_hypothetical()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T22:18:06.727",
"Id": "20732",
"ParentId": "20708",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "20732",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T12:17:27.710",
"Id": "20708",
"Score": "3",
"Tags": [
"python",
"converting"
],
"Title": "Temperature conversion program with a lot of repetition"
}
|
20708
|
<p>I'm coding a Minesweeper clone using Java and Swing. For my current knowledge, I manage to keep it working but two things are giving me nightmares. Namely, I have a VERY repetitive code so I suppose there should be a way to write it once only and use twice but I don't know how to do it as the things it does when the conditions are met are highly different.</p>
<pre><code>private void placeBombs(CellOnGrid[][] currentGrid)
{
boolean wasTheBombPlaced = false;
for(int i=_howManyMinesOnGrid; i>0; --i)
{
while(!wasTheBombPlaced)
{
int potentialY = (int) Math.rint(Math.random()*(getGridHeight()-1));
int potentialX = (int) Math.rint(Math.random()*(getGridWidth()-1));
if(!currentGrid[potentialY][potentialX].getBomb())
{
currentGrid[potentialY][potentialX].setBomb();
wasTheBombPlaced = true;
if(potentialY>0) {currentGrid[potentialY-1][potentialX].incrementHintNumber();}
if(potentialY<(getGridHeight()-1)) {currentGrid[potentialY+1][potentialX].incrementHintNumber();}
if(potentialX>0) {currentGrid[potentialY][potentialX-1].incrementHintNumber();}
if(potentialX<(getGridWidth()-1)) {currentGrid[potentialY][potentialX+1].incrementHintNumber();}
if((potentialY>0)&&(potentialX>0)) {currentGrid[potentialY-1][potentialX-1].incrementHintNumber();}
if((potentialY>0)&&(potentialX<(getGridWidth()-1))) {currentGrid[potentialY-1][potentialX+1].incrementHintNumber();}
if(potentialY<(getGridHeight()-1)&&(potentialX>0)) {currentGrid[potentialY+1][potentialX-1].incrementHintNumber();}
if(potentialY<(getGridHeight()-1)&&(potentialX<(getGridWidth()-1))) {currentGrid[potentialY+1][potentialX+1].incrementHintNumber();}
}
}
wasTheBombPlaced = false;
}
</code></pre>
<p>Its purpose is to simply put the bombs randomly and for each bomb placed, check if it's far enough from an edge (or two edges) to increment the corresponding cell's hint number. Also, please note I number my X, Y coordinates from the <em>upper-left</em> corner so (0,0) is the first cell both from the top and from the left. This code, then, just asks 8 questions of the form: "Are you at least one line from the top?" and if it is, then it increments the hint number of the cell above the one we just placed our bomb on.</p>
<p>Problem is, I use <em>the very same questions</em> when user clicks something that is not a bomb. Then, the Action Listener invokes the <code>revealEmpty</code> recursive method which looks like this:</p>
<pre><code>public void revealEmpty(int lineNumber, int columnNumber)
{
--_cellsLeftToBeRevealed;
buttonsArray[lineNumber][columnNumber].setEnabled(false);
buttonsArray[lineNumber][columnNumber].showIcon();
if(buttonsArray[lineNumber][columnNumber].getHintNumber()==0)
{
if(lineNumber>0) {
if(isSuitableForRevealing(lineNumber-1, columnNumber)){
revealEmpty(lineNumber-1, columnNumber);}
}
if(lineNumber<(getGridHeight()-1)) {
if(isSuitableForRevealing(lineNumber+1, columnNumber)){
revealEmpty(lineNumber+1, columnNumber);}
}
if(columnNumber>0) {
if(isSuitableForRevealing(lineNumber, columnNumber-1)){
revealEmpty(lineNumber, columnNumber-1);}
}
if(columnNumber<(getGridWidth()-1)) {
if(isSuitableForRevealing(lineNumber, columnNumber+1)){
revealEmpty(lineNumber, columnNumber+1);}
}
if((lineNumber>0)&&(columnNumber>0)) {
if(isSuitableForRevealing(lineNumber-1, columnNumber-1)){
revealEmpty(lineNumber-1, columnNumber-1);}
}
if((lineNumber>0)&&(columnNumber<(getGridWidth()-1))) {
if(isSuitableForRevealing(lineNumber-1, columnNumber+1)){
revealEmpty(lineNumber-1, columnNumber+1);}
}
if(lineNumber<(getGridHeight()-1)&&(columnNumber>0)) {
if(isSuitableForRevealing(lineNumber+1, columnNumber-1)){
revealEmpty(lineNumber+1, columnNumber-1);}
}
if(lineNumber<(getGridHeight()-1)&&(columnNumber<(getGridWidth()-1))) {
if(isSuitableForRevealing(lineNumber+1, columnNumber+1)){
revealEmpty(lineNumber+1, columnNumber+1);}
}
}
</code></pre>
<p>This one reveals what was under the clicked button and, asking the very same questions, goes deeper until there's nothing left to be revealed (the <code>isSuitableForRevealing()</code> just checks if a cell of given coordinates can still be revealed and <code>showIcon()</code> makes the object select an appropriate icon for itself to show while it's disabled).</p>
<p>How could I make this code better and not repeat myself twice with the same ifs?</p>
<p>Also, I know it might be confusing that in <code>placeBombs()</code> I get <code>currentGrid</code> as argument and in <code>revealEmpty()</code> I use some <code>buttonsArray</code> - please note that it's the <em>same</em> array of <code>CellOnGrid[][]</code> objects. I just didn't have the whole code neatly planned from the beginning so I wrote <code>placeBombs()</code> as it is - it will be refactored to not get any arguments as well since always there's only one grid of <code>CellOnGrid</code> objects in the <code>Grid</code> class at given moment so I guess I may just use it directly (it's the class's instance variable) instead of passing it as an argument.</p>
|
[] |
[
{
"body": "<p>Did you thought about using a n+2 grid? Just don't place bombs at the border and don't display the other ring. So you can safely check and update all direction?</p>\n\n<p>But maybe you should abstract your grid in two levels, to get rid of the +-1 stuff and implement a iterator to get all neighbours.</p>\n\n<p><strong>Update</strong> \nGetting iterateable neighbours is pretty easy when you introduce a NullObject for nonexisting cells. (This is also helpful at other places.)</p>\n\n<pre><code>public class Grid\n{\n //...\n protected Cell getCell(int x, int y) {\n if (x < 1 || x > getWidth())\n return Cell.NULL;\n if (y < 1 || y > getHeight())\n return Cell.NULL;\n return cells[x][y];\n }\n\n protected boolean placeBomb(int x, int y) {\n if (!getCell(x, y).placeBomb())\n return false;\n\n for (Cell c : getNeighbours(x, y))\n c.incrementBombCount();\n return true;\n }\n\n public Set<Cell> getNeighbours(int x, int y) {\n Set<Cell> neighbours = new HashSet<>();\n neighbours.add(getCell(x - 1, y - 1));\n neighbours.add(getCell(x, y - 1));\n neighbours.add(getCell(x + 1, y - 1));\n neighbours.add(getCell(x - 1, y));\n neighbours.add(getCell(x + 1, y));\n neighbours.add(getCell(x - 1, y + 1));\n neighbours.add(getCell(x, y + 1));\n neighbours.add(getCell(x + 1, y + 1));\n neighbours.remove(Cell.NULL);\n return neighbours;\n }\n\n}\n</code></pre>\n\n<p>And the cell class:</p>\n\n<pre><code>public class Cell {\n\n public static Cell NULL = new NullCell();\n\n public static class NullCell extends Cell {\n private NullCell() {\n super(null, -1, -1);\n }\n\n @Override\n public Set<Cell> getNeighbours() {\n return Collections.emptySet();\n }\n\n @Override\n public boolean placeBomb() {\n return false;\n }\n //...\n }\n\n private final Grid grid;\n private final int x;\n private final int y;\n private VisualState state = VisualState.HIDDEN;\n private boolean bomb = false;\n private int bombCount = 0;\n\n public Cell(Grid grid, int x, int y) {\n this.grid = grid;\n this.x = x;\n this.y = y;\n }\n\n public Set<Cell> getNeighbours() {\n return grid.getNeighbours(x, y);\n }\n\n //...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T18:19:44.797",
"Id": "33204",
"Score": "0",
"body": "Thank you. Wouldn't it mess with the GridLayout, though? I mean - wouldn't the layout reserve space even for the invisible buttons?\n\nAlso, I'm afraid I'm on a waay too low level to implement some iterators to get the neighbours."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T07:42:34.987",
"Id": "33226",
"Score": "0",
"body": "Memory? I didn't read the requirement that you want to run it in an embedded system or old dos machine :) Seriously, in most cases readability has an higher value than a premature optimization."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T14:21:29.180",
"Id": "20715",
"ParentId": "20714",
"Score": "2"
}
},
{
"body": "<p>You can increase the readability and reduce the number of checks required in your if block by performing each of the four booleans you get at the start, then checking against them instead of performing it over and over as well as separating out the check then reveal logic into its own method, like so:</p>\n\n<pre><code>private void checkAndReveal(int linePosition, int columnPosition)\n{\n if(isSuitableForRevealing(linePosition, columnPosition))\n {\n revealEmpty(linePosition, columnPosition);\n }\n}\n</code></pre>\n\n<p>Then in the method:</p>\n\n<pre><code>if(buttonsArray[lineNumber][columnNumber].getHintNumber() == 0)\n{\n boolean notBottomRow = lineNumber < (getGridHeight() - 1);\n boolean notOuterColumn = columnNumber < (getGridWidth() - 1);\n boolean notFirstColumn = columnNumber > 0;\n boolean notTopRow = lineNumber > 0;\n\n if(notTopRow)\n {\n checkAndReveal(lineNumber - 1, columnNumber);\n if(notFirstColumn)\n {\n checkAndReveal(lineNumber - 1, columnNumber - 1);\n }\n if(notOuterColumn)\n {\n checkAndReveal(lineNumber - 1, columnNumber + 1);\n }\n }\n if(notBottomRow)\n {\n checkAndReveal(lineNumber + 1, columnNumber);\n if(notFirstColumn)\n {\n checkAndReveal(lineNumber + 1, columnNumber - 1);\n }\n if(notOuterColumn)\n {\n checkAndReveal(lineNumber + 1, columnNumber + 1);\n }\n }\n if(notFirstColumn)\n {\n checkAndReveal(lineNumber, columnNumber - 1);\n }\n if(notOuterColumn)\n {\n checkAndReveal(lineNumber, columnNumber + 1);\n }\n}\n</code></pre>\n\n<p>The same can be done for your first piece of code, but I'll leave that up to you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T19:00:08.897",
"Id": "33207",
"Score": "0",
"body": "I see. So it seems there's no better easy way to somehow merge the if-ing in both methods, thanks a lot :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T08:01:01.550",
"Id": "33227",
"Score": "0",
"body": "I updated my answer do show a better an easy way:)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T18:20:33.137",
"Id": "20721",
"ParentId": "20714",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "20721",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T14:01:45.383",
"Id": "20714",
"Score": "2",
"Tags": [
"java",
"game",
"swing",
"minesweeper"
],
"Title": "Minesweeper clone using Swing"
}
|
20714
|
<p>It is a little thing about UIViewController, but it has always bothered me - the boilerplate code needed to setup some of a view controller's default properties (e.g. the tab bar item and navigation item) and the location of this code.</p>
<p>Apple's documentation says the following:</p>
<blockquote>
<p><strong>tabBarItem</strong></p>
<p>The tab bar item that represents the view controller when added to a
tab bar controller.</p>
<p><code>@property(nonatomic, retain) UITabBarItem *tabBarItem</code></p>
<p><strong>Discussion</strong></p>
<p>This is a unique instance of UITabBarItem created to represent the
view controller when it is a child of a tab bar controller. The first
time the property is accessed, the UITabBarItem is created. Therefore,
you shouldn’t access this property if you are not using a tab bar
controller to display the view controller. To ensure the tab bar item
is configured, you can either override this property and add code to
create the bar button items when first accessed or create the items in
your view controller’s initialization code.</p>
<p>The default value is a tab bar item that displays the view
controller’s title.</p>
</blockquote>
<p>The default implementation is helpful, but it's certainly not enough. So where does one setup the remaining properties of the tab bar item instance that is lazily provided by UIViewController?</p>
<p>I've seen (and done) just about every possibility, but the highlights:</p>
<p><em>1. Set the property from the "upstream" object.</em></p>
<p>If you build out a tab bar controller in code (say from your App Delegate), then it is a real temptation to setup the tab bar items. You're right there setting up the controller, and in your brain it is easy to group the tab bar item setup process as part of that. However, I fully endorse this approach is "wrong." The tab bar item is part of and managed by a view controller.</p>
<p><em>2. In the init method of your subclass.</em></p>
<p>This certainly seems logical: in order for your view controller to function you'll need a tab bar item, and so why not go ahead and set it up when you create the view controller? Well, because that defeats the lazy loading and couples your view controller with knowledge that it is part of a tab bar controller. What happens when the layout changes and that view controller actually gets pushed onto a navigation stack? Will someone remember to refactor the tab bar item code out of init? I also endorse this as "wrong" because it doesn't follow the intention of lazy loading the property. Apple's documentation suggests this is a viable option, but maybe they are implying...</p>
<p><em>3. In <code>-[UIViewController viewDidLoad]</code></em></p>
<p>I'd wager this is the most common place to do the setup. I know I've written the following lines of code a couple dozen times:</p>
<pre><code>if (self.tabBarController) {
UITabBarItem *tbi = [self tabBarItem];
[tbi setImage:[UIImage imageNamed:@"tab-bar-item-icon"]];
[tbi setTitle:NSLocalizedString(self.title, @"Tab Bar Item - View Controller 1")];
[tbi setBadgeValue:@""];
[self setTabBarItem:tbi];
}
</code></pre>
<p>My problem with this approach is it doesn't really make sense why it needs to be in viewDidLoad. The property is already lazy loaded when a the tab bar controller asks it's contained view controllers for their tab bar items. This scatters the responsibility of creating and configuring the item across non-related methods. Which leads me to the final solution...</p>
<p><em>4. Override the lazy load accessor method</em></p>
<p>Apple suggests this in their documentation, and stylistically follows the design they chose. Okay, so, how does one accomplish such a feat? There are a couple of solutions I've come up with, and I'd like to know if there are any others (that may be more elegant). Both of these seem a little too clever, which sends of alarm bells inside my head.</p>
<p><strong>Option 1</strong></p>
<p><em>Back the property with an instance variable writable by your subclass.</em></p>
<pre><code>@implementation ViewControllerA
{
UITabBarItem *_viewControllerATabBarItem;
}
- (UITabBarItem *)tabBarItem
{
if (!_viewControllerATabBarItem) {
_viewControllerATabBarItem = [super tabBarItem];
[_viewControllerATabBarItem setImage:[UIImage imageNamed:@"tab-bar-item-icon"]];
[_viewControllerATabBarItem setTitle:NSLocalizedString(self.title, @"Tab Bar Item - View Controller 1")];
[_viewControllerATabBarItem setBadgeValue:@""];
}
return _viewControllerATabBarItem;
}
- (void)setTabBarItem:(UITabBarItem *)tabBarItem
{
if (tabBarItem != _viewControllerATabBarItem) {
_viewControllerATabBarItem = tabBarItem;
}
}
@end
</code></pre>
<p>The necessity to back the property with an instance variable in our subclass is due to the fact Apple have declared the _tabBarItem instance variable with @package. This approach is perfectly reasonable, however, it certainly doesn't reduce boilerplate! Also, it costs a mostly unused _tabBarItem instance variable's resources by calling super. You certainly could alloc and init a UITabBarItem, but this might make your code brittle with future changes to the UIViewController class.</p>
<p><strong>Option 2</strong></p>
<p><em>Use Key-Value Coding to access the instance variable directly</em></p>
<pre><code>- (UITabBarItem *)tabBarItem
{
if (![self valueForKey:@"_tabBarItem"]) {
UITabBarItem *tbi = [super tabBarItem];
[tbi setImage:[UIImage imageNamed:@"tab-bar-item-icon"]];
[tbi setTitle:NSLocalizedString(self.title, @"Tab Bar Item - View Controller 1")];
[tbi setBadgeValue:@""];
[self setTabBarItem:tbi];
}
return [self valueForKey:@"_tabBarItem"];
}
</code></pre>
<p>This is less boilerplate and doesn't have a need for a second instance variable, but seems like clever shenanigans that will make future-me angry. It certainly works, but is there a more straight forward way?</p>
<p>I'm curious to get feedback on my thoughts and proposed solutions, and also see other implementations. It's such a small thing and seems silly to think about given how many possible solutions there are, but there doesn't seem to be a clear cut better-than-all-the-others solution. So, how do you handle such a mundane detail?</p>
<p><em>NOTE: I've left the discussion of XIBs and Storyboard out of possible solutions because Navigation Items and Tab Bar Items have some states you cannot influence from Interface Builder. E.g. tab bar item's <code>setFinishedSelectedImage:withFinishedUnselectedImage:</code> or navigation items's <code>leftItemsSupplementBackButton</code>. If your app doesn't need these, I fully endorse using Interface Builder to setup these properties!</em></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-17T23:28:48.130",
"Id": "435246",
"Score": "0",
"body": "option 1 but name the ivar _tabBarItem and don't have a setter. This is what Apple does in their apps, e.g. Podcasts @interface MTDownloadsCollectionViewController : UICollectionViewController <MTSSDownloadManagerDelegate, MTEpisodeDownloadCellDelegate>\n{\n UITabBarItem *_tabBarItem;"
}
] |
[
{
"body": "<p>A subclass of a vc that otherwise could be used as a tab bar vc or a nav controller vc would probably achieve your goals </p>\n\n<p>Additionally, one could make a category to tuck all the boilerplate in and just set some optional params in for that</p>\n\n<p>In reality, I think few people care to actively make their VCs independent of being in tab bars/nav controllers. There are a host of other differences (e.g. Dismissal, etc) that make them different</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T18:42:43.623",
"Id": "33242",
"Score": "0",
"body": "are you suggesting an inheritance of `UIViewController` -> `ContentViewController` -> `TabBarContentViewController`? I completely agree with your closing statement, but that's why I'm a weirdo, right? :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T16:11:45.487",
"Id": "20738",
"ParentId": "20716",
"Score": "1"
}
},
{
"body": "<p>It seems like the essential goals you're seeking in a solution are (1) proper encapsulation and (2) being in accord with the lazy-loading approach to setting up the tab bar item.</p>\n\n<p>I think Option 4.2 is closest to how I would achieve those goals, but I wouldn't use KVC. Instead, I would capture the return value of <code>[super tabBarItem]</code>, set the appropriate properties on every access, and return that instance. No extra ivar, no mucking with implementation details.</p>\n\n<p>As I see it, the laziness only has value when the VC never winds up in a tab bar controller. If you know for certain that you <strong>will</strong> need the tab bar item (knowledge that you obtain when the accessor is called), who cares about a few redundant calls to set its properties? It's not like that method gets called more than a couple of times in the lifespan of the average VC.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T19:40:29.027",
"Id": "33303",
"Score": "0",
"body": "Yes! An obvious answer, and a reasonable justification for the messy parts. I like it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T18:49:31.910",
"Id": "20771",
"ParentId": "20716",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "20771",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T15:16:16.767",
"Id": "20716",
"Score": "1",
"Tags": [
"objective-c",
"ios"
],
"Title": "iOS View Controllers - Default Lazy Loaded Properties (Tab Bar Item & Navigation Item)"
}
|
20716
|
<p>I've recently picked up the <em>Head First Design Patterns</em> book in an effort to become a more efficient and better Python programmer. Unfortunately, the code examples in this book are in Java. </p>
<p>I'm not the <a href="http://www.velocityreviews.com/forums/t338550-python-design-patterns.html">first one</a> that wishes there was a Python version of this book, but I thought that writing the Python code would be a great exercise.</p>
<p>I've tried to implement the Strategy design pattern from Chapter 1 of <em>Head First Design Patterns</em> below in Python. Now, I know that Python is not Java in a general sense, but not in the nitty-gritty sense. So, I'm sure there are more Pythonic things that I can do to this code. </p>
<p>Off the top of my head we could probably implement the <code>Duck</code> class <code>set_fly_behavior()</code> and <code>set_quack_behavior()</code> using the Python <code>property</code> built-in. </p>
<p>Any other suggestions?</p>
<pre><code>#!/usr/bin/env python
################################################################################
# Abstract Duck class and concrete Duck type classes.
################################################################################
class Duck(object):
def __init__(self):
pass
def set_fly_behavior(self, fb):
self.fly_behavior = fb
def set_quack_behavior(self, qb):
self.quack_behavior = qb
def perform_fly(self):
self.fly_behavior.fly()
def perform_quack(self):
self.quack_behavior.quack()
def swim(self):
print "All ducks float, even decoys!"
class MallardDuck(Duck):
def __init__(self):
Duck.__init__(self)
fly_instance = Fly()
self.set_fly_behavior(fly_instance)
quack_instance = Quack()
self.set_quack_behavior(quack_instance)
print "I'm a real Mallard Duck"
class ModelDuck(Duck):
def __init__(self):
Duck.__init__(self)
fly_no_way_instance = FlyNoWay()
self.set_fly_behavior(fly_no_way_instance)
squeak_instance = SqueakQuack()
self.set_quack_behavior(squeak_instance)
print "I'm a Model Duck"
class DecoyDuck(Duck):
def __init__(self):
Duck.__init__(self)
fly_no_way_instance = FlyNoWay()
self.set_fly_behavior(fly_no_way_instance)
mute_instance = MuteQuack()
self.set_quack_behavior(mute_instance)
print "I'm a Decoy Duck"
################################################################################
# Fly behavior interface and behavior implementation classes.
################################################################################
class FlyBehavior():
def __init__(self):
pass
class Fly(FlyBehavior):
def fly(self):
print "I'm flying!!"
class FlyNoWay(FlyBehavior):
def fly(self):
print "I can't fly"
class FlyRocketPowered(FlyBehavior):
def fly(self):
print "I'm flying with a rocket!"
################################################################################
# Quack behavior interface and behavior implementation classes.
################################################################################
class QuackBehavior():
def __init__(self):
pass
class Quack(QuackBehavior):
def quack(self):
print "Quack"
class MuteQuack(QuackBehavior):
def quack(self):
print "<< Silence >>"
class SqueakQuack(QuackBehavior):
def quack(self):
print "Squeak"
################################################################################
# Test Code.
################################################################################
if __name__ == "__main__":
print '#'*80
print "Mallard Duck"
print '#'*80
mallard = MallardDuck()
mallard.perform_quack()
mallard.perform_fly()
print '#'*80
print "Model Duck"
print '#'*80
model = ModelDuck()
model.perform_fly()
fly_rocket_powered_instance = FlyRocketPowered()
model.set_fly_behavior(fly_rocket_powered_instance)
model.perform_fly()
print '#'*80
print "Decoy Duck"
print '#'*80
decoy = DecoyDuck()
decoy.perform_fly()
decoy.perform_quack()
</code></pre>
|
[] |
[
{
"body": "<h1>The devil’s in the <code>_details</code></h1>\n\n<p>Your suggestion is good, but you don’t need a property; you can just use a normal attribute. All your setter does is set the variable, so just do that instead. So, this:</p>\n\n<pre><code>self.set_fly_behavior(fly_instance)\n</code></pre>\n\n<p>Can become this:</p>\n\n<pre><code>self._fly_behaviour = fly_instance\n</code></pre>\n\n<p>Note my use of <code>self._fly_behaviour</code>. Since it’s is an implementation detail of the class, the best practice is to prefix the variable name with an underscore. This tells programmers that it’s not designed to be used externally.</p>\n\n<h2>Aside: naming behaviours</h2>\n\n<p>The names <code>perform_quack()</code> and <code>perform_fly()</code> are very un-Pythonic. Why not just <code>quack()</code> and <code>fly()</code>? The <em>perform</em> tells us nothing—except, maybe leaking an implementation detail to the outside (that these delegated). This isn't something a caller needs to care about.</p>\n\n<hr>\n\n<h1>ABCs</h1>\n\n<p>Other than that, you could make your base classes Abstract Base Classes:</p>\n\n<pre><code>from abc import ABCMeta, abstractmethod\n\n...\n\nclass QuackBehavior(object):\n __metaclass__ = ABCMeta\n\n @abstractmethod\n def quack(self):\n pass\n\n @classmethod\n def __subclasshook__(cls, Check):\n required = [\"quack\"]\n rtn = True\n for r in required:\n if not any(r in vars(BaseClass) for BaseClass in Check.__mro__):\n rtn = NotImplemented\n return rtn\n</code></pre>\n\n<p>This allows you to have a more Pythonic interface for your class. </p>\n\n<p>(Also, note the removal of the empty constructor. Python provides an empty constructor anyway, so don’t bother defining one if you do nothing with it. It’s just useless extra code.)</p>\n\n<hr>\n\n<h1>A functional approach</h1>\n\n<p>This is a pretty heavyweight solution for Python. If you know that these behaviours are always just one function, I would argue classes aren’t needed.</p>\n\n<p>Instead, recall that Python functions are first-class objects:</p>\n\n<pre><code>def quack(self):\n print(\"Quack\")\n\ndef mute_quack(self):\n print \"<< Silence >>\"\n\nsome_duck = Duck()\nsome_duck.quack = mute_quack\n</code></pre>\n\n<hr>\n\n<h1>A hybrid approach</h1>\n\n<p>We can make this work with one small modification: by using a property to convert functions into methods, so that they can be called normally.</p>\n\n<p>(I’m assuming you need access to <code>self</code> in the method; if not, leave out that argument, and it’ll work as-is, like a static method.)</p>\n\n<pre><code>import types\n\nclass Duck(object):\n ...\n\n @property\n def fly(self):\n return self._fly\n\n @fly.setter\n def fly(self, value):\n self._fly = types.MethodType(value, self)\n\n @property\n def quack(self):\n return self._quack\n\n @quack.setter\n def quack(self, value):\n self._quack = types.MethodType(value, self)\n</code></pre>\n\n<h2>One step further...</h2>\n\n<p>Hmm...we’re doing the same thing for both properties. If you want, we can take it a step further.</p>\n\n<p>Let’s generalise it instead:</p>\n\n<pre><code>import types\n\ndef method_property(name):\n def getter(self):\n return getattr(self, name)\n def setter(self, value):\n setattr(self, name, types.MethodType(value, self))\n return getter, setter\n\nclass Duck(object):\n ...\n quack = property(*method_property(\"_quack\"))\n fly = property(*method_property(\"_fly\"))\n</code></pre>\n\n<p>Just assign the function as needed—perhaps in the constructor of subclasses. Obviously, if you need more complicated behaviours, this might not do. But for simple things, I’d say it’s the better solution.</p>\n\n<hr>\n\n<h1>Constructors for subclassing</h1>\n\n<p>Since a duck is useless without a quack and fly behaviour, and all subclasses assign them, it makes sense for the constructor to deal with this:</p>\n\n<pre><code>class Duck(object):\n def __init__(self, fly, quack):\n self.fly = fly\n self.quack = quack\n\n ...\n\nclass ModelDuck(Duck):\n def __init__(self):\n Duck.__init__(self, fly_no_way, squeak_quack)\n print \"I'm a Model Duck\" \n</code></pre>\n\n<p>Or, if you were using your original class’s implementation:</p>\n\n<pre><code>class Duck(object):\n def __init__(self, fly, quack):\n self._fly_behaviour = fly\n self._quack_behaviour = quack\n\n ...\n\nclass ModelDuck(Duck):\n def __init__(self):\n Duck.__init__(self, FlyNoWay(), SqueakQuack())\n print \"I'm a Model Duck\"\n</code></pre>\n\n<hr>\n\n<h1>Conclusion</h1>\n\n<p>If we wrap all this together, we end up with two implementations:</p>\n\n<ul>\n<li><a href=\"http://ideone.com/nz5gdw\">function based</a>, and </li>\n<li><a href=\"http://ideone.com/Owgfjj\">class based</a>.</li>\n</ul>\n\n<p>These implementations remove repetition, and will make this sort of thing much easier to work with in Python overall.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T23:01:07.060",
"Id": "33214",
"Score": "2",
"body": "Wow, thanks for such a detailed reply. I'll be sure to +1 you once I get enough rep. In the meantime you've given me quite a bit of material to look over and apply to my programming. I'm also going to continue working on more design patterns from the Head First book. Please be on the lookout :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T12:37:05.720",
"Id": "33231",
"Score": "0",
"body": "I'm still groking some of the code here. For the class based implementation, I'm trying to get a handle on the `__subclasshook__`. In our abstract behaviors we define the builtin `__subclasshook__` to be the `classmethod` of the function `subclasshook`, which is defined at the top of the code. So the `classmethod` builtin should return the Class of the function `subclasshook`. But I thought `__subclasshook__` was only suppose to return `True`, `False`, or `NotImplemented`. I'm certainly missing something, since the code works."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T12:52:41.147",
"Id": "33233",
"Score": "0",
"body": "Also, I'm not quite following the logic here in the for loop of the function `subclasshook(requried)` at the top. My problem is with the line `if not any(r in vars(BaseClass) for BaseClass in Check.__mro__):`. The variable `r` is the name of the abstract method that needs to be implemented in each concrete behavior. So here we check the `__mro__` of the concrete class and all of its base classes(?) for the name of the abstract method that must be implemented. Shouldn't we check to see that the method is in __every__ class of the `__mro__`, not just __any__ class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T16:11:06.220",
"Id": "33239",
"Score": "1",
"body": "@PythonJin In response to your first comment, `subclasshook()` returns a function, so when we call `__subclasshook__ = classmethod(subclasshook([\"fly\"]))`, Python evaluates the `subclasshook()` call, and gives `classmethod()` the function that returns `True`, `False`, or `NotImplemented` as the first argument. It does not pass `classmethod()` the `subclasshook()` function itself, just the value returned by it (which happens to be another function). It then makes it a class method and assigns it to `__subclasshook__`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T16:13:58.310",
"Id": "33240",
"Score": "0",
"body": "@PythonJin In response to comment two, think about how Python works when you call a function. It looks for the function you call in that class, and if it doesn't find it, works up the MRO (which is all of the base classes, with duplicates removed in a certain order - as Python support multiple inheritance this isn't trivial) and checks for it until it finds it. If we checked if it was in *all* classes, then it would be impossible to add functionality into a subclass without it being in the base class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T12:20:24.697",
"Id": "33273",
"Score": "0",
"body": "Oh, thanks! Ok, so it's the `@abstractmethod` decorator in the abstract base class that enforces the need for my subclasses to implement a particular class method (let's say the `fly` method). But if we had not implemented `fly` in the subclass, `__subclasshook__ = classmethod(subclasshook([\"fly\"]))` would still return `True`, since it would eventually find the method in the ABC? Furthermore, we never explicitly call `__subclasshook__`, is it implicitly called somewhere? Or have we just redefined it so that future use of `issubclass()` returns what we want?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T03:36:28.233",
"Id": "33320",
"Score": "0",
"body": "+1. @PythonJin: You should prefer attributes over properties in python wherever possible. This is because an attribute lookup doesn't have the computational overhead of a function call. Properties should be used when you have to preprocess the data before assigning or retrieving it (i.e. `myClass.metricLength` could be a property that converts an attribute stored in feet to meters before returning it.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T08:55:53.110",
"Id": "33336",
"Score": "0",
"body": "@PythonJin Yes, `__subclasshook__()` will say that a class that inherits from the abstract class but doesn't implement the abstract method - but that class will remain an abstract class that we can't create instances of. The `__subclasshook__()` is simply a way of allowing us to neatly check if a class implements an interface using `isinstance()` or `issubclass()` (without relying on type-checking which doesn't suit Python, as a duck-typed language)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T16:54:42.243",
"Id": "20719",
"ParentId": "20718",
"Score": "31"
}
}
] |
{
"AcceptedAnswerId": "20719",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T16:38:44.363",
"Id": "20718",
"Score": "24",
"Tags": [
"python",
"design-patterns"
],
"Title": "Strategy design pattern with various duck type classes"
}
|
20718
|
<p>I am trying to improve my C skills, and I hope someone might be able to provide me with some feedback on the following code. I avoid <code>strtok</code> function intentionally.</p>
<pre><code>#define MAX_SIZE 1000
int split_up(char* string, char* argv[])
{
char* p = string;
int argc = 0;
while(*p != '\0')
{
while(isspace(*p))
++p;
if(*p != '\0')
argv[argc++] = p;
else
break;
while(*p != '\0' && !isspace(*p))
p++;
if(*p != '\0')
{
*p = '\0';
++p;
}
}
return argc;
}
int main()
{
char *av[MAX_SIZE];
char string[] = "this is a test";
//int i, ac = makeargv(string, av, 2);
int i;
int ac = split_up(string, av);
printf("The number of token is: %d\n", ac);
for(i = 0; i < ac; i++)
printf("\"%s\"\n", av[i]);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T15:34:26.187",
"Id": "33236",
"Score": "0",
"body": "The same affect can be achieved using `sscanf()`. Just use a string format of \" %*s\" (note the leading space in the string)."
}
] |
[
{
"body": "<p>Your code looks quite nice, but here are a few nitpicking comments, for what they are worth.</p>\n\n<ul>\n<li>Missing headers, but I assume you just didn't paste them.</li>\n<li>split_up should be static and get a better name</li>\n<li>variable names are odd. argc/argv are the usual names for main() (missing here) but not for functions. I'd use <code>tokens</code> instead of argv, and maybe <code>n</code> instead of argc. Okay, <code>n</code> is not at all descriptive, but for such a short function it need not be.</li>\n<li>assigning <code>string</code> to <code>p</code> gains nothing, as the original value is not required later on.</li>\n<li>perhaps use braces, even for 1-line statements following while, for, if etc</li>\n<li>I prefer to leave a space after keywords (while, if, etc)</li>\n<li><p>when breaking out of the loop, why not do it immediately:</p>\n\n<pre><code>if (*p == '\\0') {\n break;\n}\nargv[argc++] = p;\n</code></pre></li>\n<li><p>The while loop following this knows that *p is initially not \\0, so put the check for that 2nd. Also it is better to add brackets round conditions, even if you think the precedence is obvious:</p>\n\n<pre><code>while(!isspace(*p) && (*p != '\\0')) {\n p++;\n}\n</code></pre></li>\n<li><p>you could also just check for *p instead of <code>*p == '\\0'</code>. But many will disagree. </p></li>\n<li>you also have two blank lines near the end of split_up that make the code look a little messy.</li>\n</ul>\n\n<p>Note also that you don't check for overflow of the argv array. Okay, you gave it 1000 places for the purpose of the example and that is unlikely to overflow. But in practice you will use somewhat less than 1000 and overflow will be more likely.</p>\n\n<p>And finally, my preference is not to nest loops. Your two nested while loops could be extracted into inline functions - they might be useful in themselves, after all. Here is an example with the loops extracted; you don't have to like it - it is just an example. I find this easier to read, but yours might well be slightly quicker, if that matters.</p>\n\n<pre><code>static inline char* next_token(char *p)\n{\n while (isspace(*p)) {\n ++p;\n }\n return *p ? p : NULL;\n}\n\nstatic inline char* next_space(char *p)\n{\n while (!isspace(*p) && *p) {\n ++p;\n }\n return *p ? p : NULL;\n}\n\nstatic int string_split(char *p, char* token[])\n{\n int n = 0;\n while ((p = next_token(p)) != NULL) {\n token[n++] = p;\n if ((p = next_space(p)) == NULL) {\n break;\n }\n *p++ = '\\0';\n }\n return n;\n}\n</code></pre>\n\n<p>Or you could consider using strspn and strcspn and define your own whitespace characters...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T03:18:38.940",
"Id": "20734",
"ParentId": "20722",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "20734",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T18:21:20.663",
"Id": "20722",
"Score": "1",
"Tags": [
"c",
"strings"
],
"Title": "split up a string into whitespace-seperated fields"
}
|
20722
|
<p>I've been working on my first Angular JS app for the past few days.
It's in a very early stage (no real functionality), but that will only make it easier to review what IS there.</p>
<p>The client side is written in CoffeeScript. The app used Requirejs to manage files AMD style (it loads compiled CoffeeScript).</p>
<p>The server side is very minimal at the moment. It will have a local SQLite database and uses SQLAlchemy as an ORM. Furthermore I make use of the (very nice) Flask framework to provide an restful API to the Angular app.</p>
<p>Right now the server side is not much concern to me; it works.</p>
<p>The client side works as well, but since I'm new to Angular I am really curious to know whether I do things correctly and using <code>the Angular JS way</code>.</p>
<p>The code lives in <a href="https://github.com/ElessarWebb/Sight" rel="nofollow">this repository</a>.</p>
<p>The parts I'm not so sure about are the way I am dealing with scopes right now.</p>
<p>For example:</p>
<p>I have a general dialog directive and use it to display a dialog for importing images. I would think I could have the import directive live inside the dialog (transcluded), but to be able to handle the dialog apply "event" (handle by uploading the images in this particular instance...), the import directive needs to wrap the dialog. It works, but was rather counterintuitive. Is it the right way to do things?</p>
<p>Another example:</p>
<p>To display the dialog I have its <code>visibile</code> attribute linked to a root scope property. This also seems rather hacky.</p>
<pre><code><body ng-controller="MainCtrl" >
{# let angularjs compile the templating from here #}
{% raw %}
<header>
<h1>Sight <span>beta</span></h1>
<div class="buttons">
<button ng-click="show_import_dialog = ! show_import_dialog">Import</button>
</div>
</header>
<div id="content">
<!-- import dialog -->
<div sg-import>
<div
sg-dialog title="Import Photographs"
visible="show_import_dialog"
sg-apply="upload()"
>
<p>
Drag images into the dropzone below or click on it to browse.
</p>
<br />
<div class="drop-zone">
<div ng-repeat="file in files" sg-photo title="{{ file.name }}">
</div>
<!-- hidden input -->
<input type="file" accept="image/*" multiple />
<!-- push size -->
<div class="clear"></div>
</div>
</div>
</div>
</div>
<footer>
</footer>
{% endraw %}
</body>
</code></pre>
<p>The directives and controllers <a href="https://github.com/ElessarWebb/Sight/tree/master/src/client/sight" rel="nofollow">live here</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T18:39:03.703",
"Id": "20723",
"Score": "4",
"Tags": [
"html",
"angular.js"
],
"Title": "Angular JS photo app for personal cloud"
}
|
20723
|
<p>I was writing my own implementation of BlockingQueue for practice. I am trying to avoid using the synchronized keyword for the methods. I would instead like to use ReentrantLock.</p>
<p>What is the best way to write this implementation? I am not a Java ninja and would greatly appreciate if someone could pinpoint the errors in my code here and suggest better ways of implementing it.</p>
<pre><code>public class MyBlockingQueue<T> {
private Queue<T> queue;
private AtomicInteger limit = new AtomicInteger(10);
private Lock put_lock = new ReentrantLock();
private Lock take_lock = new ReentrantLock();
private Condition put_condition = put_lock.newCondition();
private Condition take_condition = take_lock.newCondition();
public MyBlockingQueue(AtomicInteger limit){
queue = new LinkedList<T>();
this.limit = limit;
}
public boolean put(T item) throws InterruptedException{
put_lock.lockInterruptibly();
try {
while(queue.size() == limit.get()) {
put_condition.await();
}
put_condition.signal();
queue.add(item);
} finally{
put_lock.unlock();
}
return true;
}
public T take() throws InterruptedException{
take_lock.lockInterruptibly();
try {
while (queue.size() == 0) {
take_condition.await();
}
take_condition.signal();
return queue.poll();
} finally {
take_lock.unlock();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>These seem mixed up:</p>\n\n<pre><code> while(queue.size() == limit.get()) {\n put_condition.await();\n }\n put_condition.signal();\n</code></pre>\n\n<p>and</p>\n\n<pre><code> while (queue.size() == 0) {\n take_condition.await();\n }\n take_condition.signal();\n</code></pre>\n\n<p>when putting if queue is full you wait until someone takes \nand when taking if queue is empty you wait until someone puts.</p>\n\n<p>You should have test cases with 11 puts followed by 1 take.\nand 1 take followed by 1 put. To see they do not deadlock.</p>\n\n<p>What do you know, the example code for Condition is actually Bounded buffer. And you can see it here:\n<a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/locks/Condition.html\" rel=\"nofollow\">http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/locks/Condition.html</a></p>\n\n<p>But I like their condition names better;)</p>\n\n<p>Limit is a constant as it is, hence does not need atomic integer or any other synchronization. Just declare it final. best way of making something threadsafe is to make it immutable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T17:33:42.870",
"Id": "20765",
"ParentId": "20724",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T18:44:23.903",
"Id": "20724",
"Score": "4",
"Tags": [
"java",
"thread-safety"
],
"Title": "BlockingQueue Implemetation using ReentrantLock"
}
|
20724
|
<p>I am basically getting data from various APIs and using PHP to put them together - like a web mashup. I am currently using 4 <code>foreach</code> statements to insert the gathered data into their individual arrays. I believe that the current code is inefficient because it takes probably around 3 seconds to load the page which is displaying the PHP data. In the past I had just one big foreach loop to go through all the data at once and also print them. But that too felt inefficient to me.</p>
<p>So how can I make my code more efficient in term of it processing faster? I have seen a few mashup websites such as <a href="http://soundeer.com.ar/" rel="nofollow">Soundeer</a> which load around a second. Is that becuase of their code efficiency?</p>
<p>The code which I am using is:</p>
<pre><code>$echonest_uri = simplexml_load_file("http://developer.echonest.com/api/v4/artist/search?api_key=$APIkey&style=rap&results=10&start=$element_num&bucket=id:deezer&bucket=images&sort=familiarity-desc&format=xml");
//Swap the comments for when in UWE or not
//$echonest_xml = new SimpleXMLElement($echonest_uri);
$echonest_xml = $echonest_uri;
$artist_name = array();
$artist_image = array();
$echonest_id = array();
$full_deezer_id = array();
$deezer_id = array();
$num_of_albums = array();
//Loop through each entries in the id_arr and make each image of the artist a link to the album page passing all the relevant information.
foreach($echonest_xml->artists->artist as $artist){
$artist_name[] = $artist->name;
$artist_image[] = $artist->images->image[0]->url;
$echonest_id[] = $artist->id;
$full_deezer_id[] = $artist->foreign_ids->foreign_id->foreign_id;
}
foreach($full_deezer_id as $key => $value){
preg_match('#deezer:artist:([A-Z,a-z,0-9]+)#', $value, $id);
$deezer_id[] = (string)$id[1];
}
foreach($deezer_id as $id_index => $id){
$deezer_xml = simplexml_load_file("http://api.deezer.com/2.0/artist/$id/albums&output=xml");
$num_of_albums[] = $deezer_xml->total;
}
//The variable which will contain the HTML code to display the artists.
$output = null;
foreach($deezer_id as $key => $value){
$fav_count_query = "SELECT COUNT(user_index) FROM fav_artist WHERE artist_deezer_id = '$value'";
$fav_count_resource = $mysqli->query($fav_count_query);
$fav_count = $fav_count_resource->fetch_assoc();
$output .= <<<HERE
<div class="artist-container">
<a href="albums.php?echonest_id={$echonest_id[$key]}&deezer_id={$deezer_id[$key]}&artist_name={$artist_name[$key]}&artist_image={$artist_image[$key]}&num_of_albums={$num_of_albums[$key]}" class="artist-image">
<img src="{$artist_image[$key]}" alt="{$artist_name[$key]}" title="{$artist_name[$key]}"/>
</a>
<a href="albums.php?echonest_id={$echonest_id[$key]}&deezer_id={$deezer_id[$key]}&artist_name={$artist_name[$key]}&artist_image={$artist_image[$key]}&num_of_albums={$num_of_albums[$key]}" class="artist-name">
{$artist_name[$key]}
</a>
<a href="albums.php?echonest_id={$echonest_id[$key]}&deezer_id={$deezer_id[$key]}&artist_name={$artist_name[$key]}&artist_image={$artist_image[$key]}" class="album-number">Albums:
{$num_of_albums[$key]}
</a>
</div>
HERE;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T08:40:48.657",
"Id": "33228",
"Score": "0",
"body": "Would you have a few possible values to input so that I can try a few things ? (Of course, I know that the DB query will fail)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T12:54:05.747",
"Id": "33234",
"Score": "0",
"body": "foreach->simplexml_load_file(\"...\"); How many calls are this?"
}
] |
[
{
"body": "<p>Please add the following method do your code and print the runtime of every section of your code. As indicated by my comment I guess the foreach->simplexml_load_file(\"...\") might take a while.</p>\n\n<pre><code>//PHP <5.0.0\nfunction microtime_float()\n{\n list($usec, $sec) = explode(\" \", microtime());\n return ((float)$usec + (float)$sec);\n}\n\n$start=microtime_float();\n//...\necho microtime_float()-$start;\n\n//PHP>=5.0.0\n$start=microtime(true);\n//...\necho microtime(true)-$start;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T21:38:47.110",
"Id": "33256",
"Score": "1",
"body": "The codereview of YOUR code is: `microtime(true)` returns a float value without the need to explode and add. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T04:51:04.900",
"Id": "33261",
"Score": "0",
"body": "Your are right :) Nice to know. This was introduced in 5.0.0. I'm so used to this lines that I never checked if there might be a API update."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T13:00:44.347",
"Id": "20736",
"ParentId": "20725",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T19:20:03.973",
"Id": "20725",
"Score": "1",
"Tags": [
"php",
"api",
"client"
],
"Title": "Music management app, mashing data from various APIs"
}
|
20725
|
<p>The entity framework will only save properties it detects has changed via its proxy classes. I have a situation where I want a property to always be saved no matter if it changed or not.</p>
<p>I wrote a blank attribute called <code>AlwaysUpdate</code> which I apply to the property. I then overrode <code>SaveChanges</code> to scan for these attributes and mark the field as <code>Modified</code>. Is this code all right?</p>
<pre><code>public override int SaveChanges()
{
var changeSet = ChangeTracker.Entries();
if (changeSet != null)
{
foreach (var entry in changeSet.Where( c=> c.State == System.Data.EntityState.Modified ))
{
foreach (var prop in entry.Entity.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(AlwaysUpdateAttribute), true).Count() > 0).Select( p => p.Name ))
{
if (entry.State == System.Data.EntityState.Added || entry.State == System.Data.EntityState.Unchanged) continue;
// Try catch removes the errors for detached and unchanged items
try
{
entry.Property(prop).IsModified = true;
}
catch { }
}
}
}
return base.SaveChanges();
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>Instead of checking <code>.Count() > 0</code> which needs to iterate over the <code>IEnumerable</code> you can just use <code>.Any()</code> which only checks if at least one item is contained in the <code>IEnumerable</code> </p></li>\n<li><p>you should extract the result of <code>typeof(AlwaysUpdateAttribute)</code> to a variable. </p>\n\n<pre><code>Type desiredType = typeof(AlwaysUpdateAttribute);\n</code></pre></li>\n<li><p>you can restrict the outer loop by adding the \"continue condition\" to the <code>Where()</code> method. For readability we will do this outside of the loop </p>\n\n<pre><code>changeSet = changeSet.Where( c=> \n c.State == System.Data.EntityState.Modified \n && !(entry.State == System.Data.EntityState.Added \n || entry.State == System.Data.EntityState.Unchanged) \n ); \n</code></pre></li>\n<li><p>you shouldn't shorten any variable names -> <code>prop</code> should be <code>propertyName</code></p></li>\n</ul>\n\n<p><strong>Refactoring</strong> </p>\n\n<p>Implementing all above will lead to </p>\n\n<pre><code>public override int SaveChanges()\n{\n var changeSet = ChangeTracker.Entries();\n if (changeSet != null)\n {\n changeSet = changeSet.Where( c=> \n c.State == System.Data.EntityState.Modified \n && !(entry.State == System.Data.EntityState.Added \n || entry.State == System.Data.EntityState.Unchanged) \n ); \n\n Type desiredType = typeof(AlwaysUpdateAttribute);\n\n foreach (var entry in changeSet)\n {\n foreach (var propertyName in entry.Entity.GetType().GetProperties().Where(p => p.GetCustomAttributes(desiredType , true).Any()).Select( p => p.Name ))\n {\n // Try catch removes the errors for detached and unchanged items\n try\n {\n entry.Property(propertyName).IsModified = true;\n }\n catch { }\n }\n }\n }\n return base.SaveChanges();\n}\n\n\n foreach (var entry in changeSet) \n {\n foreach (var prop in entry.Entity.GetType().GetProperties().Where(p => p.GetCustomAttributes(desiredType , true).Any()).Select( p => p.Name ))\n {\n // Try catch removes the errors for detached and unchanged items\n try\n {\n entry.Property(prop).IsModified = true;\n }\n catch { }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-18T14:22:02.163",
"Id": "74068",
"ParentId": "20726",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "74068",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T19:45:43.010",
"Id": "20726",
"Score": "5",
"Tags": [
"c#",
"entity-framework",
"poco"
],
"Title": "AlwaysUpdate attribute for Entity Framework Code First POCO"
}
|
20726
|
<p>Here is my simple example: there is a class A with few primitive members and a class B with few primitive members but also a collection of objects of type A.</p>
<p>This is my A class:</p>
<pre><code>#pragma once
#include<string>
class Hero
{
private:
long id;
std::string name;
int level;
static long currentId;
public:
Hero();
Hero(std::string name, int level);
Hero(const Hero &hero);
Hero(Hero &&hero);
Hero& operator=(const Hero &hero);
Hero& Hero::operator=(const Hero &&hero);
long GetId() const { return this->id; }
std::string GetName() const { return this->name; }
int GetLevel() const { return this->level; }
void SetName(const std::string &name);
void SetLevel(const int &level);
};
#include"Hero.h"
long Hero::currentId = 0;
Hero::Hero(std::string name, int level):name(name), level(level), id(++currentId)
{
}
Hero::Hero():name(""), level(0), id(++currentId)
{
}
Hero::Hero(const Hero &hero):id(hero.id), name(hero.name), level(hero.level)
{
}
Hero::Hero(Hero &&hero):id(hero.id), name(hero.name), level(hero.level)
{
}
Hero& Hero::operator=(const Hero &hero)
{
this->id = hero.id;
this->name = hero.name;
this->level = hero.level;
return *this;
}
Hero& Hero::operator=(const Hero &&hero)
{
this->id = hero.id;
this->name = hero.name;
this->level = hero.level;
return *this;
}
void Hero::SetName(const std::string &name)
{
this->name = name;
}
void Hero::SetLevel(const int &level)
{
this->level = level;
}
</code></pre>
<p>This is my B class:</p>
<pre><code>#pragma once
#include"Hero.h"
#include<vector>
#include<memory>
class Race
{
private:
static long currentId;
long id;
std::string name;
std::vector<std::shared_ptr<Hero>> heroes;
Race(const Race &race); //disable copy constructor
Race& operator =(const Race &race); //disable assign operator
public:
Race();
explicit Race(std::string name);
std::string GetName() const { return this->name; }
void SetName(std::string name);
void AddHero(Hero &&hero);
std::vector<std::shared_ptr<Hero>> GetHeroes() const { return heroes; }
};
#include "Race.h"
long Race::currentId = 0;
Race::Race(std::string name):name(name), heroes(std::vector<std::shared_ptr<Hero>>()), id(++currentId)
{
}
Race::Race():name(""), heroes(std::vector<std::shared_ptr<Hero>>()), id(++currentId)
{
}
void Race::SetName(std::string name)
{
this->name=name;
}
void Race::AddHero(Hero &&hero)
{
heroes.push_back(std::make_shared<Hero>(hero));
}
</code></pre>
<p>And this is my main:</p>
<pre><code>#include "stdafx.h"
#include"Race.h"
int _tmain(int argc, _TCHAR* argv[])
{
Hero elvesHero1("Demon hunter", 8);
Hero elvesHero2("Warden", 4);
Race nightElf("Night elf");
nightElf.AddHero(std::move(elvesHero1));
nightElf.AddHero(std::move(elvesHero2));
std::vector<std::shared_ptr<Hero>> heroes=nightElf.GetHeroes();
return 0;
}
</code></pre>
<p>One remark: When the debugger hits <code>nightElf.AddHero(std::move(elvesHero1));</code> it enters Hero's copy constructor. Shouldn't it go through move constructor?</p>
<p>I just want start on the right foot, so I am waiting for your tips.</p>
<p>LE: If I modify the <code>AddHero</code> method like this:</p>
<pre><code>void Race::AddHero(Hero &&hero)
{
heroes.push_back(std::make_shared<Hero>(std::move(hero)));
}
</code></pre>
<p>it gives the parameter <code>std:move(hero)</code> instead of hero. It enters move constructor instead of copy constructor.</p>
|
[] |
[
{
"body": "<p>Firstly, in your header file, you don't need the <code>Hero::</code> qualification on your move assignment operator. Secondly, you are defining it as <code>Hero& Hero::operator=(const Hero &&hero);</code>. Think about what this is saying - it's saying if you have an rvalue reference to a <code>Hero</code> object, then:</p>\n\n<ol>\n<li>You cannot modify it because it is <code>const</code></li>\n<li>You want to utilize move semantics (specifically, <code>std::move</code>) which will modify the original object and leave it with an empty value.</li>\n</ol>\n\n<p>Hence, your move constructor should <em>always</em> be of the form <code>Hero& Hero::operator=(Hero&& hero)</code>. The implementation should also be using <code>std::move</code>:</p>\n\n<pre><code>Hero& operator=(Hero&& hero)\n : id(std::move(hero.id),\n name(std::move(hero.name),\n level(std::move(hero.level)\n{ }\n</code></pre>\n\n<p>For your <code>AddHero</code> methods, a <code>Hero&& hero</code> might be an rvalue reference, but without the <code>std::move</code> for its elements, you're basically saying \"take an rvalue reference to Hero, and call copy constructors on each of its elements when you utilize <code>make_shared<Hero></code>\".</p>\n\n<p>Note that moving vs copying for basic types like <code>int</code> or <code>long</code> won't have any performance difference.</p>\n\n<p>That being said, you're doing a <strong>lot of work here for no benefit</strong>. The rule is, unless you have written a custom destructor, you don't need to write custom copy constructors, copy assignment operators or move assignment operators - the compiler will generate defaults which are correct. It is only when you are managing memory (hence have a <code>delete</code> or <code>delete[]</code> in a destructor somewhere) that you need to implement these.</p>\n\n<p>Finally, a few other small points. Your constructors should be taking strings by <code>const &</code>, ie, <code>explicit Race(const std::string& name)</code>. Usage of <code>this-></code> to return member variables is a bit unidiomatic in C++, likewise in copy constructors and the like, instead of <code>this->id = hero.id;</code> it's more idiomatic to simply write <code>id = hero.id;</code>. </p>\n\n<p>I'd suggest reading the <a href=\"https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three\">Rule of Three</a> post on stackoverflow to get a better understanding of copy construction and copy assignment.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T17:08:01.463",
"Id": "33459",
"Score": "0",
"body": "As we are in C++11 land, I would strongly recommend moving from Rule of Three to [Rule of Zero](http://flamingdangerzone.com/cxx11/2012/08/15/rule-of-zero.html). Also, it would be nice to mention the [Quasi Classes](http://www.idinews.com/quasiClass.pdf) paper. But +1 anyway."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T02:12:58.723",
"Id": "20733",
"ParentId": "20729",
"Score": "7"
}
},
{
"body": "<p>In addition to @Yuushi</p>\n\n<p>I just want to emphasis this bit:</p>\n\n<pre><code>Hero elvesHero1(\"Demon hunter\", 8);\n\nnightElf.AddHero(std::move(elvesHero1));\n</code></pre>\n\n<p>Here <code>elvesHero1</code> is an object. When you call <code>AddHero()</code> you create a new object that is shared. So you now have <strong>two</strong> independent \"Demon hunter\" objects (the first is automatic<code>elvesHero1</code> the other is dynamic and controlled by a shared pointer inside <code>nightElf</code>.</p>\n\n<p>Is this really what you wanted?</p>\n\n<p>I assume that you want to create <code>Hero</code>(s) dynamically. Thus usually they are going to be created with <code>new</code> and controlled by a smart pointer. Thus the interface to <code>Race</code> should reflect this and accept the appropriate smart pointer in its interface <code>AddHero()</code>.</p>\n\n<p>Thus I would expect to see:</p>\n\n<pre><code> class Race\n {\n void AddHero(std::shared_ptr<Hero>& hero);\n };\n int main()\n {\n // STUF\n std::shared_ptr<Hero> = new elvesHero1(\"Demon hunter\", 8);\n\n Race nightElf(\"Night elf\");\n nightElf.AddHero(std::move(elvesHero1));\n }\n</code></pre>\n\n<p>The next question you want to ask <code>is std::shared_ptr the correct smart pointer</code>. I can't answer this as I don't know enough about the app. Do you expect multiple ownership of he object? Or is <code>Race</code> going to have exclusive ownership and share references externally?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T15:31:16.257",
"Id": "20737",
"ParentId": "20729",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "20733",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-19T20:52:35.787",
"Id": "20729",
"Score": "7",
"Tags": [
"c++",
"beginner",
"c++11",
"memory-management",
"smart-pointers"
],
"Title": "Am I using copy ctors/move ctors/shared_ptr correctly?"
}
|
20729
|
<p>I am using Castle Windsor as my IoC container and I registered it as a <code>DependencyResolver</code> to let the MVC framework know about it. </p>
<p>With the Entity Framework I have this <code>DbContext</code>:</p>
<pre><code>public class MyDbContext : DbContext
{
public DbSet<User> Users { get; set; }
}
</code></pre>
<p>In Castle Windsor it is registered as per web request:</p>
<pre><code>container.Register(
Component.For<DbContext, MyDbContext>()
.ImplementedBy<MyDbContext>()
.LifestylePerWebRequest()
);
</code></pre>
<p>Because I don't have control over creating the <code>MyMembershipProvider</code> object, this object is created once per web application so it is not possible to inject <code>DbContext</code> directly, because it will be disposed when the web request ends.</p>
<p>I wrote this as a solution:</p>
<pre><code>public interface IDoInContext<TContext>
{
void DoInContext(Action<TContext> action);
}
public class DoInMyDbContext : IDoInContext<MyDbContext>
{
IKernel _kernel;
public DoInMyDbContext(IKernel kernel)
{
_kernel = kernel;
}
public void DoInContext(Action<MyDbContext> action)
{
var context = _kernel.Resolve<MyDbContext>();
action(context);
_kernel.ReleaseComponent(context);
}
}
</code></pre>
<p>And I registered like this:</p>
<pre><code>container.Register(
Component.For<IDoInContext<MyDbContext>>()
.ImplementedBy<DoInMyDbContext>()
.LifestyleSingleton()
);
</code></pre>
<p>Now I can create a <code>MyMembershipProvider</code> which will be able to interact with the current and correct <code>DbContext</code> every time it needs:</p>
<pre><code>public class MyMembershipProvider : MembershipProvider
{
IDoInContext<MyContext> db;
public MyMembershipProvider()
: this(DependencyResolver.Current.GetService<IDoInContext<MyContext>>())
{ }
public MyMembershipProvider(IDoInContext<MyContext> db)
{
this.db = db;
}
public override bool ValidateUser(string username, string password)
{
bool result = false;
db.DoInContext(x => {
var encodedPassword = encodePassword(password);
result = x.Users.Any(y => y.Login == username &&
y.Password == encodedPassword);
});
return result;
}
...
}
</code></pre>
<p>It seems to be stable and I can't see any memory leaks or any other problems. What do you think? Is the <code>DoInContext(Action<TContext> action)</code> thing any sort of pattern, anti-pattern or bad practice?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-07T12:36:12.373",
"Id": "119071",
"Score": "0",
"body": "Why exactly do you say the `MyDbContext` cannot be injected directly? I'm trying to see if I understand what you mean, so I could help you out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-02T08:51:27.497",
"Id": "137280",
"Score": "0",
"body": "Because my code is not creating instance of the provider. Provider must have constructor without parameters and this constructor is used by .NET. So I cannot inject any constructor parameters."
}
] |
[
{
"body": "<p>The preferred method of doing this is to use a factory dependency that creates the DbContext for you. So instead of the DbContext as the dependency you have a ContextFactory as the dependency and its consumers can get and manage a local DbContext by calling <code>contextFactory.CreateContext()</code>;</p>\n\n<p>If you insist on having your context injected directly, I believe it would be much better to have your MembershipProvider be registered per web request (even though you don't have control over creating it, you still have to register it right?). It shouldn't be a bottleneck. From a design and testing perspective this is much preferred to having a hard dependency on a service locator. How will you test the class by itself? Would you be incorporating your service locator into your tests?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-19T17:39:50.500",
"Id": "78000",
"ParentId": "20735",
"Score": "2"
}
},
{
"body": "<p>Using delegated execution in context is acceptable.</p>\n\n<p>The other question is how to use MembershipProvider in an application using an IoC, while it’s not convenient to use MemberhipProvider in IoC context in a testable manner, using constructor injection, for example. You would need to incorporate a service locator in tests, as noted in another answer.</p>\n\n<p>If you implement your own authentication database, is it convenient to implement a custom interface, then adapt it to MembershipProvider? It’s not uncommon for an application to use features not provided by MembershipProvider, such as a user locking strategy. Some features are probably completely useless for an application. One example would be the standard authentication controls in asp.net classic, since it's an asp.net-mvc application. So there will be probably many methods with empty implementation. It would be using a leaky abstraction then.</p>\n\n<p>Provider model is designed to reuse the standard implementations for applications, which could possibly have unlimited customized deployments, such as a CMS, with a bias towards the standard implementation based on MS SQL Server, so the following questions arise:</p>\n\n<ol>\n<li>Can I use the other implementations of MembershipProvider in my application?</li>\n<li>Is my implementation reusable, can it be used by other applications?</li>\n<li>Will I ever use full functionality for which the MembershipProvider was designed, such as the standard asp.net based UI for administering users and groups?</li>\n<li>Will I use the standard user controls such as LoginControl from the asp.net classic?</li>\n<li>If I implement my own MembershipProvider, can I somehow avoid violation of encapsulation, when accessing the same database from my application code that is used in my implementation of MembershipProvider?</li>\n</ol>\n\n<p>If it’s an application with single deployment, then the most probable answer would be 'no'. Why to use MembershipProvider at all then?</p>\n\n<p>If you use it just to be able to use the standard attributes on the mvc controller methods, it’s easier to implement your own custom attribute and register it with IoC and filter pipeline with mvc: <a href=\"http://lostechies.com/jimmybogard/2010/05/03/dependency-injection-in-asp-net-mvc-filters/\" rel=\"nofollow\">Dependency Injection in ASP.NET MVC: Filters</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-18T15:17:47.970",
"Id": "81830",
"ParentId": "20735",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T11:00:40.653",
"Id": "20735",
"Score": "7",
"Tags": [
"c#",
"validation",
"asp.net-mvc-3"
],
"Title": "MembershipProvider with Entity Framework and IoC"
}
|
20735
|
<p>I have been doing TDD since I have started my first job out of university (about 5 months ago), most of which is working with legacy code. I started a personal project today and thought I would TDD it. I don't have much "green field" dev experience so I am unsure if this is the correct way of driving interface design. I am testing the interface has the expected methods, is a service contract etc... I get the feeling this is too much?</p>
<p>The code is shown below:</p>
<pre><code>[TestFixture]
public class IPairSessionTests
{
[TestCase]
public void Then_IPairSession_is_a_service_contract()
{
var iPairSessionType = typeof(IPairSession);
Assert.That(iPairSessionType.IsDefined(typeof(ServiceContractAttribute),true));
}
[TestCase]
public void Then_IPairSession_has_Insert_Method()
{
var iPairSessionType = typeof(IPairSession);
Assert.That(iPairSessionType.GetMethod("Insert"), Is.Not.Null);
}
[TestCase]
public void Then_IPairsSession_Insert_is_operation_contract()
{
var iPairSessionType = typeof(IPairSession);
var insertMethod = iPairSessionType.GetMethod("Insert");
Assert.That(insertMethod.IsDefined(typeof(OperationContractAttribute), true));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T09:52:55.273",
"Id": "33266",
"Score": "2",
"body": "The things you check in your tests are already checked by the compiler. So these tests add no value. Tests are code too, and they need maintenance. These test cases are just liabilites and not assets.\n\nFor greenfield TDD take a look at http://www.growing-object-oriented-software.com/\n\nBasic Idea is that you should have some other component that uses this interface. You should test in the unit tests of this component the assumptions about this code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T18:53:25.330",
"Id": "73065",
"Score": "0",
"body": "This question appears to be off-topic because it is primarily a design review."
}
] |
[
{
"body": "<p>Yes, it is too much. Testing that methods exist on a contract is both overkill and high-maintenance. If you decide to change a method name, it breaks tests, and the test breakage doesn't tell you something useful. Ask yourself what value you are getting out of this test.</p>\n\n<p>I tend to test interfaces into existence by TDD'ing the classes that use them. I don't think that more is useful.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T19:02:17.003",
"Id": "20743",
"ParentId": "20739",
"Score": "1"
}
},
{
"body": "<p>I think in TDD the interface itself is not the first step (Except it is somehow already given). You create your test and step by step a concrete class. While going through this process you might refactor or optimize you API. Extracting the interface class do make your implementation interchangeable is the last step.</p>\n\n<p>Thinking about the interface in first instance might unnecessarily restrict you.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T06:20:09.603",
"Id": "20751",
"ParentId": "20739",
"Score": "1"
}
},
{
"body": "<p>I'm not too familiar with the C#/.NET world but I guess there are existing tools which do this for you. They might contain more advanced tests, like checking return types, ignoring compatible changes (for example, changing a <code>MySubType</code> parameter to <code>MyType</code> where <code>MySubType</code> extends <code>MyType</code>).</p>\n\n<p>The following Stack Overflow question might be a good start: <a href=\"https://stackoverflow.com/questions/3090792/tool-to-verify-compatibility-of-a-public-apis\">Tool to verify compatibility of a public APIs</a></p>\n\n<hr>\n\n<p>If the clients of the interface and the interface are used only inside the same application (therefore, you can modify both and the compiler checks it) these kind of tests seems unnecessary.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T22:22:06.383",
"Id": "22987",
"ParentId": "20739",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T17:00:41.607",
"Id": "20739",
"Score": "3",
"Tags": [
"c#",
"unit-testing",
"interface",
"tdd"
],
"Title": "Test Driving Interface Design"
}
|
20739
|
<p>I have some data that logs kWh. I want to be able to collect the data and produce a bar chart (I'm using the Microsoft ASP.Net Chart control). I have written code that works, but it looks a little clunky to me and I wondered if somebody could point out a method that may be easier to read and/or more efficient.</p>
<p>The data should normally constantly increase in value though it can be reset. As it is an accumulative value if the values from one period are the same as the previous period then I need to display zero for that time period. Then, when the value does increase, I need to display it as the difference between this period and the last period with a value.</p>
<p>I have the following code to collect the data at hourly intervals only:</p>
<pre><code> myValues = (from values in myEntities.PointValues
where
values.PointID == dataValue &&
SqlFunctions.DatePart("n", values.DataTime) == 0
orderby values.DataTime
select new BarChart
{
Time = values.DataTime,
Value = values.DataValue
}).ToList();
</code></pre>
<p>I then use the following code to set the values that are identical in consecutive periods to 0, though, of course, maintaining the first occurrence at its original value:</p>
<pre><code>for (var i = 0; i < myValues.Count - 1; i++)
{
var j = 0;
while (Math.Abs(myValues[i].Value - myValues[i + 1].Value) < double.Epsilon)
{
i++;
j++;
if (i == myValues.Count - 1) break;
}
while (j > 0)
{
myValues[i + 1 - j].Value = 0;
j--;
}
}
</code></pre>
<p>Finally, I apply the following code to get the difference in values (difference between value this period and the last period with a positive value).</p>
<pre><code>var subValue = double.MaxValue;
foreach (var t in myValues)
{
if (t.Value > 0 && t.Value < subValue) subValue = t.Value;
if (Math.Abs(t.Value - subValue) > double.Epsilon && Math.Abs(t.Value - 0) > double.Epsilon)
{
var j = t.Value;
t.Value = t.Value - subValue;
subValue = j;
}
}
</code></pre>
<p>Which produces my final data.</p>
<p>As I say, this code works fine but if anyone can help with some optimizing/readability, it would be greatly appreciated.</p>
<p>EDIT:
For some images see:</p>
<p><a href="https://stackoverflow.com/questions/14425230/can-anyone-assist-with-some-code-optimization">https://stackoverflow.com/questions/14425230/can-anyone-assist-with-some-code-optimization</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T10:58:27.587",
"Id": "33269",
"Score": "0",
"body": "The answer from Svick below is exactly the kind of thing I was looking for. Being new to programming I hadn't even considered the concept of duplicating arrays. Techniques like this are good to know."
}
] |
[
{
"body": "<p>I think that your code to “remove the values that are identical” is quite confusing.</p>\n\n<p>First, it doesn't remove anything, it just sets the values to zero. And unless you filter that out later, it will cause problems in your final calculation.</p>\n\n<p>Second, modifying the indexing variable of a <code>for</code> is usually not a good idea. It's unexpected and creates code that is hard to understand.</p>\n\n<p>Third, I think you don't actually need this. It would be much easier to remove zero values after you compute the differences.</p>\n\n<hr>\n\n<p>Now, in your code to get the differences, I find the logic hard to follow. (One reason is probably non-descriptive variable names.) And I don't understand why do you have all those conditions there, computing a difference (even with the possibility of a reset) should be simpler. Also, you seem to ignore the fact that if you compute the difference between <em>n</em> values, you will get only <em>n</em> - 1 results.</p>\n\n<p>I would rewrite this code using <a href=\"http://msdn.microsoft.com/en-us/library/dd267698.aspx\" rel=\"nofollow\"><code>Zip()</code></a> and <code>Skip()</code> like this:</p>\n\n<pre><code>var result = Enumerable.Zip(\n data, data.Skip(1),\n (first, second) =>\n second.Value < first.Value\n ? second\n : new BarChart { second.Time, Value = second.Value - first.Value });\n</code></pre>\n\n<p>Also, naming a single value in a chart <code>BarChart</code> is confusing, a better name would be something like <code>BarChartValue</code>.</p>\n\n<hr>\n\n<p>You also asked for performance optimizations. Is your code actually causing performance problems? Have you profiled your application and has this code been identified as bottleneck? If not, don't worry (much) about performance, it won't make a difference anyway.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T18:43:48.657",
"Id": "33243",
"Score": "1",
"body": "Good answers, but from what I understand, the distinct clause won't work in the case because it removes all distinct values. I understand that you only remove them if they are the the same as the previous value. So 1, 2, 2, 3, 2, 3, 1 should turn into 1, 2, 3, 2, 3, 1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T19:02:36.697",
"Id": "33244",
"Score": "0",
"body": "Unfortunately I copied this question from StackOverflow where I had some images, I don't have enough rep here to do that. This has highlighted a few shortcomings with my description. I apologise, I didn't mean remove the identical values, I meant reduce them to 0. I.e. if the values are 10,10,10,12, then I reduce the 2nd and 3rd 10's to 0 (because it's a cumulative reading, no power has been used that period). Then I subtract the last positive value (in this case 10) from 12, and replace 12 with this difference (power used in this period). I agree with descriptive names, I will do that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T19:16:34.473",
"Id": "33246",
"Score": "0",
"body": "As for performance, no I haven't done any profiling, I just thought that having the 2 loops didn't seem very efficient, but it may be the only way to achieve what I need."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T19:33:54.193",
"Id": "33247",
"Score": "0",
"body": "@JeffVanzella You're right, I didn't realize that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T19:36:00.713",
"Id": "33248",
"Score": "0",
"body": "@Family Could you explain *why* are you reducing the values to 0? It doesn't make much sense to me. It only complicates the following code and doesn't give you anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T20:22:24.757",
"Id": "33251",
"Score": "0",
"body": "For user display purposes. If the values are e.g. 10,10,10,12 then if the bar chart displays this the user would assume that that was the usage for each hour, whereas in reality it would be 10,0,0,2. In the images I provided at StackOverflow I think it really highlights the issue. In the 2nd image it looks as though lots of energy has been consumed but the 3rd image gives a true picture."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T20:37:28.217",
"Id": "33252",
"Score": "0",
"body": "@Family But with my simple `Zip()`, you will get exactly that: 0,0,2, because that's what the difference is. No need for the zeroing step."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T20:57:35.627",
"Id": "33253",
"Score": "0",
"body": "I apologise for being slow on the uptake, I just put this code in. This is brilliant. It makes it so much easier to read. I thought my code was too confusing. Thanks so much for the help!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T21:20:08.057",
"Id": "33255",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/7176/discussion-between-svick-and-family)"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T18:29:51.557",
"Id": "20741",
"ParentId": "20740",
"Score": "2"
}
},
{
"body": "<p>For removing similar values just work through the list.</p>\n\n<p>EDIT: Changing to meet requirements</p>\n\n<pre><code>var lastPositiveValue = myValues.First();\n\nforeach (var current in myValues.Skip(1))\n{\n var lastValue = lastPositiveValue.Value;\n\n if (Math.Abs(current.Value - lastPositiveValue.Value) > double.Epsilon)\n {\n lastPositiveValue = current;\n }\n\n current.Value = current.Value - lastValue; \n}\n</code></pre>\n\n<p>svick's answer for the difference seems clean enough :)</p>\n\n<p>Another couple of suggestions, I would rename Value to MeterReading or something of the sort. That will describe it a little better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T19:06:32.543",
"Id": "33245",
"Score": "0",
"body": "Sorry, I didn't explain my problem well enough. I had posted this at http://stackoverflow.com/questions/14425230/can-anyone-assist-with-some-code-optimization where it has some images. The thing is that if values are the same from period to period they need to display 0, i.e. no power used, then the next value needs to be the reading minus the last positive reading, i.e. 10,10,10,12 would become 10,0,0,2 (indicating 10kWh, none, none, 2kWh used)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T19:38:16.063",
"Id": "33249",
"Score": "0",
"body": "@Family That's exactly what you get if you subtract each pair of values, no need for zeroing same values first."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T18:42:09.157",
"Id": "20742",
"ParentId": "20740",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "20741",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T17:07:22.977",
"Id": "20740",
"Score": "3",
"Tags": [
"c#",
"performance",
"asp.net"
],
"Title": "Can I improve this code for readability and/or performance?"
}
|
20740
|
<p>Just a quick preface, I'm not a web developer. I'm simply doing this as a favor for a friend. My goal is to be done with it as quickly as possible, but still not have the coding be horrendous. With that said, as I was coding this, my spidey senses were going off telling me that what I was doing was really bad programming practice and I was wondering if there are any quick fixes I can make to make it more efficient. </p>
<p>I have a form I need to run, but I wanted to give the user the option to choose the number of fields, so I've embedded a lot of PHP code within the body of my HTML files with if/else statements. The problem with this is that it's preventing my Javascript/CSS code in the header to run properly, so I've had to embed them within the body of the html. The code seems to be running a bit slow and probably not as neat as it should be. The code is kind of long, so I removed certain sections that were irrelevant to the discussion. I left a comment in their place to explain their function. I also need to add another block of PHP code that processes the form and enters them in the MySQl database. Any help is appreciated!</p>
<pre><code><html>
<head>
<title></title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="jquery.maskedinput-1.3.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#cash-amount").hide();
$("#transfer-amount").hide();
$(".date").mask("9999-99-99");
$("#cash_yes").click(function(){
$("#cash-amount").show();
});
$("#cash_no").click(function(){
$("#cash-amount").hide();
});
$("#trnsfr_yes").click(function(){
$("#transfer-amount").show();
});
$("#trnsfr_no").click(function(){
$("#transfer-amount").hide();
});
});
</script>
</head>
<body>
<?php
if(isset($_POST['bill_submit'])){
?>
<form id="expenses" method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<?php
if($_POST['CC'] != 0)
{
?>
<table>
<caption>Credit Cards</caption>
<tr>
<th></th>
<th>CC # (last four digits)</th>
<th>Amount</th>
<th>Approval</th>
<th>Date</th>
</tr>
<tbody>
<?php
for ($i = 1; $i <= $_POST['CC']; $i++)
{
?>
<tr>
<td> <?php echo $i; ?> </td>
<td> <input type="text" name="cc_num[]" maxlength="4" size="4" /> </td>
<td> <input type="text" name="cc_amnt[]" size="10"/> </td>
<td> <input type="text" name="cc_app[]" maxlength="10" size="10" /> </td>
<td> <input class="date" type="text" name="cc_date[]" size="10" /> </td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
if($_POST['DB'] != 0)
{
?>
<table>
<caption>Direct Bills</caption>
<tr>
<th></th>
<th>DB #</th>
<th>Amount</th>
<th>Date</th>
</tr>
<tbody>
<?php
for ($i = 1; $i <= $_POST['DB']; $i++)
{
?>
<tr>
<td> <?php echo $i; ?> </td>
<td> <input type="text" name="db_num[]" size="10"/> </td>
<td> <input type="text" name="db_amnt[]" size="10"/> </td>
<td> <input class="date" type="text" name="db_date[]" size="10" /> </td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
if($_POST['misc'] != 0)
{
?>
<table>
<caption>Miscellaneous</caption>
<tr>
<th></th>
<th>Item</th>
<th>Amount</th>
<th>Date</th>
</tr>
<tbody>
<?php
for ($i = 1; $i <= $_POST['misc']; $i++)
{
?>
<tr>
<td> <?php echo $i; ?> </td>
<td> <input type="text" name="misc_item[]" size="10" /> </td>
<td> <input type="text" name="misc_amnt[]" size="10" /> </td>
<td> <input class="date" type="text" name="misc_date[]" size="10" /> </td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
?>
<div id="cash-check">
Are you turning in any checks or cash today? &nbsp; <input type="radio" name="cash" value="Yes" id="cash_yes">Yes &nbsp; <input type="radio" name="cash" value="No" id="cash_no">No</br>
<div id="cash-amount">
Enter Amount: &nbsp; <input type="text" name="cash_amnt" id="cash_amnt" size="10" value="0.00">
</div>
</div>
<div id="transfer">
Would you like to transfer any money to another driver? &nbsp; <input type="radio" name="trnsfr" value="Yes" id="trnsfr_yes">Yes &nbsp; <input type="radio" name="trnsfr" value="No" id="trnsfr_no">No</br>
<div id="transfer-amount">
Enter Driver Number: &nbsp; <input type="text" name="transfer_amnt" id="transfer_amnt" size="10"> &nbsp;
Enter Amount: &nbsp; <input type="text" name="transfer_amnt" id="transfer_amnt" size="10" value="0.00">
</div>
</div>
<style type="text/css">
#cash-amount
{
text-indent:50px;
}
#transfer-amount
{
text-indent:50px;
}
</style>
<script type="text/javascript">
$("#cash_yes").click(function(){
$("#cash-amount").show();
});
$("#cash_no").click(function(){
$("#cash-amount").hide();
});
$("#trnsfr_yes").click(function(){
$("#transfer-amount").show();
});
$("#trnsfr_no").click(function(){
$("#transfer-amount").hide();
});
</script>
<input type="submit" value="Submit" name="submit" />
</form>
<?php
}
else
{
?>
<div>
Please indicate below how many credit cards, direct bills, and miscellaneous items you have to enter into the system. Note that you will have to start over if you enter the numbers incorrectly.
</div>
</br>
<fieldset>
<legend>Numer of Items</legend>
<form id="past_record" method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
Credit Cards: <select name="CC">
<!--List of options from 0-20!-->
</select>
&nbsp; Direct Bills: <select name="DB">
<!--List of options from 0-20!-->
</select>
&nbsp; Miscellaneous: <select name="misc">
<!--List of options from 0-20!-->
</select>
&nbsp; <input type="submit" value="Submit" name="bill_submit" />
</form>
</fieldset>
</div>
<?php
}
?>
</body>
</html>
</code></pre>
|
[] |
[
{
"body": "<p>I cleaned up your code a bit:</p>\n\n<pre><code><!doctype html>\n<html>\n<head>\n <meta charset=\"utf-8\" />\n <title></title>\n <style type=\"text/css\">\n #cash-amount\n {\n text-indent:50px;\n }\n #transfer-amount\n {\n text-indent:50px;\n }\n </style>\n</head>\n<body>\n<?php\n\nif(isset($_POST['bill_submit'])){\n?>\n <form id=\"expenses\" method=\"post\" action=\"<?php echo htmlentities($PHP_SELF); ?>\">\n<?php\n if($_POST['CC'] != 0)\n {\n ?>\n <table>\n <caption>Credit Cards</caption>\n <tr>\n <th></th>\n <th>CC # (last four digits)</th>\n <th>Amount</th>\n <th>Approval</th>\n <th>Date</th>\n </tr>\n <tbody>\n <?php\n for ($i = 1; $i <= $_POST['CC']; $i++)\n {\n ?>\n <tr>\n <td> <?php echo $i; ?> </td>\n <td> <input type=\"text\" name=\"cc_num[]\" maxlength=\"4\" size=\"4\" /> </td> \n <td> <input type=\"text\" name=\"cc_amnt[]\" size=\"10\"/> </td>\n <td> <input type=\"text\" name=\"cc_app[]\" maxlength=\"10\" size=\"10\" /> </td> \n <td> <input class=\"date\" type=\"text\" name=\"cc_date[]\" size=\"10\" /> </td>\n </tr>\n <?php\n }\n ?> \n </tbody>\n </table>\n <?php \n }\n if($_POST['DB'] != 0)\n {\n ?>\n <table>\n <caption>Direct Bills</caption>\n <tr>\n <th></th>\n <th>DB #</th>\n <th>Amount</th>\n <th>Date</th>\n </tr>\n <tbody>\n <?php\n for ($i = 1; $i <= $_POST['DB']; $i++)\n {\n ?>\n <tr>\n <td> <?php echo $i; ?> </td>\n <td> <input type=\"text\" name=\"db_num[]\" size=\"10\"/> </td> \n <td> <input type=\"text\" name=\"db_amnt[]\" size=\"10\"/> </td> \n <td> <input class=\"date\" type=\"text\" name=\"db_date[]\" size=\"10\" /> </td>\n </tr>\n <?php\n }\n ?> \n </tbody>\n </table>\n <?php \n }\n if($_POST['misc'] != 0)\n {\n ?>\n <table>\n <caption>Miscellaneous</caption>\n <tr>\n <th></th>\n <th>Item</th>\n <th>Amount</th>\n <th>Date</th>\n </tr>\n <tbody>\n <?php\n for ($i = 1; $i <= $_POST['misc']; $i++)\n {\n ?>\n <tr>\n <td> <?php echo $i; ?> </td>\n <td> <input type=\"text\" name=\"misc_item[]\" size=\"10\" /> </td> \n <td> <input type=\"text\" name=\"misc_amnt[]\" size=\"10\" /> </td> \n <td> <input class=\"date\" type=\"text\" name=\"misc_date[]\" size=\"10\" /> </td>\n </tr>\n <?php\n }\n ?> \n </tbody>\n </table>\n <?php \n }\n ?>\n <div id=\"cash-check\">\n Are you turning in any checks or cash today? &nbsp; <input type=\"radio\" name=\"cash\" value=\"Yes\" id=\"cash_yes\">Yes &nbsp; <input type=\"radio\" name=\"cash\" value=\"No\" id=\"cash_no\">No</br>\n <div id=\"cash-amount\">\n Enter Amount: &nbsp; <input type=\"text\" name=\"cash_amnt\" id=\"cash_amnt\" size=\"10\" value=\"0.00\">\n </div>\n </div>\n <div id=\"transfer\">\n Would you like to transfer any money to another driver? &nbsp; <input type=\"radio\" name=\"trnsfr\" value=\"Yes\" id=\"trnsfr_yes\">Yes &nbsp; <input type=\"radio\" name=\"trnsfr\" value=\"No\" id=\"trnsfr_no\">No</br>\n <div id=\"transfer-amount\">\n Enter Driver Number: &nbsp; <input type=\"text\" name=\"transfer_amnt\" id=\"transfer_amnt\" size=\"10\"> &nbsp;\n Enter Amount: &nbsp; <input type=\"text\" name=\"transfer_amnt\" id=\"transfer_amnt\" size=\"10\" value=\"0.00\">\n </div>\n </div>\n\n <input type=\"submit\" value=\"Submit\" name=\"submit\" />\n </form>\n\n <?php\n} \nelse\n{\n?>\n\n<div>\n Please indicate below how many credit cards, direct bills, and miscellaneous items you have to enter into the system. Note that you will have to start over if you enter the numbers incorrectly. \n</div>\n</br>\n<fieldset>\n<legend>Numer of Items</legend>\n <form id=\"past_record\" method=\"post\" action=\"<?php echo htmlentities($PHP_SELF); ?>\">\n Credit Cards: <select name=\"CC\">\n <!--List of options from 0-20!-->\n </select>\n &nbsp; Direct Bills: <select name=\"DB\">\n <!--List of options from 0-20!-->\n </select>\n &nbsp; Miscellaneous: <select name=\"misc\">\n <!--List of options from 0-20!-->\n </select>\n &nbsp; <input type=\"submit\" value=\"Submit\" name=\"bill_submit\" />\n</form>\n</fieldset>\n</div>\n\n\n<?php \n}\n?>\n<script src=\"http://code.jquery.com/jquery-latest.js\"></script>\n<script src=\"jquery.maskedinput-1.3.js\"></script>\n<script>\n $(function() {\n $(\"#cash-amount\").hide();\n $(\"#transfer-amount\").hide();\n $(\".date\").mask(\"9999-99-99\");\n $(\"#cash_yes\").on('click', function(e){\n $(\"#cash-amount\").show();\n });\n $(\"#cash_no\").on('click', function(e){\n $(\"#cash-amount\").hide();\n });\n $(\"#trnsfr_yes\").on('click', function(e){\n $(\"#transfer-amount\").show();\n });\n $(\"#trnsfr_no\").on('click', function(e){\n $(\"#transfer-amount\").hide();\n });\n });\n</script>\n</body>\n</html>\n</code></pre>\n\n<p>Script references should be moved to the bottom of the <code><body></code> tag, so that they don't block the HTML parser from doing it's job. Also, you were missing the doctype and character-set declarations, which can throw your browser into Quirks mode (which is not always fun to deal with). If you were getting paid to do this, I'd give you some grief about using <code>$_POST</code> references directly in your code, but for one-off stuff...</p>\n\n<p>Also, avoid adding <code><style></code> elements anywhere except the <code><head></code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T19:49:15.167",
"Id": "33250",
"Score": "0",
"body": "To be honest, the reason why I have all those annoying $_POST references directly in my code is because I'm running all my codes through wordpress (using embedded PHP within posts...I know, this is a bad idea). I originally chose to use wordpress because it had the benefit of nice looking themes and a user database setup, but I've come to regret that decision more and more. I was just hoping to prevent from having to learn how to make a secure user login system because I don't have the time to do so. I'm now really considering switching from Wordpress to a normal style website."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T08:01:14.493",
"Id": "33263",
"Score": "0",
"body": "@user1562781 Nice looking sites aren't too difficult if you start with something like the HTML5Boilerplate and/or Twitter Bootstrap. Also, if you're thinking of moving away from WP, the PEAR library might be worth looking into for ready-made components: http://pear.php.net/"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T19:10:35.640",
"Id": "20747",
"ParentId": "20744",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-20T19:05:18.743",
"Id": "20744",
"Score": "2",
"Tags": [
"php",
"jquery",
"mysql",
"html",
"css"
],
"Title": "I've embedded several PHP/HTML/Javascript in one page. How can I improve on the efficiency/performance?"
}
|
20744
|
<p>Here's the situation. I'm writing a simple game and I had two main actors: <code>GameController</code> and <code>GridView</code>.</p>
<ul>
<li><p><code>GridView</code> is a <code>UIView</code> subclass displaying a grid with which the user interacts. It defines its custom delegate protocol (<code>GridViewDelegate</code>) for handling callbacks such as <code>gridView:didSelectTile</code> and others.</p></li>
<li><p><code>GameController</code> is the game controller (duh!) which instantiate a <code>GridView</code> and set itself as a delegate, therefore implementing the <code>GridViewDelegate</code> protocol.</p></li>
</ul>
<p>So far so good, then I decided to add HUD components on top of the grid (a score, a timer and other stuff). The most reasonable choice seemed to wrap such HUD components along with the grid into a new <code>UIView</code> subclass called <code>GameBoard</code>.</p>
<p>And here comes the design issue: I need the controller to talk to the <code>GridView</code> and I think there's two reasonable options here.</p>
<ol>
<li><p>Expose a <code>gridView</code> property and do something like</p>
<pre><code>[self.gameBoard.gridView doStuff];
</code></pre></li>
<li><p>Forward the invocation made to <code>GameBoard</code> directly to <code>GridView</code> overriding the <code>forwardInvocation:</code> method of <code>GameBoard</code></p></li>
</ol>
<p>The first options looks like the most convenient, but I cannot get myself into liking it, due to the <a href="http://en.wikipedia.org/wiki/Law_of_Demeter" rel="nofollow">Law of Demeter</a>.</p>
<p>So I decided to go for the second approach and do something like</p>
<pre><code>// The GameBoard serves a proxy between the GameContoller and the GridView
- (void)forwardInvocation:(NSInvocation *)anInvocation {
if ([self.gridView respondsToSelector:anInvocation.selector]) {
[anInvocation invokeWithTarget:self.gridView];
} else {
[super forwardInvocation:anInvocation];
}
}
// This method is necessary for the above forwardInvocation to work
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
NSMethodSignature * signature = [super methodSignatureForSelector:aSelector];
if (!signature) {
signature = [self.gridView methodSignatureForSelector:aSelector];
}
return signature;
}
</code></pre>
<p>It works as expected, but I'd like to have a second opinion on my design choice.</p>
<p>I generally tend to avoid overusing of the dynamic features of Objective-C, but it looked like an elegant way to achieve my result fulfilling the Law of Demeter. </p>
|
[] |
[
{
"body": "<p>I think you trying to overengineer solution a bit. First of all View should not do any stuff at all. View is just a View, sheet of paper. Maximum of view's responsibility is layouting himself. So controller should take care of other view-related stuff. </p>\n\n<p>In this case I probably prefer to think about gridView as legitimate subview of GameBoard. I really doubt Demetra suffering when you doing something like <code>[self.view.titleLabel sizeToFit]</code>. </p>\n\n<p>So my advice is to use <code>[self.gameBoard.gridView doStuff];</code> as simplest and straightforward solution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T04:09:33.380",
"Id": "33386",
"Score": "0",
"body": "By the way `forwardInvocation` will not be typechecked at all. Typesystem of Objective-C already too weak, don't make your life even harder. If you insist—I can advice to define `@protocol` for `GameBoard` with methods of `GridView`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T01:47:39.160",
"Id": "20811",
"ParentId": "20749",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "20811",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T01:58:46.990",
"Id": "20749",
"Score": "4",
"Tags": [
"objective-c"
],
"Title": "Code review of forward invocation"
}
|
20749
|
<p>Is there a better way to implement my carousel in less lines?</p>
<pre class="lang-html prettyprint-override"><code><div id="myCarousel" class="carousel slide">
<div class="carousel-inner">
<% @photos.each_with_index do |photo, index| %>
<% if index == 0 %>
<div class="item active">
<img src="<%= photo.image_url(:large) %>" alt="<%= photo.title %>">
<div class="container">
<div class="carousel-caption">
<h1>TITLE</h1>
</div>
</div>
</div>
<% end %>
<% if index == 1 %>
<div class="item">
<img src="<%= photo.image_url(:large) %>" alt="<%= photo.title %>">
</div>
<% end %>
<% if index == 2 %>
<div class="item">
<img src="<%= photo.image_url(:large) %>" alt="<%= photo.title %>">
</div>
<% end %>
<% if index == 3 %>
<div class="item">
<img src="<%= photo.image_url(:large) %>" alt="<%= photo.title %>">
</div>
<% end %>
<% if index == 4 %>
<div class="item">
<img src="<%= photo.image_url(:large) %>" alt="<%= photo.title %>">
</div>
<% end %>
<% if index == 5 %>
<div class="item">
<img src="<%= photo.image_url(:large) %>" alt="<%= photo.title %>">
</div>
<% end %>
<% end %>
</div>
</div><!-- /.carousel -->
</code></pre>
|
[] |
[
{
"body": "<p>Get rid of unnecessary code:</p>\n\n<pre><code><div id=\"myCarousel\" class=\"carousel slide\">\n <div class=\"carousel-inner\">\n <% @photos.each_with_index do |photo, index| %>\n <% if index.zero? %>\n <div class=\"item active\">\n <img src=\"<%= photo.image_url(:large) %>\" alt=\"<%= photo.title %>\">\n <div class=\"container\">\n <div class=\"carousel-caption\">\n <h1>TITLE</h1>\n </div>\n </div>\n </div>\n <% else %>\n <div class=\"item\">\n <img src=\"<%= photo.image_url(:large) %>\" alt=\"<%= photo.title %>\">\n </div>\n <% end %>\n <% end %>\n </div>\n</div>\n</code></pre>\n\n<p>Move stuff to helpers:</p>\n\n<pre><code>module PhotoHelpers\n def slider_image(photo)\n image_tag photo.image_url(:large), alt: photo.title\n end\nend\n\n<div id=\"myCarousel\" class=\"carousel slide\">\n <div class=\"carousel-inner\">\n <% @photos.each_with_index do |photo, index| %>\n <% if index.zero? %>\n <div class=\"item active\">\n <%= slider_image photo %>\n <div class=\"container\">\n <div class=\"carousel-caption\">\n <h1>TITLE</h1>\n </div>\n </div>\n </div>\n <% else %>\n <div class=\"item\">\n <%= slider_image photo %>\n </div>\n <% end %>\n <% end %>\n </div>\n</div>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T10:44:40.287",
"Id": "20755",
"ParentId": "20750",
"Score": "4"
}
},
{
"body": "<p>Along with @NARKOZ's excellent answer, consder converting your template to <a href=\"http://haml.info/\" rel=\"nofollow\">haml</a>:</p>\n\n<pre><code>#myCarousel.carousel.slide\n .carousel-inner\n - @photos.each_with_index do |photo, index|\n - if index.zero?\n .item.active\n %img{:alt => photo.title, :src => photo.image_url(:large)}/\n .container\n .carousel-caption\n %h1 TITLE\n - else\n .item\n %img{:alt => photo.title, :src => photo.image_url(:large)}/\n</code></pre>\n\n<p>All you have to do is name your template <em>.haml</em> instead of <em>.erb</em>, and include the haml gem in your Gemfile.</p>\n\n<p>The haml gem comes with a conversion script, <em>html2haml</em>, which will convert your <em>erb</em> to <em>haml</em>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T13:51:05.073",
"Id": "20803",
"ParentId": "20750",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20755",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T02:30:15.607",
"Id": "20750",
"Score": "6",
"Tags": [
"html",
"erb"
],
"Title": "Showing items as in a Carousel"
}
|
20750
|
<p>I use the following code to verify that columns have data and display the appropriate error message.</p>
<p>My code is working but it just doesn't look tidy. Is there any way to refactor all the <code>if</code> statements into a loop to display the error message, possibly another method which checks all? <code>checkIfColumnIsEmpty</code> is a <code>bool</code> method which returns <code>true</code> if the column is empty.</p>
<pre><code> //if either column 0 and 1 are empty && column 2,3,4 and 5 are not
if (!checkIfColumnisEmpty(r.ItemArray[0]) || !checkIfColumnisEmpty(r.ItemArray[1])
&& checkIfColumnisEmpty(r.ItemArray[2]) && checkIfColumnisEmpty(r.ItemArray[3])
&& checkIfColumnisEmpty(r.ItemArray[4]) && checkIfColumnisEmpty(r.ItemArray[5]))
{
if (checkIfColumnisEmpty(r.ItemArray[0]) && !checkIfColumnisEmpty(r.ItemArray[1]))
{
throw new ImportBOQException("Error importing document: First column is empty");
}
else if (!checkIfColumnisEmpty(r.ItemArray[0]) && checkIfColumnisEmpty(r.ItemArray[1]))
{
throw new ImportBOQException("Error importing document: Second column is empty");
}
else if (!checkIfColumnisEmpty(r.ItemArray[0]) && !checkIfColumnisEmpty(r.ItemArray[1]))
{
//all columns are valid so...
Column0inSpreadsheet = r.ItemArray[0] as string;
Column1inSpreadsheet = r.ItemArray[1] as string;
//Other code which performs other operations, once the level as reached this far
}
}
//if column 0 and 1 are NOT empty && Either column 2,3,4 or 5 is empty
else if (checkIfColumnisEmpty(r.ItemArray[0]) && checkIfColumnisEmpty(r.ItemArray[1])
|| !checkIfColumnisEmpty(r.ItemArray[2]) || !checkIfColumnisEmpty(r.ItemArray[3])
|| !checkIfColumnisEmpty(r.ItemArray[4]) || !checkIfColumnisEmpty(r.ItemArray[5]))
{
if (checkIfColumnisEmpty(r.ItemArray[2]))
{
throw new ImportBOQException("Error importing document: Third column is empty");
}
else if (checkIfColumnisEmpty(r.ItemArray[3]))
{
throw new ImportBOQException("Error importing document: Fourth column is empty");
}
else if (checkIfColumnisEmpty(r.ItemArray[4]))
{
throw new ImportBOQException("Error importing document: Fifth column is empty");
}
else if (checkIfColumnisEmpty(r.ItemArray[5]))
{
throw new ImportBOQException("Error importing document: Sixth column is empty");
}
else
//all columns are valid so...
{
Column2inSpreadsheet = (r.ItemArray[2]) as string;
Column3inSpreadsheet = (r.ItemArray[3]) as string;
Column4inSpreadsheet = (r.ItemArray[4]) as string;
Column5inSpreadsheet = (r.ItemArray[5]) as string;
//Other code which performs other operations, once the level as reached this far
}
}
else
//other errors ot related to empty colums
{
throw new Exception("Error Uploading");
}
}
</code></pre>
|
[] |
[
{
"body": "<p>First of all, better names than columnX would be nice. I guess the indentation is a copying-issue, otherwise this would be the next optimization. Furthermore I have the feeling that mixing the && and the || in your condition without parenthesis is not what you want to do?</p>\n\n<pre><code>col0empty=checkIfColumnisEmpty(r.ItemArray[0])\ncol1empty=checkIfColumnisEmpty(r.ItemArray[1])\ncol2empty=checkIfColumnisEmpty(r.ItemArray[2])\ncol3empty=checkIfColumnisEmpty(r.ItemArray[3])\ncol4empty=checkIfColumnisEmpty(r.ItemArray[4])\ncol5empty=checkIfColumnisEmpty(r.ItemArray[5])\n\nif ((!col0empty || !col1empty) && col2empty && col3empty && col4empty && col5empty)\n{\n if (col0empty && !col1empty) errorWithEmptyColumn(\"First\");\n else if (!col0empty && col1empty) errorWithEmptyColumn(\"Second\");\n else if (!col0empty && !col1empty)\n {\n //Code after validation\n }\n}\nelse if ((col0empty && col1empty) || !col2empty || !col3empty || !col4empty || !col5empty)\n{\n if (col2empty) errorWithEmptyColumn(\"Third\");\n else if (col3empty) errorWithEmptyColumn(\"Fourth\");\n else if (col4empty) errorWithEmptyColumn(\"Fifth\");\n else if (col5empty) errorWithEmptyColumn(\"Sixth\");\n else\n {\n //Code after validation\n }\n}\nelse\n{\n throw new ImportBOQException(\"Error Uploading\"); //don't throw raw exceptions\n}\n// } one to much\n\nprivate void errorWithEmptyColumn(String columnName) throws ImportBOQException\n{\n throw new ImportBOQException(\"Error importing document: \"+columnName+\" column is empty\");\n}\n</code></pre>\n\n<p>For further optimization it is import to know how similar the code in the two remaining branches is?</p>\n\n<p>You could also extract the condition in an variable and give them a name: i.e. rowTypeX and rowTypeY. Maybe the result is more intuitive if you move the handling of the row types in a method each:</p>\n\n<pre><code>empty=col0empty && col1empty && col2empty && col3empty && col4empty && col5empty\nrowTypeX=col2empty && col3empty && col4empty && col5empty;\nrowTypeY=col0empty && col1empty;\nif ( empty) throw new ImportBOQException(\"Empty row\");\nelse if (rowTypeX) handleRowTypeX(r);\nelse if (rowTypeY) handleRowTypeY(r);\nelse throw new ImportBOQException(\"Error Uploading\"); \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T13:08:36.610",
"Id": "20758",
"ParentId": "20757",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "20758",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T12:30:10.767",
"Id": "20757",
"Score": "3",
"Tags": [
"c#",
"asp.net"
],
"Title": "Importing an Excel document into a project"
}
|
20757
|
<p>I have this code and I think it is very slow, about 50ms. I need to make it execute faster:</p>
<pre><code> switch (unit)
{
case 0:
if (u == 2)
{
if (u1 == "piece" || u1 == "gram")
result = quantity * y;
else
result = quantity * z;
}
if (u == 1)
{
if (u1 == "piece" || u1 == "gram")
result = quantity * y;
else
result = quantity;
}
res_name = "gram";
break;
case 1: //ml
if (u == 2)
{
if (u1 == "piece" || u1 == "gram")
result = quantity * x;
else
result = quantity * y;
}
if (u == 0)
{
if (u1 == "piece" || u1 == "gram")
result = quantity * x;
else
result = quantity;
}
res_u = "ml";
break;
case 2:
res_u = "pieces";
break;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T15:07:15.800",
"Id": "33279",
"Score": "1",
"body": "Can you give more information about unit, u, u1, res_u, result, quantity, x, y, z?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T15:12:21.290",
"Id": "33280",
"Score": "0",
"body": "@Romoku x, y, and z are fields I get from db. result and res_u are the fields I return from the method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T15:19:19.770",
"Id": "33281",
"Score": "0",
"body": "I more or less meant what are their object types?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T15:31:23.070",
"Id": "33282",
"Score": "0",
"body": "@Srcee, please describe the meaning of parameters and their values. What the it mean when `unit` is equal to `0`, `1` and `2`? Are these the only values it can have? What is the logical meaning of `u`, and what does the values `0`, `1` and `2` mean? Basically your code suffers from well-known [magic numbers](http://en.wikipedia.org/wiki/Magic_number_(programming)) problem"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T15:34:50.143",
"Id": "33283",
"Score": "5",
"body": "@Srcee as to your statement `I think it is very slow, about 50ms. I need to make it execute faster` - that is not the case, this code will perform much faster unless you're running it on 20 Mhz computer ;). Most likely the slow part is the data retrieval. Please describe how exactly you've measured the performance"
}
] |
[
{
"body": "<p>The first thing I would do is refactor your names to something understandable. After that I would try to create a data structure to encapsulate the nested logic.</p>\n\n<p>Without knowing more about the background it is hard to refactor without breaking some kind of functionality. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T15:25:14.470",
"Id": "20761",
"ParentId": "20759",
"Score": "3"
}
},
{
"body": "<p>Rather than guessing which lines <em>might</em> be the ones taking up a lot of CPU time, you should run this code through a profiler, which will tell you which parts take up most of the run-time, which are the parts you should then target for optimization.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T18:44:24.593",
"Id": "33292",
"Score": "0",
"body": "I get the 50ms time with profiler."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T18:56:34.590",
"Id": "33298",
"Score": "0",
"body": "Which profiler are you using?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T19:10:21.280",
"Id": "33299",
"Score": "0",
"body": "This one: http://miniprofiler.com/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T19:30:09.280",
"Id": "33301",
"Score": "0",
"body": "It looks like miniprofiler has a `step` function you can use to narrow down how long specific pieces of code take.\n\nAlternatively, you could time parts of your code manually with the System.Diagnostics.Stopwatch class."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T18:17:30.300",
"Id": "20767",
"ParentId": "20759",
"Score": "3"
}
},
{
"body": "<p>I agree with <a href=\"https://codereview.stackexchange.com/users/21332/romoku\">Romoku</a>. Unless there is a definite requirement to make this faster and a noticeable effect on performance of your application within this method I would consider making it more DRY, more developer friendly and less procedural.</p>\n\n<p>Without more code and explanation of whats there here are some things I would consider:</p>\n\n<ol>\n<li><p>Try and remove duplicated code. I notice you repeat your <code>if(u1 == \"piece\"</code> ... code everywhere. Consider moving that into a method and passing in the parameters required. </p>\n\n<pre><code>private int GetConversion(UnitsEnum units, int pieceGramsMultipler, int otherMultipler)\n{\n return units == UnitsEnum.Piece || units == UnitsEnum.Gram\n ? pieceGramsMultipler\n : otherMultipler; \n}\n</code></pre>\n\n<p>Then used like</p>\n\n<pre><code>if (u == 2)\n{\n result = quantity * GetConversion(u1, y, z); \n}\n</code></pre></li>\n<li><p>Consider changing your string literals into enumerations. So \"piece\" and \"gram\" might become:</p>\n\n<pre><code>private enum UnitsEnum\n{\n Piece,\n Gram\n}\n</code></pre></li>\n<li><p>Consider changing your case statements into constants or enumerations. So rather than case 1, it might be case <code>Metric.Ml</code> or <code>ML</code> or <code>Milliliters</code> etc</p></li>\n<li><p>Offer better names for your variables. u1, x, y, z gives me no idea of what they are trying to do. </p></li>\n<li><p>Use if else instead of 2 if statements. If u == 2 then there is no chance that it will be == 1 so convert your if's into if elses to make that more obvious.</p></li>\n</ol>\n\n<p>Otherwise, perhaps posting the full code that this piece resides in might get your more help and suggestions. I get the feeling that there is more help this community can offer you here than just what you have posted.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T19:28:09.900",
"Id": "33367",
"Score": "0",
"body": "Very good advice in this post; just one minor quibble: `UnitsEnum` should probably be called `Unit`, I don't see a reason to encode the type in the name. In fact, the enums may be unnecessary if the raw integer values can be replaced with domain types — but your answer is still the best one possible given the limited information in the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T19:38:28.513",
"Id": "33369",
"Score": "0",
"body": "@codesparkle Good points. I don't even know if even Unit is the best name. Took a wild guess there :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T21:08:12.870",
"Id": "20774",
"ParentId": "20759",
"Score": "5"
}
},
{
"body": "<p>dreza is correct that you could split some of your code up into functions.</p>\n\n<p>Many parts of it can be combined into smaller sections:</p>\n\n<pre><code>if (u == 2)\n{\n if (u1 == \"piece\" || u1 == \"gram\")\n result = quantity * y;\n else\n result = quantity * z;\n}\nif (u == 1)\n{\n if (u1 == \"piece\" || u1 == \"gram\")\n result = quantity * y;\n else\n result = quantity;\n}\n</code></pre>\n\n<p>I would write this instead:</p>\n\n<pre><code>if (u == 1 || u == 2)\n{\n if (u1 == \"piece\" || u1 == \"gram\")\n {\n result = quantity * y;\n }\n else\n {\n result = u == 1 ? quantity : quantity * z;\n\n // This also works the same way:\n // result = quantity * (u == 1 ? 1 : z);\n }\n}\n</code></pre>\n\n<p>This makes fewer (by half) the lines of code to maintain, not counting braces. Also, notice how I put braces around my code to help prevent errors.</p>\n\n<p>Romoku also make very good points about renaming your variables to reflect what they are doing better.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-05T16:47:10.823",
"Id": "83312",
"ParentId": "20759",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T15:03:14.697",
"Id": "20759",
"Score": "2",
"Tags": [
"c#",
"performance"
],
"Title": "Optimizing nested if statements in switch"
}
|
20759
|
<p>This is my code:</p>
<pre><code>var test = (from x in myDb.myTable
where (x.name == tmp || x.name == tmp2 || x.name == tmp3) && x.unit == u
select x).FirstOrDefault();
if (test == null)
test = (from x in myDb.myTable
where (x.name == tmp || x.name == tmp2 || x.name == tmp3)
select x).FirstOrDefault();
</code></pre>
<p>How to optimize it>?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T15:46:31.107",
"Id": "33285",
"Score": "1",
"body": "Could you explain your logic? Why are you doing it this way? If there are rows with both `tmp` and `tmp2` (which are bad variable names, BTW) as their `name`, why is it okay to get any one of them? What is the schema of your table? How many rows does your table have? Does it have any indexes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T18:45:08.947",
"Id": "33293",
"Score": "0",
"body": "@svick tmp, tmp2 and tmp3 are basically the same string, but with different encoding."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T18:46:09.180",
"Id": "33294",
"Score": "0",
"body": "@svick myTable has a primary key which is int and autoincremented. It doesn't have indexes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T18:50:44.937",
"Id": "33295",
"Score": "1",
"body": "Can't you modify your database so that it used only one encoding?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T18:54:07.553",
"Id": "33297",
"Score": "0",
"body": "Also, are you performing this query in a loop, or something like that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T19:11:29.020",
"Id": "33300",
"Score": "0",
"body": "@svick Actually yes, this code is in a foreach loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T21:53:41.727",
"Id": "33309",
"Score": "0",
"body": "@Srcee: Try to avoid the loop and change the condition to `tempNames.Contains(x.name)` where tempNames is a list containing the names. This will be translated to SQL `WHERE name IN (\"aaa\", \"bbb\", \"ccc\")` and be much faster! Also don't compare to different encodings just because you are not sure which one is the right one. Figure out which one is the right one and use this one only."
}
] |
[
{
"body": "<pre><code>var test = (from x in myDb.myTable\n where (x.name == tmp || x.name == tmp2 || x.name == tmp3)\n select x)\n .AsEnumerable()\n .OrderBy(x => x.unit == u ? 0 : 1)\n .FirstOrDefault();\n</code></pre>\n\n<p>I removed the <code>x.unit == u</code> condition. Instead I sort the items to make the ones where \nthis condition would be met to appear first. <code>FirstOrDefault</code> then makes the rest.</p>\n\n<p>I split the EF part from the LINQ-to-objects part with <code>AsEnumerable()</code> as I am not sure if EF can translate the order by to SQL. If it can, you can try this</p>\n\n<pre><code>var test = (from x in myDb.myTable\n where (x.name == tmp || x.name == tmp2 || x.name == tmp3)\n orderby x.unit == u ? 0 : 1\n select x)\n .FirstOrDefault();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T18:43:56.950",
"Id": "33291",
"Score": "0",
"body": "Tnx for your answer. But will you pls explain how will this fasten the execution?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T18:52:32.313",
"Id": "33296",
"Score": "0",
"body": "@Srcee It will always make a single query, while your code might make two queries. Making smaller number of queries is usually more efficient."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T21:45:49.157",
"Id": "33308",
"Score": "0",
"body": "@Srcee: You did not specify what you wanted to have optimized (execution speed, code size, code maintainablity, others?). My solution will be faster, because it queries the database only once in any case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T07:21:51.650",
"Id": "33329",
"Score": "0",
"body": "I wanted to fasten the time, so I guess your solution will work."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T15:25:29.747",
"Id": "20762",
"ParentId": "20760",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "20762",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T15:12:46.830",
"Id": "20760",
"Score": "3",
"Tags": [
"c#",
"optimization",
"entity-framework"
],
"Title": "Optimization of code for searching in db"
}
|
20760
|
<p>I have a much needed rewrite of an inherited application ahead of me and have started to sketch out some possible solutions / build some prototypes for different parts of the application.</p>
<p>I'd like to have some feedback if this is a good approach to provide application events.</p>
<p>Goals:</p>
<ul>
<li>Loosely coupled</li>
<li>Strictly typed / refactor friendly</li>
<li>Declarative</li>
<li>Adhere to SRP (Single responsibility principle)</li>
<li>Lightweight</li>
</ul>
<p>All events are classes derived from <code>EventBase</code>. An IoC Container will handle lifetimes of brokers and subscribers. Constructor injection is used. All types implementing <code>IEventSubscriber<></code> (where T : EventBase) will be automatically registered in the container. My <code>DefaultEventBroker</code> implementation then has an optional <code>IEnumerable<IEventSubscriber<>></code> dependency, which the container will resolve to all visible subscribers for a given event type. Under the hood a <code>System.Reactive.Subjects.Subject<></code> (Microsoft Reactive Extensions) will do the heavy lifting.</p>
<p>Essentially I provide two ways to subscribe to events:</p>
<h2>Subscribe by setting a dependency on (one or more) IEventBroker<></h2>
<pre><code>public class MyEventListeningComponent
{
public MyEventListeningComponent(IEventBroker<ProgramStartedEvent> eventBroker)
{
eventBroker.Subscribe(e =>
{
Console.WriteLine("[MyEventListeningComponent] Program Started: {0}", e.StartDate.ToString());
});
}
}
</code></pre>
<h2>Subscribe by implementing (one or more) IEventSubscriber<></h2>
<pre><code>public class MyEventSubscriber : IEventSubscriber<ProgramStartedEvent>, IEventSubscriber<ProgramEndedEvent>
{
public void OnNext(ProgramStartedEvent value)
{
Console.WriteLine("[MyEventSubscriber] OnNext: Program Started: {0}", value.StartDate.ToString());
}
public void OnNext(ProgramEndedEvent value)
{
Console.WriteLine("[MyEventSubscriber] OnNext: Program Ended: {0}", value.EndDate.ToString());
}
}
</code></pre>
<p>Any more or less obvious pitfalls? Suggestions?</p>
<p>Side note: <code>IEventSubscriber<></code> is essentially an <code>IObserver<></code> without the OnCompleted and OnError methods, because I can subscribe to multiple event types by implementing <code>IEventSubscriber<></code> with different generic type arguments and I wouldn't be able to get an event type context in OnCompleted and OnError (because those methods do not have generic type arguments). I'm relatively sure I won't be needing those hooks in this scenario anyway.</p>
<p><strong>Edit:</strong> Events are raised (or published) via <code>IEventBroker<></code></p>
<pre><code>public class MyEventRaisingComponent
{
public MyEventRaisingComponent(IEventBroker<ProgramStartedEvent> eventBroker)
{
eventBroker.Publish(new ProgramStartedEvent() { StartDate = DateTime.Now });
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T21:31:23.687",
"Id": "33307",
"Score": "1",
"body": "This looks reasonable. But the same pitfall as with every rewrite applies: you're potentially throwing away hours and hours of bug fixes and experience. Proceed with care, **unit test** along the way and don't rewrite the parts that will be similar to your old code base — you can refactor those safely."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T06:28:15.190",
"Id": "33328",
"Score": "0",
"body": "The original codebase is insanely complicated for what it does, e.g. custom made script engine and language for mundane tasks, custom file formats for configuration and an unqueryable database structure. Fortunately, for now I only have to port a subset of features."
}
] |
[
{
"body": "<p>The code itself looks good, but I would look into providing a single way of subscribing to events, it will make the job easier for other developers reading and changing the code.</p>\n\n<p>The first method of subscribing (via <code>IEventBroker<T></code> injection) requires subscriber object to be created first, so it may not receive all events that you may expect it to receive. Every time you create an instance of subscriber it adds a new event subscription thus causing potential memory leaks and side effects. You might need to add <code>Unsubscribe</code> method to <code>IEventBroker<T></code> if you prefer to leave it.</p>\n\n<p>Second method (the one I would prefer) is better suited for application-wide events since it moves the responsibility of subscription to the infrastructure thus avoiding multiple subscriptions and memory leaks (comparing to first option). It is also easier to unit-test since part of responsibilities are taken away from subscriber.</p>\n\n<p><strong>Update based on question update</strong>: Publishing messages also looks good. In this case (following my suggestion to leave only second method of event subscription) I would remove <code>Subscribe</code> method from <code>IEventBroker<T></code> declaration, and refactor it to non-generic <code>IEventPublisher</code> interface with generic method <code>void Publish<T>(T eventToPublish)</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T16:41:47.820",
"Id": "33362",
"Score": "0",
"body": "Sorry, I got interrupted after making that edit and before I could answer. Since `IEventBroker<>` is used to publish events and my default implementation gets all `IEventSubscriber<>`s passed to it's constructor by the container and hooks those up, there should never be a case were a subscriber misses an event. My `DefaultEventBroker` also implements `IDisposable` and takes care of disposing the underlying `Subject<>`. My container calls Dispose() on any component that implements `IDisposable` when it's lifetime ends, so there should be no memory leaks (I hope)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T16:43:11.517",
"Id": "33363",
"Score": "0",
"body": "That being said, I like the idea of having an `IEventPublisher` counterpart to `IEventSubscriber<>`. I think one could argue that by making `IEventPublisher` a generic type, a component would state what types of events it generates through it's constructor parameters. On the other hand it could lead to alot of parameters in some cases."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T19:04:36.997",
"Id": "33366",
"Score": "0",
"body": "@Marcel to answer your first comment, \"there should never be a case were a subscriber misses an event\"... When I mentioned about loosing events I was talking about the `Subscribe by setting a dependency on (one or more) IEventBroker<>` case: if instance of the component has not been created then subscription code wouldn't have been executed. And that's true that in case of `IEventSubscriber<>` you won't miss any event."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T08:48:58.247",
"Id": "33393",
"Score": "0",
"body": "I'd argue that it's ok that a component only starts listening in on events when it's lifetime begins (assuming subscription happens in the constructor)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T14:37:18.200",
"Id": "33405",
"Score": "0",
"body": "I ended up refactoring `IEventBroker` like you suggested, but as a generic `IEventPublisher<>` for the reasons mentioned earlier. If the amount of constructor parameters this leads to get out of hand I might change that to what you suggested as well."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T11:12:17.057",
"Id": "20796",
"ParentId": "20775",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "20796",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T21:08:55.243",
"Id": "20775",
"Score": "4",
"Tags": [
"c#"
],
"Title": "Loosely coupled application wide events"
}
|
20775
|
<p>I decided to run a few test on js functions on jspref to see which method of using function is better suited for this small particular example, to get a better understanding.</p>
<p><a href="http://jsperf.com/with-func-or-not" rel="nofollow">Page with tested functions</a></p>
<p>Problem:</p>
<p>Getting different results each time, Cold Start, Re-test, Re-Re Test are all coming with different results</p>
<p>First function - is just embedded in normally</p>
<pre><code>$(function() {
var up = $('#horiz_line').offset().top + $('#horiz_line').height() + 25,
triga = $('.trigger');
triga.css("display", "none");
$(window).scroll(function() {
var down = $(this).scrollTop();
(down > up) ? triga.fadeIn('fast') : triga.fadeOut('fast')
});
});
</code></pre>
<p>Second function - calling a global function</p>
<pre><code>$(function() {
triga.css("display", "none");
$(window).scroll(function() {
scrollMenu($(this).scrollTop())
});
});
function scrollMenu(down) {
var up = $('#horiz_line').offset().top + $('#horiz_line').height() + 25,
triga = $('.trigger');
(down > up) ? triga.fadeIn('fast') : triga.fadeOut('fast')
}
</code></pre>
<p>Third function - registering/calling variable function (to test/learn: I have no idea what I'm doing)</p>
<pre><code>$(function() {
$(window).scroll(function() {
scrollMenu($(this).scrollTop())
});
var scrollMenu = function(down) {
var triga = $('.trigger'),
up = $('#horiz_line').offset().top + $('#horiz_line').height() + 25;
(down > up) ? triga.fadeIn('fast') : triga.fadeOut('fast')
}
});
</code></pre>
<p>Fourth Func - Same as Third except Up is called before hand, and registered as a global func. Which i'm guessing is not a good idea if the project gets bigger over time.</p>
<pre><code>// Variable Up Takes up The Global Namespace. Is it better to pre-define it OR have it inside the scroll Menu anonymous func and get calculated each time the function is run?
$(function() {
var up = $('#horiz_line').offset().top + $('#horiz_line').height() + 25;
$(window).scroll(function() {
scrollMenu(up, $(this).scrollTop())
});
var scrollMenu = function(up, down) {
var triga = $('.trigger');
(down > up) ? triga.fadeIn('fast') : triga.fadeOut('fast')
}
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T00:06:12.923",
"Id": "33311",
"Score": "0",
"body": "To be clear, are you interested specifically in performance (speed)? Can the position of #horiz_line change? If so then the functions will do slightly different things. I imagine the speed differences will be negligible in this case, and the important question is more one of programme design."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T01:24:49.993",
"Id": "33313",
"Score": "0",
"body": "Yeah it can change. I would very much appreciate program design help or anything I can learn from this like implementing the same variable and causing redundancy in the code, etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T01:34:51.693",
"Id": "33314",
"Score": "0",
"body": "have you tested these on an actual page? it would be helpful to see what is happening e.g. with jsfiddle. Also, if you test them I think you will see they are doing different things."
}
] |
[
{
"body": "<p>These four functions are doing different things:</p>\n\n<p>The 1st and 4th set <code>up</code> immediately and <code>down</code> when the user scrolls.</p>\n\n<p>The 2nd and 3rd set both <code>up</code> and <code>down</code> when the user scrolls. (The 2nd seems unlikely to work properly because <code>triga</code> is not defined in the 1st function, so the line <code>triga.css(\"display\", \"none\");</code> will result in an error. Only in the 1st will the <code>triga</code> element be initially hidden.)</p>\n\n<p>So they will behave differently if the element <code>#horiz_line</code> changes position between the function being set and the user scrolling.</p>\n\n<p>I'm guessing what you want is to check the position of the horizontal line and the scroll top <em>when the user scrolls</em>. In this case something like the 2nd and 3rd function should work, but it is needlessly complicated to pass the values as parameters and call a function from within a function. Instead you can do either:</p>\n\n<pre><code>$(function() {\n var triga = $('.trigger');\n triga.css(\"display\", \"none\");\n $(window).scroll(function() {\n var down = $(this).scrollTop(),\n up = $('#horiz_line').offset().top + $('#horiz_line').height() + 25;\n triga[down > up ? 'fadeIn' : 'fadeOut']('fast');\n });\n});\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$(function() {\n var triga = $('.trigger');\n triga.css(\"display\", \"none\");\n $(window).scroll(scrollMenu);\n function scrollMenu() {\n var down = $(window).scrollTop(),\n up = $('#horiz_line').offset().top + $('#horiz_line').height() + 25;\n triga[down > up ? 'fadeIn' : 'fadeOut']('fast');\n }\n});\n</code></pre>\n\n<p>If, on the other hand, <code>up</code> never changes, then there will be a performance advantage to either defining <code>up</code> as a global variable <em>or</em> passing it as a parameter to the scrolling function (because accessing the DOM is usually costly in terms of performance.)</p>\n\n<p>I think the other aspect of your question is whether there is a performance difference in passing a value as a parameter to a function vs. having it in the scope of an outer function; I don't know but suspect it makes a negligible difference, especially if the parameter is first defined as a variable in the outer function anyway.</p>\n\n<p>More generally: focus on understanding how the code works before worrying about performance optimisation!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T02:43:12.397",
"Id": "33317",
"Score": "0",
"body": "Thank you so much Stuart. I made sure to read everything carefully to fully understand everything you said. First and Sec func both had the \"triga\" css display to hidden, I completely forgot to remove that from the code since it wasn't needed anymore. As for Up it makes complete sense to what you are saying about DOM is costly, and I should have kept that in mind. Even though I knew about it. I was just thinking that aern't we also suppose to limit the global namespace as well?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T11:21:33.460",
"Id": "33344",
"Score": "0",
"body": "You're running the code inside an anonymous function so it's not polluting the global namespace anyway (except in case 2, where you have one function outside of the `$(function...)`). If your code got more complex then the scrolling function could e.g. become part of an object that stored some state information such as `up`; organising your code into a small number of objects (each possibly containing smaller objects) is how you'd avoid having hundreds of variables in the outermost scope. A step further would be to 'package' the code into modules as @JosephtheDreamer suggests."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T11:28:58.993",
"Id": "33346",
"Score": "0",
"body": "Anyway you seem to be mixing up performance concerns with code design generally. Global variables in some cases might make code faster, but are avoided for the reasons already mentioned. Also having loads of 'quasi-global' variables (variables that are within a function scope but used by inner functions without passing the values) usually suggests the code could be reorganised."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T02:04:13.130",
"Id": "20779",
"ParentId": "20777",
"Score": "1"
}
},
{
"body": "<h1>Protecting your code</h1>\n<p>When this project becomes bigger, you might want to wrap this code like in it's own scope similar to how jQuery plugins are packaged. This is to prevent naming collisions, protect your code and portability. This also implies that you should avoid globals. So case #2 is out.</p>\n<h1>Abstraction vs Performance</h1>\n<p>The more you abstract and simplify the API, the more code you actually create thus the more processing it will take. Keep your code simple.</p>\n<h1>Browser Implementation</h1>\n<p>Browser will also be a factor in performance. A browser with a more powerful implementation of a certain routine will tend to be faster at that routine compared to the others. In Chrome's case, the first 2 tests run best. However, in Firefox, all tests run at almost the same performance.</p>\n<h1>DOM querying</h1>\n<p>Now back to the code with case #2 out of the way. In cases #3 and #4, your code is querying the DOM every time the scroll event is triggered. This causes performance degradation. If you have references to static elements, it's better to cache them outside the function rather than being fetched every time.</p>\n<p>This code should do the trick as well as <a href=\"http://jsperf.com/scroll-handler-optimization\" rel=\"nofollow noreferrer\">a jsPerf test for your case #1 vs my modified code</a>. As you can see, my Firefox 18 performs both operations equally while Chrome 23 performs better with the modified code which proves that browser implementation can make a difference.</p>\n<pre><code>$(function() {\n //cache non-changing elements and values\n var horizLine = $('#horiz_line')\n , up = horizLine.offset().top + horizLine.height() + 25\n , triga = $('.trigger')\n , $window = $(window)\n ;\n\n triga.css('display', 'none');\n\n //we cached window wrapped in jQuery earlier so we reuse it\n $window.scroll(function(){\n //omitting down variable since it was only used once\n ($window.scrollTop() > up) ? triga.fadeIn('fast') : triga.fadeOut('fast')\n });\n\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T02:55:33.077",
"Id": "33318",
"Score": "0",
"body": "Great Advice from you and Stuart. I really appreciate it. I guess the only thing now to ask is limit setting the global name space or like you mentioned \"to prevent naming collisions, protect your code and portability. This also implies that you should avoid globals\". Would a better approach be something like (function(){ var masterfunc = init: function(){}, step1:function(){}}) Anyways thanks again, I'll take some time to read more about the subject at hand. Have a great day"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T02:36:17.903",
"Id": "20780",
"ParentId": "20777",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20780",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T21:58:01.867",
"Id": "20777",
"Score": "0",
"Tags": [
"javascript",
"jquery",
"comparative-review"
],
"Title": "Different function test result inquiry"
}
|
20777
|
<p>Due to a weird server setup on one of my client's websites, I needed to setup a script to load referenced pdf files through a case-insensitive lookup. We originally looked into mod_speling, but it was causing issues with other mod_rewrite declarations. I'm not entirely sure why, but I didn't have much control over those other declarations, since they had other people working on their site as well.</p>
<p>So anyway, they have a bunch of references to their PDF files all over the internet with a bunch of different capitalization. Realizing that getting all of these to switch over to the proper file name was gonna be nearly impossible, I opted to write a script to do the translation for me. </p>
<p>The script forces <a href="http://www.somedomain.com/somedirectory/subdirectory/anypdffile.pdf" rel="nofollow">http://www.somedomain.com/somedirectory/subdirectory/anypdffile.pdf</a> to load through my pdffiles.php file.</p>
<p>The script seems to work perfectly. I'm not too worried about server performance, as I don't think it's gonna be used all that often. I just wanted to get a second pair of eyes to make sure I didn't leave any major security loopholes in here since I'm reading a directory/file from a $_GET variable. </p>
<p>First I added this to the .htaccess file to redirect all pdf files to a php script</p>
<pre><code>RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_URI} \.pdf$ [NC]
RewriteRule (.*) pdffiles.php?p=$1
</code></pre>
<p>Then put the following code in the pdffiles.php file:</p>
<pre><code><?php
// shorthand for our docroot
$root = $_SERVER['DOCUMENT_ROOT'];
// get our filepath (correct format is "somedir/otherdir/xyz.pdf")
$path= $_GET['p'];
// Rule 1 - Don't allow empty path
if (!empty($path)) {
// get the directory for our file
$dir = dirname($root.'/'.$path);
// get the filename
$file = basename($path);
// get our extension
$ext = pathinfo($file, PATHINFO_EXTENSION);
// Rule 2 - Don't allow direct access to the script
if (!strstr($_SERVER['REQUEST_URI'], 'pdffiles.php')) {
// Rule 3 - Ensure PDF extension
if (strtolower($ext) == "pdf") {
// Rule 3 - Make sure document root + path is a real path
if (($dir = realpath($dir))) {
// Loop through directory contents
if ($fh = opendir($dir)) {
while (false !== ($tfile = readdir($fh))) {
// ignore the default directories
if ($tfile != "." && $tfile != "..") {
// convert both to all lower case and try to match
if (strtolower($tfile) == strtolower($file)) {
// if they match then go ahead and output file
header("Content-type: application/pdf");
readfile($dir.'/'.$tfile);
exit;
}
}
}
}
}
}
}
}
// we failed one of our checkpoints, redirect to 404
header("HTTP/1.1 301 Moved Permanently");
header("Location: /notfound.html");
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T05:50:45.717",
"Id": "33326",
"Score": "1",
"body": "Not sure if it's an exploitable issue, but what would happen if someone set `p` to a relative path like `../cgi/example.pdf`? I can't forsee any issues though as the `pdf` extension check will stop you mistakenly serving up internal files."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-28T16:51:06.667",
"Id": "33688",
"Score": "0",
"body": "@JasonLarke yeah I thought about that after I wrote it. They aren't really storing any sensitive PDFs anywhere on the server, so I'm not entirely worried about that, but it would definitely be an issue if it was in another context."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T23:33:12.633",
"Id": "35418",
"Score": "0",
"body": "You may not have had any sensitive documents on the server when you wrote this script but how can you be sure that's still the case in two months? Checking for path traversal is almost always a very good idea."
}
] |
[
{
"body": "<p>As Jason stated checking for \"..\" is a good idea. If there are only a limited number of path where the pdfs are located on the server, I would even prefer matching against this set.</p>\n\n<p>Nevertheless, you might also want to invert your ifs to get rid of the nesting and use guard conditions.</p>\n\n<pre><code><?php\n // !!!! comment intention, not what your code is doing\n\n // Don't allow direct access to the script\n if (strstr($_SERVER['REQUEST_URI'], 'pdffiles.php')) notFound();\n\n // expected format is \"somedir/otherdir/xyz.pdf\"\n $path= $_GET['p'];\n if (empty($path)) notFound();\n\n $root = $_SERVER['DOCUMENT_ROOT'];\n $dir = realpath(dirname($root.'/'.$path));\n if ($dir===FALSE) notFound();\n $file = basename($path);\n $ext = pathinfo($file, PATHINFO_EXTENSION);\n if (strtolower($ext) != \"pdf\") notFound();\n\n if ($fh = opendir($dir)) {\n while (false !== ($tfile = readdir($fh))) {\n if ($tfile == \".\" || $tfile == \"..\") continue;\n if (strtolower($tfile) != strtolower($file)) continue;\n\n header(\"Content-type: application/pdf\");\n readfile($dir.'/'.$tfile);\n exit; \n }\n }\n\n function notFound() {\n // we failed one of our checkpoints, redirect to 404\n header(\"HTTP/1.1 301 Moved Permanently\"); \n header(\"Location: /notfound.html\");\n exit();\n }\n// ? > !!!! omit this. It's not necessary and you will have no empty line in you php files.\n</code></pre>\n\n<p>Maybe you want to also have a look at the <a href=\"http://php.net/manual/de/class.directoryiterator.php\" rel=\"nofollow\">DirectoryIterator</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T13:36:21.683",
"Id": "33353",
"Score": "0",
"body": "The concept of a \"document directory\" is a good one, most sites I've worked on generally store all their documents in a specific folder (with various levels of sub-folders). I'm not sure how the OP's filesystem is set up (and it sounds like he's inherited a bit of a mess), but something like this may be possible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T15:11:37.033",
"Id": "33359",
"Score": "0",
"body": "@David In addition to that you might want to check if the filenames are unique so you can drop the path completely and create the new \"document directory\" we recommend."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-28T16:46:19.253",
"Id": "33687",
"Score": "0",
"body": "Ideally I would build the document directory, but this is kind of low budget and just a quick fix. The client didn't have the money for the time involved with doing it that way. As far rewriting the code to use guard conditions, does that actually provide any sort of benefit, other than making the code more readable? Don't get me wrong, I'm all about readable code, but if the existing code works as is, is there a point to rewriting it this way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-29T04:57:45.410",
"Id": "33735",
"Score": "0",
"body": "@David The code is your realm. You have to work and live with it. Of course no customer will pay for a refactor/cleanup/test item on the invoice, you just have to include it in your estimation and just do it. Nevertheless even on a short run a cleaner, more readable and structured code will speed up your issue fixing, this means either more time for cleaning up other code or lower cost for your customer. Especially on long term projects you waste a lot of time in understanding your own code after some months."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-01T20:58:20.153",
"Id": "34027",
"Score": "0",
"body": "@mnhg I don't disagree with you on that. I just figured in this case the code as is. It's not very long and I could easily come back a few years later and figure out what I was doing. It doesn't look unreadable to me. Yes, for code much longer than this, I probably would have written it differently, but for what this script is, it seems fine to me. That said I'll give you the answer just because you spent your time working through my stuff, so I appreciate it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-02T07:25:03.533",
"Id": "34044",
"Score": "1",
"body": "@David Just for completenes: [broken window theory](https://www.google.com/search?q=broken+window+theory+software) and [leave the place cleaner than you found it](https://www.google.com/search?q=leave+the+place+cleaner+than+you+found+it+software)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T07:06:09.733",
"Id": "20787",
"ParentId": "20782",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20787",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T20:46:11.733",
"Id": "20782",
"Score": "2",
"Tags": [
"php",
"security"
],
"Title": "Am I missing any security loopholes in this php script that reads and outputs directory/file from $_GET variable"
}
|
20782
|
<p>I've implemented adding and multiplying arbitrary precision integers.</p>
<p>Also available as a <a href="https://gist.github.com/aba0a2d1194d2cd0967a">gist</a>.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int *data;
int size;
} bi;
bi *bi_new() {
bi *a = malloc(sizeof(bi));
return a;
}
bi *bi_from_string(char *a) {
bi *b = bi_new();
int skip = 0;
while(a[skip] == '0') { skip++; }
b->size = strlen(a) - skip;
if(b->size == 0) {
b->size++;
b->data = malloc(b->size * sizeof(int));
b->data[0] = 0;
} else {
b->data = malloc(b->size * sizeof(int));
int i;
for(i = 0; i < b->size; i++) {
b->data[i] = a[skip + i] - '0';
}
}
return b;
}
char *bi_to_string(bi *a) {
char *b = malloc(a->size * sizeof(char));
int i;
for(i = 0; i < a->size; i++) {
b[i] = a->data[i] + '0';
}
return b;
}
bi *bi_add(bi *a, bi *b) {
bi *c = bi_new();
// max possible size
c->size = (a->size > b->size ? a->size : b->size) + 1;
c->data = malloc(c->size * sizeof(int));
int i = a->size - 1, j = b->size - 1;
int k = c->size - 1;
int carry = 0, tmp;
while(i >= 0 || j >= 0 || carry > 0) {
if(i >= 0 && j >= 0) {
tmp = a->data[i] + b->data[j];
} else if(i >= 0) {
tmp = a->data[i];
} else if(j >= 0) {
tmp = b->data[j];
} else {
tmp = 0;
}
tmp += carry;
carry = tmp / 10;
c->data[k] = tmp % 10;
i--; j--; k--;
}
// this is definitely leaking memory
if(c->data[0] == 0) { c->size--; c->data++; }
return c;
}
bi *bi_multiply(bi *a, bi *b) {
bi *c = bi_new();
// max size
c->size = a->size + b->size;
c->data = malloc(c->size * sizeof(int));
{ int i; for(i = 0; i < c->size; i++) { c->data[i] = 0; } }
int i = a->size - 1, j = b->size - 1, k = c->size - 1;
int carry = 0, tmp, push_left = 0;
while(i >= 0) {
k = c->size - 1 - push_left++;
j = b->size - 1;
while(j >= 0 || carry > 0) {
if(j >= 0) {
tmp = a->data[i] * b->data[j];
} else {
tmp = 0;
}
tmp += carry;
carry = tmp / 10;
c->data[k] += tmp % 10;
carry += c->data[k] / 10;
c->data[k] = c->data[k] % 10;
j--; k--;
}
i--;
}
// Leaking memory for sure
while(c->data[0] == 0) { c->size--; c->data++; }
return c;
}
</code></pre>
<p>Tests:</p>
<pre><code>#include <assert.h>
#include "bi.c"
int main() {
// Simple conversion
char *a = "21739871283971298371298371289371298371298371298371298371293";
assert(strcmp(a, bi_to_string(bi_from_string(a))) == 0);
// Remove leading zeros
char *b = "000123000";
assert(strcmp("123000", bi_to_string(bi_from_string(b))) == 0);
// But don't segfault on empty string or string consisting of only zeros
assert(strcmp("0", bi_to_string(bi_from_string("000"))) == 0);
assert(strcmp("0", bi_to_string(bi_from_string(""))) == 0);
char *c = "11111111111111111111111111111111111111111111111111111111111000";
char *d = "33333333333333333333333333333333333333333333333333333333333789";
char *e = "44444444444444444444444444444444444444444444444444444444444789";
assert(strcmp(e, bi_to_string(bi_add(bi_from_string(c),
bi_from_string(d)))) == 0);
assert(strcmp("1024", bi_to_string(bi_add(bi_from_string("512"),
bi_from_string("512")))) == 0);
// Starting with 1 digit by n digit multiplication
assert(strcmp("16384", bi_to_string(bi_multiply(bi_from_string("2048"),
bi_from_string("8")))) == 0);
// Now multiple
assert(strcmp("16384", bi_to_string(bi_multiply(bi_from_string("1024"),
bi_from_string("16")))) == 0);
char *f = "781239128739123";
char *g = "902183901283901283019283012938120";
char *h = "704821365001497990452726836222051105131222068760";
assert(strcmp(h, bi_to_string(bi_multiply(bi_from_string(f),
bi_from_string(g)))) == 0);
printf("Reached the end!\n");
}
</code></pre>
<p>Oh and, I'd appreciate some extra comments on the two places in the code I've written "leaking memory".</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T11:42:05.093",
"Id": "33347",
"Score": "1",
"body": "Have you considered using a base16 or base32 system, rather than a base10 system?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T13:19:54.523",
"Id": "33352",
"Score": "1",
"body": "@nightcracker If you already convert representation bases, why would you use anything other than base `sizeof(underlying_storage) * 8`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T16:22:35.170",
"Id": "33361",
"Score": "0",
"body": "@KonradRudolph: absolutely no reason, I meant to say base32 or base64, rather than base16. (Unless you have a base16 architecture lying around.)"
}
] |
[
{
"body": "<p>The good part is that without any real modifications, I can compile your code with lots of the extra compiler flags to detect errors: <code>-Wall, -Wextra, -Werror, -pedantic</code> under <code>-std=c99</code>. That's a good start. There are a few problems, though:</p>\n<h2>Memory Leaking</h2>\n<p>You provide a <code>bi_new()</code> function, but nothing to <code>free</code> any of the memory that you allocate. Any time you have something returning a pointer to a heap-allocated struct, you should probably provide a convenience function for deallocation.</p>\n<pre><code>void bi_free(bi* a)\n{\n free(a->data);\n free(a);\n}\n</code></pre>\n<p>This is evident in the fact that nothing in your <code>main</code> function cleans up any of the memory you've allocated - thus leaking memory (until the OS kills your process and reclaims it, anyway). For the comments where state you're leaking memory, the fix is to simply modify only <code>size</code> and leave the actual data alone.</p>\n<h2>Includes</h2>\n<p>When you start writing larger programs, you should try to break them up into a header file and an implementation file. Here, you <code>#include</code> a <code>.c</code> file. This is very bad practice. It (probably) won't hurt you now, but if you ever move to C++, it can cause a lot of problems. Pull out all of your function prototypes and structs into a header file, and include that into the implementation.</p>\n<p>When you're doing this, you'll also want to surround your header file with an <a href=\"http://en.wikipedia.org/wiki/Include_guard\" rel=\"noreferrer\">include guard</a>.</p>\n<h2>Strings</h2>\n<p>Converting to a string with <code>char* bi_to_string(bi *a)</code> works, but in C, it's generally better to take a <code>char *</code> as a parameter into which you can put something, so <code>int bi_to_string(bi *a, char *str)</code>. The reason for this is you dynamically (<code>malloc</code>) allocate a string which you then return. This places the onus on the programmer to remember to free it later. If they pass in a <code>char *</code>, they are either already responsible for freeing it later, or can stack allocate it and have it cleaned up automatically. This does mean the user can pass in a string that is too short, however, either an <code>assert(...)</code> or returning an error_code (hence the <code>int</code> return) can catch that.</p>\n<p>A similar argument can be made for your add and multiply functions to take a 3rd parameter which is the result value.</p>\n<h2>NULL-Terminating Strings</h2>\n<p>You've been bitten by the oldest (C) bug in the book - not NULL-terminating your strings. It's an easy fix:</p>\n<pre><code>char *bi_to_string(bi *a) \n{\n //Remember to allocate an extra spot for the NULL terminator\n //Also, you don't need a sizeof(char). The standard says it is guaranteed \n //to be 1. \n char *b = malloc(a->size + 1); \n int i;\n for(i = 0; i < a->size; i++) {\n b[i] = a->data[i] + '0';\n }\n b[a->size] = '\\0'; //NULL terminate\n return b;\n}\n</code></pre>\n<p>That fixes your first assert: <code>assert(strcmp(a, bi_to_string(bi_from_string(a))) == 0);</code>. However, <code>assert(strcmp(e, bi_to_string(bi_add(bi_from_string(c), bi_from_string(d)))) == 0);</code> fails for me. I'd look into debugging that :)</p>\n<h2>Naming</h2>\n<p>This is a minor thing. I know everything in C is generally terse, but the name <code>bi</code> really isn't descriptive at all. Maybe <code>big_int</code> if you still want to be terse, but make it completely unambiguous as to what it is.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T12:46:02.440",
"Id": "33350",
"Score": "0",
"body": "I thought `C` prohibits declarations not at the beginning of the block. Am I mistaken?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T13:01:52.267",
"Id": "33351",
"Score": "3",
"body": "@Constantius `c99` and above allows declarations not at the beginning. Further, things like `for(int i = ...)` are perfectly legal `c99`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T06:16:59.600",
"Id": "20784",
"ParentId": "20783",
"Score": "15"
}
},
{
"body": "<p>You're right to suspect the <code>data++</code>, <code>data--</code> lines, but I'm not sure \"leaking memory\" is the worst of your problems. If you pass one of these \"offset from the original allocation\" addresses into <code>realloc</code> or <code>free</code>, for example, you're likely to get crashes. The way it usually works under the hood is that at an address <em>just before</em> the buffer, <code>malloc</code> and friends sneak in things like the allocation size, so it can maintain its own data structures ahead of \"your\" buffer. (It's not guaranteed to work that way, but this is most often the case.) The important takeaway is that <em>if you call <code>malloc</code>, save the original pointer so that you have something to pass to <code>free</code></em>.</p>\n\n<p>For that particular issue I would recommend one of the following:</p>\n\n<ul>\n<li><p>Option A: Store the original allocation (what was returned from <code>malloc</code>) in your struct alongside any pointers derived from it (<code>data</code>).</p></li>\n<li><p>Option B: Instead of doing pointer arithmetic on <code>data</code>, store the current index in the struct as an integer, and access with <code>p->data[p->idx]</code>. Thinking about it some more I think this is the cleaner approach. For example you wouldn't need to re-calculate the offset again after a <code>realloc</code>.</p></li>\n</ul>\n\n<p>Which brings me to the next point. I don't see any calls to <code>free</code>. For a structure like this I think it's good practice to have a single alloc function (which is good, you already have that) and a single free function. So let's write the latter:</p>\n\n<pre><code>void bi_free(bi *b)\n{\n if (b)\n {\n free(b->data);\n free(b);\n }\n}\n</code></pre>\n\n<p>While on the topic of your alloc function, it'd be a good idea to initialize the struct.</p>\n\n<pre><code>bi *bi_new() {\n bi *a = malloc(sizeof(bi));\n if (a)\n {\n a->data = NULL;\n a->size = 0;\n }\n return a;\n}\n</code></pre>\n\n<p>Note that <code>malloc</code> can fail, so we don't initialize anything in that case. (Callers of <code>bi_new()</code> should do the same check.)</p>\n\n<p>Actually your allocation also highlights something:</p>\n\n<pre><code> bi *a = malloc(sizeof(bi));\n</code></pre>\n\n<p>See the part where you type \"<code>bi</code>\" twice? Let's say you wanted to change the type of <code>a</code> later on to some other struct. Now there's two places you have to update it. I would much prefer:</p>\n\n<pre><code> bi *a = malloc(sizeof(*a));\n</code></pre>\n\n<p>On the topic of heap allocations... It seems like every <code>bi</code> operation takes 2 <code>bi</code>s and does a new allocation for a return value. This is a bit subjective, but that seems tedious. What about an interface which takes two operands, where one is also a destination? (Like many assembly languages..) Or perhaps 2 source operands and 1 destination. (Like RISC.) Each operation could see if the destination is big enough and possibly call <code>realloc</code> to grow the buffer. But the caller would decide to free the operands, and you'd probably get plenty of buffer re-use.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T06:26:06.480",
"Id": "20785",
"ParentId": "20783",
"Score": "3"
}
},
{
"body": "<p>Dogbert, I have some comments to add to those from other commenters (use of free, naming)</p>\n\n<ul>\n<li>minor quibbles: put the opening { of a function on a new line, column 0; put a space after keywords such as for, while, if, etc; make functions static where possible; make parameters const where possible; avoid multiple statements on the same line.</li>\n<li>negative numbers are not handled</li>\n<li><p>your type <code>bi</code> uses an allocated integer array to store values in the range [0..9]. This seems wasteful. A signed char would do. Also, you have to allocate twice to create a <code>bi</code> when once would be preferable. Here I have rearranged the structure so that the array is at the end and can be expanded by allocating more memory that is needed just for the struct:</p>\n\n<pre><code>typedef struct {\n size_t size;\n signed char data[1]; // you can also use just data[] and adjust calloc call\n} Bigint;\n\nstatic Bigint* bigint_new(size_t size) \n{\n Bigint *b = calloc(sizeof(*b) + size - 1, 1); /* calloc zeroes allocated memory */\n if (b) {\n b->size = size;\n }\n return b;\n}\n</code></pre></li>\n<li><p>you have no error checking in your input routine - ie. there is no check for characters not in the range '0'..'9'.</p></li>\n<li><p>skipping leading zeroes could be better done with <code>strspn</code>. Also, I think you should store your values in the opposite order. This simplifies the loops in add and multiply (see below), so <code>bi_from_string</code> becomes this (note also the const)</p>\n\n<pre><code>static Bigint* bi_from_string(const char *s)\n{\n s += strspn(s, \"0\");\n size_t size = strlen(s);\n int min = (size == 0) ? 1 : 0;\n\n Bigint *b = bi_new(size + min);\n for (int i = 0; i < size; ++i) {\n b->data[size - i - 1] = s[i] - '0';\n }\n return b;\n}\n</code></pre></li>\n<li><p>your <code>bi_add</code> is a mess. You have too many loop variables and they count downward, which is normally a bad idea. By reversing the storage order of the data in the <code>bi</code> type you can also reverse the loops and avoid so many loop variables. Notice how much simpler the loop is now</p>\n\n<pre><code>static Bigint* bi_add(const Bigint *a, const Bigint *b)\n{\n size_t max = (a->size > b->size ? a->size : b->size);\n Bigint *c = bi_new(max + 1);\n\n int carry = 0;\n int i;\n for (i=0; i<max; ++i) {\n int tmp = carry;\n\n if (i < a->size) {\n tmp += a->data[i];\n }\n if (i < b->size) {\n tmp += b->data[i];\n }\n carry = tmp / 10;\n c->data[i] = tmp % 10;\n }\n if (carry) {\n c->data[i] = 1;\n } else {\n c->size--; //extra space added for growth of value was not used\n }\n return c;\n}\n</code></pre></li>\n<li><p>your <code>bi_multiply</code> is also rather messy. It suffers the same problems as <code>bi_add</code> but compounds this with a nested loop. Nested loops are sometimes necessary but more often than not can be usefullly split into two functions. Here is an example of multiplying with two separate functions:</p>\n\n<pre><code>static signed char* bi_multiply_by_n(const Bigint *a, int n, signed char *result)\n{\n int carry = 0;\n for (int i=0; i<a->size; ++i) {\n int tmp = carry + (a->data[i] * n) + *result;\n carry = tmp / 10;\n *result++ = tmp % 10;\n }\n if (carry) {\n *result++ = carry;\n }\n return result; // pointer to char beyond end of result\n}\n\nstatic Bigint* bi_multiply(const Bigint *a, const Bigint *b)\n{\n size_t max = a->size + b->size;\n Bigint *c = bi_new(max);\n signed char *end;\n\n for (int i=0; i<b->size; ++i) {\n end = bi_multiply_by_n(a, b->data[i], c->data + i);\n }\n c->size = end - c->data; // actual space used\n return c;\n}\n</code></pre></li>\n</ul>\n\n<p>Note that I tested these functions, so they should be ok.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T02:13:32.053",
"Id": "33383",
"Score": "0",
"body": "I noticed that bi_multiply fails if one of the args is zero. This can be fixed by calling `bi_multiply_by_n` only if `c->data[i] != 0` and by initialising `end` to `c->data + 1`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T10:18:35.467",
"Id": "33541",
"Score": "0",
"body": "`signed char data[1]; // you can also use just data[] and adjust calloc call` - I recently found out (through crashes and strange behavior) that LLVM generates bad code when using this hack. If you do it the C99-compliant way and declare simply `data[]` with no element count, it works. Knowing this I would only put something in the `[]` when using MS's compiler, since it doesn't support the C99 way."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T20:53:53.260",
"Id": "20809",
"ParentId": "20783",
"Score": "4"
}
},
{
"body": "<p>Couple of other comments:</p>\n\n<p>1) How are you handling negative numbers?</p>\n\n<p>2) Since the numbers per digit stored is in the range 0-9 does it require to be an int type? Why it can't be unsigned char type?</p>\n\n<p>Considering above this is my suggestion for the bigint struct (assuming c99 standard):</p>\n\n<pre><code>struct bigint {\n bool negative;\n size_t num_digits;\n unsigned char *digits;\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-22T12:36:01.677",
"Id": "397450",
"Score": "0",
"body": "These points are already addressed by the earlier reviewers - do you have any new insights to add?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-22T04:52:32.103",
"Id": "206018",
"ParentId": "20783",
"Score": "-2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-01-22T04:51:32.897",
"Id": "20783",
"Score": "9",
"Tags": [
"beginner",
"c",
"integer"
],
"Title": "BigInteger implementation in C, supporting addition and multiplication"
}
|
20783
|
<p>I have the following JavaScript function:</p>
<pre><code>function registerEvents() {
var isTapholding = false;
$(document).delegate('.add-control .add-image', 'tap', function (evt) {
handleAddControlEvent(this);
});
$(document).delegate('.delete-image', 'tap', function (evt) {
evt.stopPropagation();
handleDeleteControlEvent(this);
});
$(document).delegate('.edit-control', 'tap', function (evt) {
if (isTapholding)
return;
handleEditControlEvent(this);
});
$(document).delegate('.edit-control', 'vmouseup', function (evt) {
setTimeout(function () {
isTapholding = false;
}, 100);
});
$(document).delegate('.add-control .insert-image', 'tap', function (evt) {
handleInsertImageEvent(this);
});
setTimeout(function () {
$(document).delegate('.edit-control', 'taphold', function (evt) {
evt.stopPropagation();
isTapholding = true;
handleEditControlTapHoldEvent(this);
});
}, 100);
}
</code></pre>
<p>How I can make this DRY (Don't Repeat Yourself)?</p>
|
[] |
[
{
"body": "<p>All calls have different parameters and different bodies. If there is no fancy JQuery trick, there is nothing you can do about this, and even if such a trick exist I have the feeling that this will result in a switch for every call.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T11:03:40.740",
"Id": "33343",
"Score": "0",
"body": "Joseph showed how to merge multiple events. But I'm still not sure if this is better/cleaner/more readable than the native approach."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T07:16:54.763",
"Id": "20789",
"ParentId": "20786",
"Score": "1"
}
},
{
"body": "<p>You can refactor this to follow DRY by using the Strategy Pattern.</p>\n\n<pre><code>function registerEvents(){ \n var delegationStrategies = [\n {var1: '.add-control .add-image',\n var2: 'tap',\n func: function (evt) {\n handleAddControlEvent(this);\n }\n },\n {var1: '.delete-image',\n var2: 'tap',\n func: function (evt) {\n evt.stopPropagation();\n handleDeleteControlEvent(this);\n }\n },\n // Add more strategies here.\n ];\n\n for (var i=0; i< delegationStrategies.length; i++){\n strategy = delegationStrategies[i];\n $(document).delegate(strategy.var1, strategy.var2, strategy.func);\n }\n}\n</code></pre>\n\n<p>You may need to add a special case for the timeout.</p>\n\n<p>The question is whether you foresee the need to add further delegation handlers in the future. If so, then it is a matter of adding another entry to the strategy.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T08:41:52.897",
"Id": "33335",
"Score": "0",
"body": "var1=>selector var2=>eventType"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T07:47:29.657",
"Id": "20790",
"ParentId": "20786",
"Score": "7"
}
},
{
"body": "<pre><code>//protect your code in a namespace\n//here's a simple modular \"shielding\" which is not immediately useful with the current code\n(function (ns) {\n\n //so in your namespace, we place your register event\n ns.registerEvents = function () {\n\n var isTapholding = false //comma separated declaration notation\n , $document = $document //cache the delegate parent\n ; //I suggest a closer parent/nearest common parent rather than document\n\n //.delegate() is already superseded by .on()\n //it also accepts an event-handler map for the chosen selector\n $document\n .on({\n tap : function (e) {\n //always use {} for those one-liners to avoid readability issues\n if(isTapholding){return;}\n handleEditControlEvent(this);\n },\n vmouseup : function (e) {\n isTapholding = false;\n },\n taphold : function (e) {\n //i'd have to note that .delegate(), .live() and .on() use delegation\n //propagation depends on how, when and where the handlers were attached\n //see this answer for further clarification: http://stackoverflow.com/a/10672682/575527\n e.stopPropagation();\n isTapholding = true;\n handleEditControlTapHoldEvent(this);\n }\n },'.edit-control')\n //for the others, since I can't factor anything else, they stay, but we chain it instead\n .on('tap', '.add-control .insert-image', function (e) {\n handleInsertImageEvent(this);\n });\n .on('tap', '.add-control .add-image', function (e) {\n handleAddControlEvent(this);\n });\n .on('tap', '.delete-image', function (e) {\n evt.stopPropagation();\n handleDeleteControlEvent(this);\n });\n }\n}(this.MyCodez = this.MyCodez || {}));\n\n//instead of firing a timer to delay registration until DOM loads\n//why not use the .ready() or in this case it's shorthand\n$(function () {\n MyCodez.registerEvents();\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T09:04:37.440",
"Id": "20793",
"ParentId": "20786",
"Score": "3"
}
},
{
"body": "<p>One big takeaway here to be DRY and more efficient is that you're making several calls to $(document) that could be reduced. Not only is it DRYer to only call it once, but even caching the result of $(document) to a variable would improve things:</p>\n\n<pre><code>$(document)\n .delegate('.add-control .add-image', 'tap', function (evt) {\n handleAddControlEvent(this);\n })\n .delegate('.delete-image', 'tap', function (evt) {\n evt.stopPropagation();\n handleDeleteControlEvent(this);\n })\n .delegate('.edit-control', 'tap', function (evt) {\n if (isTapholding)\n return;\n handleEditControlEvent(this);\n })\n .delegate('.edit-control', 'vmouseup', function (evt) {\n setTimeout(function () {\n isTapholding = false;\n }, 100);\n })\n .delegate('.add-control .insert-image', 'tap', function (evt) {\n handleInsertImageEvent(this);\n });\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-21T14:54:01.327",
"Id": "67447",
"ParentId": "20786",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "20790",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T07:04:27.490",
"Id": "20786",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "How to Make This JavaScript Snippet DRY (Don't Repeat Yourself)?"
}
|
20786
|
<p>I'm new to RSpec and testing in general. I've come up with a spec for testing my <code>Content</code> model and I need some feedback because I think there are many improvements that can be done. I don't know if the way I did it is considered over-testing, bloated/wrong code or something. This test is kinda slow but this doesn't bother me that much for now.</p>
<p><strong>app/models/content.rb</strong></p>
<pre><code>class Content < ActiveRecord::Base
extend FriendlyId
friendly_id :title, use: [ :slugged, :history ]
acts_as_mediumable
delegate :title, to: :category, prefix: true
# Associations
belongs_to :category
has_many :slides, dependent: :destroy
# Accessible attributes
attr_accessible :title, :summary, :body, :category_id,
:seo_description, :seo_keywords, :seo_title,
:unpublished_at, :published_at, :is_draft
# Validations
validates :title, presence: true
validates :body, presence: true
validates :category, presence: true
validates :published_at, timeliness: { allow_nil: false, allow_blank: false }
validates :unpublished_at, timeliness: { allow_nil: true, allow_blank: true, after: :published_at }, :if => "published_at.present?"
scope :published, lambda { |*args|
now = ( args.first || Time.zone.now )
where(is_draft: false).
where("(published_at <= ? AND unpublished_at IS NULL) OR (published_at <= ? AND ? <= unpublished_at)", now, now, now).
order("published_at DESC")
}
def self.blog_posts
joins(:category).where(categories: { acts_as_blog: true })
end
def self.latest_post
blog_posts.published.first
end
def to_s
title
end
def seo
meta = Struct.new(:title, :keywords, :description).new
meta.title = seo_title.presence || title.presence
meta.description = seo_description.presence || summary.presence
meta
end
end
</code></pre>
<p><strong>spec/models/content_spec.rb</strong></p>
<pre><code>require 'spec_helper'
describe Content do
it "has a valid factory" do
create(:content).should be_valid
end
it "is invalid without a title" do
build(:content, title: nil).should_not be_valid
end
it "is invalid without a body" do
build(:content, body: nil).should_not be_valid
end
it "is invalid without a category" do
build(:content, category: nil).should_not be_valid
end
it "is invalid when publication date is nil" do
build(:content, published_at: nil).should_not be_valid
end
it "is invalid when publication date is blank" do
build(:content, published_at: "").should_not be_valid
end
it "is invalid when publication date is malformed" do
build(:content, published_at: "!0$2-as-#{nil}").should_not be_valid
end
# TODO: You shall not pass! (for now)
# it "is invalid when expiration date is malformed" do
# build(:content, unpublished_at: "!0$2-as-#{nil}").should_not be_valid
# end
it "is invalid when publication date is nil and expiration date is set" do
build(:content, published_at: nil, unpublished_at: 3.weeks.ago).should_not be_valid
end
it "is invalid when expiration date is before publication date" do
build(:content, published_at: 1.week.ago, unpublished_at: 2.weeks.ago).should_not be_valid
end
it "returns a content's title as a string" do
content = create(:content)
content.to_s.should eq content.title
end
describe "filters by publication dates" do
before :each do
@published_three_weeks_ago = create(:published_three_weeks_ago_content)
@expiring_in_two_weeks = create(:expiring_in_two_weeks_content)
@publish_in_tree_weeks = create(:publish_in_tree_weeks_content)
end
context "with matching dates" do
it "returns a sorted array of results that match for current time" do
Content.published.should include @published_three_weeks_ago, @expiring_in_two_weeks
end
it "returns a sorted array of results that match for future time" do
Content.published(3.weeks.from_now).should include @published_three_weeks_ago, @publish_in_tree_weeks
end
end
context "without matching dates" do
it "returns an empty array" do
Content.published(2.months.ago).should eq [ ]
end
end
end
describe "filters contents by blog category" do
before :each do
@blog_category = create(:blog_category)
end
context "with matching contents" do
it "returns only blog posts" do
one_page = create(:content)
another_page = create(:content)
first_post = create(:content, category: @blog_category)
second_post = create(:content, category: @blog_category)
Content.blog_posts.should include first_post, second_post
end
end
context "without matching contents" do
it "returns an empty array" do
one_page = create(:content)
another_page = create(:content)
Content.blog_posts.should eq [ ]
end
end
end
describe "retrieves latest post" do
before :each do
@blog_category = create(:blog_category)
end
context "with existing posts" do
it "return the latest content that belongs to a blog category" do
first_post = create(:published_three_weeks_ago_content, category: @blog_category)
second_post = create(:content, published_at: Time.zone.now, category: @blog_category)
Content.latest_post.should eq second_post
end
end
context "without existing posts" do
it "returns an nil object" do
Content.latest_post.should eq nil
end
end
end
describe "uses seo attributes when present" do
before :each do
@it = create(:content)
end
context "seo title present" do
it "returns seo title when present" do
@it.seo.title.should eq @it.seo_title
end
end
context "seo title non present" do
it "returns title when seo title is blank" do
@it.seo_title = ""
@it.seo.title.should eq @it.title
end
it "returns title when seo title is nil" do
@it.seo_title = nil
@it.seo.title.should eq @it.title
end
end
context "seo description present" do
it "returns seo description when present" do
@it.seo.description.should eq @it.seo_description
end
end
context "seo description non present" do
it "returns description when seo description is blank" do
@it.seo_description = ""
@it.seo.description.should eq @it.summary
end
it "returns description when seo description is nil" do
@it.seo_description = nil
@it.seo.description.should eq @it.summary
end
end
end
end
</code></pre>
<p><strong>spec/factories/contents.rb</strong></p>
<pre><code>FactoryGirl.define do
factory :content do
association :category
title { Faker::Lorem.sentence }
summary { Faker::Lorem.sentence(10) }
body { Faker::Lorem.sentence(15) }
seo_title { Faker::Lorem.sentence }
seo_description { Faker::Lorem.sentence }
seo_keywords { Faker::Lorem.words(8).join(", ") }
published_at { Time.zone.now }
is_draft { false }
factory :published_three_weeks_ago_content do
published_at { 3.weeks.ago }
end
factory :expiring_in_two_weeks_content do
unpublished_at { 2.weeks.from_now }
end
factory :publish_in_tree_weeks_content do
published_at { 3.weeks.from_now }
end
end
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T20:26:20.380",
"Id": "62863",
"Score": "0",
"body": "Note that David Chelimsky advises against the use of an explicit subject: http://blog.davidchelimsky.net/2012/05/13/spec-smell-explicit-use-of-subject/"
}
] |
[
{
"body": "<p>Nice job. Your tests are nicely compartmentalized. It is indeed good to test the factory independently. Good use of <em>describe</em> and <em>context</em>.</p>\n\n<p><strong>Consider using the shoulda-matchers gem</strong></p>\n\n<p>Tests for many of the rails model associations and validations can be handled by the <a href=\"https://github.com/thoughtbot/shoulda-matchers\" rel=\"nofollow\">shoulda-matchers</a> gem. For example, this line:</p>\n\n<pre><code>validates :title, presence: true\n</code></pre>\n\n<p>can be tested like so:</p>\n\n<pre><code>it {should validate_presence_of(:title)}\n</code></pre>\n\n<p><strong>Consider using <a href=\"https://www.relishapp.com/rspec/rspec-core/v/2-0/docs/pending/pending-examples\" rel=\"nofollow\"><em>pending</em></a></strong></p>\n\n<p>Here's a commented-out test:</p>\n\n<pre><code># TODO: You shall not pass! (for now)\n# it \"is invalid when expiration date is malformed\" do\n# build(:content, unpublished_at: \"!0$2-as-#{nil}\").should_not be_valid\n# end\n</code></pre>\n\n<p>Rspec has a method for documenting tests that don't (and can't yet be made to) pass:</p>\n\n<pre><code>it \"is invalid when expiration date is malformed\" do\n pending\n build(:content, unpublished_at: \"!0$2-as-#{nil}\").should_not be_valid\nend\n</code></pre>\n\n<p>The nice thing about <em>pending</em> is that it shows up in the test output, making it less easily forgotten than commented-out code. Also, you can give a reason, e.g.:</p>\n\n<pre><code>pending \"Can't pass until the vendor fixes library xyz\"\n</code></pre>\n\n<p><strong>For clarity, Consider redoing things the factory did</strong></p>\n\n<p>This test:</p>\n\n<pre><code>context \"seo description present\" do\n it \"returns seo description when present\" do\n @it.seo.description.should eq @it.seo_description\n end\nend\n</code></pre>\n\n<p>Relies upon the factory having having set the description, but the factory is a long way from the test. This would be clearer if explicit:</p>\n\n<pre><code>context \"seo description present\" do\n it \"returns seo description when present\" do\n @it.seo_description = 'foo bar baz'\n @it.seo.description.should eq @it.seo_description\n end\nend\n</code></pre>\n\n<p><strong>Consider using <em>subject</em></strong></p>\n\n<p>Some of your test sets a variable in a <code>before</code> block and later tests that variable:</p>\n\n<p>before :each do\n @it = create(:content)\n end</p>\n\n<pre><code>context \"seo title present\" do\n it \"returns seo title when present\" do\n @it.seo.title.should eq @it.seo_title\n end\nend\n</code></pre>\n\n<p>Instead of assigning to a variable, rspec lets you <a href=\"http://rubydoc.info/gems/rspec-core/RSpec/Core/Subject/ExampleGroupMethods#subject-instance_method\" rel=\"nofollow\">declare a subject</a>:</p>\n\n<pre><code>subject {create(:content)}\n</code></pre>\n\n<p>Once you've declared a subject, some snazzy syntax becomes available to you:</p>\n\n<pre><code>its('seo.title') {should == subject.title}\n</code></pre>\n\n<p><code>subject.seo_title</code> is <a href=\"http://blog.davidchelimsky.net/2012/05/13/spec-smell-explicit-use-of-subject/\" rel=\"nofollow\">a little awkward</a>, so rspec lets you name your subject:</p>\n\n<pre><code>subject(:content) {create(:content)}\nits('seo.title') {should == content.title}\n</code></pre>\n\n<p><strong>Consider using <em>let</em> along with <em>subject</em></strong></p>\n\n<p>In rspec, <em>let</em> defines a memoized, lazily-evaluated value. When used with <code>subject</code>, this can <a href=\"http://benscheirman.com/2011/05/dry-up-your-rspec-files-with-subject-let-blocks\" rel=\"nofollow\">DRY up a spec</a>:</p>\n\n<pre><code>describe \"seo.title\" do\n\n let(:title) {'title'}\n subject {create :content, :title => title, :seo_title => seo_title}\n\n context 'seo title present' do\n let(:seo_title) {'seo title'}\n its('seo.title') {should eq seo_title}\n end\n\n context 'seo title missing' do\n let(:seo_title) {nil}\n its('seo.title') {should eq title}\n end\n\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T12:07:01.253",
"Id": "33398",
"Score": "0",
"body": "Hey Wayne thanks for the reply. You pointed out some really useful stuff. The let/subject/its seems useful, so I'll have to take a look at the documentation. Cheers ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T12:33:54.137",
"Id": "33400",
"Score": "0",
"body": "One more to get this right. When using `subject` here: `subject {create :content, :title => title, :seo_title => seo_title}`, does the `seo_title` gets evaluated when `let(:seo_title) {'seo title'}` is executed later on? Normally it would raise an error for using an undefined variable... \n\nAlso here: `its('seo.title') {should eq title}` is `title` referring to `subject.title` or to the variable `title` set in the beggining, cause every time I tried something like this `its('seo.title') {should eq subject.title}` just got that `subject` is a string."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T17:00:42.347",
"Id": "33413",
"Score": "0",
"body": "@gtz, Instead of `its('seo.title') {should eq subject.title}` try `specify {subject.seo.title.should eq subject.title}`. There are... quirks... with _its_ ability to evaluate an arbitrary string."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T10:24:07.000",
"Id": "33496",
"Score": "0",
"body": "I see. I'm just starting to discover the ways of RSpec. Thanks a lot for the tips!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T13:29:49.627",
"Id": "20799",
"ParentId": "20792",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "20799",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T08:44:30.660",
"Id": "20792",
"Score": "3",
"Tags": [
"ruby",
"ruby-on-rails",
"rspec"
],
"Title": "Testing a Content model"
}
|
20792
|
<p>I feel that my current business view logic is not efficient or very clean. The problem is building the right output, but with less code and more DRY.</p>
<p>I have 3 'static' links, as in, direct tags: </p>
<pre><code>about, contact, search
</code></pre>
<p>I also have three navigation menu's.</p>
<p>The first (URI position 1):</p>
<pre><code>category = ['home', 'cat_1', 'cat_2', 'cat_3', 'cat_4', 'cat_5']
</code></pre>
<p>the second (URI position 2):</p>
<pre><code>country = ['all', 'filter_1', 'filter_2', 'filter_3', 'filter_4', 'filter_5']
</code></pre>
<p>the third menu (URI position 3), is NOT on ever page, but only on pages that are not category 'home' AND not filter 'all'.</p>
<pre><code>content = ['latest news', 'media and cartoons', 'country profile']
</code></pre>
<p>The third menu also does not use its last entry (profile) on any page whose filter is 'all'.</p>
<p>Possible page 'modes' are:</p>
<pre><code>Home Page // 1 or 2 of the latest articles from all categories
URI: "/home/all/latest/"
List Page // list of latest 10 articles using category and filter for WHERE
URI: "/home/!all/latest/" OR "!home/(any)/latest/"
Article Page // full article
URI: "/(any)/(any)/article/"
About, Contact, Search page // simple pages
URI: "/about/", "/contact/", "/search/"
</code></pre>
<p>I am currently using URI position 1 to load a class of the same name as the URI string; validating if the class exists, and loading home page if it doesn't.</p>
<p>In the class that is instantiated by the URI Position, I have to validate and use <code>if</code> <code>else</code> statements to determine which of the above four page modes to load. As it stands now, that means I have about 9 pages that have a lot of repeating code:</p>
<p>CONTROLLER:</p>
<pre><code>/** START page
* = build page elements using templates */
$page = new TemplateMan();
/** ADD content
* = add main page content to output */
$content_class = str_replace('-', '_', $this->breadcrumbs->getCrumb(1));
try {
if (!class_exists($content_class)) {
throw new Exception ('<b>Error - Content class is missing: ' . $content_class . '</b>');
}
$content = new $content_class($this->breadcrumbs, $this);
$content->setMainContent($inc_path);
} catch (Exception $e) {
echo
'<p><b>EXCEPTION</b><br />Message: '
. $e->getMessage()
. '<br />File: '
. $e->getFile()
. '<br />Line: '
. $e->getLine()
. '</p>';
}
$page->setDataValues('content', $content->getOutput());
/** RENDER page
* = render output to display page */
$page->buildOutput();
echo $page->renderOutput();
</code></pre>
<p>"home" class:</p>
<pre><code> public function setMainContent($inc_path) {
/** ADD main content
* = add the main content to the output */
$array_helper = new ArrayHelp();
if ($array_helper->recValueReturn($this->breadcrumbs->getCrumb(3), $this->config->getNavThree())) {
switch ($this->breadcrumbs->getCrumb(3)) {
case 'latest':
if ($this->breadcrumbs->getCrumb(2) !== 'all') {
$this->output .= '<div>this is the list of articles page</div>';
} else {
$this->output .= '<div>this is the home page</div>';
}
break;
case 'media':
$this->output .= '<div>this is the media & cartoons page</div>';
break;
case 'country':
if ($this->breadcrumbs->getCrumb(2) !== 'all') {
$this->output .= '<div>this is the country profile page</div>';
}
break;
case 'article':
$this->output .= '<div>this is the article page</div>';
break;
default:
$this->output .= '<div>this is the default (home) page</div>';
break;
}
}
}
</code></pre>
<p>How can I make the logic better?</p>
<p><strong>BTW: I have already come up with a different solution that works better since I posted this an hour ago, but I would really like to see what others would come up with.</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-23T23:25:33.043",
"Id": "37460",
"Score": "1",
"body": "You should really take a look at [Symfony's Routing](http://symfony.com/doc/master/book/routing.html), whic as a component, can be used wholly separately from the rest of the project that fall under Sensio. What you had above and what you suggest below are, in my opinion, customization over configuration, when you really should only have to configure it to use it (like a standalone component)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T11:14:33.217",
"Id": "37931",
"Score": "0",
"body": "Thanks! I will look into it. Though I've moved on a fair distance from this in fact.. I've adopted this method: http://www.youtube.com/watch?v=Aw28-krO7ZM"
}
] |
[
{
"body": "<p>The following if..else stack in the controller allows me to load one of the 4 views, while containing the logic in one location, rather than across multiple files.</p>\n\n<p>Still a bit long, but probably the best way:</p>\n\n<pre><code> /** ADD content\n * = add main page content to output */\n// array helper\n$array_helper = new ArrayHelp();\n\n// Home Page: 1 or 2 of the latest articles from all categories\nif ($this->breadcrumbs->getCrumb(3) == 'latest'\n && $this->breadcrumbs->getCrumb(2) == 'all'\n && $this->breadcrumbs->getCrumb(1) == 'home') {\n\n //$content = new Homepage();\n $check = '<div><p> Requested page is the <b>Home Page</b></p></div>';\n}\n// List Page: list of latest 10 articles using category and filter for WHERE\nelse if (($this->breadcrumbs->getCrumb(3) == 'latest'\n && $this->breadcrumbs->getCrumb(2) !== 'all'\n && $this->breadcrumbs->getCrumb(1) == 'home')\n ||\n ($this->breadcrumbs->getCrumb(3) == 'latest'\n && $array_helper->recValueReturn($this->breadcrumbs->getCrumb(2), $this->getNavTwo())\n && $array_helper->recValueReturn($this->breadcrumbs->getCrumb(1), $this->getNavOne())\n && $this->breadcrumbs->getCrumb(1) !== 'home')) {\n\n //$content = new ListPage();\n $check = '<div><p> Requested page is a <b>List Page</b> for..<br /> Category: <b>'\n . $array_helper->recValueReturn($this->breadcrumbs->getCrumb(1), $this->getNavOne())[1]\n . '</b> and country filter: <b>'\n . $array_helper->recValueReturn($this->breadcrumbs->getCrumb(2), $this->getNavTwo())[1]\n . '</b></p></div>';\n}\n// Media & Cartoons Page: list of latest media & cartoons\nelse if ($this->breadcrumbs->getCrumb(3) == 'media'\n && $array_helper->recValueReturn($this->breadcrumbs->getCrumb(2), $this->getNavTwo())\n && $array_helper->recValueReturn($this->breadcrumbs->getCrumb(1), $this->getNavOne())) {\n\n //$content = new MediaPage();\n $check = '<div><p> Requested page is a <b>Media Page</b> for..<br /> Category: <b>'\n . $array_helper->recValueReturn($this->breadcrumbs->getCrumb(1), $this->getNavOne())[1]\n . '</b> and country filter: <b>'\n . $array_helper->recValueReturn($this->breadcrumbs->getCrumb(2), $this->getNavTwo())[1]\n . '</b></p></div>';\n}\n// Country Profile Page: country information\nelse if ($this->breadcrumbs->getCrumb(3) == 'country'\n && $this->breadcrumbs->getCrumb(2) !== 'all'\n && $array_helper->recValueReturn($this->breadcrumbs->getCrumb(1), $this->getNavOne())) {\n\n //$content = new ProfilePage();\n $check = '<div><p> Requested page is a <b>Country Profile Page</b> for..<br /> Category: <b>'\n . $array_helper->recValueReturn($this->breadcrumbs->getCrumb(1), $this->getNavOne())[1]\n . '</b> and country filter: <b>'\n . $array_helper->recValueReturn($this->breadcrumbs->getCrumb(2), $this->getNavTwo())[1]\n . '</b></p></div>';\n}\n// Article Page\nelse if ($this->breadcrumbs->getCrumb(3) == 'article'\n && $array_helper->recValueReturn($this->breadcrumbs->getCrumb(2), $this->getNavTwo())\n && $array_helper->recValueReturn($this->breadcrumbs->getCrumb(1), $this->getNavOne())\n && is_numeric($this->breadcrumbs->getCrumb(4)) {\n\n //$content = new ListPage();\n $check = '<div><p> Requested page is an <b>Article</b><br /> Article ID is: <b>'\n . $this->breadcrumbs->getCrumb(4) . '</b></p></div>';\n}\n// About Page\nelse if ($this->breadcrumbs->getCrumb(1) == 'about') {\n\n //$content = new AboutPage();\n $check = '<div><p> Requested page is the <b>About Us Page</b></p></div>';\n}\n// Contact Page\nelse if ($this->breadcrumbs->getCrumb(1) == 'contact') {\n\n //$content = new ContactPage();\n $check = '<div><p> Requested page is the <b>Contact Us Page</b></p></div>';\n}\n// Search Page\nelse if ($this->breadcrumbs->getCrumb(1) == 'search') {\n\n //$content = new SearchPage();\n $check = '<div><p> Requested page is the <b>Advanced Search Page</b></p></div>';\n}\nelse {\n $check = '<div><p> Requested page is either <b>Missing</b> or <b>Incorrect</b>.\n Please use the menus above to navigate the site, or <a href=\"/home\">click here</a> to go to the Home page.</p></div>';\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T23:30:17.033",
"Id": "33378",
"Score": "0",
"body": "If you have to edit source code to add more tabs (or content) to a web site, you've done something wrong. If you have duplication (such as `'latest'`) strewn throughout the code, a mistake has been made."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T04:11:24.360",
"Id": "33387",
"Score": "0",
"body": "can you explain a little further? You talking about the updated method i'm using, or the old? and do you mean 'latest' as in using it multiple times in an if..else stack as above? The new stack only calls a page view once as opposed to the old way i did it.. so not sure what you mean."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T04:32:15.677",
"Id": "33389",
"Score": "1",
"body": "You can map the navigation menu combinations to HTML fragments and encode the rules to choose the correct fragment based on the map. This then requires a single look-up to find the correct check fragment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T04:36:56.250",
"Id": "33391",
"Score": "0",
"body": "You're talking about routing, correct? I need to learn that a bit more, didn't fully understand it all the first couple of run throughs, so did this for now. Thanks."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T13:40:37.537",
"Id": "20801",
"ParentId": "20795",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T10:33:52.057",
"Id": "20795",
"Score": "4",
"Tags": [
"php",
"template"
],
"Title": "Cleaner way to determine and load page template"
}
|
20795
|
<p>This is my try at <a href="http://en.wikipedia.org/wiki/Proxy_pattern" rel="nofollow">the proxy pattern</a>.</p>
<p>What do you Pythoneers think of my attempt?</p>
<pre><code>class Image:
def __init__( self, filename ):
self._filename = filename
def load_image_from_disk( self ):
print("loading " + self._filename )
def display_image( self ):
print("display " + self._filename)
class Proxy:
def __init__( self, subject ):
self._subject = subject
self._proxystate = None
class ProxyImage( Proxy ):
def display_image( self ):
if self._proxystate == None:
self._subject.load_image_from_disk()
self._proxystate = 1
print("display " + self._subject._filename )
proxy_image1 = ProxyImage ( Image("HiRes_10Mb_Photo1") )
proxy_image2 = ProxyImage ( Image("HiRes_10Mb_Photo2") )
proxy_image1.display_image() # loading necessary
proxy_image1.display_image() # loading unnecessary
proxy_image2.display_image() # loading necessary
proxy_image2.display_image() # loading unnecessary
proxy_image1.display_image() # loading unnecessary
</code></pre>
<p>Output:</p>
<pre><code>loading HiRes_10Mb_Photo1
display HiRes_10Mb_Photo1
display HiRes_10Mb_Photo1
loading HiRes_10Mb_Photo2
display HiRes_10Mb_Photo2
display HiRes_10Mb_Photo2
display HiRes_10Mb_Photo1
</code></pre>
|
[] |
[
{
"body": "<p>It seems like overkill to implement a class to represent the proxy pattern. <em>Design patterns are patterns, not classes.</em> What do you gain from your implementation compared to a simple approach like the one shown below?</p>\n\n<pre><code>class Image(object):\n def __init__(self, filename):\n self._filename = filename\n self._loaded = False\n\n def load(self):\n print(\"loading {}\".format(self._filename))\n self._loaded = True\n\n def display(self):\n if not self._loaded:\n self.load()\n print(\"displaying {}\".format(self._filename))\n</code></pre>\n\n<p>Some other notes on your code:</p>\n\n<ol>\n<li><p>It doesn't follow <a href=\"http://www.python.org/dev/peps/pep-0008/\">PEP8</a>. In particular, \"Avoid extraneous whitespace [...] immediately inside parentheses.\"</p></li>\n<li><p>No docstrings.</p></li>\n<li><p>It makes more sense to use <code>True</code> and <code>False</code> for a binary condition than to use <code>None</code> and <code>1</code>.</p></li>\n<li><p>It's not necessary to append the class name to all the methods. In a class called <code>Image</code>, the methods should just be called <code>load</code> and <code>display</code>, not <code>load_image</code> and <code>display_image</code>.</p></li>\n<li><p>You should use new-style classes (inheriting from <code>object</code>) to make your code portable between Python 2 and 3.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T14:08:17.773",
"Id": "33356",
"Score": "0",
"body": "I think it can make sense to have separate `Image` and `ImageProxy` objects (though a better name might be something like `LazyImage`), because of separation of concerns. And even better (assuming the added complexity would be worth it) would be some sort of generic `LazyLoadingProxy` class, which could work with `Image`s and also other objects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T14:17:05.750",
"Id": "33357",
"Score": "1",
"body": "It's possible, but we'd only know in the context of a whole application: if there really are several different types of assets that need to be lazily loaded, then it might make sense to have a class to handle the lazy loading, but it might still be simpler to implement that class as a mixin rather than a proxy. A proxy object is usually a last resort when you don't control the code for the class you are proxying."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T13:33:10.253",
"Id": "20800",
"ParentId": "20798",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "20800",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T13:08:25.817",
"Id": "20798",
"Score": "3",
"Tags": [
"python",
"design-patterns"
],
"Title": "proxy pattern in Python"
}
|
20798
|
<p>This is a sample class using Rhino (1.7R4). I need it because in the context of JSON Schema, regexes should be ECMA 262. One requirement is that it is thread safe, and it is.</p>
<p>But I'm not sure I actually use it correctly. Can you comment?</p>
<pre><code>public final class RhinoHelper
{
/**
* JavaScript scriptlet defining functions {@link #regexIsValid}
* and {@link #regMatch}
*/
private static final String jsAsString
= "function regexIsValid(re)"
+ '{'
+ " try {"
+ " new RegExp(re);"
+ " return true;"
+ " } catch (e) {"
+ " return false;"
+ " }"
+ '}'
+ ""
+ "function regMatch(re, input)"
+ '{'
+ " return new RegExp(re).test(input);"
+ '}';
/**
* Script context to use
*/
private static final Context ctx;
/**
* Script scope
*/
private static final Scriptable sharedScope;
/**
* Reference to Javascript function for regex validation
*/
private static final Function regexIsValid;
/**
* Reference to Javascript function for regex matching
*/
private static final Function regMatch;
private RhinoHelper()
{
}
static {
ctx = Context.enter();
sharedScope = ctx.initStandardObjects();
ctx.evaluateString(sharedScope, jsAsString, "re", 1, null);
regexIsValid = (Function) sharedScope.get("regexIsValid", sharedScope);
regMatch = (Function) sharedScope.get("regMatch", sharedScope);
ctx.seal(null);
}
/**
* Validate that a regex is correct
*
* @param regex the regex to validate
* @return true if the regex is valid
*/
public static boolean regexIsValid(final String regex)
{
final Context context = Context.enter();
try {
final Scriptable scope = context.newObject(sharedScope);
scope.setPrototype(sharedScope);
scope.setParentScope(null);
return (Boolean) regexIsValid.call(context, scope, scope,
new Object[]{ regex });
} finally {
Context.exit();
}
}
/**
* <p>Matches an input against a given regex, in the <b>real</b> sense
* of matching, that is, the regex can match anywhere in the input. Java's
* {@link java.util.regex} makes the unfortunate mistake to make people
* believe that matching is done on the whole input... Which is not true.
* </p>
*
* <p>Also note that the regex MUST have been validated at this point
* (using {@link #regexIsValid(String)}).</p>
*
* @param regex the regex to use
* @param input the input to match against (and again, see description)
* @return true if the regex matches the input
*/
public static boolean regMatch(final String regex, final String input)
{
final Context context = Context.enter();
try {
final Scriptable scope = context.newObject(sharedScope);
scope.setPrototype(sharedScope);
scope.setParentScope(null);
return (Boolean) regMatch.call(context, scope, scope,
new Object[]{ regex, input });
} finally {
Context.exit();
}
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T13:42:54.257",
"Id": "20802",
"Score": "3",
"Tags": [
"java",
"multithreading",
"regex",
"rhino"
],
"Title": "Rhino helper class to support ECMA-262 regular expressions"
}
|
20802
|
<p>My app communicates with a server over an internal network through HTTPS. The SSL certificate on this server is listed for the host as its external host name. I want to accept this certificate, but I don't want to accept ANY certificate as many workarounds I've seen seem to do. I would also like to have it so that later on, in the strong possibility that his app is accessing a different server with a correct SSL certificate, that I don't have to change it. I have it working as I would like it seems, but I am very unsure of myself when it comes to implementing my own methods to override a library used for secure communications, and I am not very strong in my knowledge of SSL communications. </p>
<p>I would basically like input on security loopholes and its effectiveness at doing what I need.</p>
<p>Here is the code I have:</p>
<pre><code>HttpClient httpclient = new DefaultHttpClient();
SSLSocketFactory ssf = SSLSocketFactory.getSocketFactory();
ssf.setHostnameVerifier( new X509HostnameVerifier() {
@Override
public void verify( String host, String[] cns, String[] subjectAlts )
throws SSLException
{
}
@Override
public void verify( String host, X509Certificate cert ) throws SSLException
{
}
@Override
public void verify( String host, SSLSocket ssl ) throws IOException
{
boolean foundHost = false;
for( javax.security.cert.X509Certificate cert : ssl.getSession().getPeerCertificateChain() )
{
String[] tokens = cert.getSubjectDN().getName().split( "," );
for( String token : tokens )
{
String[] keyVal = token.split( "=" );
if( keyVal.length > 1 && keyVal[0].equals( "CN" ) )
{
foundHost = keyVal[1].equals( context.getString( R.string.CertHostName ) );
if(!foundHost)
{
foundHost = keyVal[1].equals( host );
}
}
if(foundHost)
{
break;
}
}
if(foundHost)
{
break;
}
}
if(!foundHost)
{
throw new IOException( "Mismatched host in SSL certificate" );
}
}
@Override
public boolean verify( String host, SSLSession session )
{
return false;
}
} );
httpclient.getConnectionManager().getSchemeRegistry().unregister( "https" );
httpclient.getConnectionManager().getSchemeRegistry().register( new Scheme( "https", ssf, 443 ) );
</code></pre>
<p>Basically, I found out which method to override through some log statements to see which one was being used in the anonymous inner <code>X509HostnameVerifier</code> class, and hopefully handled it appropriately. Input would be appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T03:41:58.560",
"Id": "58244",
"Score": "0",
"body": "Since certificate authorities will [stop issuing certificates with internal hostnames](http://www.digicert.com/internal-names.htm), I see your options as: a) Implement this workaround; b) Always use the public hostname and interface, or c) Deploy split DNS such that from inside your network, the public hostname resolves to an internal IP address. I believe options (b) and (c) are less hackish."
}
] |
[
{
"body": "<p>There are a few items inhere I would suggest can be improved (assuming the security aspects of the code are valid - i.e. legal disclaimer about 'safe' and SSL means speak to someone who's more of a security expert than me).</p>\n\n<p>First, I assume you are using the apache-commons based HttpClient code.... this is fine, but it would have been useful to show the import statements ;-).</p>\n\n<p>Regardless. There are three things I would change.</p>\n\n<p>First, whenever you do an anonymous class implementation and it has more than 1 method that needs to be overridden, then I recommend that you create a full class implementation for it. In this case, your code should have a (perhaps nested) class that implements the </p>\n\n<pre><code>private static final class AlternateHostnameVerifier implements X509HostnameVerifier {\n ....\n}\n</code></pre>\n\n<p>then your code becomes:</p>\n\n<pre><code>HttpClient httpclient = new DefaultHttpClient();\nSSLSocketFactory ssf = SSLSocketFactory.getSocketFactory();\nssf.setHostnameVerifier(new AlternateHostnameVerifier());\nhttpclient.getConnectionManager().getSchemeRegistry().unregister( \"https\" );\nhttpclient.getConnectionManager().getSchemeRegistry().register( new Scheme( \"https\", ssf, 443 ) );\n</code></pre>\n\n<p>This is a much better way to show the critical logic of your program, and still make it readable.</p>\n\n<p>Next up, in your new AlternateHostnameVerifier class, I would recommend you implement all the interface methods fully. Leaving two of the methods as stub methods is only a short-term solution. In the future the apache-commons implementation may change and call one of the other verify methods, and then you have a sudden, unexplained bug. Specifically throwing a <code>UnsupportedOperationException</code> is a much better alternative than leaving it blank.</p>\n\n<p>Finally, I have a preference for methods that can to simply 'return' when they succeed rather than trying to break out of loops and keep track of variables outside of the loops.</p>\n\n<p>In this case, you have <code>foundHost</code> which tracks the state. you can eliminate this variable if you just 'return' each time you set it to true, and otherwise always throw the exception.</p>\n\n<p>So, you can rewrite the code as:</p>\n\n<pre><code>@Override\npublic void verify( String host, SSLSocket ssl ) throws IOException { \n for( javax.security.cert.X509Certificate cert : ssl.getSession().getPeerCertificateChain() ) {\n String[] tokens = cert.getSubjectDN().getName().split( \",\" );\n for( String token : tokens ) {\n String[] keyVal = token.split( \"=\" , 2);\n\n if( keyVal.length > 1 && keyVal[0].equals( \"CN\" ) ) {\n if (keyVal[1].equals( host ) || keyVal[1].equals( context.getString( R.string.CertHostName ) )) {\n // our CN matches the Android's certificate host.\n return;\n }\n }\n }\n }\n throw new IOException( \"Mismatched host in SSL certificate\" );\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T02:13:35.860",
"Id": "58238",
"Score": "0",
"body": "+1 - yet another nice review, keep it up!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T13:33:41.653",
"Id": "58319",
"Score": "0",
"body": "Definitely should have gone with the nested class. Coding standards where I work frown upon a return breaking out of several levels or returning before the end of the method, but I'm sure it would be fine in the cleaned up way presented here. Thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T02:08:44.247",
"Id": "35797",
"ParentId": "20806",
"Score": "2"
}
},
{
"body": "<p>Instead of implementing your <code>X509HostnameVerifier</code> from scratch, extend <a href=\"http://grepcode.com/file/repo1.maven.org/maven2/org.apache.httpcomponents/httpclient/4.0/org/apache/http/conn/ssl/AbstractVerifier.java#85\" rel=\"nofollow\"><code>org.apache.http.conn.ssl.AbstractVerifier</code></a>, which does most of that work for you. All you have to do is override <a href=\"http://grepcode.com/file/repo1.maven.org/maven2/org.apache.httpcomponents/httpclient/4.0/org/apache/http/conn/ssl/AbstractVerifier.java#152\" rel=\"nofollow\"><code>.verify(String host, String[] cns, String[] subjectAlts, boolean stringWithSubDomains()</code></a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T13:30:32.237",
"Id": "58318",
"Score": "0",
"body": "Very nice, I wasn't aware of that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T14:06:08.167",
"Id": "58330",
"Score": "1",
"body": "Well duh, I guess I don't know the HttpClient API well enough. Good catch."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T03:34:58.657",
"Id": "35800",
"ParentId": "20806",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T17:03:12.487",
"Id": "20806",
"Score": "10",
"Tags": [
"java",
"security",
"android",
"https",
"ssl"
],
"Title": "Safely accepting a known SSL certificate with a different host name"
}
|
20806
|
<p>I'm still learning JavaScript and I'm building an Ajax website that loads in content for each page from external files (e.g. test1.php, test2.php). I spent several hours cobbling together some code that works, but it feels really clunky. Any recommendations on how to streamline it? Or anything I am doing that is stupid and should be done differently?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {
var hash = window.location.hash.substr(1);
var projectID = $('#topNav a').each(function(){
var projectID = $(this).attr('id');
if(hash==projectID){
var toLoad = hash+'.php .content';
$('.content').load(toLoad);
$(this).siblings().removeClass('active');
$(this).addClass('active');
}
});
$('#topNav a').click(function(){
var toLoad = $(this).attr('href')+' .content',
newId = $(this).attr('rel'),
oldHeight = $('#shell').css("height"),
viewportHeight = $(window).height()
if (!$(this).hasClass("active")) {
$(this).siblings().removeClass('active');
$(this).addClass('active');
$('<div/>', {
id: newId,
class: 'content'
}).css({ top: viewportHeight + "px", display: "none" }).appendTo('#shell').load(toLoad);
$('#' + newId).show(function() {
$(this).animate({ top: "0px", queue: false}, 600);
$('#shell > div:first').animate({ top: "-" + oldHeight, queue: false}, 600, function() {
$('#shell > div:first').remove()
});
});
var newHash = $(this).attr('id');
window.history.pushState(null, "", "#" + newHash);
}
return false;
});
window.addEventListener("popstate", function(e) {
var hash = window.location.hash.substr(1),
oldHeight = $('#shell').css("height"),
viewportHeight = $(window).height()
var projectID = $('#topNav a').each(function(){
var projectID = $(this).attr('id');
if(hash==projectID){
var toLoad = hash+'.php .content'
$(this).siblings().removeClass('active');
$(this).addClass('active');
$('<div/>', {
id: hash,
class: 'content'
}).css({ top: viewportHeight + "px", display: "none" }).appendTo('#shell').load(toLoad, function() {
$(this).show(function() {
$(this).animate({ top: "0px", queue: false}, 600);
$('#shell > div:first').animate({ top: "-" + oldHeight, queue: false}, 600, function() {
$('#shell > div:first').remove()
});
});
});
}
});
});
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#topNav {
position: fixed; overflow: auto; top: 0; left: 0;
width: 100%; z-index: 100; background: #fff; height: 80px;
}
#topNav a { margin-right: 30px; color: #a9a9a9; }
#topNav a.active { color: #333; }
#shell { margin: 0px; padding: 0px; width: 100%; height: 100%; }
.content {
position: absolute; margin: 0px; padding-bottom: 0px;
width: 100%; height: 100%;
}
#content1 { background: #000; color: #fff; }
#content2 { background: red; }
#content3 { background: blue; }</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav id="topNav">
<a href="test1.php" id="test1" rel="content1" class="active">Test 1</a>
<a href="test2.php" id="test2" rel="content2">Test 2</a>
<a href="test3.php" id="test3"rel="content3">Test 3</a>
</nav>
<div id="shell">
<div id="content1" class="content">
<p>Here is the first page</p>
</div>
</div></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>You should really combine code that is the same and put them into functions. Then call the functions.</p>\n\n<p>I put your functionality into two categories.<br>\n 1. Updating the tab links to show the active link. \n 2. Pulling the content from the specified pages.</p>\n\n<p>So in order to do these I separated out the functionality into two separate functions and called them where appropriate. I took out the looping through of the tabs. If you had that in there as some sort of check to make sure the hash was valid then you may want to add that back in as another function. </p>\n\n<p>After doing this one problem became obvious. You are losing the styles applied by id (#content1, #content2) when hitting the back button. This is because you are using the hash as the ID instead of the 'rel' attribute of the links as you are doing in other places. </p>\n\n<p>Anyway here are my changes. These don't solve all problems (i.e. you now have global functions) but should lead you in the right direction. </p>\n\n<pre><code> function loadContent(newId, toLoad) {\n\n var oldHeight = $('#shell').css(\"height\"),\n viewportHeight = $(window).height();\n\n $('<div/>', {\n id: newId,\n class: 'content'\n }).css({ top: viewportHeight + \"px\", display: \"none\" }).appendTo('#shell').load(toLoad, function () {\n\n $(this).show(function () {\n $(this).animate({ top: \"0px\", queue: false }, 600);\n $('#shell > div:first').animate({ top: \"-\" + oldHeight, queue: false }, 600, function () {\n\n $('#shell > div:first').remove()\n });\n });\n\n });\n\n }\n\n function setActiveTab(id) {\n $('#topNav a').removeClass('active');\n $('#' + id).addClass('active');\n }\n\n\n $(document).ready(function () {\n\n var hash = window.location.hash.substr(1);\n\n setActiveTab(hash);\n $('.content').load( hash + '.php .content');\n\n\n $('#topNav a').click(function () {\n\n var toLoad = $(this).attr('href') + ' .content',\n newId = $(this).attr('rel'),\n newHash = $(this).attr('id');\n\n if (!$(this).hasClass(\"active\")) {\n\n setActiveTab(newHash);\n loadContent(newId, toLoad);\n\n window.history.pushState(null, \"\", \"#\" + newHash);\n\n }\n\n return false;\n });\n\n window.addEventListener(\"popstate\", function (e) {\n\n var hash = window.location.hash.substr(1);\n setActive(hash);\n loadContent(hash, hash + '.php .content');\n\n });\n });\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T20:40:47.327",
"Id": "20808",
"ParentId": "20807",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-22T19:45:46.707",
"Id": "20807",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"ajax"
],
"Title": "AJAX navigation"
}
|
20807
|
<p>What is the most elegant and readable way to in include (potentially long) <code>image_tag</code> calls inside of <code>link_to</code>?</p>
<p>Example</p>
<pre><code><%= link_to image_tag('buckminsterfullerene.png', width: '210', height: '60', alt: 'Molecular structure of Buckminsterfullerene'), 'some_long_path.html', title: 'Buckminsterfullerene', rel: 'tooltip', relative: true %>
</code></pre>
|
[] |
[
{
"body": "<p>You could create a helper to keep your views less bloated. For example:</p>\n\n<p><code>app/helpers/application_helper.rb</code></p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>...\ndef image_link_to(image_path, url, image_tag_options = { }, link_to_options = { })\n link_to url, link_to_options do\n image_tag image_path, image_tag_options\n end\nend\n...\n</code></pre>\n\n<p><code>app/views/pages/show.html.haml</code></p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>...\n= image_link_to \"buckminsterfullerene.png\", my_url_helper, { size: '210x60', alt: 'Molecular structure of Buckminsterfullerene' }, { title: 'Buckminsterfullerene', rel: 'tooltip', relative: true }\n...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T12:56:02.433",
"Id": "20821",
"ParentId": "20812",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "20821",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T02:39:38.770",
"Id": "20812",
"Score": "6",
"Tags": [
"ruby",
"ruby-on-rails",
"erb"
],
"Title": "Best way to include image_tag inside link_to"
}
|
20812
|
<p>I am new to programming as you can probably tell from the code below I am curious if there is a way to create a loop so I don't have so many copy's of the same code with only different variable names. The way the code works is that for each variable that is represented as a day of the week the value is a string such as <code>01/20/13</code> I obtain these values from another piece of code so I don't have to hard code the date values in each time. I have included this code snippet as well. I have 4 places in my code that there is a similar approach used here where I have 7 separate code blocks where only a few variable names are changed. I also don't know if my method of repetitive MySQL query's are hurting performance at all or if there is a more efficient method to do this in one query instead of 7.</p>
<p>This is the repetitive code:</p>
<pre><code>$stmt = $conn->prepare('SELECT `employeeID`, SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(`timeOut`, `timeIn`))))
AS `totalSunday` FROM `timeRecords` WHERE `date` = :Sunday
AND `employeeID` = 1 GROUP BY `employeeID`;');
$stmt->execute(array(':Sunday'=>$Sunday));
$row = $stmt->fetch();
$data['TotalSunday'] = $row['totalSunday'];
$stmt = $conn->prepare('SELECT `employeeID`, SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(`timeOut`, `timeIn`))))
AS `totalMonday` FROM `timeRecords` WHERE `date` = :Monday
AND `employeeID` = 1 GROUP BY `employeeID`;');
$stmt->execute(array(':Monday'=>$Monday));
$row = $stmt->fetch();
$data['TotalMonday'] = $row['totalMonday'];
$stmt = $conn->prepare('SELECT `employeeID`, SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(`timeOut`, `timeIn`))))
AS `totalTuesday` FROM `timeRecords` WHERE `date` = :Tuesday
AND `employeeID` = 1 GROUP BY `employeeID`;');
$stmt->execute(array(':Tuesday'=>$Tuesday));
$row = $stmt->fetch();
$data['TotalTuesday'] = $row['totalTuesday'];
$stmt = $conn->prepare('SELECT `employeeID`, SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(`timeOut`, `timeIn`))))
AS `totalWednesday` FROM `timeRecords` WHERE `date` = :Wednesday
AND `employeeID` = 1 GROUP BY `employeeID`;');
$stmt->execute(array(':Wednesday'=>$Wednesday));
$row = $stmt->fetch();
$data['TotalWednesday'] = $row['totalWednesday'];
$stmt = $conn->prepare('SELECT `employeeID`, SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(`timeOut`, `timeIn`))))
AS `totalThursday` FROM `timeRecords` WHERE `date` = :Thursday
AND `employeeID` = 1 GROUP BY `employeeID`;');
$stmt->execute(array(':Thursday'=>$Thursday));
$row = $stmt->fetch();
$data['TotalThursday'] = $row['totalThursday'];
$stmt = $conn->prepare('SELECT `employeeID`, SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(`timeOut`, `timeIn`))))
AS `totalFriday` FROM `timeRecords` WHERE `date` = :Friday
AND `employeeID` = 1 GROUP BY `employeeID`;');
$stmt->execute(array(':Friday'=>$Friday));
$row = $stmt->fetch();
$data['TotalFriday'] = $row['totalFriday'];
$stmt = $conn->prepare('SELECT `employeeID`, SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(`timeOut`, `timeIn`))))
AS `totalSaturday` FROM `timeRecords` WHERE `date` = :Saturday
AND `employeeID` = 1 GROUP BY `employeeID`;');
$stmt->execute(array(':Saturday'=>$Saturday));
$row = $stmt->fetch();
$data['TotalSaturday'] = $row['totalSaturday']
</code></pre>
<p>Here is how I obtain the date string to be placed in the variables:</p>
<pre><code>// set current date
$date7 = date("m/d/y");
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date7);
// calculate the number of days since Monday
$dow = date('w', $ts);
$offset = $dow;
if ($offset < 0) {
$offset = 6;
}
// calculate timestamp for the Monday
$ts = $ts - $offset*86400;
// loop from Monday till Sunday
for ($i = 0; $i < 7; $i++, $ts += 86400){
$date1 = date("m/d/y", $ts);
$date3 = date("l", $ts);
$date2 = $date1;
$$date3 = $date1;
}
</code></pre>
|
[] |
[
{
"body": "<p>The first thing to do would be to change whatever can be changed in the code so that the behavior doesn't change but the code looks the same everywhere. Here's what I've done :</p>\n\n<pre><code>$stmt = $conn->prepare('SELECT `employeeID`, SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(`timeOut`, `timeIn`)))) \n AS `totalDay` FROM `timeRecords` WHERE `date` = :myDay\n AND `employeeID` = 1 GROUP BY `employeeID`;');\n$stmt->execute(array(':myDay'=>$Sunday));\n$row = $stmt->fetch();\n$data['TotalSunday'] = $row['totalDay'];\n\n$stmt = $conn->prepare('SELECT `employeeID`, SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(`timeOut`, `timeIn`)))) \n AS `totalDay` FROM `timeRecords` WHERE `date` = :myDay\n AND `employeeID` = 1 GROUP BY `employeeID`;');\n$stmt->execute(array(':myDay'=>$Monday));\n$row = $stmt->fetch();\n$data['TotalMonday'] = $row['totalDay'];\n\n$stmt = $conn->prepare('SELECT `employeeID`, SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(`timeOut`, `timeIn`)))) \n AS `totalDay` FROM `timeRecords` WHERE `date` = :myDay\n AND `employeeID` = 1 GROUP BY `employeeID`;');\n$stmt->execute(array(':myDay'=>$Tuesday));\n$row = $stmt->fetch();\n$data['TotalTuesday'] = $row['totalDay'];\n\n$stmt = $conn->prepare('SELECT `employeeID`, SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(`timeOut`, `timeIn`)))) \n AS `totalDay` FROM `timeRecords` WHERE `date` = :myDay\n AND `employeeID` = 1 GROUP BY `employeeID`;');\n$stmt->execute(array(':myDay'=>$Wednesday));\n$row = $stmt->fetch();\n$data['TotalWednesday'] = $row['totalDay'];\n\n$stmt = $conn->prepare('SELECT `employeeID`, SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(`timeOut`, `timeIn`)))) \n AS `totalThursday` FROM `timeRecords` WHERE `date` = :myDay\n AND `employeeID` = 1 GROUP BY `employeeID`;');\n$stmt->execute(array(':myDay'=>$Thursday));\n$row = $stmt->fetch();\n$data['TotalThursday'] = $row['totalThursday'];\n\n$stmt = $conn->prepare('SELECT `employeeID`, SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(`timeOut`, `timeIn`)))) \n AS `totalDay` FROM `timeRecords` WHERE `date` = :myDay\n AND `employeeID` = 1 GROUP BY `employeeID`;');\n$stmt->execute(array(':myDay'=>$Friday));\n$row = $stmt->fetch();\n$data['TotalFriday'] = $row['totalDay'];\n\n$stmt = $conn->prepare('SELECT `employeeID`, SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(`timeOut`, `timeIn`)))) \n AS `totalDay` FROM `timeRecords` WHERE `date` = :myDay\n AND `employeeID` = 1 GROUP BY `employeeID`;');\n$stmt->execute(array(':myDay'=>$Saturday));\n$row = $stmt->fetch();\n$data['TotalSaturday'] = $row['totalDay'] \n</code></pre>\n\n<p>Then you can check what's the same and what's different in the different iterations.</p>\n\n<p>The typical iterations looks like this :</p>\n\n<pre><code>$stmt = $conn->prepare('SELECT `employeeID`, SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(`timeOut`, `timeIn`)))) \n AS `totalDay` FROM `timeRecords` WHERE `date` = :myDay\n AND `employeeID` = 1 GROUP BY `employeeID`;');\n$stmt->execute(array(':myDay'=>$THIS_PART_IS_DIFFERENT));\n$row = $stmt->fetch();\n$data['Total' . THIS_PART_IS_DIFFERENT] = $row['totalDay'];\n</code></pre>\n\n<p>Finally, you can make an array out of the different parts. Here, it's pretty simple : only 2 elements are changing so we can use a simple associative array.</p>\n\n<p>The result would be something like</p>\n\n<pre><code>$day = arrays(\n 'Sunday' => $Sunday,\n // etc\n 'Monday' => $Monday,\n);\n\nforeach ($days as $name => $value)\n{\n $stmt = $conn->prepare('SELECT `employeeID`, SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(`timeOut`, `timeIn`)))) \n AS `totalDay` FROM `timeRecords` WHERE `date` = :myDay\n AND `employeeID` = 1 GROUP BY `employeeID`;');\n $stmt->execute(array(':myDay'=>$value));\n $row = $stmt->fetch();\n $data['Total' . $name] = $row['totalDay'];\n}\n</code></pre>\n\n<p>Because we associate each name to the value of the corresponding variable, please note that you could also use the double dollar sign to do something like :</p>\n\n<pre><code>$day = arrays(\n 'Sunday',\n // etc\n 'Monday',\n);\n\n$stmt = $conn->prepare('SELECT `employeeID`, SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(`timeOut`, `timeIn`)))) \n AS `totalDay` FROM `timeRecords` WHERE `date` = :myDay\n AND `employeeID` = 1 GROUP BY `employeeID`;');\nforeach ($days as $name)\n{\n $stmt->execute(array(':myDay'=>$$value));\n $row = $stmt->fetch();\n $data['Total' . $name] = $row['totalDay'];\n}\n</code></pre>\n\n<p>The whole thing could probably be done in a clearer way if we also wanted to update the code you use to get the string in the different variables.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-27T01:03:11.673",
"Id": "33572",
"Score": "0",
"body": "I edited this answer to create the statement only once. Prepare once, use over and over!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T05:57:05.950",
"Id": "20815",
"ParentId": "20813",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "20815",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T05:09:30.257",
"Id": "20813",
"Score": "0",
"Tags": [
"php",
"mysql"
],
"Title": "Create loop to shorten this code up"
}
|
20813
|
<p>I've been taking a stab at implementing test cases using the Jasmine testing framework. To do so, I've made an application which has a User object. This User object is created by the server, but its ID is stored in a couple of client-side data storage locations. When a new User model is initialized I check those storage locations before fetching User data from the server.</p>
<p>My model is doing too much work in the constructor. This is making it difficult to test. I am wondering how I could improve my architecture to make it easier to test and also if there are any other mistakes with how I am implementing Backbone, Require, and Jasmine.</p>
<pre><code>// A singleton representing the sole logged on user for the program.
// Tries to load itself by ID stored in localStorage and then by chrome.storage.sync.
// If still unloaded, tells the server to create a new user and assumes that identiy.
define(['programState'], function(programState) {
'use strict';
var userIdKey = 'UserId';
// Loads user data by ID from the server, writes the ID
// to client-side storage locations for future loading and then announces
// that the user has been loaded fully.
function fetchUser(shouldSetSyncStorage) {
this.fetch({
success: function(model) {
// TODO: Error handling for writing to sync too much.
// Write to sync as little as possible because it has restricted read/write limits per hour.
if (shouldSetSyncStorage) {
chrome.storage.sync.set({ userIdKey: model.get('id') });
}
localStorage.setItem(userIdKey, model.get('id'));
// Announce that user has loaded so managers can use it to fetch data.
model.trigger('loaded');
},
error: function (error) {
console.error(error);
}
});
}
// User data will be loaded either from cache or server.
var User = Backbone.Model.extend({
defaults: {
id: localStorage.getItem(userIdKey),
name: ''
},
urlRoot: programState.getBaseUrl() + 'User/',
// TODO: I am doing too much work in this initialize constructor.
initialize: function () {
// If user's ID wasn't found in local storage, check sync because its a pc-shareable location, but doesn't work synchronously.
if (this.isNew()) {
var self = this;
// chrome.Storage.sync is cross-computer syncing with restricted read/write amounts.
chrome.storage.sync.get(userIdKey, function (data) {
// Look for a user id in sync, it might be undefined though.
var foundUserId = data[userIdKey];
if (typeof foundUserId === 'undefined') {
// No stored ID found at any client storage spot. Create a new user and use the returned user object.
self.save({}, {
// TODO: I might need to pull properties out of returned server data and manually push into model.
// Currently only care about userId, name can't be updated.
success: function (model) {
// Announce that user has loaded so managers can use it to fetch data.
self.trigger('loaded');
},
error: function(error) {
console.error(error);
}
});
} else {
// Update the model's id to proper value and call fetch to retrieve all data from server.
self.set('id', foundUserId);
fetchUser.call(self, false);
}
});
} else {
// User's ID was found in localStorage. Load immediately.
fetchUser.call(this, true);
}
}
});
// Return an already instantiated User model so that we have only a single instance available.
return new User();
});
</code></pre>
<p>and here is my sole test case currently with notes on the others: </p>
<pre><code>// Test cases for the background's user model. Hopes to ensure that the user
// loads successfully from the server from a client-side id or, alternatively,
// that it is created successfully by the server.
define(['user'], function (user) {
'use strict';
var userIdKey = 'UserId';
describe('The User', function () {
// TODO: The way user is currently written isn't very testable.
// I would like to be able to test more specific actions such as the tests left blank here.
xit('creates when no id found in storage locations', function () {
localStorage.setItem(userIdKey, null);
});
xit('loads from chrome.sync if no id found in localStorage', function () {
});
xit('loads from localStorage', function() {
});
// Makes sure a user loads. A bad test case because the user's loadability is dependent on code
// that isn't modifiable by this method, so I can only infer current state.
it('loads', function () {
var userLoaded = false;
runs(function () {
user.on('loaded', function () {
userLoaded = true;
});
});
waitsFor(function() {
return userLoaded === true;
}, "The user should have loaded.", 5000);
runs(function() {
expect(user.isNew()).toBe(false);
});
});
});
});
</code></pre>
|
[] |
[
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li>The trigger name <code>'loaded'</code> should be a constant, declared on the <code>userIdKey</code> level</li>\n<li>You should not be using <code>console.log</code>, at the very least you should consoledate those calls into a function.</li>\n<li>It seems that if the user needs to be created thru <code>.save()</code>, that you are not storing the <code>userIdKey</code> neither in <code>localStorage</code> nor <code>chrome.storage</code>, rendering most of the code meaningless? I could be wrong.</li>\n<li>It also seems that if you find the <code>localStorage</code> item, you force the writing to <code>chrome.storage</code>, why ? If it's in the <code>localStorage</code>, I would expect it in the <code>chrome.storage</code> as well, at the very least you should try a <code>get</code> before you try a <code>set</code> to reduce writing to <code>chrome.storage</code> ?</li>\n<li><code>fetchUser</code> should be part of the model, then you dont have to use <code>.call()</code></li>\n<li>JsHint could find nothing to complain about</li>\n<li>Commenting might be a tad excessive</li>\n<li>I can easily understand what the code does (that is, if my prior analysis is correct)</li>\n</ul>\n\n<p>I don't think that too much is going in <code>initialize</code>, but I do think that you need to work some more on this code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T15:44:55.907",
"Id": "42963",
"ParentId": "20814",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T05:41:10.120",
"Id": "20814",
"Score": "4",
"Tags": [
"javascript",
"unit-testing",
"backbone.js",
"require.js"
],
"Title": "User model with BackboneJS and RequireJS with test cases in Jasmine"
}
|
20814
|
<p>I need to write a function which will do the following functionalities</p>
<p>I would get a string and a array as input parameters</p>
<p>The string would be like one of the following for example </p>
<pre><code>catalog
level1Cats
level2Cats
</code></pre>
<p>The String array would be containing the data for the strings mentioned above for example</p>
<pre><code>catalog:("12605")
level1Cats:("12605_For the Home") OR level1Cats:("12605_Clothing")
level2Cats:("12605_For the Home_Appliances")
</code></pre>
<p>Now if the String is catalog and the array is the one mentioned above then the output should be <code>12605</code>.</p>
<p>If its is <code>level1Cats</code> then the output should be an array of the following strings </p>
<pre><code>12605_For the Home
12605_Clothing
</code></pre>
<p>I wrote the following code to implement the above mentioned logic It's doing the functionality without a flaw, Can i implement the same in a different and a more efficient way?</p>
<pre><code>public static String[] parseFQ(String fqField, String fqs[]) {
List<String> prefixes = new ArrayList<String>();
if(fqField != null && fqField.length() > 0
&& fqs != null && fqs.length > 0) {
//Get the fq which starts with given field name.
for(String fq : fqs) {
if(fq.startsWith(fqField)) {
fqField = fq;
break;
}
}
boolean parsed = false;
while(!parsed) {
int quoteStart = fqField.indexOf("\"");
int quoteEnd = (quoteStart >= 0) ? fqField.indexOf("\"", quoteStart+1) : -1;
if(quoteEnd > 0) {
prefixes.add(fqField.substring(quoteStart+1, quoteEnd));
fqField = fqField.substring(quoteEnd+1, fqField.length());
} else {
parsed = true;
}
}
}
//Return the prefixes array
return prefixes.toArray(new String[]{});
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T11:10:21.633",
"Id": "33394",
"Score": "0",
"body": "How about using JSON.\n{\n name: \"12605\",\n children: [{\n name: \"For the Home\",\n children: [{\n name: \"Appliances\"\n }]\n }, {\n name: \"Clothing\"\n }]\n}"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T10:55:06.800",
"Id": "33415",
"Score": "0",
"body": "just curiosity, your string contains label and actual value, right? why you can put them into ie map?"
}
] |
[
{
"body": "<p>Below code is more readable and no need of using our logic around single quotes.</p>\n\n<pre><code>String[] w = fqField.split(\"\\\"\");\nfor (int i = 1; i < w.length; i+=2) {\n prefixes.add(w[i]);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T07:17:35.077",
"Id": "20855",
"ParentId": "20819",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T10:21:25.773",
"Id": "20819",
"Score": "2",
"Tags": [
"java",
"algorithm",
"functional-programming"
],
"Title": "Implementing logic in a different way"
}
|
20819
|
<p>I am just about to embark upon a massive job of multi-threading a cost-engine. I could use TPL of which I am very familiar, but would like to leverage the <code>async</code>/<code>await</code> keywords of .NET 4.5 to make life that little bit simpler.</p>
<p>Is my understanding of what is going on correct? How can I improve this design?</p>
<pre><code>CancellationTokenSource cancelSource;
// Mark the event handler with async so you can use await in it.
private async void StartButton_Click(object sender, RoutedEventArgs e)
{
cancelSource = new CancellationTokenSource();
CancellationToken token = cancelSource.Token;
TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
IProgress<ProgressInfo> progressInfo = new Progress<ProgressInfo>(ReportProgress);
await ProcessScript(progressInfo, token, uiScheduler);
// await sets up the following as an Contnuation to
// continue once returned from await.
this.resultsTextBox.AppendText("\nReturn to caller...\n\n");
}
// Class to report progress...
private void ReportProgress(ProgressInfo progressInfo)
{
this.progressBar.Value = progressInfo.PrecentComplete;
this.progressLabel.Content = progressInfo.Message;
}
private async Task ProcessScript(IProgress<ProgressInfo> progressInfo,
CancellationToken token,
TaskScheduler uiScheduler)
{
ProgressInfo pi = new ProgressInfo();
pi.PrecentComplete = 0;
pi.Message = "In script processor...";
progressInfo.Report(pi);
Thread.Sleep(5000); // This is UI Blocking...
string str = this.resultsTextBox.Text;
str = "We have added this => going into await...";
this.resultsTextBox.AppendText(str);
Task task = Task.Factory.StartNew(() => LongRunning(uiScheduler));
pi.Message = "Task set";
pi.PrecentComplete = 50;
progressInfo.Report(pi);
// awaits the long runniing task - non-UI blocking.
await task;
// The await above sets this up as a continuation on the UI thread.
pi.Message = "Task awaited";
pi.PrecentComplete = 95;
progressInfo.Report(pi);
this.resultsTextBox.AppendText("Where are we now??");
return;
}
private bool LongRunning(TaskScheduler uiScheduler)
{
// Allow access to the UI from this background thread from
// the ThreadPool.
Task.Factory.StartNew(() =>
{
this.resultsTextBox.AppendText("\n\nNow in 'LongRunning'!! Waiting 5s simulating HARD WORK!!");
}, CancellationToken.None,
TaskCreationOptions.None,
uiScheduler);
// Simulate hard work.
Thread.Sleep(7000);
Task.Factory.StartNew(() =>
{
this.resultsTextBox.AppendText("\n\n\nHARD WORK COMPLETE!!");
}, CancellationToken.None,
TaskCreationOptions.None,
uiScheduler);
return true;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T14:04:37.743",
"Id": "33403",
"Score": "0",
"body": "You may want to rephrase the question to better fit the code-review style described in the [faq]. There are currently a couple of close requests because questions like *\"Help me understand this code\"* are off topic here. *\"How can I improve this `async`/`await` code\"*, for instance, would be a better fit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T15:50:03.760",
"Id": "33408",
"Score": "0",
"body": "I'm confused. The sight is called \"CodeReview\", I am asking someone to do exactly that, review my code. I will take you advice and make an edit; I hope it helps and thanks for your time..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T20:28:32.020",
"Id": "33423",
"Score": "0",
"body": "What's off topic is to ask us to explain the code to you. As long as you aren't asking that, its okay."
}
] |
[
{
"body": "<p>Yes, your understanding is correct. Note that you're not using <code>CancellationToken</code> provided to <code>ProcessScript</code>. If your operations are cancellable and/or you're using other asynchronous API that accepts <code>CancellationToken</code>s it's highly recommended to pass it through the code, otherwise just don't create the <code>CancellationTokenSource</code>.</p>\n\n<p>Following your comments:</p>\n\n<pre><code>Thread.Sleep(5000); // This is UI Blocking...\n</code></pre>\n\n<p>This is correct since <code>async</code> methods return control to the caller only when something is <code>await</code>ed.</p>\n\n<pre><code>// awaits the long runniing task - non-UI blocking.\nawait task;\n</code></pre>\n\n<p>Here we release the UI thread and running a (computing) task in parallel. The reason I've added \"computing\" is that you're manually spanning a new task using <code>Task.Factory</code>. In case of I/O-related task returned by .NET framework it won't actually represent a new thread as it can wait for external data on the same thread.</p>\n\n<pre><code>// The await above sets this up as a continuation on the UI thread.\n</code></pre>\n\n<p>Correct. See good article <a href=\"http://blogs.msdn.com/b/pfxteam/archive/2012/01/20/10259049.aspx\" rel=\"nofollow\">Await, SynchronizationContext, and Console Apps</a> that describes in details the behavior of <code>await</code>.</p>\n\n<pre><code>// Allow access to the UI from this background thread from \n// the ThreadPool.\nTask.Factory.StartNew(() =>\n {\n this.resultsTextBox.AppendText(\"\\n\\nNow in 'LongRunning'!! Waiting 5s simulating HARD WORK!!\");\n }, CancellationToken.None,\n TaskCreationOptions.None,\n uiScheduler);\n</code></pre>\n\n<p>You're passing <code>TaskScheduler</code> corresponding to UI thread so naturally the code will be safe to work with UI. I would recommend using <code>IProgress<T></code> to update/inform UI about changes in long-running task though, since you may want to separate computation logic from UI-related code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T13:18:06.843",
"Id": "20822",
"ParentId": "20820",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "20822",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T11:30:57.667",
"Id": "20820",
"Score": "6",
"Tags": [
"c#",
".net",
"asynchronous",
"task-parallel-library",
"async-await"
],
"Title": "Use and understanding of async/await in .NET 4.5 +"
}
|
20820
|
<p>I've been writing a small site which is essentially just a service API for other applications but deals with the caching and serving of files. In an effort to make the site as scalable and maintainable as possible I did some research into the most efficient ways to serve files to the client, using PHP for access control. </p>
<p>I figured I'd probably need this sort of functionality again somewhere down the line so I decided to write a small-ish static utility class to serve up files. I'd like feedback on the overall robustness/efficiency of the code as well as comments on how well this follows the HTTP specifications. Improvements are always welcome as I haven't had a chance to really stress test the code yet.</p>
<p>A few of the optimizations are really targeted towards an Apache web-server, but the code itself should work on any PHP box. If anyone knows how to check for the <code>mod_xsendfile</code> module on Nginx/lighttpd accurately that would be a great addition.</p>
<pre><code><?php
class FileServer {
const TRANSFER_CHUNK_SIZE = 8192;
/**
* void serveFile(string $filepath, string $realname, string $mimeType, [bool $publicFile=true, [bool $allowPartial=true, [callable $callback=false ]]])
* Serve the file residing at $filepath to the client.
* @param $filepath The absolute or relative URI to the file
* @param $realname The name to give the client for this file (such as in the Save dialog from a browser)
* @param $mimeType The desired MIME type to send with the response (allows for custom mime-types rather than just using PECLs FileInfo)
* @param $publicFile Whether the file is safe for public access or not (i.e you want to hide the true location of the file from clients). Optional, defaults to true
* @param $allowPartial Whether or not to accept partial requests (via the HTTP_RANGE header) to download the file.
* @param $callback An optional callback to invoke before terminating the script, allows for any cleanup code to run.
* Function singature should match 'int function(int)' where the parameter indicates the status code being sent to the client.
* The function should return the desired exit code
*
* @remarks After calling this function the script will be guaranteed to terminate on all branches after invoking $callback
*/
public static function serveFile($filepath, $realname, $mimeType, $publicFile=true, $allowPartial=true, $callback=false) {
if (!is_file($filepath)) {
header('HTTP/1.0 404 Not Found', true, 404);
exit(self::invokeCallback($callback, 404));
}
$size = filesize($filepath);
$headers = array();
// get all available headers
foreach($_SERVER as $k=>$v) {
$key = strtolower($k);
if (strpos($key, 'http_') === 0) { $key = substr($key, 5); }
$headers[$key] = $v;
}
// pick up any apache http headers that weren't in $_SERVER (need reference as to whether this is even possible?)
if (function_exists('apache_request_headers')) {
$headers += array_change_key_case(apache_request_headers());
}
// check if a range was specified
$range = (isset($headers['range']) ? $headers['range'] : false);
if ($range !== false && $allowPartial) { // need to handle a partial request
if (($ranges = self::parseRange($range, $size)) === false) { // badly formatted range from client
header('HTTP/1.1 416 Requested Range Not Satisfiable', true, 416);
header('Content-Range: bytes */' . $size, true);
exit(self::invokeCallback($callback, 416));
}
}
// Allow for some caching optimization, although in my experience this won't hit too often from browsers.
$ims = !empty($headers['if_modified_since']) ? $headers['if_modified_since'] : false;
$inm = !empty($headers['if_none_match']) ? $headers['if_none_match'] : false;
if (self::cacheControl($filepath, $ims, $inm)) {
header("HTTP/1.1 304 Not Modified", true, 304);
exit(self::invokeCallback($callback, 304));
}
if (function_exists('apache_get_modules')) { // try to optimize with apache (x-sendfile header)
if (in_array('mod_xsendfile', apache_get_modules())) {
// note: X-Sendfile claims to handle HTTP_RANGE headers properly,
// so that is why this is the leading code branch
header('X-Sendfile: ' . $filepath);
header("Content-Type: {$mimeType}");
header("Content-Disposition: attachment; filename=\"{$realname}\"");
exit(self::invokeCallback($callback, 200));
}
}
// Common headers
header("Content-Type: {$mimeType}", true);
header("Accept-Ranges: " . ($acceptPartial ? 'bytes' : 'none'), true);
// send a partial request
if ($range !== false && $allowPartial) {
$contentRanges = self::implodeAssoc($ranges, '-', ',');
// send appropriate partial header info
header("HTTP/1.1 206 Partial Content", true, 206);
header("Content-Range: bytes {$contentRanges}/{$size}", true);
if (($fp = fopen($filepath, 'r')) === false) {
header("HTTP/1.0 500 Internal Server Error", true, 500);
exit(self::invokeCallback($callback, 500));
}
foreach($ranges as $start=>$end) {
$length = ($end - $start) + 1;
// Open up a file stream to serve the chunked request
if ($start > 0 && fseek($fp, $start, SEEK_SET) === -1) {
header("HTTP/1.0 500 Internal Server Error", true, 500);
exit(self::invokeCallback($callback, 500));
}
// Transfer the data, one TRANSFER_CHUNK_SIZE block at a time to
// reduce the memory footprint on larger files
$chunks = (int)($length / self::TRANSFER_CHUNK_SIZE);
$delta = $length % self::TRANSFER_CHUNK_SIZE;
for($i = 0; $i < $chunks; ++$i) {
echo fread($fp, self::TRANSFER_CHUNK_SIZE);
}
// handle the residual data that didn't align along TRANSFER_CHUNK_SIZE
echo fread($fp, $delta);
}
fclose($fp);
exit(self::invokeCallback($callback, 206));
}
// By now it's a pretty grim situation for file i/o.
// Possible redirect opportunity using the Location header. Note: this only works
// on public documents, $publicFile should be false when serving restricted content.
// Also, the file must reside in the document root to be accessible by setting Location
if ($publicFile && ($url = self::filepathToUrl($filepath, true)) !== false) {
header("Location: {$url}", true);
exit(self::invokeCallback($callback, 302));
}
// Give up, going to have to use PHP :)
header("Content-Length: {$size}", true);
header("Content-Disposition: attachment; filename=\"{$realname}\"", true);
readfile($filepath);
exit(self::invokeCallback($callback, 200));
}
// Pretty self-explanatory, just a helper to abstract the way ETags are generated
public static function generateETag($filepath, $salt='') {
return hash('sha256', $filepath . $salt);
}
// Another lazy helper to validate a callback and invoke it, or return a default value
private static function invokeCallback($callback, $response, $default=0) {
if (is_callable($callback)) {
return call_user_func($callback, $response);
}
return $default;
}
private static function cacheControl($filepath, $ifModifiedSince, $ifNoneMatch) {
// Do the caching housekeeping.
// Function returns true if the cached version is up-to-date (i.e a 304 is acceptable), or false otherwise
$mtime = filemtime($filepath);
$time = gmdate('D, d M Y H:i:s \G\M\T', $mtime);
$etag = self::generateETag($filepath, $mtime);
if ($ifModifiedSince !== false || $ifNoneMatch !== false) {
if ($ifModifiedSince == $time || $etag == str_replace('"', '', stripslashes($ifNoneMatch))) {
return true;
}
}
// send some validation headers for cache-control later
header('Last-Modified: ' . $time, true);
header('Cache-Control: must-revalidate', true);
header('ETag: ' . $etag, true);
return false;
}
private static function implodeAssoc($assoc, $keyValueSeparator, $entrySeparator) {
// A really, really lazy way to implode an array by first delimiting the keys and values by one delimiter
// then delimiting this new array by another delimiter
return implode($entrySeparator,
array_map(function($k,$v) use($keyValueSeparator) {
return "{$k}{$keyValueSeparator}{$v}";
}, array_keys($assoc), $assoc)
);
}
private static function filepathToUrl($filepath, $relative=false) {
// normalize to *Nix path separators
$root = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']);
$filepath = str_replace('\\', '/', realpath($filepath));
$relpath = str_replace($root, '', $filepath);
if ($filepath === $relpath && $filepath[0] !== '/') // can't convert the absolute path to a URL because it's outside the document root
return false;
if ($relpath[0] != '/') $relpath = '/' . $relpath;
if (!$relative) {
$protocol = "http" . ((empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off') ? '' : 's') . '://';
return $protocol . $_SERVER['SERVER_NAME'] . $relpath;
}
return $relpath;
}
/**
* Parse a HTTP_RANGE header value into an array of 'start' => 'end' ranges
* @param $range the raw HTTP_RANGE value to parse
* @param $size the size of the file that is being partially requested
*
* @return an associative array of 'start' => 'end' integer pairs if the range is valid, false otherwise
*/
private static function parseRange($range, $filesize) {
if (!preg_match('/^bytes=\\d*-\\d*(,\d*-\d*)*$/', $range)) {
return false;
}
$ranges = explode(',', substr($range, 6));
$specs = array();
for($i = 0; $i < count($ranges); ++$i) {
$parts = explode('-', $ranges[$i]);
if (empty($parts[0]) && empty($parts[1])) {
return false; //have to specify at least one side of the range
}
// Try to comply with the standard as best I understand it here
$end = !empty($parts[1]) ? intval($parts[1]) : $filesize - 1;
$start = !empty($parts[0]) ? intval($parts[0]) : ($filesize - ($end + 1));
if ($end > ($filesize - 1)) $end = $filesize - 1;
if ($start > $end) {
return false;
}
$specs[$start] = $end;
}
return $specs;
}
}
?>
</code></pre>
<p>Appreciate the advice.</p>
|
[] |
[
{
"body": "<h2>That's a lot of code</h2>\n\n<p>It looks like it works but since it's apache specific what's wrong with using <a href=\"http://php.net/manual/es/function.virtual.php\" rel=\"nofollow\">virtual</a>? It's an apache-specific php function for serving files. I.e.</p>\n\n<pre><code>public static function serveFile($filepath, $realname, $mimeType, $publicFile=true, $allowPartial=true, $callback=false) {\n ...\n\n // do whatever and then just hand the file to apache to handle\n virtual($filepath);\n exit();\n}\n</code></pre>\n\n<h2>Not testable</h2>\n\n<p>The biggest failing with the code as written is that you can't unit test it - I.e. you can't use <a href=\"http://phpunit.de\" rel=\"nofollow\">PHPUnit</a>, mock things and verify that it handles all circumstances you think it can. The main roadblock to this is putting <code>exit()</code> directly in the same method that does things. A better idea is to do:</p>\n\n<pre><code>public static function whatever() {\n ...\n static::_stop();\n}\n\nprotected static function _stop($reason = null) {\n exit($reason);\n}\n</code></pre>\n\n<p>In this way you <em>can</em> mock the test class, or simply subclass it and override <code>_stop</code> so that it does not exit execution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-29T07:59:47.230",
"Id": "33741",
"Score": "0",
"body": "Thanks for the reply, I hadn't heard of the `virtual` method before today, so I'll be sure to look into that as an alternate method when it's available. Presumably it doesn't work with `range` requests but it'd be a nice alternative to the final `readfile` case on Apache servers. As for the testable aspect, I can't say I spent much time considering it as a lot of the branches are server-specific and not really something a unit-test would be able to handle anyway. Valid point though. Thanks again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-29T09:20:52.883",
"Id": "33744",
"Score": "0",
"body": "why would you presume that passing a request back to apache does not handle range requests? Code you can't test - is code you cannot be sure actually works :). Being server-specific does not affect whether code should be testable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-30T15:36:43.547",
"Id": "33836",
"Score": "0",
"body": "I said using `virtual` is unlikely to check the HTTP_RANGE header. X-Sendfile had to write specific code to handle this. Just because code does not work specifically with your chosen testing suite, does not make it `untestable`; I ran few of my own tests against this."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T08:29:39.970",
"Id": "20889",
"ParentId": "20823",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T13:32:46.957",
"Id": "20823",
"Score": "1",
"Tags": [
"php",
"optimization"
],
"Title": "PHP File Serving code"
}
|
20823
|
<p>I'm implementing a Java version of the game <a href="http://en.wikipedia.org/wiki/Mastermind_%28board_game%29" rel="nofollow">Mastermind</a>. </p>
<p>My version uses numbers to represent colors, for example <code>2315</code>. This function compares a string of numbers to the secret <code>code</code> the object stored. It works, but I'm wondering if this could be done in a more elegant way.</p>
<pre><code>public Answer evaluate(String guess) {
boolean[] codeUsed = new boolean[code.length()];
boolean[] guessUsed = new boolean[guess.length()];
int correct = 0;
int match = 0;
// Compare correct color and position
for (int i = 0; i < code.length(); i++) {
if (code.charAt(i) == guess.charAt(i)) {
correct++;
codeUsed[i] = guessUsed[i] = true;
}
}
// Compare matching colors for "pins" that were not used
for (int i = 0; i < code.length(); i++) {
for (int j = 0; j < guess.length(); j++) {
if (!codeUsed[i] && !guessUsed[j] && code.charAt(i) == guess.charAt(j)) {
match++;
codeUsed[i] = guessUsed[j] = true;
break;
}
}
}
return new Answer(guess, correct, match, guess.length() - correct - match);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T16:22:10.877",
"Id": "33409",
"Score": "0",
"body": "Why do you return `guess` also?\nAnd what is `guess.length() - correct - match`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T16:34:09.187",
"Id": "33410",
"Score": "0",
"body": "The Answer is used to print out the results for a given attempt. Its toString() method for example returns a string \"1234 -> 0 correct, 2 match, 2 wrong\". guess.length() - correct- match are the `wrong` pins."
}
] |
[
{
"body": "<p>The algorithm is short and concise. There might be a more clever way to do it, but it would likely be less readable. </p>\n\n<p>This code will break if the <code>guess</code> is not the same length as the code. An empty string causes an out of out of bounds exception. A string longer than the code could cause other problems. You don't show what <code>Answer</code> is, but it looks like the last argument is the number of incorrect pins. This could lead to having more incorrect pins than there are in the code. You need to protect against each of these cases.</p>\n\n<p>Since you are using strings, the value could contain characters other than digits. A guess with invalid characters should be treated differently than an incorrect guess.</p>\n\n<p>You can add a check before the second loop to see if the all of the characters are correct. In that case you would skip over a N x M loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T16:37:21.317",
"Id": "33411",
"Score": "0",
"body": "Those checks are done in another method which returns status messages (result for given string, remaining tries, Conratulations you won, **wrong input**). Should those checks be performed additionally in this method?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T16:05:49.500",
"Id": "20828",
"ParentId": "20825",
"Score": "2"
}
},
{
"body": "<p>There's an alternative and slightly simpler algorithm that works by counting the number of times each color appears in the code and in the answer. The total number of pins (white and black) in the evaluation is then given by the sum (over all colors) of whichever is the smaller of these. Here's how you might implement it (I've written <code>COLORS</code> for the number of different colors):</p>\n\n<pre><code>public Answer evaluate(String guess) {\n // Total number of pins in the answer.\n int pins = 0;\n\n // Number of black pins in the answer.\n int black = 0;\n\n // Number of times each color appears in the code and the guess.\n int[] codeColorCount = new int[COLORS];\n int[] guessColorCount = new int[COLORS];\n\n for (int i = 0; i < code.length(); i++) {\n char c = code.charAt(i);\n char g = guess.charAt(i);\n ++ codeColorCount[c.getNumericValue()];\n ++ guessColorCount[g.getNumericValue()];\n if (c == g) {\n ++ black;\n }\n }\n\n for (int i = 0; i < COLORS; i++) {\n pins += Math.min(codeColorCount[i], guessColorCount[i]);\n }\n\n return new Answer(guess, black, pins - black, guess.length() - pins);\n}\n</code></pre>\n\n<p>(Since the numbers in <code>codeColorCount</code> never change during a game, you might decide to cache them.)</p>\n\n<p>In some languages this algorithm can be expressed tersely, for example in Python you could write it like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from collections import Counter\ndef evaluate(code, guess):\n pins = sum((Counter(code) & Counter(guess)).values())\n black = sum(c == g for c, g in zip(code, guess))\n return guess, black, pins - black, len(guess) - pins\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T17:46:22.547",
"Id": "20831",
"ParentId": "20825",
"Score": "2"
}
},
{
"body": "<pre><code>boolean[] codeUsed = new boolean[code.length()];\nboolean[] guessUsed = new boolean[guess.length()];\ncodeUsed[i] = guessUsed[i] = true;\nif (!codeUsed[i] && !guessUsed[j] && ...) {\ncodeUsed[i] = guessUsed[j] = true;\n</code></pre>\n\n<p>I can not see why both of them are used? You always set both of them to the same value and access both of them. So one can safely be removed.</p>\n\n<pre><code>return new Answer(guess, correct, match, guess.length() - correct - match);\n</code></pre>\n\n<p>In general, you should try to reduce the number of arguments. In this case, you do not need the fourth argument, because you can easily calculate it inside the Answer object.</p>\n\n<pre><code>for (int i = 0; i < code.length(); i++) {\n for (int j = 0; j < guess.length(); j++) {\n if (!codeUsed[i] && !guessUsed[j] && code.charAt(i) == guess.charAt(j)) {\n match++;\n codeUsed[i] = guessUsed[j] = true;\n break;\n }\n }\n}\n</code></pre>\n\n<p>You do not need to keep track of the already used parts. Just do a <code>match = correct - match</code>or something like this after you have counted all matches. To simplify this, i would count the appearance in a temporary string, which is reduced for every hit.</p>\n\n<p>I would add some error checking for the guess argument. Could be helpful if something weird happens.</p>\n\n<p>All combined, it could look like this:</p>\n\n<pre><code>public Answer evaluate(final String guess) {\n if (guess == null || guess.isEmpty() || guess.length() != code.length())\n throw new IllegalArgumentException(\"Invalid input. guess: \" + guess + \", code: \" + code);\n\n int correct = 0;\n int matchAll = 0;\n\n String reducedString = guess;\n for (int i = 0; i < code.length(); i++) {\n if (code.charAt(i) == guess.charAt(i))\n ++correct;\n\n final String currentCharAsString = String.valueOf(code.charAt(i));\n if (reducedString.contains(currentCharAsString))\n {\n ++matchAll;\n reducedString = reducedString.replaceFirst(Pattern.quote(currentCharAsString), \"\");\n }\n }\n return new Answer(guess, correct, matchAll - correct);\n}\n</code></pre>\n\n<p>After all, you should write some unit tests to check the code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T22:45:59.013",
"Id": "20844",
"ParentId": "20825",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20831",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T15:07:02.527",
"Id": "20825",
"Score": "1",
"Tags": [
"java",
"optimization",
"algorithm"
],
"Title": "Evaluating result for mastermind comparison"
}
|
20825
|
<p>I have a class file that would be used to connect and execute queries into the database. The only thing I am confused about is this: do you really need to drop tables and re-create them everytime you run the application? Or does this depend on your coding or class file? I followed a tutorial on the Internet and kind of recycled the class file it provided to cope with my needs. </p>
<p>Do give me suggestions to better my class file if needed. I am a bit new to Java/Android and do not know the best way to do these, though I would love to learn how.</p>
<pre><code>package com.thesis.menubook;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBConnect {
int id = 0;
public static final String KEY_ROWID = "_id";
public static final String KEY_IP = "saved_ip_address";
private static final String TAG = "DBConnect";
private static final String DATABASE_NAME = "MenuBook";
private static final String DATABASE_TABLE_1 = "ipaddress";
private static final String DATABASE_TABLE_2 = "menudb";
private static final String DATABASE_TABLE_3 = "recipelist";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
"CREATE TABLE ipaddress (_id integer primary key autoincrement, " +
"saved_ip_address text not null " +
"); "+
"CREATE TABLE menudb (menu_ID varchar(255) NOT NULL, " +
"menu_name longtext, " +
"menu_price double DEFAULT NULL, " +
"menu_description longtext, " +
"menu_category text, " +
"menu_status text, " +
"PRIMARY KEY (menu_ID) " +
"); "+
"CREATE TABLE recipelist (recipe_ID int(11) NOT NULL AUTOINCREMENT, " +
"menu_ID varchar(255) DEFAULT NULL, " +
"stock_ID varchar(255) DEFAULT NULL, " +
"recipe_quantity double DEFAULT NULL, " +
"PRIMARY KEY (recipe_ID) " +
");" ;
private final Context context;
private static DatabaseHelper DBHelper;
private static SQLiteDatabase db;
public DBConnect(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
public static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS ipaddress");
db.execSQL("DROP TABLE IF EXISTS menudb");
db.execSQL("DROP TABLE IF EXISTS recipelist");
onCreate(db);
}
}
//---opens the database---
public DBConnect open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a title into the database---
public long insertIPAddress(String ipaddress)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_IP, ipaddress);
return db.insert(DATABASE_TABLE_1, null, initialValues);
}
}
</code></pre>
<p>I haven't finished this class file yet since I am still looking for more codes that I could use thus there are only 3 methods available here as of now. I am using it on an <code>onClick</code> event on one activity like this.</p>
<pre><code>ipaddress = (EditText) findViewById(R.id.ipAddress);
ip = ipaddress.getText().toString();
db.open();
db.insertIPAddress(ip);
db.close();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T22:38:39.220",
"Id": "33483",
"Score": "1",
"body": "Heck no, you don't need to be constantly creating/dropping the tables. For one, thing, that's terribly 'expensive'. Also, what happens when users come back to the app - they'd complain about missing data! There should be a way to do 'one time setup', either as part of the android install process, or simply the first time your app runs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T18:08:51.983",
"Id": "59341",
"Score": "0",
"body": "@Clockwork-Muse: `onCreate` and `onUpgrade` are called by the Android framework only when necessary, so this code is not constantly creating/dropping tables."
}
] |
[
{
"body": "<p>If you're using one instance of <code>SQLiteOpenHelper</code> across your application (which you should be doing), you should never need to call <code>close</code> on it or the <code>SQLiteDatabase</code> object.</p>\n\n<p>Why do you need the <code>DBConnect</code> class? See <a href=\"https://codereview.stackexchange.com/a/36230/8891\">this answer for another question</a> for a proper thread-safe <code>SQLiteOpenHelper</code> subclass. If you follow that example, this would be its usage:</p>\n\n<pre><code>DatabaseHelper dbHelper = DatabaseHelper.getInstance(getActivity());\ndbHelper.insertIPAddress(ipAddr);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T18:05:03.000",
"Id": "36232",
"ParentId": "20827",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T15:53:15.007",
"Id": "20827",
"Score": "2",
"Tags": [
"java",
"beginner",
"android",
"sqlite"
],
"Title": "SQLite class to manage recipes for an Android application"
}
|
20827
|
<p>I have a view model with properties that represent years and months: </p>
<pre><code>public IEnumerable<SelectListItem> Years
{
get
{
return new SelectList(
Enumerable.Range(1900, 112)
.OrderByDescending(year => year)
.Select(year => new SelectListItem
{
Value = year.ToString(CultureInfo.InvariantCulture),
Text = year.ToString(CultureInfo.InvariantCulture)
}
), "Value", "Text");
}
}
public IEnumerable<SelectListItem> Months
{
get
{
return new SelectList(
Enumerable.Range(1, 12)
.OrderByDescending(month => month)
.Select(month => new SelectListItem
{
Value = month.ToString(CultureInfo.InvariantCulture),
Text = month < 10 ? string.Format("0{0}", month) : month.ToString(CultureInfo.InvariantCulture)
}
), "Value", "Text");
}
}
</code></pre>
<p>I definitely use copy & paste approach here. How can I refactor this code? Maybe somehow passing the numbers as parameters to some helper method?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T19:29:57.780",
"Id": "33422",
"Score": "2",
"body": "You don't need to order anything here, `.Reverse()` is simpler and more efficient. Also, do you really want to have the months backwards, or is that a copy & paste error?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T08:26:24.013",
"Id": "33435",
"Score": "0",
"body": "thanks @svick! I really do not need orderByDescending here))"
}
] |
[
{
"body": "<p>You're over-creating these objects on each call. Cache static values:</p>\n\n<pre><code> private static readonly IEnumerable<SelectListItem> years = new SelectList(\n Enumerable.Range(1900, 112)\n .OrderByDescending(year => year)\n .Select(year => new SelectListItem\n {\n Value = year.ToString(CultureInfo.InvariantCulture),\n Text = year.ToString(CultureInfo.InvariantCulture)\n }),\n \"Value\",\n \"Text\");\n\n private static readonly IEnumerable<SelectListItem> months = new SelectList(\n Enumerable.Range(1, 12)\n .OrderByDescending(month => month)\n .Select(month => new SelectListItem\n {\n Value = month.ToString(CultureInfo.InvariantCulture),\n Text = month < 10 ? string.Format(\"0{0}\", month) : month.ToString(CultureInfo.InvariantCulture)\n }),\n \"Value\",\n \"Text\");\n\n public IEnumerable<SelectListItem> Years\n {\n get\n {\n return years;\n }\n }\n\n public IEnumerable<SelectListItem> Months\n {\n get\n {\n return months;\n }\n }\n</code></pre>\n\n<p>As for creating a helper method? I likely wouldn't. These mean two different things - years and months. Keep that logic separate.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T18:20:07.363",
"Id": "20833",
"ParentId": "20832",
"Score": "2"
}
},
{
"body": "<p>You can use a format string to ensure that there are at least 2 digits in the format without having to check first. The format: <code>{0:00}</code> ensures there are at least 2 digits, but allows for more. It will prefix 0 to any single-digit input.</p>\n\n<p><code>string.Format</code> also has an overload which takes in an <code>IFormatProvider</code>, so my personal preference is just to collapse that into the <code>string.Format</code> call. It also happens to line up nicely :)</p>\n\n<p>With that, you can create a method with appropriate parameters which can handle both cases:</p>\n\n<pre><code> public IEnumerable<SelectListItem> Years2 { get { return BuildList (1900, 112); } }\n public IEnumerable<SelectListItem> Months2 { get { return BuildList (1, 12); } }\n\n public IEnumerable<SelectListItem> BuildList (int start, int count)\n {\n return new SelectList (\n Enumerable.Range (start, count)\n .OrderByDescending (val => val)\n .Select (val => new SelectListItem\n {\n Value = val.ToString (CultureInfo.InvariantCulture),\n Text = string.Format (CultureInfo.InvariantCulture, \"{0:00}\", val)\n }\n ), \"Value\", \"Text\");\n }\n</code></pre>\n\n<p>Note: I suffixed my properties with 2 so I could run them side-by-side and compare results to be sure I didn't miss anything.</p>\n\n<p>Note2: as Jesse suggests, you should ideally cache the results.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T19:28:51.103",
"Id": "33421",
"Score": "0",
"body": "This feels like too much sharing for the format part to me. Just because you know that years are always going to have at least 4 digits doesn't mean you should use the `00` format for them."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T18:21:00.747",
"Id": "20834",
"ParentId": "20832",
"Score": "3"
}
},
{
"body": "<p>I dislike the way you specify your year range, especially the upper bound. It looks like you want the current year as upper bound, and not a magic value of <code>112</code> years since the start.</p>\n\n<p><code>112</code> is bad in two ways: </p>\n\n<ol>\n<li>Its meaning isn't clear by itself, it only becomes the year <code>2011</code> when you look at the start value <code>1900</code></li>\n<li>You probably need to update it every year. It seems unlikely that you want to have a constant upper bound of <code>2011</code> forever.</li>\n</ol>\n\n<p>I'd use something like:</p>\n\n<pre><code>int startYear = 1900;\nint endYear = DateTime.Today.Year;\n\nvar years = Enumerable.Range(StartYear, endYear - startYear + 1).Reverse();\n</code></pre>\n\n<p>Potentially factoring out the current date/year to a property of the current viewmodel or a service so your helper method doesn't access any external mutable state (<code>DateTime.Today</code>). </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-05T10:40:39.560",
"Id": "34222",
"Score": "0",
"body": "thanks! it's a great insight to use DateTime.Today.Year;"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-04T14:51:02.870",
"Id": "21293",
"ParentId": "20832",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "20834",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T17:58:58.923",
"Id": "20832",
"Score": "4",
"Tags": [
"c#",
"asp.net",
"datetime",
"asp.net-mvc-3"
],
"Title": "View model with properties that represent years and months"
}
|
20832
|
<p>In the interests of improving my Python coding skills, I wanted to post a program I recently built and get it critiqued by you fine folks. Please let me know where you think I might improve this program. I tried to stick to PEP8 and follow other standard conventions mentioned here.</p>
<pre><code>### This program will filter a list of tweets by a certain
### threshold of retweets divided by followers
# Fetch tweets from Twitter list
# Store them in SQlite3
# Query database
# Output an HTML file with the results
# Clean database of data older than a month
import json
import re
import datetime
import time
import urllib
import sqlite3
params = {
'threshold': 0.02, # retweet / follower threshold percentage.
'db_file': '/blah/blah/blah/news_tweets.sqlite',
'tweet_list_url': 'https://api.twitter.com/1/lists/statuses.json'\
'?slug=my-news-sources&owner_screen_name=mshea&page=',
'output_file': '/blah/blah/blah/news.html',
'output_weekly_file': '/blah/blah/blah/weekly_news.html',
'page_header': '''<!DOCTYPE html>
<meta name="viewport" content="user-scalable=yes, width=device-width">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<style>
body { font-family: Verdana, Geneva, sans-serif; color:#333; max-width:35em;
margin:auto; }
.score { font-size: .6em; color: #999; }
ul { list-style:none; }
/* Desktops and laptops ----------- */
@media only screen and (min-width : 321px) {
ul, h1, .updated { margin:0; padding:0; }
li { padding-left: 1.3em; padding-bottom: 1em; line-height: 1.6em;
text-indent: -1em; }
ul { list-style:none; }
h1 { font-weight: normal; font-size: 1.4em; padding-top: 1em;
padding-bottom: 1em; }
.updated { font-size:.8em; text-align: center; padding-bottom: 1em;}
}
/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-width : 320px) and (max-width : 480px) {
ul, h1, .updated { margin:0; padding:0; }
li, h1, .updated { border-top:1px #ddd solid; }
li { font-size:.9em; line-height:1.5em; padding:.5em; text-indent: 0; }
.updated { font-size:.8em; padding: .8em; text-align: center; }
h1 { font-size:1.2em; font-weight: normal; padding:.5em;
text-align: center; background: #eee;}
}
</style>
<title>News</title>
'''
}
conn = sqlite3.connect(params['db_file'])
# Filter strange character encodings to pure ascii.
def only_ascii(char):
if ord(char) < 32 or ord(char) > 127: return ''
else: return char
# Fetch tweets from the list and dump them into SQLite3
def fetch_tweets(tweet_list_url):
jsonaggregate = []
for jsonpagecount in range (1,30):
fh = urllib.urlopen(tweet_list_url+str(jsonpagecount))
data = fh.read()
try:
jsonaggregate += json.loads(data)
except:
print 'failed on page '+str(jsonpagecount)
print 'parsing twitter json page '+str(jsonpagecount)
print str(len(jsonaggregate))+ ' tweets parsed...'
# Dump tweets to SQlite
tweetinsertquery = conn.cursor()
for item in jsonaggregate:
tweet_time = time.strptime(item['created_at'],
'%a %b %d %H:%M:%S +0000 %Y')
timestring = time.strftime('%Y-%m-%dT%H:%M:%S', tweet_time)
tweetinsertquery.execute('''
insert or replace into tweets
values (?, ?, ?, ?, ?, ?, ?, ?)
''',
[
item['id_str'],
item['text'],
timestring,
item['favorited'],
item['user']['screen_name'],
item['retweet_count'],
item['user']['followers_count'],
item['user']['location']
]
)
conn.commit()
def link_text(text):
return re.sub('http://[^ ,]*', lambda t: '<a href="%s">%s</a>'
% (t.group(0), t.group(0)), text)
def build_page(): #Pull tweets from the database
daycache = ''
first_header = 1
tweetquery = conn.cursor()
tweetquery.execute('''
select *, ((retweet_count*100.0) / (follower_count*100.0))
from tweets
where (retweet_count*1.0 / follower_count*1.0 > (? / 100))
and tweet like '%http%'
and datetime(created_at) > date('now','-6 day')
order by created_at desc;'''
, [params['threshold']])
fileoutput = [params['page_header']]
for result in tweetquery:
id, tweet, created_at, favorited, screen_name, \
retweet_count, follower_count, location, score = result
time_struct = time.strptime(created_at, '%Y-%m-%dT%H:%M:%S')
currentday = time.strftime('%A, %d %B',
time.localtime(time.mktime(time_struct)-14400))
if currentday != daycache:
daycache = currentday
if first_header != 1: #flag so we don't add an extra </ul>
fileoutput.append('</ul>\n')
else:
first_header = 0
fileoutput.append('<h1>%s</h1>\n<ul>\n' % daycache)
score = str(round(score*100, 3)).replace("0.",".")
fileoutput.append('''<li><strong>%(screen_name)s:</strong>'''
''' %(tweet)s <span class="score">%(score)s</span>'''
% { 'screen_name': screen_name,
'tweet': filter(only_ascii, link_text(tweet)),
'score': score
})
# Query for the top_weekly_tweets
tweetquery.execute('''
select *, ((retweet_count*100.0) / (follower_count*100.0))
as value_rank
from tweets
where datetime(created_at) > date('now','-6 day')
and tweet like '%http%'
order by value_rank desc limit 50;
''')
fileoutput.append('\n<h1>Top Weekly Links</h1>\n<ul>')
for result in tweetquery:
id, tweet, created_at, favorited, screen_name, \
retweet_count, follower_count, location, score = result
score = str(round(score*100, 3)).replace("0.",".")
fileoutput.append('<li><strong>%(screen_name)s</strong>: ' \
'%(tweet)s <span class="score">%(score)s</span></li>\n'
% {
'screen_name': screen_name,
'tweet': filter(only_ascii, link_text(tweet)),
'score': score
})
fileoutput.append('</ul>\n<p class="updated">Updated %(updated)s</p>'
% {'updated': time.strftime("%d %B at %I:%M %p", time.localtime()) })
with open(params['output_file'], "w") as outputfile:
outputfile.write(''.join(fileoutput).encode("utf8"))
def purge_database():
cleandatabase = conn.cursor()
cleandatabase.execute('''
delete from tweets
where datetime(created_at) < date('now','-14 day');
''')
cleandatabase.execute('vacuum;')
conn.commit()
fetch_tweets(params['tweet_list_url'])
build_page()
purge_database()
</code></pre>
|
[] |
[
{
"body": "<pre><code>### This program will filter a list of tweets by a certain\n### threshold of retweets divided by followers\n\n# Fetch tweets from Twitter list\n# Store them in SQlite3\n# Query database\n# Output an HTML file with the results\n# Clean database of data older than a month\n\nimport json\nimport re\nimport datetime\nimport time\nimport urllib\nimport sqlite3\n\nparams = {\n</code></pre>\n\n<p>By python convention, global constants should be ALL_CAPS</p>\n\n<pre><code> 'threshold': 0.02, # retweet / follower threshold percentage.\n 'db_file': '/blah/blah/blah/news_tweets.sqlite',\n 'tweet_list_url': 'https://api.twitter.com/1/lists/statuses.json'\\\n '?slug=my-news-sources&owner_screen_name=mshea&page=',\n 'output_file': '/blah/blah/blah/news.html',\n 'output_weekly_file': '/blah/blah/blah/weekly_news.html',\n</code></pre>\n\n<p>This is a rather unusual way of handling parameters. Typically, we define global constants not a dict of parameters. I can't say there is anything really bad about the approach, but I don't see how it helps much either.</p>\n\n<pre><code> 'page_header': '''<!DOCTYPE html>\n<meta name=\"viewport\" content=\"user-scalable=yes, width=device-width\">\n<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">\n<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black\">\n<style>\nbody { font-family: Verdana, Geneva, sans-serif; color:#333; max-width:35em; \n margin:auto; }\n.score { font-size: .6em; color: #999; }\nul { list-style:none; }\n\n/* Desktops and laptops ----------- */\n@media only screen and (min-width : 321px) {\n ul, h1, .updated { margin:0; padding:0; }\n li { padding-left: 1.3em; padding-bottom: 1em; line-height: 1.6em; \n text-indent: -1em; }\n ul { list-style:none; }\n h1 { font-weight: normal; font-size: 1.4em; padding-top: 1em; \n padding-bottom: 1em; }\n .updated { font-size:.8em; text-align: center; padding-bottom: 1em;}\n}\n\n/* Smartphones (portrait and landscape) ----------- */\n@media only screen and (min-width : 320px) and (max-width : 480px) {\n ul, h1, .updated { margin:0; padding:0; }\n li, h1, .updated { border-top:1px #ddd solid; }\n li { font-size:.9em; line-height:1.5em; padding:.5em; text-indent: 0; }\n .updated { font-size:.8em; padding: .8em; text-align: center; }\n h1 { font-size:1.2em; font-weight: normal; padding:.5em; \n text-align: center; background: #eee;}\n}\n</style>\n\n<title>News</title>\n'''\n</code></pre>\n\n<p>For that amount of stuff I really suggest looking into using a template file.</p>\n\n<pre><code>}\n\nconn = sqlite3.connect(params['db_file'])\n\n# Filter strange character encodings to pure ascii.\ndef only_ascii(char):\n if ord(char) < 32 or ord(char) > 127: return ''\n else: return char\n\n# Fetch tweets from the list and dump them into SQLite3\ndef fetch_tweets(tweet_list_url):\n</code></pre>\n\n<p>This function is named <code>fetch_tweets</code>, but it also dumps, so the name doesn't quite fit</p>\n\n<pre><code> jsonaggregate = []\n</code></pre>\n\n<p>I'd call that <code>json_aggregate</code></p>\n\n<pre><code> for jsonpagecount in range (1,30):\n fh = urllib.urlopen(tweet_list_url+str(jsonpagecount))\n data = fh.read()\n</code></pre>\n\n<p>fh?</p>\n\n<pre><code> try:\n jsonaggregate += json.loads(data)\n</code></pre>\n\n<p>Why not use <code>json.load(fh)</code>?</p>\n\n<pre><code> except:\n</code></pre>\n\n<p>Don't do this, catch the specific exceptions you want to handle here. As it is you may hide other things going wrong</p>\n\n<pre><code> print 'failed on page '+str(jsonpagecount)\n print 'parsing twitter json page '+str(jsonpagecount)\n</code></pre>\n\n<p>No you aren't, you've already parsed them</p>\n\n<pre><code> print str(len(jsonaggregate))+ ' tweets parsed...'\n\n # Dump tweets to SQlite\n tweetinsertquery = conn.cursor()\n</code></pre>\n\n<p>Its a cursor not a query</p>\n\n<pre><code> for item in jsonaggregate:\n tweet_time = time.strptime(item['created_at'], \n '%a %b %d %H:%M:%S +0000 %Y')\n timestring = time.strftime('%Y-%m-%dT%H:%M:%S', tweet_time)\n</code></pre>\n\n<p>I'd pull those last two lines to a <code>convert_timestamp</code> function</p>\n\n<pre><code> tweetinsertquery.execute('''\n insert or replace into tweets \n values (?, ?, ?, ?, ?, ?, ?, ?)\n ''',\n [\n item['id_str'],\n item['text'],\n timestring,\n item['favorited'],\n item['user']['screen_name'],\n item['retweet_count'],\n item['user']['followers_count'],\n item['user']['location']\n ]\n</code></pre>\n\n<p>This should really be a tuple, not a list. I'd look into using executemany or prepared statements.</p>\n\n<pre><code> )\n conn.commit()\n\ndef link_text(text):\n return re.sub('http://[^ ,]*', lambda t: '<a href=\"%s\">%s</a>'\n % (t.group(0), t.group(0)), text)\n\ndef build_page(): #Pull tweets from the database\n daycache = ''\n first_header = 1\n tweetquery = conn.cursor()\n tweetquery.execute('''\n select *, ((retweet_count*100.0) / (follower_count*100.0))\n from tweets \n where (retweet_count*1.0 / follower_count*1.0 > (? / 100)) \n and tweet like '%http%' \n and datetime(created_at) > date('now','-6 day') \n order by created_at desc;'''\n , [params['threshold']])\n fileoutput = [params['page_header']]\n for result in tweetquery:\n id, tweet, created_at, favorited, screen_name, \\\n retweet_count, follower_count, location, score = result\n time_struct = time.strptime(created_at, '%Y-%m-%dT%H:%M:%S')\n currentday = time.strftime('%A, %d %B', \n time.localtime(time.mktime(time_struct)-14400))\n if currentday != daycache:\n daycache = currentday\n if first_header != 1: #flag so we don't add an extra </ul>\n fileoutput.append('</ul>\\n')\n else:\n first_header = 0 \n fileoutput.append('<h1>%s</h1>\\n<ul>\\n' % daycache)\n score = str(round(score*100, 3)).replace(\"0.\",\".\")\n fileoutput.append('''<li><strong>%(screen_name)s:</strong>'''\n ''' %(tweet)s <span class=\"score\">%(score)s</span>'''\n % { 'screen_name': screen_name,\n 'tweet': filter(only_ascii, link_text(tweet)),\n 'score': score\n })\n</code></pre>\n\n<p>All this HTML output would be cleaner to use a proper template such as those provided by Mako.</p>\n\n<pre><code> # Query for the top_weekly_tweets\n tweetquery.execute('''\n select *, ((retweet_count*100.0) / (follower_count*100.0)) \n as value_rank \n from tweets \n where datetime(created_at) > date('now','-6 day') \n and tweet like '%http%' \n order by value_rank desc limit 50;\n ''')\n fileoutput.append('\\n<h1>Top Weekly Links</h1>\\n<ul>')\n for result in tweetquery:\n id, tweet, created_at, favorited, screen_name, \\\n retweet_count, follower_count, location, score = result\n score = str(round(score*100, 3)).replace(\"0.\",\".\")\n fileoutput.append('<li><strong>%(screen_name)s</strong>: ' \\\n '%(tweet)s <span class=\"score\">%(score)s</span></li>\\n' \n % {\n 'screen_name': screen_name,\n 'tweet': filter(only_ascii, link_text(tweet)),\n 'score': score\n })\n fileoutput.append('</ul>\\n<p class=\"updated\">Updated %(updated)s</p>'\n % {'updated': time.strftime(\"%d %B at %I:%M %p\", time.localtime()) })\n with open(params['output_file'], \"w\") as outputfile:\n outputfile.write(''.join(fileoutput).encode(\"utf8\"))\n\ndef purge_database():\n cleandatabase = conn.cursor()\n cleandatabase.execute('''\n delete from tweets\n where datetime(created_at) < date('now','-14 day');\n ''')\n cleandatabase.execute('vacuum;')\n conn.commit()\n\nfetch_tweets(params['tweet_list_url'])\nbuild_page()\npurge_database()\n</code></pre>\n\n<p>Typically, it makes sense to put your root level function into a main function.</p>\n\n<p>Example main function:</p>\n\n<pre><code># this is the function that actually does your work\ndef main():\n fetch_tweets(params['tweet_list_url'])\n build_page()\n purge_database()\n\n# this is true only if you directly execute this file\n# it's not true if you import the file.\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T18:20:12.547",
"Id": "33463",
"Score": "0",
"body": "Thank you very much, Winston. This is very helpful. I'll look into templating, though my ISP doesn't let me install Python plugins so I am limited in how much I can add. I made a list of tuples and then used executemany for the query. Someone else on a previous program mentioned using params that way for program parameters. Can you tell me more about the main function? What would it look like?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T20:18:54.137",
"Id": "33478",
"Score": "0",
"body": "@MikeShea, you don't have to install the python library, just copy the python source files into the same directory and it will find them. I've added an example main."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T22:05:48.350",
"Id": "33481",
"Score": "0",
"body": "Thanks again Winston. Can you describe the advantage of the main function you have there? Is it for security? Performance? Thanks again for all the help. I'll try out the templating."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T22:27:16.553",
"Id": "33482",
"Score": "0",
"body": "@MikeShea, code will run slightly faster inside a function then at the global scope. It also prevents the variables from becoming global to module. It also lets you import the module from another python module without actually running it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T20:14:51.213",
"Id": "20838",
"ParentId": "20837",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "20838",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T19:38:50.300",
"Id": "20837",
"Score": "2",
"Tags": [
"python",
"parsing",
"twitter"
],
"Title": "Python Twitter parser"
}
|
20837
|
<p>I wrote this class to make it reusable in any project. It uses PDO as the MySQL connection. Beside not using Setters and Getters, is this code secure and good practice for CRUD?</p>
<pre><code>class ContactsRow
{
const PDO_CHARSET = PDO_CHARSET;
const PDO_DBNAME = PDO_DBNAME;
const PDO_DRIVER = PDO_DRIVER;
const PDO_HOSTNAME = PDO_HOSTNAME;
const PDO_PASSWORD = PDO_PASSWORD;
const PDO_USERNAME = PDO_USERNAME;
const CURRENT_TIMESTAMP = CURRENT_TIMESTAMP;
const PHP_AUTH_USER = PHP_AUTH_USER;
protected $id = null;
public $name = null;
public $email = null;
public $filename = null;
public $created_by = self::PHP_AUTH_USER;
public $modified_by = self::PHP_AUTH_USER;
public $date_created = null;
public $date_modified = null;
public $published = 1;
public $publish_up = null;
public $publish_down = null;
public $ordering = null;
/**
* Getters for Protected Vars
**/
public function getId()
{
return (int)$this->id;
}
/**
* Save
* @return boolean $query
*/
public function save()
{
if(! (isset($_SESSION['errors']) AND !empty($_SESSION['errors']))){
$db = new PDO(self::PDO_DRIVER . ':host=' . self::PDO_HOSTNAME . ';dbname=' . self::PDO_DBNAME, self::PDO_USERNAME, self::PDO_PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . self::POD_CHARSET));
$values = array(
':name' => $this->id_parent,
':email' => $this->email,
':filename' => $this->filename,
':created_by' => self::PHP_AUTH_USER,
':modified_by' => $this->modified_by,
':date_created' => $this->date_created,
':date_modified' => self::CURRENT_TIMESTAMP,
':published' => $this->published,
':publish_up' => $this->publish_up,
':publish_down' => $this->publish_down,
':ordering' => $this->ordering,
':id' => $this->id
);
if((int)$this->id > 0){
$sql = '
UPDATE contacts
SET
name = :name,
email = :email,
filename = :filename,
created_by = :created_by,
modified_by = :modified_by,
date_created = :date_created,
date_modified = :date_modified,
published = :published,
publish_up = :publish_up,
publish_down = :publish_down,
ordering = :ordering
WHERE 1
AND id = :id
LIMIT 1
';
$stmt = $db->prepare($sql);
$query = $stmt->execute($values);
}else{
$sql = '
INSERT INTO contacts
SET
name = :name,
email = :email,
filename = :filename,
created_by = :created_by,
modified_by = :modified_by,
date_created = :date_created,
date_modified = :date_modified,
published = :published,
publish_up = :publish_up,
publish_down = :publish_down,
ordering = :ordering,
id = :id
';
$stmt = $db->prepare($sql);
$query = $stmt->execute($values);
$this->id = $db->lastInsertId();
}
$db = null;
return (bool)$query;
}
return false;
}
/**
* Delete
* @return boolean $query
*/
public function delete()
{
if((int)$this->id > 0){
$db = new PDO(self::PDO_DRIVER . ':host=' . self::PDO_HOSTNAME . ';dbname=' . self::PDO_DBNAME, self::PDO_USERNAME, self::PDO_PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . self::POD_CHARSET));
$sql = '
DELETE t, tt
FROM contacts AS t
WHERE 1
AND t.id = :id
';
$stmt = $db->prepare($sql);
$query = $stmt->execute(array(
':id' => $this->id
));
$db = null;
return (bool)$query;
}
return false;
}
/**
* fetchRow
* @return $this
*/
public function fetchRow($id = null)
{
$db = new PDO(self::PDO_DRIVER . ':host=' . self::PDO_HOSTNAME . ';dbname=' . self::PDO_DBNAME, self::PDO_USERNAME, self::PDO_PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . self::POD_CHARSET));
$sql = '
SELECT *
FROM contacts
WHERE 1
AND id = :id
LIMIT 1
';
$stmt = $db->prepare($sql);
$stmt->execute(array(
':id' => (int)$id
));
if($row = $stmt->fetch(PDO::FETCH_OBJ)){
foreach($row as $i => $e){
if($e != "") $this->{$i} = $e;
}
}
$db = null;
return $this;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The main security concern here I guess is protection from sql injection. Good news. You got that part right by using bound parameters.</p>\n\n<p>Here is what you should improve and why:</p>\n\n<p>Make the name of the class match what it is. In this case, it represents 1 Contact. So, name it Contact.</p>\n\n<p>You said \"besides no use of getters and setters\". However, I'll point out that the reason you should use them is to provide a stable api to your calling code and to encapsulate future behavior. There are more reasons, but those are important ones.</p>\n\n<p>Inject an instance of PDO instead of creating it all over the place. For one, all those connections will kill your performance. And, it will separate the concern of making the connection from this class - making it simpler.</p>\n\n<pre><code>public function __construct(PDO $pdo)\n{\n $this->pdo = $pdo;\n}\n</code></pre>\n\n<p>You will likely have other kinds of classes that represent different kinds of rows. Move the common behavior (find, save, delete) into a parent class. </p>\n\n<p>Create proper doc blocks for your methods:</p>\n\n<pre><code>/**\n * @param int|string $id\n * @return null|Contract\n */\npublic function fetchRow($id)\n</code></pre>\n\n<p>Add proper error handling for PDO. You can configure PDO to throw exceptions. Or, if not, you should do checks like:</p>\n\n<pre><code>$stmt = $this->pdo->prepare(...);\nif (! $stmt) {\n //handle this error situation\n}\n</code></pre>\n\n<p>Remove direct access to $_SESSION. This kind of global access is very difficult to maintain and test in the long run.</p>\n\n<p>Now, having said all this, your approach here (which is sort of an active record pattern) has been done many times over. Check out a library such as <a href=\"http://www.phpactiverecord.org/\" rel=\"nofollow\">php active record</a> and you will save yourself countless hours and hassle.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T17:17:57.317",
"Id": "33518",
"Score": "0",
"body": "Hi!\nI can't vote but thanks for the reply. Very Very Appreciated."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T03:21:34.073",
"Id": "20887",
"ParentId": "20841",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "20887",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T21:52:41.250",
"Id": "20841",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"mysql",
"pdo",
"crud"
],
"Title": "Reusable project for CRUD"
}
|
20841
|
<p>This technique is more general than just for config files which is why I'm not using Config::Any in this example.</p>
<p>I have a config file with lines like this:</p>
<pre><code>userid foo-admin # foo-comment
directory /some/dir # bar-comment
</code></pre>
<p>And I'm using some very awkward code to get the values.</p>
<pre><code>my @userline = grep /userid/, <$configfh>;
my @userparts = split(' ', $userline[0]);
my @user = $userparts[1];
seek($configfh, 0, 0);
my @pathline = grep /directory/, <$configfh>;
my @pathparts = split(' ', $pathline[0]);
my $path = $pathparts[1];
</code></pre>
<p>It works! But man, is it ugly. There's got to be a clearer way to extract the values I want from the file.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T16:33:45.680",
"Id": "33453",
"Score": "1",
"body": "even though you may not just be using it for \"config\" files, can't you still use a module like Config::Any?"
}
] |
[
{
"body": "<p>If you're determined to avoid using a module for this, how about something like the following:</p>\n\n<pre><code>my %config;\nwhile (my $line = <$configfh>) {\n chomp $line; # Strip trailing linefeeds, you probably don't want them there\n my @fields = split(/\\s+/, $line);\n $config{$fields[0]} = $fields[1] if $fields[0];\n}\n</code></pre>\n\n<p>But perhaps your config file may contain values with whitespace? If you can require those to be wrapped in quotes, or some other convenient character, that's not a problem.</p>\n\n<pre><code>my %config;\nwhile (my $line = <$configfh>) {\n chomp $line;\n my ($field, $value) = split(/\\s+/, $line, 2); # The 2 is how many parts to split into\n if ($value =~ /^\\\"/) {\n $value =~ s/^\\\"(.*?)\\\"/$1/; # Keep what's in the first pair of quotes\n } else {\n ($value, undef) = split(/\\s+/, $value); # Drop trailing comments\n }\n $config{$field} = $value if $field;\n}\n</code></pre>\n\n<p>(Note that the \" characters don't actually need escaping, but the syntax highlighting breaks otherwise...)</p>\n\n<p>Obviously there are other possible cases which this doesn't cover, but if your use cases are that extensive, you should probably reconsider and use a module.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T17:16:00.327",
"Id": "20870",
"ParentId": "20843",
"Score": "1"
}
},
{
"body": "<p>Your config file <em>almost</em> matches the style of <code>Config::Simple</code>. This module is easy to use and needs no extra configuration to read your key-value pairs separated by white-space.</p>\n\n<p>But, I said <em>almost</em> because you will have a problem with the inline comments. The comments actually become part of the <em>value</em> ... so they could be filtered off later but that seems risky and bothersome.</p>\n\n<p>If you could tolerate keeping your comments on a separate line, the following should work for you.</p>\n\n<pre><code>use Config::Simple;\nmy $cfg = new Config::Simple($configfh);\nmy $userid = $cfg->param('userid');\nmy $directory = $cfg->param('$directory');\n</code></pre>\n\n<p>It's also possible to pull in the entire config file to a single hash directly from the first call (this is how I use it):</p>\n\n<pre><code>Config::Simple->import_from($configfh, \\%cfg);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T02:06:17.117",
"Id": "22807",
"ParentId": "20843",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20870",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T22:16:27.130",
"Id": "20843",
"Score": "3",
"Tags": [
"perl"
],
"Title": "Reading fields idiomatically"
}
|
20843
|
<p>Just looking for some critiques hopefully from haskellers of how I might be breaking monad laws or just monadding all wrong. My <code>or</code> is something like the <code>mplus</code> for <code>either</code> and usable as a catch for failures from <code>then</code> which behaves mostly like the error monad.</p>
<p>I'm barely a haskeller so this was a big stretch for me, but I think it came out pretty well. Basic goal was some combinators you could create state machines compositionally with like how parser combinators are used to create state machines.</p>
<p>I wonder if my <code>or</code> might be more like the applicative <code><|></code> and if it could be improved to be less repeating.. does my structure anywhere cause repetition dangers where an entire chain gets executed twice because of one of the pieces composed into it?</p>
<pre><code>(function() {
this.m_ = {};
/* canContinue: error monad gate, and general monad validator */
this.m_.canContinue = function(m) { return m !== undefined && m.m !== undefined && m.m === Success && m.a !== undefined; };
/* functor instance */
this.m_.map = function(m, f) { return m.m === Failure ? new m.m.f(m.a) : new m.m.f(f(m.a)); };
/* applicative instance; ret = return = pure */
this.m_.ret = function(a) { return new success(a); };
this.m_.ap = function(mf, ma) {
return
mf.m === Failure ? new mf.m.f(mf.a) :
(ma.m === Failure ? new ma.m.f(ma.a) :
new success(mf.a(ma.a)));
};
/* alternative instance */
this.m_.alternative = function(f1, f2) {
return function(a) {
var resultf1 = f1(a);
if (resultf1.m === Success) return resultf1;
return f2(a);
};
};
/* monad instance */
this.m_.bind = function(f, m) { return m_.canContinue(m) ? f(m.a) : m; };
this.m_.kleisli = function(f1, f2) { return function(a) { return m_.bind(f2, f1(a)) }; };
/* error monad's monadic actions, and some english verbiage aliases */
this.m_.until = function(f, p) {
return function(a) {
var result = f(a);
var goodResult = result;
while(m_.bind(p, result).m === Failure) {
if (result.m === Failure) return goodResult;
else goodResult = result;
result = m_.bind(f, result);
}
return result;
};
};
this.m_.run = function(f, a) { return m_.bind(f, m_.ret(a)); };
this.m_.or = this.m_.alternative;
this.m_.then = this.m_.kleisli;
(function() {
this.or = function(f2) { return m_.or(this, f2); };
this.then = function(f2) { return m_.then(this, f2); };
this.until = function(p) { return m_.until(this, p); };
}).call(Function.prototype);
var either = function(m, a) { this.m = m; this.a = a; };
var Success = {}
var Failure = {}
Success.f = this.success = function(a) { return new either(Success, a); };
Failure.f = this.failure = function(a) { return new either(Failure, a); };
}).call(this);
///////////////////////////////////////////////////////////////
///////// TEST GARBAGE FOR PONDERING USES BELOW ///////////////
var assertEqual = function(a, b, msg) {
return function(x) { return a === b ? new success(b) : new failure(msg); };
};
var validateCar = function(x) {
return m_.run(
assertEqual(x.color, "red", "wrong color")
.then(assertEqual(x.gas, 20, "wrong gas"))
.then(assertEqual(x.mph, 30, "wrong mph")), 0);
};
m_.run(validateCar, { gas: 20, mph: 30, color: "red" });
var inc = function(a) { return a > -1 ? new success(a+1) : new failure("need positive number"); };
var dec = function(a) { return a < 0 ? new success(a-1) : new failure("need negative number"); };
var stop = function(limit, isDec) { return function(a) {
return isDec ?
(a > limit ? new failure("go") : new success("stop")) :
(a < limit ? new failure("go") : new success("stop")); };
};
var bla = new failure("ah fail");
var test = function(a) {
return typeof a == "string" ? new success(a) : new failure(a);
};
var incOrDecTwice = m_.or(inc, dec).then(m_.or(inc, dec));
m_.run(incOrDecTwice.until(stop(22, true)), 2);
m_.run(incOrDecTwice.then(dec), 4);
m_.run(m_.or(inc, dec), 1);
m_.run(m_.or(inc, dec).until(m_.or(stop(22, false), stop(-22, true))), 1);
m_.run(m_.or(inc, dec).until(m_.or(stop(22, false), stop(-22, true))), -1);
</code></pre>
<p>Any thoughts on whether to put <code>or</code> onto <code>Function.prototype</code> like <code>then</code> is? I feel it's scoping is a touch confused there to a reader.. but at the same time it creates a nice symmetry, so I'm on the fence about it...</p>
|
[] |
[
{
"body": "<pre><code>liftM2 f m1 m2 = do { x1 <- m1; x2 <- m2; return (f x1 x2) }\nap = liftM2 id\n</code></pre>\n\n<p><code>ap</code> is already defined in <a href=\"http://www.haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/src/Control-Monad.html#line-307\" rel=\"nofollow\">Control.Monad library</a>, against the <code>Monad</code> interface. </p>\n\n<p>What if you decide to also implement the <code>Maybe</code> and <code>Identity</code> and <code>List</code>. Will you implement the <code>ap</code> again for each of them?</p>\n\n<ul>\n<li><p>My main point is that the use of making an interface explicit is it\nwill enable you to program against it. It will enable some part of\nyour programs DRY that would otherwise would not be. </p></li>\n<li><p>Another benefit would be enabling you to use preexisting algorithms,\n<code>Monad</code> libraries in this case or STL algorithm library is another\nexample. </p></li>\n<li><p>Yet another benefit is that even if you cannot DRY up some routine at least your <em>code</em> readers will be able to identify the Idioms and patterns you are using.</p></li>\n</ul>\n\n<p>UPDATE:I give an example in JS below. I would give Maybe and your Error monads and the <code>ap</code> function, without currying and infix operators they don't read well at all. So I give <code>kleisli</code> which proved to be easier to read and write.</p>\n\n<h2>As for the question of obeying monad laws.</h2>\n\n<p>Monadic laws are as follows from Haskell wiki.\n<strong>Left identity:</strong> </p>\n\n<pre><code>return a >>= f eqv. f a\n</code></pre>\n\n<p>converted to JS:</p>\n\n<pre><code>bind(f, ret(a)) eqv. f(a)\n</code></pre>\n\n<p><strong>Right identity:</strong> </p>\n\n<pre><code>m >>= return eqv. m\n</code></pre>\n\n<p>converted to JS:</p>\n\n<pre><code>bind(ret, m) eqv. m\n</code></pre>\n\n<p><strong>Associativity:</strong> </p>\n\n<pre><code>(m >>= f) >>= g eqv. m >>= (\\x -> f x >>= g)\n</code></pre>\n\n<p>converted to JS:</p>\n\n<pre><code>bind(g, bind(f, m)) eqv. bind(function(x){ return bind(g, f(x)); }, m)\n</code></pre>\n\n<p>How do one check that an implementation obeys these laws? If your implementation is side effect free, as it should be, you can trace the statements using <a href=\"http://mitpress.mit.edu/sicp/full-text/sicp/book/node10.html\" rel=\"nofollow\">substitution model</a></p>\n\n<p>Associativity Law (for case Success)</p>\n\n<pre><code>bind(g, bind(f, m)) where m is {m:Success, a:X} // start with LHS\nbind(g, bind(f, {m:Success, a:X}))\nbind(g, (m_.canContinue(m) ? f(m.a) : m))\nbind(g, (true ? f(m.a) : m))\nbind(g, f(m.a))\nbind(g, f(X)) //(I)\n\nbind(function(x){ return bind(g, f(x)); }, m) where m is {m:Success, a:X} // start with RHS\nbind(function(x){ return bind(g, f(x)); }, m)\n(m_.canContinue(m) ? f(m.a) : m) where f is function(x){ return bind(g, f(x)); } and m is {m:Success, a:X}\n(true ? f(m.a) : m) where f is same as above and m is same as above\nf(m.a) where f is same as above and m is same as above\nf(X) where f is function(x){ return bind(g, f(x)); } (same as above) and m is same as above\nbind(g, f(X)) //(II)\n</code></pre>\n\n<p>Associativity Law (for case Failure)</p>\n\n<pre><code>bind(g, bind(f, m)) where m is {m:Failure, a:X} // start with LHS\n// binding failure to anything returns itself no need to write down all the steps\nm where m is {m:Failure, a:X} // (I)\n\n\nbind(function(x){ return bind(g, f(x)); }, m) where m is {m:Failure, a:X} // start with RHS\n// binding failure to anything returns itself no need to write down all the steps\nm where m is {m:Failure, a:X} // (II)\n</code></pre>\n\n<p>It is verbose. I was a little lax with the notation. (But this is not the exam, right?)</p>\n\n<p>Identities follow similarly for cases m is {m:Success, a:X} and m is {m:Failure, a:X}</p>\n\n<h2>Separation of concerns in <code>canContinue</code></h2>\n\n<p>One of the things I want to add here is that <code>canContinue</code> is trying to do two things at once. This has two consequences. First, it affects readability adversely. Its core algorithmic/logical bit <code>m.m == Success</code> is being lost to the reader in the validation code. Also at its only use site, name <code>bind</code> function, it is not evident immediately that you are doing a case analysis on type tag. (cond/pattern match on type) \nSecond you are doing that validation many times unnecessarily on values produced by <code>success(a)</code> constructor.</p>\n\n<h2>Type tag <code>.m</code></h2>\n\n<p>Haskell <code>data</code> structures are tagged records alright. But it pattern matches on the constructor name.\nJS has a <code>constructor</code> property as a type tag and an <code>instanceof</code> operator.</p>\n\n<p><code>m instanceof Success</code> is more readable to me than <code>m.m === Success</code>. It also excludes structures that happens to have a <code>.m</code> member but not constructed with the <code>Success</code> constructor. <code>m.constructor === Success</code> may be another option. This is a stylistic opinion and I am not a JS developer.</p>\n\n<h2>Implementing the Monad interface in JS.</h2>\n\n<pre><code>var Just = function(value) {\n this.value = value;\n}\nvar Nothing = function(){};\n\nvar just = function(a) {return new Just(a)}\nvar nothing = new Nothing();\n\nvar Monad = function(impl) {\n this.bind = impl.bind\n this.ret = impl.ret\n\n //each instance gets this for free\n this.fail = function(s) { throw s;}\n\n var ret = this.ret.bind(this);\n var bind = this.bind.bind(this);\n\n //each instance gets this for free\n this.liftM2 = function(f) {\n return function(m1, m2) {\n return bind(\n m1, \n function (x1) { \n return bind(\n m2, \n function(x2) { \n return ret(f(x1,x2));})})};\n };\n};\n</code></pre>\n\n<p>Maybe Monad instance in haskell</p>\n\n<pre><code> return :: a -> Maybe a\n return x = Just x\n\n\n (>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b\n (>>=) m g = case m of\n Nothing -> Nothing\n Just x -> g x\n</code></pre>\n\n<p>Compare the pattern matching with above haskell impl</p>\n\n<pre><code>var maybeMonad = new Monad({\n bind: function(m, f) {\n if (m instanceof Nothing) return nothing;\n if (m instanceof Just) return f(m.value);\n // may want to raise error here?\n },\n ret: function(a) {return just(a)}\n });\n\n// We can add library functions after the fact\n// other monad instances should also see this automatically\n// NOTE: I switched the order of the parameters of bind\nMonad.prototype.kleisli = function(f1, f2) { return function(a) { return this.bind(f1(a), f2) }.bind(this); };\n\n// some tests, just for demo purposes\n// === doesn't work on Just we compare the values instead\nvar myAdd = function (a, b) { return a + b;}\n\nvar tryDivide = function(a, b) { if (b !== 0) return just(a/b); else return nothing;}\n\n(function(_) {\n console.log(_.liftM2(myAdd)(_.ret(10), tryDivide(10, 2)))\n\n // a test case for monad identity law in kleisli form\n console.assert(_.kleisli(_.ret, _.ret)(10).value === _.ret(10).value)\n\n // a test case for monad associativity law in kleisli form\n console.assert(_.kleisli(_.ret, _.kleisli(_.ret, _.ret))(10).value \n === _.kleisli(_.kleisli(_.ret, _.ret), _.ret)(10).value)\n\n})(maybeMonad)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-27T21:36:48.247",
"Id": "33595",
"Score": "0",
"body": "Great point, I was wondering how I could define some of these functions in terms of the other functions. I'll have to test ap implemented as you suggest to see if it works or not, this would be a sign of whether I implemented my monad correctly.. I think it may."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-28T00:40:39.453",
"Id": "111243",
"Score": "0",
"body": "...I never saw all the expansion you added to this answer until now. I am sorry for this because you put a ton of work into this critique and frankly it's awesome. Way more than I expected as finding good critiques of any code that acts like a monad is always very difficult... I can't disagree with any of your points off hand, awesome!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-27T10:19:16.100",
"Id": "20951",
"ParentId": "20845",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T23:14:02.517",
"Id": "20845",
"Score": "2",
"Tags": [
"javascript",
"haskell"
],
"Title": "Wrote javascript version of error monad / monadplus, did I obey monad laws correctly?"
}
|
20845
|
<p>I have an event recurring on the first friday of the month (at 7pm), and I need to output the date of the next first friday coming up.</p>
<p>This is the first bit of PHP I've written, and I was wondering if there is a better way to implement this? Server is running PHP 5.3</p>
<p>Here's what I wrote:</p>
<pre><code>$todays_date = strtotime('today');
$first_friday = strtotime('first friday of this month');
if ($todays_date > $first_friday) {
$next_month = date('M j', strtotime('first friday of next month'));
echo 'Friday, '.$next_month;
} elseif ($todays_date == $first_friday) {
echo 'Today';
} else {
$this_month = date('M j', strtotime('first friday of this month'));
echo 'Friday, '.$this_month;
}
</code></pre>
<p>And here is a suggested improvement offered by someone else, which also introduced me to ternary operators:</p>
<pre><code>$today = new DateTime();
$this_months_friday = new DateTime('first friday of this month');
$next_months_friday = new DateTime('first friday of next month');
echo ($today < $this_months_friday) ? 'Friday, '.$this_months_friday->format('M j').' at 7pm' : 'Friday, '.$next_months_friday->format('M j').' at 7pm';
</code></pre>
<p>I had looked all over for a short way to do this and was only running into very large and complicated answers. Both my way and the answer provided by someone else are much much shorter and more readable.</p>
|
[] |
[
{
"body": "<p>You can improve your ternary operator by using it like this :</p>\n\n<pre><code>$today = new DateTime();\n$this_months_friday = new DateTime('first friday of this month');\n$next_months_friday = new DateTime('first friday of next month');\necho 'Friday, '. (($today < $this_months_friday) ? $this_months_friday->format('M j') : $next_months_friday->format('M j')) . ' at 7pm';\n</code></pre>\n\n<p>which can them become :</p>\n\n<pre><code>echo 'Friday, '. (($today < $this_months_friday) ? $this_months_friday : $next_months_friday)->format('M j') . ' at 7pm';\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T05:16:59.613",
"Id": "33432",
"Score": "0",
"body": "Concatenating the ternary operator onto the string was causing some strange behavior when I was testing the improved version. What you wrote there works as expected. Thank you!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T06:34:00.720",
"Id": "33433",
"Score": "0",
"body": "You're welcome. Perhaps were you missing parenthesis ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T19:05:00.570",
"Id": "33467",
"Score": "0",
"body": "That was the problem all along. It was evaluating the whole string when I didn't have the parenthesis in there. Thanks @Josay!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T01:15:58.360",
"Id": "20847",
"ParentId": "20846",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "20847",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T23:18:17.943",
"Id": "20846",
"Score": "3",
"Tags": [
"php"
],
"Title": "PHP First Friday Display Improvement?"
}
|
20846
|
<p>I saw a posting on Hacker News this morning that was ranting about people not being able to solve an interview question. I thought I would give it a shot, but I would like to know how my attempt could be improved.</p>
<pre><code>def get_pascal_row(n):
"""
Returns the nth row of Pascal's Triangle for a given n. Uses
Gray's algorithm.
"""
if n == 0: return []
n -= 1
row = [1]
for i in xrange(1,n+1):
row.append(row[-1] * n/i)
n -= 1
return row
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T01:45:35.923",
"Id": "33431",
"Score": "0",
"body": "Stop half way through and stick a copy of the first half reversed to the end of your return."
}
] |
[
{
"body": "<p>You can <a href=\"http://en.wikipedia.org/wiki/Memoization\" rel=\"nofollow noreferrer\">memoize</a> the rows you have already computed previously. </p>\n\n<p>Alternatively, you could compute it in closed form using the <a href=\"http://en.wikipedia.org/wiki/Binomial_coefficient\" rel=\"nofollow noreferrer\">binomial coefficients</a>:</p>\n\n<p><img src=\"https://i.stack.imgur.com/GiV8X.png\" alt=\"enter image description here\"></p>\n\n<p>Start looking in <a href=\"http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.binom.html\" rel=\"nofollow noreferrer\"><code>scipy.special.binom</code></a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T01:47:53.680",
"Id": "20851",
"ParentId": "20850",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T01:32:07.507",
"Id": "20850",
"Score": "4",
"Tags": [
"python"
],
"Title": "How can this function be faster? Solving for a row of Pascal's triangle"
}
|
20850
|
<p>I am trying to model a domain of metrics for use in a BI application. I recently read the <a href="http://fsharpforfunandprofit.com/posts/designing-with-types-intro/" rel="nofollow">Designing with Types</a> series, and felt that it could be useful, so I wanted to give it a try. What I'm not sure is if I'm trying too hard....</p>
<ol>
<li>The metrics are application-defined, meaning they are finite and won't change during runtime. A dozen metrics would probably be a lot.</li>
<li>New metrics will be introduced as the application grows</li>
<li>A user will be selecting which metrics they want to use, and the application has to take that and go "do stuff", like building a query to the backend store (MongoDB, in this case).</li>
<li>There may be application logic associated with metrics that I would like enforced through pattern matching so that when I introduce a new metric, I want the compiler to tell me that I need to do some work.</li>
</ol>
<p>Here's what I have:</p>
<pre><code>type Metrics =
| Revenue
| Volume
| PriceAsp
with
member m.FormatGroupings =
match m with
| Revenue -> [("revenue", """$sum: { "$Amount" }" """)]
| Volume -> [("volume", """$sum: { "$Quantity" }" """)]
| PriceAsp -> List.append Revenue.FormatGroupings Volume.FormatGroupings
member m.FormatProjections =
match m with
| Revenue -> [("revenue", "$revenue")]
| Volume -> [("volume", "$volume")]
| PriceAsp -> [("priceAsp", """ $divide: ["$revenue", "$volume"] """)]
let buildQuery groupBy (metrics:Metrics list) =
let concatenate f =
let x = metrics
|> List.collect f
|> List.map (fun m -> sprintf "{%s: %s}" (fst m) (snd m) )
System.String.Join(",", x)
let groupings = concatenate (fun m -> m.FormatGroupings)
let projections = concatenate (fun m -> m.FormatProjections)
sprintf """{$group: {_id: {%s: "$%s"}}, %s}, $project: {%s}}""" groupBy groupBy groupings projections
</code></pre>
<p>With examples of usage:</p>
<pre><code>buildQuery "foo" [Revenue; Volume] //Simple
buildQuery "foo" [PriceAsp] //Compound
</code></pre>
<p>Note that <code>PriceAsp</code> is "made up of" both <code>Revenue</code> and <code>Volume</code>.</p>
<p>Please provide any general comments. Some specific questions I have are:</p>
<ol>
<li>Have the business rules for the metric calculations be embedded within the types</li>
<li>Show that some metrics are built off of other metrics (for example, <code>PriceAsp</code>), and enforce the explicit relationship. Above, we see that <code>PriceAsp</code> is made up of <code>Revenue</code> and <code>Volume</code> because it's in that list. But it would be better to make it enforced explicitly through typing.</li>
<li>There are formatting rules around an "instance" of a specific metric. For example, when Revenue is shown to a user, it should be rounded to the nearest whole dollar, with thousand separators and a currency symbol (ex: $1,234,567).</li>
<li>Is there an elegant way (using <code>List.fold</code>, perhaps) for doing what String.Join does? String.Join is just so convenient...</li>
</ol>
<p>A base metric would look like this (no <code>$project</code>):</p>
<pre><code>{
$group: {
_id: {
foo: "$Foo"
},
revenue: { $sum: "$Amount" }
}
}
</code></pre>
<p>A compound metric may look like this:</p>
<pre><code>{
$group: {
_id: {
foo: "$Foo"
},
revenue: { $sum: "$Amount" },
volume: { $sum: "$Quantity" }
},
$project: {
priceAsp: { $divide: ["$revenue", "$volume"] }
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Do you have only a limited number of metric types?</p>\n\n<p>In which case, you might want to make a union case of the possible types.\nThe compound cases can be recursive, referring to the type.</p>\n\n<pre><code>type Metric = \n | Revenue of string * string \n | Volume of string * string\n | Compound of string * Metric list\n</code></pre>\n\n<p>Then your <code>formatMetric</code> function needs to handle each case separately</p>\n\n<pre><code>let formatMetric metric =\n match metric with\n | Revenue (label,formula) -> \n sprintf \"%s: {%s}\" label formula\n | Volume (label,formula) -> \n sprintf \"%s: {%s}\" label formula\n | Compound (label,metrics) -> \n sprintf \"%s: {%s}\" label \"other metrics\"\n</code></pre>\n\n<p>Note that that if you use this approach you don't really need the label any more, as the cases <em>are</em> the label.</p>\n\n<pre><code>type Metric = \n | Revenue of string \n | Volume of string\n | Compound of Metric list\n</code></pre>\n\n<p>And then you could also make <code>formatMetric</code> recursive, printing all the child formulas for a compound formula</p>\n\n<pre><code>let rec formatMetric metric =\n match metric with\n | Revenue formula -> \n sprintf \"Revenue={%s}\" formula\n | Volume formula -> \n sprintf \"Volume={%s}\" formula\n | Compound metrics -> \n let childFormats = \n metrics \n |> List.map formatMetric\n |> List.reduce (+) \n sprintf \"Compound: {%s}\" childFormats\n</code></pre>\n\n<p>The formatting is not exactly what you want, but I'm sure you get the general idea.</p>\n\n<h3>EDIT</h3>\n\n<p><strong>General Comment</strong></p>\n\n<p>Personally, I wouldn't add those member functions to the type. I would focus on designing the types in their own module independent of any particular representation, and then have a <em>separate</em> module that mapped them into the appropriate representation for MongoDB. That way you are not mixing up different requirements. </p>\n\n<p><strong>String join.</strong></p>\n\n<p>A simple string join is trivial to write:</p>\n\n<pre><code>let stringJoin sep list :string = \n let append s t = s + sep + t\n list |> List.reduce append\n\nstringJoin \", \" [\"a\"; \"b\"; \"c\"; ]\n</code></pre>\n\n<p><strong>Separate the types from the representation</strong></p>\n\n<p>But if you separate the types from the representation, you may find that you naturally create MongoDB specific functions that generate the appropriate representation. The idea is to build up a mini-language that you can compose together to make bigger blocks.\nI don't know the MongoDB syntax, but maybe something like this?</p>\n\n<pre><code>let mSum p = sprintf \"{ $sum: \"\"%s\"\" }\" p\nlet mDivide p q = sprintf \"{ $divide: [\"\"%s\"\", \"\"%s\"\"] }\" p q\nlet mLabel p q = sprintf \"%s : %s\" s\nlet mGroup id ps = sprintf \"$group: { %s, %s }\" id (stringJoin \", \" ps)\nlet mProject p q = sprintf \"$project: { %s }\" (stringJoin \", \" ps)\n</code></pre>\n\n<p>If you are doing a lot of this, you might be better off using a JSON library. In which case the workflow would be:</p>\n\n<pre><code>domain type ==> convert to intermediate type for Mongo API ==> convert to JSON\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T01:18:11.143",
"Id": "33489",
"Score": "0",
"body": "This is more inline with my original thinking. I think the article I linked to in the original question made my try too hard. I edited the question with this updated code. I would be interested in your feedback on that. thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T15:52:32.067",
"Id": "33549",
"Score": "0",
"body": "I really like the thought behind this answer. Distilling the types down to \"regular\" and \"compound\" is good. Regarding my question #2, could I do `PriceAsp of [Revenue;Volume]`? The separation of building the query from the type makes a lot of sense."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T22:32:50.033",
"Id": "20881",
"ParentId": "20852",
"Score": "1"
}
},
{
"body": "<p>Regarding your types, I think that simple metrics and compound metrics should have their own types, to enforce their requirements and to avoid repeating yourself. One way to do that is to define <code>Metric</code> as:</p>\n\n<pre><code>type Metric =\n | SimpleMetric of SimpleMetric\n | CompoundMetric of CompoundMetric\n</code></pre>\n\n<p>Here, <code>SimpleMetric</code> and <code>CompoundMetric</code> are separate discriminated unions, and both of them have members specific to their case.</p>\n\n<p>The whole code could look like this:</p>\n\n<pre><code>type SimpleMetric =\n | Revenue\n | Volume\n with\n member m.Name =\n match m with\n | Revenue -> \"revenue\"\n | Volume -> \"volume\"\n\n member m.Grouping =\n match m with\n | Revenue -> \"\"\"$sum: { \"$Amount\" }\" \"\"\"\n | Volume -> \"\"\"$sum: { \"$Quantity\" }\" \"\"\"\n\n member m.Projection =\n \"$\" + m.Name\n\ntype CompoundMetric =\n | PriceAsp\n with\n member m.Name =\n match m with\n | PriceAsp -> \"priceAsp\"\n\n member m.Metrics =\n match m with\n | PriceAsp -> [SimpleMetric Revenue; SimpleMetric Volume]\n\n member m.Projection =\n match m with\n | PriceAsp -> \"\"\" $divide: [\"$revenue\", \"$volume\"] \"\"\"\n// CompoundMetric references Metric, so the two types have to be declared together\nand Metric =\n | SimpleMetric of SimpleMetric\n | CompoundMetric of CompoundMetric\n with\n member m.Name =\n match m with\n | SimpleMetric sm -> sm.Name\n | CompoundMetric cm -> cm.Name\n\n member m.Projection =\n match m with\n | SimpleMetric sm -> sm.Projection\n | CompoundMetric cm -> cm.Projection\n\n member m.FormatGroupings =\n match m with\n | SimpleMetric sm -> [(sm.Name,sm.Grouping)]\n | CompoundMetric cm -> cm.Metrics |> List.collect (fun m -> m.FormatGroupings)\n\n member m.FormatProjections = [(m.Name, m.Projection)]\n\nlet buildQuery groupBy (metric:Metric list) =\n let concatenate f =\n let x = metric\n |> List.collect f\n |> List.map (fun (name, value) -> sprintf \"{%s: %s}\" name value)\n System.String.Join(\",\", x)\n\n let groupings = concatenate (fun m -> m.FormatGroupings)\n let projections = concatenate (fun m -> m.FormatProjections)\n\n sprintf \"\"\"{$group: {_id: {%s: \"$%s\"}}, %s}, $project: {%s}}\"\"\" groupBy groupBy groupings projections\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>buildQuery \"foo\" [SimpleMetric Revenue; SimpleMetric Volume]\nbuildQuery \"foo\" [CompoundMetric PriceAsp]\n</code></pre>\n\n<p>The whole code is longer than your version, but I think adding new metrics will be easier this way.</p>\n\n<p>Also, I don't like that I have to define <code>Name</code> and <code>Projection</code> in <code>Metric</code>, but I don't see a way around that.</p>\n\n<p>Now, to your questions:</p>\n\n<blockquote>\n <p>Any general comments?</p>\n</blockquote>\n\n<p>I think the type shouldn't be called <code>Metrics</code>, it should be <code>Metric</code>, because a value of that type defines a single metric, not some collection.</p>\n\n<p>Also, your <code>concatenate</code> function can be simplified by using pattern matching instead of <code>fst</code> and <code>snd</code> (see the above code).</p>\n\n<blockquote>\n <p>Is there an elegant way for doing what <code>String.Join</code> does?</p>\n</blockquote>\n\n<p>I don't think so. There is a <a href=\"http://msdn.microsoft.com/en-us/library/ee353758.aspx\" rel=\"nofollow\"><code>String</code> module</a>, but it doesn't have anything like <code>Join</code>. (And its documentation specifically refers methods of the <code>System.String</code> type.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T16:14:41.023",
"Id": "33551",
"Score": "0",
"body": "I like the distinction between Simple and Compound. Good point on the `concatenate` - much more readable. If the formatting for the query were separate from the types, like @Grundoon suggests, then maybe `Name` and `Projection` go away. I think what I'm struggling with now is if all the operations should be with the type, or separated out in other modules."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T15:37:46.697",
"Id": "20898",
"ParentId": "20852",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T04:44:53.620",
"Id": "20852",
"Score": "2",
"Tags": [
"f#",
"mongodb"
],
"Title": "Using Types to Designing Domain"
}
|
20852
|
<p>My function converts an improper fraction to a mixed number (it does not AND should not simplify the fraction).</p>
<pre><code>// Improper fraction to mixed number
// n = numerator
// d = denominator
// i = number
function improperFractionToMixedNumber(n, d) {
i = (n / d) >> 0;
n -= i * d;
return [i, n, d];
}
// Convert 14/4 to mixed number
improperFractionToMixedNumber(14, 4); // 3, 2, 4
</code></pre>
<p><strong>Can this be improved or simplified?</strong></p>
<p>I don't care for this part:</p>
<pre><code>i = (n / d) >> 0;
</code></pre>
<p>But it's the only way I could figure out how to see how many times a number equally divides into another number.</p>
|
[] |
[
{
"body": "<p>What you're doing with <code>i = (n / d) >> 0</code> is a sign-propagating right shift. The interesting this is, you're doing a right shift by 0 (I'd imagine because you'd otherwise get <code>NaN</code>. Your method of doing so is a cheap version (read: performance hack?) of doing <code>i = parseInt(n / d)</code>. Here's your function with the SPRS removed and replaced with <code>parseInt()</code> instead. I've also implemented simplification. </p>\n\n<pre><code>function improperFractionToMixedNumber(n, d) {\n i = parseInt(n / d);\n n -= i * d;\n return [i, n, d]; \n}\n</code></pre>\n\n<p>Here is the same function, but also implementing simplification via a helper function <code>reduce</code>:</p>\n\n<pre><code>// Improper fraction to mixed number\n// n = numerator\n// d = denominator\n// i = number\nfunction improperFractionToMixedNumber(n, d) {\n i = parseInt(n / d);\n n -= i * d;\n return [i, reduce(n,d)]; \n}\n\n\nfunction reduce(numerator,denominator){\n if (isNaN(numerator) || isNaN(denominator))\n return NaN;\n var gcd = function gcd(a, b){ return b ? gcd(b, a%b) : a; };\n gcd = gcd(numerator, denominator);\n return [numerator/gcd, denominator/gcd];\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T16:50:33.820",
"Id": "20868",
"ParentId": "20854",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "20868",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T06:57:34.810",
"Id": "20854",
"Score": "4",
"Tags": [
"javascript"
],
"Title": "Convert Improper Fraction to Mixed Number with JavaScript"
}
|
20854
|
<p>From what I understand this site help to check if my solution is proper or not..so forgive me if the header is bad.</p>
<p>This is my solution for the question:</p>
<pre><code>#include <stdio.h>
int main()
{
double num1, num2, different, product, answer;
printf("please enter 2 floatig point numbers:\n");
printf("number one is?\n");
scanf("%lf", &num1);
printf("number two is?\n");
scanf("%lf", &num2);
if (num1 > num2)
{
different = num1 - num2;
}
if (num2 > num1)
{
different = num2 - num1;
}
if (num1 == num2)
{
different = 0;
}
product = num1*num2;
answer = different/product;
printf("%lf", answer);
}
</code></pre>
<p>How bad is it?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T11:53:54.683",
"Id": "33439",
"Score": "0",
"body": "Are you using C99 (the newer version of the language)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T12:20:07.663",
"Id": "33440",
"Score": "0",
"body": "@svick how do I know that? sorry im learning C for less than 2 weeks :/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T12:27:18.223",
"Id": "33441",
"Score": "0",
"body": "That depends on your compiler. Which compiler are you using, what is its version? (Most of them should support C99, I believe.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T12:28:14.353",
"Id": "33442",
"Score": "0",
"body": "@svick I'm using xcode on macbook pro 64 bit"
}
] |
[
{
"body": "<p>For a newbie, your solution is ok. You can simplify it quite a bit though by using the function <code>fabs</code>. It's a fairly simple function: <code>fabs(x)</code> returns <code>x</code> if <code>x >= 0</code>, and returns <code>-x</code> if <code>x < 0</code>. So all of your <code>if</code> checks can be replaced by the line:</p>\n\n<pre><code>different = fabs(num1 - num2);\n</code></pre>\n\n<p>Note that you need to <code>#include <math.h></code> for this.</p>\n\n<p>Also, what happens if one of your numbers is <code>0</code>? Then your product will also be <code>0</code> and your program will crash. It's always a good idea to add some basic checks. Unfortunately, with floating point numbers this can be a bit tricky, so simply doing something like:</p>\n\n<pre><code>if(product == 0.0) { ... }\n</code></pre>\n\n<p>may not actually work! Fixing this might be a bit tricky for someone who is just learning, but it's something to always keep in mind.</p>\n\n<p>Finally, <code>main</code> should return an <code>int</code> - generally, <code>0</code> is what is returned if everything works as it should - so down the bottom should be a <code>return 0;</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T11:01:28.510",
"Id": "33499",
"Score": "1",
"body": "Testing a float against 0 (or 0.0) is going to be an exact match (its one of the few comparisons on floats that works). Also division by zero using floats is not undefined behavior (that only applies to integers). In float values division by 0 result in infinity value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T14:00:14.920",
"Id": "33506",
"Score": "0",
"body": "@LokiAstari Yeah, good point. I forgot floating point division by 0 doesn't generate a SIGFPE or equivalent, it simply yields `NaN`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T13:16:23.903",
"Id": "20861",
"ParentId": "20858",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "20861",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T10:30:55.173",
"Id": "20858",
"Score": "1",
"Tags": [
"c"
],
"Title": "Program that requests two floating-point numbers and prints the value of their difference divided by their product"
}
|
20858
|
<p>For the first time I have to play with Threads in java.</p>
<p>Basically, my code is a simple FIFO job queue.
The main thread regularly puts jobs in the queue wich need to be executed.</p>
<p>The code below is a striped down version of what I am doing :</p>
<pre><code>public class JobPerformer implements Runnable {
private final ArrayList<Job> jobList = new ArrayList<Job>();
private final AtomicBoolean threadStop = new AtomicBoolean(false);
private Thread thread;
public JobExecuter(){
thread = new Thread(this)
thread.start();
}
public void perform(Job job, bool async){
if(async){
jobList.add(job);
jobList.notifyAll();
}
else{
job.perform();
}
}
public void perform(Job job){
this.perform(job, false);
}
public void shutdown(){
threadStop.set(true);
if(thread.getState() == Thread.State.WAITING){
thread.interrupt();
}
}
public void run(){
while(! threadStop.get()){
if(jobList.isEmpty()){
try{
jobList.wait();
} catch (InterruptedException ex) {}
}
jobList.get(0).perform();
jobList.remove(0);
}
// Finish the jobs still in the queue
while(!jobList.isEmpty()){
jobList.get(0).perform();
jobList.remove(0);
}
}
}
</code></pre>
<p>I have two questions :</p>
<ol>
<li><p>I use wait() and notifyAll() to avoid polling. But nowhere do I synchronize. Since it's a FIFO queue, threads are just adding jobs at the end or reading at the start. I don't see any conflict that would make me say "Hey, I have to make sure that during this op. only one thread can be working on this object", is there a possible conflict I am overseeing that would require me to synchronize anyway ?</p></li>
<li><p>I am using an "Atomic boolean" because of this question : <a href="https://codereview.stackexchange.com/questions/18740/multithreading-correctly-done">Multithreading correctly done?</a> What was wrong with using a normal boolean ? </p></li>
</ol>
|
[] |
[
{
"body": "<p>Why don't you use the classes provided in java.util.concurrent that can handle these requirements? Or is this written for practice?</p>\n\n<p>There is still problem if you don't synchronize, because the <code>ArrayList.add()</code> method is not thread-safe thus it can happen that two threads trying to add a new job into the queue nearly the same instant (to the same slot in the array), then it is possible that the one adding later will overwrite the job added by the first thread.</p>\n\n<p>Using normal boolean does not guarantee, that if one thread writes the value, and another accesses immediately after that then it will see the new value. You can use <code>volatile</code> with <code>boolean</code> as well, as in mentioned in the answer you linked. See <a href=\"http://jeremymanson.blogspot.in/2008/11/what-volatile-means-in-java.html\" rel=\"nofollow\">an explanation for volatile</a></p>\n\n<p>Or refer to <a href=\"http://rads.stackoverflow.com/amzn/click/0321349601\" rel=\"nofollow\">Java Concurrency in Practice</a>, pretty good book.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T12:02:52.443",
"Id": "20860",
"ParentId": "20859",
"Score": "1"
}
},
{
"body": "<p>There are several issues in your code, most importantly:</p>\n\n<ul>\n<li>don't start a thread in your constructor, it is very possible that <code>jobList.isEmpty()</code> in your run method could throw a NPE because your object has not been fully constructed yet</li>\n<li>the alternatives are: provide a <code>start</code> method, or start the thread the first time <code>perform</code> is called</li>\n<li>you must call <code>wait</code> / <code>notifyAll</code> within a synchronized block or you will get an exception at runtime</li>\n<li>ArrayList is not thread safe so you can't add in the main thread (in <code>perform</code>) and get in the worker thread without synchronization. The result could be anything, including a corruption of the data structure.</li>\n<li>using an ArrayList where you keep adding and removing is not very efficient - you could use a LinkedList instead</li>\n<li>even better, use a <code>BlockingQueue</code> which will handle all the low level synchronization and waiting for you</li>\n<li>if you use a simple boolean for <code>threadStop</code>, it is very possible that your work thread will never see the value become <code>true</code> (even if the main thread calls <code>shutdown</code>)</li>\n<li>instead of <code>AtomicBoolean</code>, you could simply mark the boolean as <code>volatile</code></li>\n</ul>\n\n<p>Bottom line: as it is your class will throw an exception very quickly. Once you have fixed that, it might work for some time and fail inexplicably, or not work at all.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T17:28:52.267",
"Id": "20872",
"ParentId": "20859",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20860",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T11:40:57.370",
"Id": "20859",
"Score": "3",
"Tags": [
"java",
"multithreading",
"thread-safety"
],
"Title": "Simple FIFO Job list in Java"
}
|
20859
|
<p>The query works fine but I'm just intrigued to know if there is a cleaner solution. The data are results from a survey and I'm obtaining the counts per question within a zone and an overall zone count.</p>
<pre><code>With Cte1 (ZoneId, QuestionId, Count1)
AS
(
Select
tz.ZoneId,
qn.QuestionId,
Count(1) as Count1
From
Customers cust
Inner Join Shops td on td.ShopCode = cust.ShopCode
Inner Join Zones tz on tz.Id = td.SlsZone
Inner Join Responses res on res.SampleId = cust.SampleId
Inner Join QstNodes qn on qn.QuestionId = res.QstNodeId
Where
Event >= 201201 And Event <= 201212
Group BY
tz.ZoneId, qn.QuestionId
)
SELECT
ZoneId,
QuestionId
Count1,
(
SELECT SUM(Count1)
FROm Cte1 as innercte
Where innercte.ZoneId = outercte.ZoneId
)
as ZoneTotal
FROM
Cte1 outercte
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T15:31:38.153",
"Id": "33447",
"Score": "1",
"body": "The answer to your question is `rollup`, but that depends on the database that you are using."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T16:48:10.810",
"Id": "33455",
"Score": "0",
"body": "@Gordon Linoff. Rollup was the the answer to my question. thanks"
}
] |
[
{
"body": "<p>how about using <code>CASE</code></p>\n\n<pre><code>SELECT tz.ZoneId,\n qn.QuestionId,\n SUM(CASE WHEN Event >= 201201 AND Event <= 201212\n THEN 1 \n ELSE 0\n END) as Count1,\n COUNT(*) AS ZoneTotal\nFROM Customers cust\n INNER JOIN Shops td\n ON td.ShopCode = cust.ShopCode\n INNER JOIN Zones tz\n ON tz.Id = td.SlsZone\n INNER JOIN Responses res\n ON res.SampleId = cust.SampleId\n INNER JOIN QstNodes qn\n ON qn.QuestionId = res.QstNodeId\nGROUP BY tz.ZoneId, qn.QuestionId\n</code></pre>\n\n<p><strong>UPDATE 1</strong></p>\n\n<p>The following illustrated on the demo has different records but that thought is the same.</p>\n\n<ul>\n<li><a href=\"http://www.sqlfiddle.com/#!3/e5c70/1\" rel=\"nofollow\">SQLFiddle Demo Link</a></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T15:37:16.593",
"Id": "20866",
"ParentId": "20865",
"Score": "3"
}
},
{
"body": "<p>Using <a href=\"https://msdn.microsoft.com/en-us/library/ms189461.aspx\" rel=\"nofollow\"><code>OVER</code></a>, you can do it in one pass:</p>\n\n<pre><code>With Cte1 (ZoneId, QuestionId, Count1, sum1, rn)\nAS\n(\n Select \n tz.ZoneId, \n qn.QuestionId \n , COUNT(1) OVER(PARTITION BY tz.ZoneId, qn.QuestionId) AS \"Count1\" \n , COUNT(1) OVER(PARTITION BY tz.ZoneId) AS \"Sum1\"\n , row_number() OVER(PARTITION BY tz.ZoneId, qn.QuestionId order by ShopCode) AS \"rn\"\n From \n Customers cust \n Inner Join Shops td on td.ShopCode = cust.ShopCode\n Inner Join Zones tz on tz.Id = td.SlsZone\n Inner Join Responses res on res.SampleId = cust.SampleId\n Inner Join QstNodes qn on qn.QuestionId = res.QstNodeId\n Where \n Event >= 201201 And Event <= 201212\n)\nSELECT *\nFROM \n Cte1 outercte \nwhere \n rn = 1;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-14T06:38:12.003",
"Id": "259231",
"Score": "0",
"body": "Answers should review the original code, not just present a code snippet."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-14T06:46:37.057",
"Id": "259232",
"Score": "0",
"body": "@Jamal That is not a snippet. That is complete code. Check my SQL related rep on stackoverflow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-14T06:48:41.973",
"Id": "259233",
"Score": "0",
"body": "What I mean is, answers here shouldn't just contain code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-14T07:10:19.757",
"Id": "259234",
"Score": "0",
"body": "@Jamal If that intro is not enough feel free to delete"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-14T07:12:11.177",
"Id": "259235",
"Score": "0",
"body": "Good enough for me."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-14T06:35:19.820",
"Id": "138671",
"ParentId": "20865",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "138671",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T15:26:48.800",
"Id": "20865",
"Score": "2",
"Tags": [
"sql",
"sql-server",
"t-sql"
],
"Title": "SQL query to obtain totals and subtotals"
}
|
20865
|
<p>This is the code I implemented so far to create a single instance WPF application:</p>
<pre><code>#region Using Directives
using System;
using System.Globalization;
using System.Reflection;
using System.Threading;
using System.Windows;
using System.Windows.Interop;
#endregion
namespace MyWPF
{
public partial class MainApplication : Application, IDisposable
{
#region Members
private Int32 m_Message;
private Mutex m_Mutex;
#endregion
#region Methods: Functions
private IntPtr HandleMessages(IntPtr handle, Int32 message, IntPtr wParameter, IntPtr lParameter, ref Boolean handled)
{
if (message == m_Message)
{
if (MainWindow.WindowState == WindowState.Minimized)
MainWindow.WindowState = WindowState.Normal;
Boolean topmost = MainWindow.Topmost;
MainWindow.Topmost = true;
MainWindow.Topmost = topmost;
}
return IntPtr.Zero;
}
private void Dispose(Boolean disposing)
{
if (disposing && (m_Mutex != null))
{
m_Mutex.ReleaseMutex();
m_Mutex.Close();
m_Mutex = null;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region Methods: Overrides
protected override void OnStartup(StartupEventArgs e)
{
Assembly assembly = Assembly.GetExecutingAssembly();
Boolean mutexCreated;
String mutexName = String.Format(CultureInfo.InvariantCulture, "Local\\{{{0}}}{{{1}}}", assembly.GetType().GUID, assembly.GetName().Name);
m_Mutex = new Mutex(true, mutexName, out mutexCreated);
m_Message = NativeMethods.RegisterWindowMessage(mutexName);
if (!mutexCreated)
{
m_Mutex = null;
NativeMethods.PostMessage(NativeMethods.HWND_BROADCAST, m_Message, IntPtr.Zero, IntPtr.Zero);
Current.Shutdown();
return;
}
base.OnStartup(e);
MainWindow window = new MainWindow();
MainWindow = window;
window.Show();
HwndSource.FromHwnd((new WindowInteropHelper(window)).Handle).AddHook(new HwndSourceHook(HandleMessages));
}
protected override void OnExit(ExitEventArgs e)
{
Dispose();
base.OnExit(e);
}
#endregion
}
}
</code></pre>
<p>Everything works perfectly... but I have some doubts about it and I would like to receive your suggestions about how my approach could be improved.</p>
<ol>
<li><p>I was asked by Code Analysis to implement <code>IDisposable</code> interface because I was using <code>IDisposable</code> members (the <code>Mutex</code>). Is my <code>Dispose()</code> implementation good enough? Should I avoid it because it's never going to be called?</p></li>
<li><p>It's better to use <code>m_Mutex = new Mutex(true, mutexName, out mutexCreated);</code> and check for the result or to use <code>m_Mutex = new Mutex(false, mutexName);</code> and then check for <code>m_Mutex.WaitOne(TimeSpan.Zero, false);</code> ? In case of multithreading I mean... </p></li>
<li><p><code>RegisterWindowMessage</code> API call should return <code>UInt32</code>... but <code>HwndSourceHook</code> is only accepting <code>Int32</code> as message value... should I be worried about unexpected behaviors (like a result bigger than <code>Int32.MaxValue</code>)?</p></li>
<li><p>In <code>OnStartup</code> override... should I execute <code>base.OnStartup(e);</code> even if another instance is already running and I'm going to shutdown the application?</p></li>
<li><p>Is there a better way to bring the existing instance to the top that doesn't need to set <code>Topmost</code> value? Maybe <code>Activate()</code>?</p></li>
<li><p>Can you see any flaw in my approach? Something concerning multithreading, bad exceptions handling and something like that? For example... what happens if my application crashes between <code>OnStartup</code> and <code>OnExit</code>?</p></li>
</ol>
|
[] |
[
{
"body": "<p>This might be against the spirit of Code Review, but you don't need to write your own single instance manager for WPF! <a href=\"http://blogs.microsoft.co.il/blogs/arik/archive/2010/05/28/wpf-single-instance-application.aspx\">Microsoft has already written code to accomplish this</a>, but it has been poorly advertised.</p>\n\n<p>Microsoft's single instance manager is extremely comprehensive, and I have yet to find any issues with it. (And if you don't want to use it, it can at least be a good reference for your own implementation.)</p>\n\n<h1>How to manage single instances in WPF</h1>\n\n<p><strong>Step 1:</strong> Add the <code>System.Runtime.Remoting</code> reference to your project.</p>\n\n<p><strong>Step 2:</strong> Add <a href=\"http://blogs.microsoft.co.il/blogs/arik/SingleInstance.cs.txt\">this single instance class</a> to your project.</p>\n\n<p><strong>Step 3:</strong> Implement the <code>ISingleInstanceApp</code> interface in your main application class in <code>App.xaml.cs</code> (this interface is provided by the <code>SingleInstance.cs</code> file).</p>\n\n<p>For example:</p>\n\n<p><code>public partial class App : Application, ISingleInstanceApp</code></p>\n\n<p><strong>Step 4:</strong> Change your startup object by going to <code>Project</code> --> <code><projectname> Properties</code> in Visual Studio, clicking the <code>Application</code> tab. Locate <code>Startup object:</code> and select the <code><projectname>.App</code> option.</p>\n\n<p><img src=\"https://i.stack.imgur.com/XzTfR.png\" alt=\"Setting WPF startup object\"></p>\n\n<p><strong>Step 5:</strong> Define a <code>Main</code> method in <code>App.xaml.cs</code>, and give it a unique string in the <code>Unique</code> variable.</p>\n\n<pre><code>// TODO: Make this unique!\nprivate const string Unique = \"Change this to something that uniquely identifies your program.\";\n\n[STAThread]\npublic static void Main()\n{ \n if (SingleInstance<App>.InitializeAsFirstInstance(Unique))\n {\n var application = new App();\n application.InitializeComponent();\n application.Run();\n\n // Allow single instance code to perform cleanup operations\n SingleInstance<App>.Cleanup();\n }\n}\n\n#region ISingleInstanceApp Members\npublic bool SignalExternalCommandLineArgs(IList<string> args)\n{\n // Handle command line arguments of second instance\n return true;\n}\n#endregion\n</code></pre>\n\n<p><strong>Step 6:</strong> Right-click on <code>App.xaml</code> in the Solution Explorer, select <code>Properties</code>, and change the Build Action to <code>Page</code>.</p>\n\n<h1>Single Instance techniques</h1>\n\n<h2>Do nothing when new instance is opened</h2>\n\n<p>If you don't want anything to happen when a single instance is launched, you don't need to modify the sample code above.</p>\n\n<h2>Activate original window when new instance is opened</h2>\n\n<p>Rather than doing nothing when a user attempts to open a second instance of the program, it's often beneficial to <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.window.activate%28v=vs.110%29.aspx\">Activate</a> the original window and change its window state to <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.windowstate%28v=vs.110%29.aspx\">WindowState.Normal</a>, which can provide an improved user experience if the original window was minimized.</p>\n\n<p>To activate and make the window visible, modify the <code>SignalExternalCommandLineArgs</code> method as shown . (Note that <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.application.mainwindow%28v=vs.110%29.aspx\"><code>MainWindow</code></a> is a property of the <code>App</code> class, not to be confused with an arbitrarily-named <code>MainWindow.xaml.cs</code> class.)</p>\n\n<pre><code>public bool SignalExternalCommandLineArgs(IList<string> args)\n{\n // Bring window to foreground\n if (this.MainWindow.WindowState == WindowState.Minimized)\n {\n this.MainWindow.WindowState = WindowState.Normal;\n }\n\n this.MainWindow.Activate();\n\n return true;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T19:06:39.230",
"Id": "86601",
"Score": "0",
"body": "using this setup, how would you for example show, activate and unminimize the windows belonging to the app already running?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-10T23:34:53.540",
"Id": "114099",
"Score": "0",
"body": "@Julien I just added an additional section to my answer called **Single Instance techniques** which answers this question. Short version: Call the `Activate()` method on the `MainWindow` property of `App`, and set its `WindowState` to `WindowState.Normal`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-26T22:12:27.907",
"Id": "166718",
"Score": "0",
"body": "@EvanWondrasek, I have tried your solution for a clickone wpf, which used WindowsFormApplictionBase before.However,both of the approach has same issue of not capture second/later instances startup args. It only works for first instance and not for anything after. I have a separate post, which describe more about the issue. Any help? http://stackoverflow.com/questions/30463690/clickonce-not-passing-second-uri"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-01T03:42:33.633",
"Id": "232006",
"Score": "0",
"body": "This solution is great, if you want to add Microsoft source code that is not given under any license only declares \"All Rights Reserved\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-17T23:50:07.623",
"Id": "259963",
"Score": "1",
"body": "Updated version available here (with an Apache license): https://code.msdn.microsoft.com/Windows-7-Taskbar-Single-4120eafd (which the original blog owner referenced in this post: http://blogs.microsoft.co.il/arik/2011/04/04/wpf-single-instance-application-update/)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-29T15:58:38.237",
"Id": "366129",
"Score": "1",
"body": "Isn't it important for App.xaml's build action to be ApplicationDefinition? Can you comment on the implications of changing it?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T00:07:13.067",
"Id": "25667",
"ParentId": "20871",
"Score": "33"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T17:22:48.303",
"Id": "20871",
"Score": "31",
"Tags": [
"c#",
"singleton",
"wpf"
],
"Title": "Single-instance WPF application"
}
|
20871
|
<p>I'm creating cards for a game of <a href="https://en.wikipedia.org/wiki/Set_%28card_game%29" rel="nofollow noreferrer">SET</a>.</p>
<p>Can the following be rewritten in a more programmatic way, possibly getting rid of the embedded <code>for</code> loops?</p>
<pre><code>function createCards() {
var cards = [];
var i, j, k, l;
for(i = 0; i < 3; i += 1)
for(j = 0; j < 3; j += 1)
for(k = 0; k < 3; k += 1)
for(l = 0; l < 3; l += 1)
cards.push([i, j, k, l]);
return cards;
}
</code></pre>
<p>Since this is code is targetting Node, I'm happy to use EcmaScript 6 features.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T19:10:23.467",
"Id": "33468",
"Score": "5",
"body": "What is the purpose of the code? Are those playing cards in a game?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T19:11:37.543",
"Id": "33469",
"Score": "0",
"body": "Yes. It's a representation for the cards in the game of Set."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T19:12:09.503",
"Id": "33470",
"Score": "0",
"body": "What does the data represent?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T19:12:40.523",
"Id": "33471",
"Score": "0",
"body": "Each card has four features, and each feature has three variations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T19:12:44.447",
"Id": "33472",
"Score": "1",
"body": "Is the code doing what it's supposed to do? Because if it is, and you don't have to throw any of the cards away later, I'd say the code is as good as it's going to get."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T19:15:28.053",
"Id": "33473",
"Score": "0",
"body": "@RobertHarvey: I have to throw away cards later."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T19:19:23.717",
"Id": "33475",
"Score": "0",
"body": "The only thing I would suggest is that you use an anonymous object instead of an array. `cards.push({shape:i,color:j,number:k+1,shade:l});`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T11:21:24.087",
"Id": "33501",
"Score": "0",
"body": "I find your simple solution more readable (and efficient) than most of the answers. I would stick with that, or with the answer you accepted."
}
] |
[
{
"body": "<p>If you wanted the number and size of dimensions for your final cards array to be dynamic, you could use a recursive solution like this (<a href=\"http://jsfiddle.net/QshGE/\"><strong>DEMO</strong></a>):</p>\n\n<pre><code>function createCards(dimensions) {\n if (dimensions.length == 0) {\n return [];\n } else if (dimensions.length == 1) {\n var cards = [];\n for (var i = 0; i < dimensions[0]; i++)\n cards.push([i]);\n return cards;\n } else {\n var subDimensions = dimensions.splice(1);\n var subCards = createCards(subDimensions);\n var cards = [];\n for (var i = 0; i < dimensions[0]; i++)\n for (var k = 0; k < subCards.length; k++) {\n cards.push([i].concat(subCards[k]));\n }\n return cards;\n }\n}\n</code></pre>\n\n<p>You would use it by passing in an array of dimensions:</p>\n\n<pre><code>var cards = createCards([3, 3, 3, 3]);\nconsole.log(cards);\n</code></pre>\n\n<p>This solution is not the most efficient due to the re-creation of all the arrays with every dimension. However, it is very flexible and should work ok for small sets.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T19:23:43.013",
"Id": "20875",
"ParentId": "20874",
"Score": "6"
}
},
{
"body": "<p>I thought of a neat solution to this. Not sure how efficient it is, but I thought it was neat.</p>\n\n<p>If you look at your result array, you'll see results from \"0000\" to \"2222\". These are the numbers from 0 to 80. In base 3!</p>\n\n<p>So, using that, I whipped up a function to create all numbers in that range as an array.</p>\n\n<pre><code>function createCards(length, max){\n var cards = [],\n // How many array elements\n total = Math.pow(max, length),\n // This will help with left padding\n // since JavaScript doesn't have str_repeat('0', length)\n pad = Math.pow(10, length).toString().substring(1),\n // temp loop variables\n index, value;\n\n for(index = 0; index < total; index++){\n // Convert number into its new base\n value = index.toString(max);\n // Left pad it so each string is the same length\n value = pad.substring(0, pad.length - value.length) + value;\n // Push into the array\n cards.push(value.split('').map(function(a){\n // Convert result to ints\n return +a;\n }));\n }\n\n return cards;\n}\n</code></pre>\n\n<p>It's called using <code>createCards(4,3)</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T19:31:50.040",
"Id": "33476",
"Score": "0",
"body": "Great answer! While trying to come up with a solution, I went with modulo and didn't even consider base 3."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T19:33:00.770",
"Id": "33477",
"Score": "0",
"body": "@Shmiddty: I noticed his loops were making all possible 4 digit numbers with the digits 0-2. Suddenly, I realized: those are 4 digit base 3 numbers! :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T22:41:55.093",
"Id": "33484",
"Score": "0",
"body": "You can easily work in base-3 without creating hundreds of strings and lambda-functions..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T11:13:32.183",
"Id": "33500",
"Score": "1",
"body": "I like the original code more than this..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T14:24:10.077",
"Id": "33508",
"Score": "0",
"body": "@HonzaBrabec: It's not the best solution, but it was the 1st thing I could come up with :-P"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T19:26:01.797",
"Id": "20876",
"ParentId": "20874",
"Score": "9"
}
},
{
"body": "<blockquote>\n <p>I'm happy to use EcmaScript 6 features</p>\n</blockquote>\n\n<p>Try <a href=\"http://wiki.ecmascript.org/doku.php?id=harmony%3aarray_comprehensions\">array comprehensions</a>!</p>\n\n<pre><code>var vals = range(0, 3);\nreturn [ [i, j, k, l] for (i of vals) for (j of vals) for (k of vals) for (l of vals) ]\n</code></pre>\n\n<p>Still, it translates to the same nested loops. If you need a variable nesting level, you can use a recursive solution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T23:11:28.090",
"Id": "33485",
"Score": "0",
"body": "Unfortunately Node.JS does not yet have array comprehensions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-27T03:41:35.410",
"Id": "166735",
"Score": "1",
"body": "Some of us who left Python were hoping to never see that kind of nightmare in our adopted homeland of Javascript…!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-08T15:40:23.787",
"Id": "532632",
"Score": "0",
"body": "As readers still seem to be coming to this post, it should be noted that this no longer works! https://stackoverflow.com/questions/31353213/does-javascript-support-array-list-comprehensions-like-python"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-08T15:49:59.793",
"Id": "532636",
"Score": "0",
"body": "@Stuart Oh, this is old indeed. The modern way would be `vals.flatMap(i => vals.flatMap(j => vals.flatMap(k => vals.map(l => [i, j, k, l]))))` I guess"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T20:21:29.783",
"Id": "20877",
"ParentId": "20874",
"Score": "13"
}
},
{
"body": "<p><em>(Updated answer in 2021)</em></p>\n<p>This question is asking for the <a href=\"https://stackoverflow.com/questions/12303989/cartesian-product-of-multiple-arrays-in-javascript\">Cartesian product of several arrays</a> and so the answers to that post will work.</p>\n<p>In the special case where the arrays are all ranges of the same length, we can write a version like this:</p>\n<pre><code>function repeatProduct(length, repetitions) {\n //--- Repeated Cartesian product of the array [0, 1, 2, ... length-1)]\n const arr = new Array(repetitions).fill(0);\n const r = [arr.slice()];\n for (let i = 0; i < length ** repetitions - 1; i++) {\n let j = repetitions - 1;\n while (arr[j] === length - 1) {\n arr[j] = 0;\n j--;\n }\n arr[j]++;\n r.push(arr.slice());\n }\n return r;\n}\nlet cards = repeatedProduct(4, 4);\n</code></pre>\n<p>Or using <code>map</code> and <code>flatMap</code>, similar to <a href=\"https://stackoverflow.com/a/43053803/567595\">this answer</a>:</p>\n<pre><code>function repeatProduct(array, repetitions) {\n let r = [[]];\n while (repetitions--) {\n r = r.flatMap(sub => array.map(item => [...sub, item]));\n }\n return r;\n}\nlet cards = repeatProduct([0, 1, 2, 3], 4);\n</code></pre>\n<p><em>Original answer from 2013:</em> A flexible solution is to start with a card with all the features set to zero, then use a <code>for</code> loop which gets the next card in the sequence, within an outer <code>while</code> loop that terminates when no more valid cards can be generated. (<a href=\"http://jsfiddle.net/y4XAd/1/\" rel=\"nofollow noreferrer\">jsfiddle</a>).</p>\n<pre><code>function createCards(dim) {\n var card = [], cards = [];\n while (card.length < dim.length) card.push(0);\n while (card.length === dim.length) {\n cards.push(card.slice(0));\n for (var feature = 0; ++card[feature] === dim[feature]; feature++) {\n card[feature] = 0;\n }\n }\n return cards;\n}\nconsole.log(createCards([3, 3, 3, 3]));\n</code></pre>\n<p>Or <a href=\"http://jsfiddle.net/4u8Gr/1/\" rel=\"nofollow noreferrer\">similarly</a> (but counting down instead of up)</p>\n<pre><code>function createCards(dim) {\n var cards = [], card = dim.slice(0);\n while (true) {\n cards.push(card.slice(0));\n for (var feature = dim.length - 1; !--card[feature]; card[feature] = dim[feature--]) {\n if (feature < 1) return cards;\n }\n }\n}\n</code></pre>\n<p>Alternatively, loop through the current set of cards, progressively adding variations of each feature.</p>\n<pre><code>function createCards(dim) {\n var cards = [dim.slice(0)];\n for (var feature = 0; feature < dim.length; feature++) {\n var numberOfCards = cards.length;\n for (var variation = dim[feature] - 1; variation > 0; variation--) {\n for (var i = 0; i < numberOfCards; i++) {\n var card = cards[i].slice(0);\n card[feature] = variation;\n cards.push(card);\n }\n }\n }\n return cards;\n}\n</code></pre>\n<p>These should have the same result as mellamokb's answer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-01-24T22:05:05.040",
"Id": "20880",
"ParentId": "20874",
"Score": "3"
}
},
{
"body": "<p>Check check it out <a href=\"http://jsfiddle.net/GpAUP/\" rel=\"nofollow\">http://jsfiddle.net/GpAUP/</a></p>\n\n<p>Here is the meat of the code:</p>\n\n<pre><code>var maxSize = 3*3*3*3;\nfor(var i = 0; i < maxSize; ++i){ \n var a = Math.floor(i/27) % 3;\n var b = Math.floor(i/9) % 3;\n var c = Math.floor(i/3) % 3;\n var d = i % 3; \n $(\"body\").append(a + \",\" + b + \",\" + c + \",\" + d );\n $(\"body\").append(\"<br />\");\n}\n</code></pre>\n\n<p>essentially using modulus and a little linear math. You want <code>cards.push([a,b,c,d])</code> instead of appending to body. You can change the ordering if you want it a different way.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T23:10:04.643",
"Id": "20882",
"ParentId": "20874",
"Score": "2"
}
},
{
"body": "<p>The code seems fine except for omitting curly braces and unfortunate naming.</p>\n<p>I would name the features and their variations.</p>\n<pre><code>const numbers = [1, 2, 3];\nconst colors = ["Red", "Green", "Blue"];\nconst shapes = ["Diamond", "Ellipse", "Swirl"];\nconst shades = ["Full", "Striped", "Empty"];\n\nfunction createDeck() {\n\n const deck = [];\n for(const number of numbers)\n for(const color of colors)\n for(const shapes of shapes)\n for(const shade of shades)\n deck.push({number, color, shape, shade});\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-09T08:24:18.020",
"Id": "269901",
"ParentId": "20874",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20877",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-01-24T19:08:20.623",
"Id": "20874",
"Score": "14",
"Tags": [
"javascript",
"node.js",
"ecmascript-6",
"playing-cards"
],
"Title": "Creating cards for a game of SET"
}
|
20874
|
<p>I was solving some <code>Haskell</code> exercises as a way to refresh some of the language concepts.</p>
<p>I encounter the following exercise:</p>
<pre><code>data LTree a = Leaf a | Fork (LTree a) (LTree a)
crossing :: LTree a -> [(a,Int)]
crossing (Leaf x) = [(x,0)]
crossing (Fork e d) = map(\(x,y) -> (x,y+1)) (crossing e ++ crossing d)
</code></pre>
<p>The above function basically takes a Ltree and turns into a list of pars (Lists the tree leaves, along with their depth).</p>
<p>The exercise is to make a function <code>build :: [(a,Int)] -> LTree a</code>, that does the inverse of the <code>crossing</code> function, such as <code>build (crossing a) = a</code> for any 'a' tree.</p>
<p>What I have done so far:</p>
<pre><code>build :: [(a,Int)] -> LTree a
build l = fst (multConvert (map (\(x,n) -> (Leaf x, n)) l))
multConvert :: [(LTree a,Int)] -> (LTree a,Int)
multConvert [x] = x
multConvert l = multConvert (convert l)
convert :: [(LTree a,Int)] -> [(LTree a,Int)]
convert [] = []
convert [x] = [x]
convert ((a,b):(c,d):xs) | b == d = ((Fork a c),(b-1)):xs
| otherwise = (a,b):convert ((c,d):xs)
</code></pre>
<p>Basically, I turn the list produce by the <code>crossing</code> into an list of (LTree,a) , for example <code>[(3,3),(4,3)..]</code> becomes <code>[(Leaf 3, 3), (Leaf 4, 3)...]</code>. The <code>convert</code> function will take this list of <code>(LTree,a)</code> and turn consecutive elements with the same depth into a <code>Fork</code> with both elements. For example <code>[(Leaf 3, 3), (Leaf 4, 3), (Leaf 5, 2)...]</code> becomes <code>[(Fork (Leaf 3) (Leaf 4),2), (Leaf 5, 2)...]</code>. Note, that the new produced element have a depth-1.</p>
<p><code>multConvert</code> function will apply the above idea on the list, over and over, until this list have only one element. This element will represent the original tree. In other words, my algorithm builds the Ltree using a bottom up approach.</p>
<p>I would like to know if there is a more robust way to solve this problem. For example using high order functions, instead of explicitly recursive (possibly using <code>foldr</code>).</p>
|
[] |
[
{
"body": "<p>I think this is a continuation-passing solution (simple parser) for writing <code>build</code>:</p>\n\n<pre><code>build :: [(a,Int)] -> LTree a\nbuild xs = parseAt 0 xs fst\n\n-- The first Int is the depth of the \"root\" of parseAt\nparseAt :: Int -> [(a,Int)] -> ( (LTree a, [(a,Int)]) -> r ) -> r\nparseAt r [] k = error \"input too short\"\nparseAt r xs@((a,n):rest) k =\n case compare r n of\n GT -> error \"depth too small\"\n EQ -> k (Leaf a,rest)\n LT -> parseAt (succ r) xs (\\ (left,rest1) ->\n parseAt (succ r) rest1 (\\ (right,rest2) ->\n k (Fork left right, rest2)))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T22:01:09.720",
"Id": "20879",
"ParentId": "20878",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20879",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T21:18:00.577",
"Id": "20878",
"Score": "1",
"Tags": [
"haskell"
],
"Title": "Ltree inverse crossing function using high order functions"
}
|
20878
|
<p>I've been working on converting some legacy code from T-SQL stored procedures. My aim is to use DDD to make the transition. Below is an attempt to do this. Any comments on how well this is following DDD? Also any comments on the AreaGeneration domain service and its CalculateLocationsInArea would be most appreciated.</p>
<pre><code> //consumer code
var locationRepository = new LocationRepository();
//areaGenerator is a domain service which is used to calculate locations between a from and to location
var areaGenerator = new AreaGenerator(locationRepository);
var areaParameters = new List<AreaParameter>
{
new AreaParameter("A001A", "A002B", AreaDirection.Column),
new AreaParameter("A001A", "A003C", AreaDirection.Row)
};
var locations = areaGenerator.CalculateLocationsInArea(areaParameters);
var area = Area.CreateArea("Test Area", "Special Area",areaParameters,locations);
public class Location
{
public string LocationCode { get; set; }
public int LocationID { get; set; }
public int Aisle { get; set; }
public int Column { get; set; }
public int Row { get; set; }
public string SortKey
{
get { return Aisle + "," + Column + "," + Row; }
}
}
public class AreaParameter
{
public AreaParameter(string fromLocation, string toLocation, AreaDirection areaDirection)
{
StartLocation = fromLocation;
EndLocation = toLocation;
AreaDirecton = areaDirection;
}
public string StartLocation { get; private set; }
public string EndLocation { get; private set; }
public AreaDirection AreaDirecton { get; private set; }
}
public class AreaGenerator
{
private readonly ILocationRepository _locationRepository;
public AreaGenerator(ILocationRepository locationRepository)
{
_locationRepository = locationRepository;
}
internal IEnumerable<Location> CalculateLocationsInArea(List<AreaParameter> areaParameters)
{
var locationsInArea = new List<Location>();
foreach (var areaDetail in areaParameters)
{
var startLocation = _locationRepository.GetLocationByCode(areaDetail.StartLocation);
var endLocation = _locationRepository.GetLocationByCode(areaDetail.EndLocation);
var startAisle = startLocation.Aisle;
var startColumn = startLocation.Column;
var startRow = startLocation.Row;
var endAisle = endLocation.Aisle;
var endColumn = endLocation.Column;
var endRow = endLocation.Row;
switch (areaDetail.AreaDirecton)
{
case AreaDirection.Row:
if (startAisle == endAisle)
{
Func<Location, bool> withinAisleAndColAndNotLastRow =
l =>
((l.Aisle == startAisle && l.Column >= startColumn && l.Row == startRow) &&
startRow != endRow)
||
((l.Aisle == startAisle && l.Column <= endColumn && l.Row == endRow) &&
startRow != endRow);
Func<Location, bool> withinAisleAndColAndIsLastRow =
l =>
((l.Aisle == startAisle && l.Column >= startColumn && l.Column <= endColumn &&
l.Row == startRow) && startRow == endRow)
||
((l.Aisle == startAisle && l.Column >= startColumn && l.Column <= endColumn &&
l.Row == endRow) && startRow == endRow);
Func<Location, bool> inBetweener =
l => l.Aisle == startAisle && l.Row > startRow && l.Row < endRow;
var results =
_locationRepository.GetLocations(
l =>
withinAisleAndColAndNotLastRow(l) || withinAisleAndColAndIsLastRow(l) ||
inBetweener(l));
locationsInArea.AddRange(results);
}
else
{
Func<Location, bool> withinAisleAndColAndIsLastRow =
l => (l.Aisle == startAisle && l.Column >= startColumn && l.Row == startRow)
|| (l.Aisle == endAisle && l.Column <= endColumn && l.Row == endRow);
Func<Location, bool> withinAisleAndColAndNotLastRow =
l =>
((l.Aisle == startAisle && l.Row > startRow) || (l.Aisle == endAisle && l.Row < endRow));
Func<Location, bool> inBetweener = l => l.Aisle > startAisle && l.Aisle < endAisle;
var results =
_locationRepository.GetLocations(
l =>
withinAisleAndColAndNotLastRow(l) || withinAisleAndColAndIsLastRow(l) ||
inBetweener(l));
locationsInArea.AddRange(results);
}
break;
case AreaDirection.Column:
Func<Location, bool> predicate1 =
l => ((l.Aisle == startAisle && l.Row >= startRow && l.Column == startColumn)
|| (l.Aisle > startAisle && l.Aisle < endAisle && l.Column == startColumn));
Func<Location, bool> predicate2 =
l =>
((l.Aisle >= startAisle & l.Aisle <= endAisle &&
l.Column > startColumn & l.Column < endColumn)
|| (l.Aisle == endAisle && l.Row <= endRow && l.Column == endColumn));
var locations = _locationRepository.GetLocations(l => predicate1(l) || predicate2(l));
locationsInArea.AddRange(locations);
break;
case AreaDirection.ALL:
var allLocations =
_locationRepository.GetLocations(
l =>
l.SortKey.CompareTo(startLocation.SortKey) >= 0 &&
l.SortKey.CompareTo(endLocation.SortKey) <= 0);
locationsInArea.AddRange(allLocations);
break;
default:
break;
}
}
return locationsInArea.OrderBy(l => l.Aisle).ThenBy(l => l.Column).ThenBy(l => l.Row);
}
}
public class Area
{
private string areaName;
private string areaDescription;
private readonly IList<Location> _locationsInArea;
private List<AreaParameter> _areaParameters;
private Area(string areaName, string areaDescription)
{
this.areaName = areaName;
this.areaDescription = areaDescription;
_locationsInArea = new List<Location>();
}
internal static Area CreateArea(string areaName, string areaDescription, List<AreaParameter> areaParameters,
IEnumerable<Location> locationsInArea)
{
var area = new Area(areaName, areaDescription);
area.AddAreaParameters(areaParameters);
area.AddLocationsToArea(locationsInArea);
return area;
}
private void AddLocationsToArea(IEnumerable<Location> locationsInArea)
{
foreach (var location in locationsInArea)
{
if (_locationsInArea.Any(l => l.LocationID == location.LocationID))
{
continue;
}
_locationsInArea.Add(location);
}
}
private void AddAreaParameters(List<AreaParameter> areaParameters)
{
_areaParameters = areaParameters;
}
}
public interface ILocationRepository
{
Location GetLocationByCode(string LocationCode);
IEnumerable<Location> GetLocations(Func<Location, bool> predicate);
}
public class LocationRepository : ILocationRepository
{
private readonly List<Location> _locations;
public LocationRepository()
{
_locations = new List<Location>
{
new Location {LocationCode = "A001A", LocationID = 1, Aisle = 1, Column = 1, Row = 1},
new Location {LocationCode = "A001B", LocationID = 2, Aisle = 1, Column = 1, Row = 2},
new Location {LocationCode = "A001C", LocationID = 3, Aisle = 1, Column = 1, Row = 3},
new Location {LocationCode = "A002A", LocationID = 4, Aisle = 1, Column = 2, Row = 1},
new Location {LocationCode = "A002B", LocationID = 5, Aisle = 1, Column = 2, Row = 2},
new Location {LocationCode = "A002C", LocationID = 6, Aisle = 1, Column = 2, Row = 3},
new Location {LocationCode = "A003A", LocationID = 7, Aisle = 1, Column = 3, Row = 1},
new Location {LocationCode = "A003B", LocationID = 8, Aisle = 1, Column = 3, Row = 2},
new Location {LocationCode = "A003C", LocationID = 9, Aisle = 1, Column = 3, Row = 3},
new Location {LocationCode = "A004A", LocationID = 10, Aisle = 1, Column = 4, Row = 1},
new Location {LocationCode = "A004B", LocationID = 11, Aisle = 1, Column = 4, Row = 2},
new Location {LocationCode = "A004C", LocationID = 12, Aisle = 1, Column = 4, Row = 3},
new Location {LocationCode = "B001A", LocationID = 13, Aisle = 2, Column = 1, Row = 1},
new Location {LocationCode = "B001B", LocationID = 14, Aisle = 2, Column = 1, Row = 2},
new Location {LocationCode = "B001C", LocationID = 15, Aisle = 2, Column = 1, Row = 3},
};
}
public Location GetLocationByCode(string LocationCode)
{
return _locations.FirstOrDefault(l => l.LocationCode == LocationCode);
}
public IEnumerable<Location> GetLocations(Func<Location, bool> predicate)
{
return _locations.Where(l => predicate(l));
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I do like what you've done here. I'm a big fan of immutable objects and interface-based programming (for dependency injection, mocking via unit tests, etc.), so I've done a little squidging to make those happen as per below:</p>\n\n<pre><code> // consumer code\n var locationRepository = new LocationRepository();\n\n // areaGenerator is a domain service which is used to calculate locations between a from and to location\n var areaGenerator = new AreaGenerator(locationRepository);\n var areaParameters = new AreaParameterList\n {\n { \"A001A\", \"A002B\", AreaDirection.Column },\n { \"A001A\", \"A003C\", AreaDirection.Row }\n };\n var locations = areaGenerator.CalculateLocationsInArea(areaParameters);\n var area = Area.CreateArea(\"Test Area\", \"Special Area\", areaParameters, locations);\n\n Console.WriteLine(\"Area Name: \" + area.AreaName);\n Console.WriteLine(\"Area Description: \" + area.AreaDescription);\n Console.WriteLine(\"Area Parameters:\");\n foreach (var parameter in area.AreaParameters)\n {\n Console.WriteLine(\"\\tStart Location: \" + parameter.StartLocation);\n Console.WriteLine(\"\\tEnd Location: \" + parameter.EndLocation);\n Console.WriteLine(\"\\tDirection: \" + parameter.AreaDirection);\n Console.WriteLine();\n }\n\n Console.WriteLine(\"Locations in Area:\");\n foreach (var location in area.LocationsInArea)\n {\n Console.WriteLine(\"\\tLocation Code: \" + location.LocationCode);\n Console.WriteLine(\"\\tLocation ID: \" + location.LocationID);\n Console.WriteLine(\"\\tAisle: \" + location.Aisle);\n Console.WriteLine(\"\\tColumn: \" + location.Column);\n Console.WriteLine(\"\\tRow: \" + location.Row);\n Console.WriteLine();\n }\n\n Console.ReadLine();\n\npublic enum AreaDirection\n{\n Column,\n\n Row,\n\n ALL\n}\n\npublic interface ILocation\n{\n string LocationCode { get; }\n\n int LocationID { get; }\n\n int Aisle { get; }\n\n int Column { get; }\n\n int Row { get; }\n\n string SortKey { get; }\n}\n\npublic sealed class Location : ILocation\n{\n private readonly string locationCode;\n\n private readonly int locationId;\n\n private readonly int aisle;\n\n private readonly int column;\n\n private readonly int row;\n\n public Location(string locationCode, int locationId, int aisle, int column, int row)\n {\n this.locationCode = locationCode;\n this.locationId = locationId;\n this.aisle = aisle;\n this.column = column;\n this.row = row;\n }\n\n public string LocationCode\n {\n get\n {\n return this.locationCode;\n }\n }\n\n public int LocationID\n {\n get\n {\n return this.locationId;\n }\n }\n\n public int Aisle\n {\n get\n {\n return this.aisle;\n }\n }\n\n public int Column\n {\n get\n {\n return this.column;\n }\n }\n\n public int Row\n {\n get\n {\n return this.row;\n }\n }\n\n public string SortKey\n {\n get\n {\n return this.aisle + \",\" + this.column + \",\" + this.row;\n }\n }\n}\n\npublic interface ILocationList : IList<ILocation>\n{\n void Add(string locationCode, int locationId, int aisle, int column, int row);\n}\n\npublic sealed class LocationList : List<ILocation>, ILocationList\n{\n public void Add(string locationCode, int locationId, int aisle, int column, int row)\n {\n this.Add(new Location(locationCode, locationId, aisle, column, row));\n }\n}\n\npublic interface IAreaParameter\n{\n string StartLocation { get; }\n\n string EndLocation { get; }\n\n AreaDirection AreaDirection { get; }\n}\n\npublic sealed class AreaParameter : IAreaParameter\n{\n private readonly string startLocation;\n\n private readonly string endLocation;\n\n private readonly AreaDirection areaDirection;\n\n public AreaParameter(string fromLocation, string toLocation, AreaDirection areaDirection)\n {\n this.startLocation = fromLocation;\n this.endLocation = toLocation;\n this.areaDirection = areaDirection;\n }\n\n public string StartLocation\n {\n get\n {\n return this.startLocation;\n }\n }\n\n public string EndLocation\n {\n get\n {\n return this.endLocation;\n }\n }\n\n public AreaDirection AreaDirection\n {\n get\n {\n return this.areaDirection;\n }\n }\n}\n\npublic interface IAreaParameterList : IList<IAreaParameter>\n{\n void Add(string fromLocation, string toLocation, AreaDirection areaDirection);\n}\n\npublic sealed class AreaParameterList : List<IAreaParameter>, IAreaParameterList\n{\n public void Add(string fromLocation, string toLocation, AreaDirection areaDirection)\n {\n this.Add(new AreaParameter(fromLocation, toLocation, areaDirection));\n }\n}\n\npublic sealed class AreaGenerator\n{\n private readonly ILocationRepository locationRepository;\n\n public AreaGenerator(ILocationRepository locationRepository)\n {\n this.locationRepository = locationRepository;\n }\n\n internal IEnumerable<ILocation> CalculateLocationsInArea(IAreaParameterList areaParameters)\n {\n var locationsInArea = new LocationList();\n\n foreach (var areaDetail in areaParameters)\n {\n var startLocation = this.locationRepository.GetLocationByCode(areaDetail.StartLocation);\n var endLocation = this.locationRepository.GetLocationByCode(areaDetail.EndLocation);\n var startAisle = startLocation.Aisle;\n var startColumn = startLocation.Column;\n var startRow = startLocation.Row;\n var endAisle = endLocation.Aisle;\n var endColumn = endLocation.Column;\n var endRow = endLocation.Row;\n\n switch (areaDetail.AreaDirection)\n {\n case AreaDirection.Row:\n if (startAisle == endAisle)\n {\n Func<ILocation, bool> withinAisleAndColAndNotLastRow = l =>\n ((l.Aisle == startAisle && l.Column >= startColumn && l.Row == startRow) &&\n startRow != endRow)\n ||\n ((l.Aisle == startAisle && l.Column <= endColumn && l.Row == endRow) &&\n startRow != endRow);\n Func<ILocation, bool> withinAisleAndColAndIsLastRow = l =>\n ((l.Aisle == startAisle && l.Column >= startColumn && l.Column <= endColumn &&\n l.Row == startRow) && startRow == endRow)\n ||\n ((l.Aisle == startAisle && l.Column >= startColumn && l.Column <= endColumn &&\n l.Row == endRow) && startRow == endRow);\n Func<ILocation, bool> inBetweener = l =>\n l.Aisle == startAisle && l.Row > startRow && l.Row < endRow;\n var results = this.locationRepository.GetLocations(l =>\n withinAisleAndColAndNotLastRow(l) || withinAisleAndColAndIsLastRow(l) ||\n inBetweener(l));\n\n locationsInArea.AddRange(results);\n }\n else\n {\n Func<ILocation, bool> withinAisleAndColAndIsLastRow = l =>\n (l.Aisle == startAisle && l.Column >= startColumn && l.Row == startRow)\n || (l.Aisle == endAisle && l.Column <= endColumn && l.Row == endRow);\n Func<ILocation, bool> withinAisleAndColAndNotLastRow = l =>\n ((l.Aisle == startAisle && l.Row > startRow) || (l.Aisle == endAisle && l.Row < endRow));\n Func<ILocation, bool> inBetweener = l => l.Aisle > startAisle && l.Aisle < endAisle;\n var results = this.locationRepository.GetLocations(l =>\n withinAisleAndColAndNotLastRow(l) || withinAisleAndColAndIsLastRow(l) ||\n inBetweener(l));\n\n locationsInArea.AddRange(results);\n }\n\n break;\n case AreaDirection.Column:\n Func<ILocation, bool> predicate1 = l =>\n ((l.Aisle == startAisle && l.Row >= startRow && l.Column == startColumn)\n || (l.Aisle > startAisle && l.Aisle < endAisle && l.Column == startColumn));\n Func<ILocation, bool> predicate2 = l =>\n ((l.Aisle >= startAisle & l.Aisle <= endAisle &&\n l.Column > startColumn & l.Column < endColumn)\n || (l.Aisle == endAisle && l.Row <= endRow && l.Column == endColumn));\n var locations = this.locationRepository.GetLocations(l => predicate1(l) || predicate2(l));\n\n locationsInArea.AddRange(locations);\n break;\n case AreaDirection.ALL:\n var allLocations =\n this.locationRepository.GetLocations(\n l =>\n l.SortKey.CompareTo(startLocation.SortKey) >= 0 &&\n l.SortKey.CompareTo(endLocation.SortKey) <= 0);\n locationsInArea.AddRange(allLocations);\n break;\n }\n }\n\n return locationsInArea.OrderBy(l => l.Aisle).ThenBy(l => l.Column).ThenBy(l => l.Row);\n }\n}\n\npublic interface IArea\n{\n string AreaName { get; }\n\n string AreaDescription { get; }\n\n IAreaParameterList AreaParameters { get; }\n\n IEnumerable<ILocation> LocationsInArea { get; }\n}\n\npublic sealed class Area : IArea\n{\n private readonly string areaName;\n\n private readonly string areaDescription;\n\n private readonly IAreaParameterList areaParameters;\n\n private readonly ILocationList locationsInArea = new LocationList();\n\n private Area(string areaName, string areaDescription, IAreaParameterList areaParameters)\n {\n this.areaName = areaName;\n this.areaDescription = areaDescription;\n this.areaParameters = areaParameters;\n }\n\n public string AreaName\n {\n get\n {\n return this.areaName;\n }\n }\n\n public string AreaDescription\n {\n get\n {\n return this.areaDescription;\n }\n }\n\n public IAreaParameterList AreaParameters\n {\n get\n {\n return this.areaParameters;\n }\n }\n\n public IEnumerable<ILocation> LocationsInArea\n {\n get\n {\n return this.locationsInArea;\n }\n }\n\n internal static IArea CreateArea(\n string areaName,\n string areaDescription,\n IAreaParameterList areaParameters,\n IEnumerable<ILocation> locationsInArea)\n {\n var area = new Area(areaName, areaDescription, areaParameters);\n\n area.AddLocationsToArea(locationsInArea);\n return area;\n }\n\n private void AddLocationsToArea(IEnumerable<ILocation> newLocationsInArea)\n {\n foreach (var location in newLocationsInArea.Where(location => this.locationsInArea.All(l => l.LocationID != location.LocationID)))\n {\n this.locationsInArea.Add(location);\n }\n }\n}\n\npublic interface ILocationRepository\n{\n ILocation GetLocationByCode(string LocationCode);\n\n IEnumerable<ILocation> GetLocations(Func<ILocation, bool> predicate);\n}\n\npublic sealed class LocationRepository : ILocationRepository\n{\n private static readonly ILocationList locations = new LocationList\n {\n { \"A001A\", 1, 1, 1, 1 },\n { \"A001B\", 2, 1, 1, 2 },\n { \"A001C\", 3, 1, 1, 3 },\n { \"A002A\", 4, 1, 2, 1 },\n { \"A002B\", 5, 1, 2, 2 },\n { \"A002C\", 6, 1, 2, 3 },\n { \"A003A\", 7, 1, 3, 1 },\n { \"A003B\", 8, 1, 3, 2 },\n { \"A003C\", 9, 1, 3, 3 },\n { \"A004A\", 10, 1, 4, 1 },\n { \"A004B\", 11, 1, 4, 2 },\n { \"A004C\", 12, 1, 4, 3 },\n { \"B001A\", 13, 2, 1, 1 },\n { \"B001B\", 14, 2, 1, 2 },\n { \"B001C\", 15, 2, 1, 3 }\n };\n\n public ILocation GetLocationByCode(string LocationCode)\n {\n return locations.FirstOrDefault(l => l.LocationCode == LocationCode);\n }\n\n public IEnumerable<ILocation> GetLocations(Func<ILocation, bool> predicate)\n {\n return locations.Where(predicate);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T15:41:24.763",
"Id": "20899",
"ParentId": "20883",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-24T23:53:10.253",
"Id": "20883",
"Score": "7",
"Tags": [
"c#",
"design-patterns"
],
"Title": "How can I make this C# code better so it more closely follows DDD principles? Am I using factory correctly?"
}
|
20883
|
<p>Please tell me if this function is correct (I believe it to be), efficient, and clean.</p>
<p>Function to check:</p>
<pre><code>::CURLcode CURL_DownloadFile( __in ::LPCSTR URL, __in ::LPCSTR Destination )
{
::CURL* Curl;
::CURLcode Return_CurlCode;
std::FILE* File;
if( ( Curl = ::curl_easy_init( ) ) )
{
File = std::fopen( Destination, "wb" );
::curl_easy_setopt( Curl, CURLOPT_URL, URL );
::curl_easy_setopt( Curl, CURLOPT_WRITEFUNCTION, WriteData );
::curl_easy_setopt( Curl, CURLOPT_WRITEDATA, File );
Return_CurlCode = ::curl_easy_perform( Curl );
std::fclose( File );
} else { ( Return_CurlCode = CURLE_FAILED_INIT ); }
return( Return_CurlCode );
};
</code></pre>
<p>Example of usage:</p>
<pre><code>#include "Global.h"
::CURLcode CURL_DownloadFile( __in ::LPCSTR URL, __in ::LPCSTR Destination );
int main( void )
{
if( CURL_DownloadFile( "http://stackoverflow.com/", "c:\\users\\xorr\\desktop\\stackoverflow.txt" ) != CURLE_OK )
std::printf( "An error has occured...\n" );
std::cin.get( );
return( EXIT_SUCCESS );
// Xorr@Hotmail.com
};
size_t WriteData( void *ptr, size_t size, size_t nmemb, std::FILE *stream ) {
size_t written;
written = fwrite(ptr, size, nmemb, stream);
return written;
}
::CURLcode CURL_DownloadFile( __in ::LPCSTR URL, __in ::LPCSTR Destination )
{
::CURL* Curl;
::CURLcode Return_CurlCode;
std::FILE* File;
if( ( Curl = ::curl_easy_init( ) ) )
{
File = std::fopen( Destination, "wb" );
::curl_easy_setopt( Curl, CURLOPT_URL, URL );
::curl_easy_setopt( Curl, CURLOPT_WRITEFUNCTION, WriteData );
::curl_easy_setopt( Curl, CURLOPT_WRITEDATA, File );
Return_CurlCode = ::curl_easy_perform( Curl );
std::fclose( File );
} else { ( Return_CurlCode = CURLE_FAILED_INIT ); }
return( Return_CurlCode );
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T03:10:13.060",
"Id": "33490",
"Score": "0",
"body": "One obvious thing that strikes me is `::CURLcode Return_CurlCode;` is never initialized if `::curl_easy_init()` returns false."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T03:47:57.593",
"Id": "33492",
"Score": "0",
"body": "@Matthew thanks! Fixed it. This is what I added: else { ( Return_CurlCode = CURLE_FAILED_INIT ); }"
}
] |
[
{
"body": "<p>Your write function is incorrect:</p>\n\n<pre><code>size_t WriteData( void *ptr, size_t size, size_t nmemb, std::FILE *stream ) {\n size_t written;\n written = fwrite(ptr, size, nmemb, stream);\n return written;\n}\n</code></pre>\n\n<p>CURL will abort the transfer if you do not return <code>size*nmemb</code>. So you need to take care to make sure that you actually write all the data provided.</p>\n\n<p>Also this is the action of the default <code>CURLOPT_WRITEFUNCTION</code> so there is no need to write your own version.</p>\n\n<p>You don't check if the File pointer is NULL</p>\n\n<pre><code> File = std::fopen( Destination, \"wb\" );\n</code></pre>\n\n<p>This is a C function (even if you have used it from C++). This means you must check the return value to make sure the faction succeeded.</p>\n\n<p>Don't artifically stop the application. You may forget to remove this and then it will make the program look like it is broken.</p>\n\n<pre><code>std::cin.get( );\n</code></pre>\n\n<p>If you run from the command line it is not needed. If you are running inside an IDE set up your IDE so that it does not close the output window when the application finishes.</p>\n\n<p>If your program always succeeded. Then I prefer not to return an exit value from main(). The compiler in this one special case will plant a <code>return 0;</code> for you to indicate success. This is a good indication that you have designed your application so that it never fails.</p>\n\n<pre><code>return( EXIT_SUCCESS );\n</code></pre>\n\n<p>I only return a value if there is a potential for failure and I want to be able to indicate the possible failure states.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T10:20:58.487",
"Id": "35001",
"Score": "0",
"body": "Isn't a `return 0` a good indication that something suceeds... ? This is more explicit and clearer to me than letting the compiler do it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T16:37:39.777",
"Id": "35007",
"Score": "0",
"body": "@Cygal: No. If you have a return at the end of main() you are indicating that there is a possibility of a failure. With no return you are indicating that there is no error condition that will ever be returned by the application."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T10:48:44.370",
"Id": "20891",
"ParentId": "20886",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T02:18:30.237",
"Id": "20886",
"Score": "3",
"Tags": [
"c++",
"file-system",
"curl"
],
"Title": "DownloadFile Function (using LibCurl)"
}
|
20886
|
<p>I wondered if anyone has any ideas to make this cleaner or more efficient. Mostly this was an exercise to generate the data once (So speed really isn't too important, but I'd love to see what techniques you could think of)
This is an algorithm I derived and implemented without external guidance of any kind, so I'm asking for guidance now.</p>
<p>This does give the output I am expecting, I validated it with a recursive implementation that I made first.</p>
<p>I'm thinking this might be helpful in validating solutions, or in generating new boards.</p>
<p>For the Sudoku table:</p>
<pre><code>--1 --- ---
--- 1-- ---
--- --- --1
--- -1- ---
1-- --- ---
--- --- 1--
--- --- -1-
--- --1 ---
-1- --- ---
</code></pre>
<p>1 would be represented by the array: 238316751. In the first 9 cell box, the 1 is at position 2 in the array of that box.</p>
<pre><code>///This outputs the valid pointers
///for example 327742830 is valid, a number could be in pos 3 of cell 0, 2 in cell 1, etc
/// So arrays are compatable when no columns have the same number in them
/// A starting board with a high number of compatable arrays would be very difficult i believe
public IEnumerable<string> OutputArrayPoints()
{
return OutputArrayPoints(new int[9]);
}
//Will contain the cell indexes that are not excluded by other cells already
int[][] ToCheck = new int[9][];
//Pointers to the current cell indexes in use
int[] ToCheckPointers = new int[9];
//arrayPoints will contain the current value to return
//Really it should be equal to loop through ToCheck[c][ToCheckPointers[c]]
public IEnumerable<string> OutputArrayPoints(int[] arrayPoints)
{
//This loop is basically a depth first search
//ToCheck gets filled with possible values for each cell,
// and the lowest pointer gets incremented until it runs out,
// then moves up a cell to go down a different path
for (int c = 0; c >= 0; /*++c*/)
{
if (c == 8 && ToCheck[c] != null && ToCheckPointers[c] < ToCheck[c].Length)
{
//Should be a valid solution, yield it
yield return GetResult(arrayPoints);
++ToCheckPointers[c];
}
else if (c < 9 && ToCheck[c] != null && ToCheckPointers[c] < ToCheck[c].Length)
{
//Fill this cell of arrayPointers, and move to the next
arrayPoints[c] = ToCheck[c][ToCheckPointers[c]];
++c;
}
else if (ToCheck[c] != null && ToCheckPointers[c] == ToCheck[c].Length)
{
//ToCheck at this level has been fully processed, clear it out
ToCheck[c] = null;
//Step up a cell to start processing the next
--c;
//if c is less than 0, we have gone through every option
if (c == -1) yield break;
//Increase the pointer I'm pointing at
++ToCheckPointers[c];
}
else if (c < 9 && ToCheck[c] == null)
{
//Fill any empty ones
ToCheck[c] = CellsToCheck(arrayPoints, c).ToArray();
ToCheckPointers[c] = 0;
//lazy? (could this be in a cleaner spot? or do I need to store arrayPoints at all?):
arrayPoints[c] = ToCheck[c][ToCheckPointers[c]];
if (c < 8) ++c;
}
}
}
//Return the cells that are possible given the other positions taken
IEnumerable<int> CellsToCheck(int[] arrayPoints, int depth)
{
int rowSkip1 = (depth % 3) > 0 ? arrayPoints[depth - 1] / 3 : -1;
int rowSkip2 = (depth % 3) > 1 ? arrayPoints[depth - 2] / 3 : -1;
int colSkip1 = depth > 2 ? arrayPoints[depth - 3] % 3 : -1;
int colSkip2 = depth > 5 ? arrayPoints[depth - 6] % 3 : -1;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
if ((rowSkip1 != i && rowSkip2 != i)
&& (colSkip1 != j && colSkip2 != j)) yield return j + i*3;
}
}
}
//Return a string representation
string GetResult(IEnumerable<int> cells)
{
return string.Join("", cells.Select(i => i.ToString()).ToArray());
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T15:35:47.243",
"Id": "33513",
"Score": "3",
"body": "First and foremost: if you have any complicated algorithm in your code, *you need to explain it* in comments. Otherwise, it's hard to understand what your code does, which makes it hard to review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T20:27:25.043",
"Id": "33526",
"Score": "0",
"body": "I added a few comments now, some of the operations I'm not clear how to best describe at this point. In essence it should be very similar to the 8 queens chess problem, but without the diagonal and can't be in the same block of 9 cells (I just thought of that similarity, so really looking up that would be about all the info I'd need..)"
}
] |
[
{
"body": "<ul>\n<li><p>You have some \"Magic Numbers\". If you wanted to work with a different grid size you'd have to replace <code>9</code> at many different places. Find the relationships between your hard-coded numbers and declare them as <code>const</code>. For example, <code>const int Size = 9;</code> and <code>const int Box = 3;</code></p></li>\n<li><p>I like that you are using <code>yield</code></p></li>\n<li><p>Your code is quite hard to understand, even with your comments. This can have something to do with your <strong>variable names</strong> probably. <code>ToCheck</code> for example, if that is checking rows, columns, values, what kind of values, etc. is not clear at all from the name. From what I understand, you are sometimes considering the array indexes as index of a 3x3 grid, and sometimes as a row/column. That's confusing for me.</p></li>\n<li><p>Instead of using integer arrays, you could use <code>Set<int></code>.</p></li>\n<li><p><code>int[][] ToCheck</code> and <code>int[] ToCheckPointers</code> should be local variables inside the <code>OutputArrayPoints</code> method, they do not seem to be used outside it.</p></li>\n<li><p>As you are not incrementing the <code>c</code> variable on every iteration, I would use a <code>while (c >= 0)</code> rather than <code>for</code>.</p></li>\n<li><p>Slightly related is <a href=\"https://codereview.stackexchange.com/questions/37448/sudokusharp-solver-with-advanced-features\">my Code Review question for a Sudoku Solver</a>, it might give you an idea of how things can be organized into a more object-oriented approach</p></li>\n<li><p>All things considered, I must say that your code seems to be quite fast. I am quite sure it can be made faster but it's hard to tell how exactly because of the lack of clarity of the code.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-27T18:08:56.383",
"Id": "45530",
"ParentId": "20888",
"Score": "6"
}
},
{
"body": "<p>The loop in <code>OutputArrayPoints</code> has several redundant conditions. Introducing a bit of nesting will allow easier refactoring later:</p>\n\n<pre><code>if (c == 8 && ToCheck[c] != null && ToCheckPointers[c] < ToCheck[c].Length)\n{ /* */ }\nelse if (c < 9 && ToCheck[c] != null && ToCheckPointers[c] < ToCheck[c].Length)\n{ /* */ }\nelse if (ToCheck[c] != null && ToCheckPointers[c] == ToCheck[c].Length)\n{ /* */ }\nelse if (c < 9 && ToCheck[c] == null)\n{ /* */ }\n</code></pre>\n\n<p>Can turn into:</p>\n\n<pre><code>if (ToCheck[c] == null)\n{\n if (c < 9)\n { /* */ }\n}\nelse\n{\n if (ToCheckPointers[c] == ToCheck[c].Length)\n { /* */ }\n else\n {\n if (ToCheckPointers[c] < ToCheck[c].Length)\n {\n if (c == 8)\n { /* */ }\n else if (c < 9)\n { /* */ }\n }\n }\n}\n</code></pre>\n\n<p>One reason for doing this, is that <em>the order of the conditions <strong>does</strong> matter</em>. When <code>c == 8</code> evaluates to <code>false</code>, the rest of the condition isn't even evaluated, so the code jumps right to <code>if (c < 9 && ToCheck[c] != null...</code> - if <code>ToCheck[c] == null</code>, then <code>ToCheckPointers[c] < ToCheck[c].Length</code> will not be evaluated.</p>\n\n<p>Nested conditions are annoying, but they're less annoying and more efficient than <em>redundant</em> conditions (you can probably gain a couple of milliseconds by doing this). The good thing though, is that it's easy to extract a method out of nested conditions. Much easier than out of redundant conditions.</p>\n\n<hr>\n\n<p>I've noticed you're systematically doing <code>++n</code> or <code>--n</code> to increment or decrement. When the pre-increment/decrement isn't warranted by an assignment operation, I find <code>n++</code> and <code>n--</code> to be more readable.</p>\n\n<hr>\n\n<pre><code>string GetResult(IEnumerable<int> cells)\n{\n return string.Join(\"\", cells.Select(i => i.ToString()).ToArray());\n}\n</code></pre>\n\n<p>Minor nitpick, but rather than hard-coding a <code>\"\"</code> here, I'd use <code>string.Empty</code>, which makes the intent more explicit.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T01:32:47.043",
"Id": "45574",
"ParentId": "20888",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T03:34:45.263",
"Id": "20888",
"Score": "4",
"Tags": [
"c#",
"performance",
"algorithm",
"sudoku"
],
"Title": "Sudoku Valid Arangements Permutations Enumerator"
}
|
20888
|
<p>I have this code that generally creates directories within a directory.</p>
<pre><code>File userFolder = new File(rootPath+"/media/"+userBean.getUsername());
File userPhotosDir = new File(rootPath+"/media/"+userBean.getUsername()+"/photos");
File userAudioDir = new File(rootPath+"/media/"+userBean.getUsername()+"/tracks");
userFolder.mkdir();
userPhotosDir.mkdir();
userAudioDir.mkdir();
</code></pre>
<p>When I this code runs it will generally look like this</p>
<p>The userFolder</p>
<pre><code>\media\somename
</code></pre>
<p>The Photos folder</p>
<pre><code>\media\somename\photos
</code></pre>
<p>The Audio Folder</p>
<pre><code>\media\somename\folder
</code></pre>
<p>Where the photos and audio folder are inside the somename folder. while the somename folder is inside the media folder</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T18:14:01.600",
"Id": "33521",
"Score": "0",
"body": "what is the question?"
}
] |
[
{
"body": "<p>Well, for the purpose of codereview:</p>\n\n<ul>\n<li>There is a <code>mkdirs()</code> methods instead of the <code>mkdir()</code> method</li>\n<li>You can use the <code>new File(String, String)</code> constructor to avoid taking care of slashes</li>\n<li><p>If you have Java7, you can (and probably should) use <code>Path</code>. Especially, because there is a way to construct Paths with unlimited arguments, not only 2 as for <code>File</code>:</p>\n\n<pre><code>Path dir = Paths.get(rootPath, \"media\", userBean.getUsername(), arg1);\nFiles.createDirectories(dir);\n</code></pre></li>\n<li><p>You should check the return codes and errors. Could be helpful.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T18:26:43.317",
"Id": "20912",
"ParentId": "20892",
"Score": "2"
}
},
{
"body": "<p>My main concern would be dealing with file path separators to construct long file paths. Luckily Java has <code>File.separator</code> which can be used to to manually construct paths. However try not to use them if necessary, and get the File objects to do the path creation for you.</p>\n\n<pre><code>String rootPath = \"/\";\nString username = \"tom\";\nString mediaDir = \"media\"\nFile root = new File(rootPath);\nFile userFolder = new File(root, mediaDir + File.separator + username);\nFile photos = new File(userFolder, \"photos\");\nFile tracks = new File(userFolder, \"tracks\");\nif (photos.isFile()) {\n // delete it? Do something...\n}\nif (!photos.exists()) {\n photos.mkdirs();\n}\n</code></pre>\n\n<p>Like tb- suggests in his answer, if you have Java 7 you may also want to look into <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/file/Paths.html\" rel=\"nofollow\">Paths</a>, <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html\" rel=\"nofollow\">Path</a> and <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html\" rel=\"nofollow\">Files</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T12:30:49.500",
"Id": "20932",
"ParentId": "20892",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T10:55:01.837",
"Id": "20892",
"Score": "3",
"Tags": [
"java",
"file-system",
"directory"
],
"Title": "Better way to create directories using File"
}
|
20892
|
<p>I've recently discovered the wonders of the Python world, and am quickly learning. Coming from <code>Windows/C#/.NET</code>, I find it refreshing working in <code>Python</code> on <code>Linux</code>. A day you've learned something new is not a day wasted.</p>
<p>I need to unpack data received from a device. Data is received as a string of "bytes", of arbitrary length. Each packet (string) consists of samples, for eight channels. The number of samples varies, but will always be a multiple of the number of channels. The channels are interleaved. To make things a bit more complex, samples can be either 8 or 16 bits in length. Check the code, and you'll see.</p>
<p>I've already got a working implementation. However, as I've just stumbled upon generators, iterators, maps and ... numpy, I suspect there might be a more efficient way of doing it. If not efficient, maybe more "pythonic". I'm curious, and if someone would spend some time giving me a pointer in the right (or any) direction, I would be very grateful. As of now, I am aware of the fact that my Python has a strong smell of C#. But I'm learning ...</p>
<p>This is my working implementation. It is efficient enough, but I suspect it can be improved. Especially the de-interleaving part. On my machine it prints:</p>
<pre><code>time to create generator: 0:00:00.000040
time to de-interleave data: 0:00:00.004111
length of channel A is 750: True
</code></pre>
<p>As you can see, creating the generator takes no amount of time. De-interleaving the data is the real issue. Maybe the data generation and de-interleaving can be done simultaneously?</p>
<p>This is not my first implementation, but I never seem to be able to drop below approx <code>4 ms</code>.</p>
<hr>
<pre><code>from datetime import datetime
def unpack_data(data):
l = len(data)
p = 0
while p < l:
# convert 'char' or byte to (signed) int8
i1 = (((ord(data[p]) + 128) % 256) - 128)
p += 1
if i1 & 0x01:
# read next 'char' as an (unsigned) uint8
#
# due to the nature of the protocol,
# we will always have sufficient data
# available to avoid reading past the end
i2 = ord(data[p])
p += 1
yield (i1 >> 1 << 8) + i2
else:
yield i1 >> 1
# generate some test data ...
test_data = ''
for n in range(500 * 12 * 2 - 1):
test_data += chr(n % 256)
t0 = datetime.utcnow()
# in this example we have 6000 samples, 8 channels, 750 samples/channel
# data received is interleaved: A1, B1, C1, ..., A2, B2, C2, ... F750, G750, H750
channels = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H')
samples = { channel : [] for channel in channels}
# call unpack_data(), receive a generator
gen = unpack_data(test_data)
t1 = datetime.utcnow()
print 'time to create generator: %s' % (t1-t0)
try:
while True:
for channel in channels:
samples[channel].append(gen.next())
except StopIteration:
pass
print 'time to de-interleave data: %s' % (datetime.utcnow()-t1)
print 'length of channel A is 750: %s' % (len(samples['A']) == 750)
</code></pre>
|
[] |
[
{
"body": "<p><em>simple unpacking</em> can be done with the zip built-in as @Lattyware has pointed out:<br>\nthat could be something like: </p>\n\n<pre><code>zip(*[data[idx:idx + num_channels] for idx in range(0, len(data), num_channels)])\n</code></pre>\n\n<p>(note the (*) which is inverting zip by handing over the items of the sequence as separate parameters).</p>\n\n<p>However, as you are transforming the values while you unpack, and even have different cases with 1 or 2 bytes per sample, I think your approach is ok.<br>\nAnyway, you won't be able to avoid iterating over all the samples. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T16:41:29.953",
"Id": "20902",
"ParentId": "20895",
"Score": "2"
}
},
{
"body": "<pre><code>from datetime import datetime\n\ndef unpack_data(data):\n l = len(data)\n p = 0\n</code></pre>\n\n<p>I'd avoid such small variable names, it makes your code harder to follow</p>\n\n<pre><code> while p < l:\n # convert 'char' or byte to (signed) int8\n i1 = (((ord(data[p]) + 128) % 256) - 128)\n p += 1\n if i1 & 0x01:\n # read next 'char' as an (unsigned) uint8\n #\n # due to the nature of the protocol,\n # we will always have sufficient data\n # available to avoid reading past the end\n i2 = ord(data[p])\n p += 1\n yield (i1 >> 1 << 8) + i2\n else:\n yield i1 >> 1\n\n\n# generate some test data ...\ntest_data = ''\nfor n in range(500 * 12 * 2 - 1):\n test_data += chr(n % 256)\n</code></pre>\n\n<p>It usually better to put all the pieces of a string in a list and then join them. Python doesn't have good performance for added strings.</p>\n\n<pre><code>t0 = datetime.utcnow()\n\n# in this example we have 6000 samples, 8 channels, 750 samples/channel\n# data received is interleaved: A1, B1, C1, ..., A2, B2, C2, ... F750, G750, H750\nchannels = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H')\n\nsamples = { channel : [] for channel in channels}\n\n# call unpack_data(), receive a generator\ngen = unpack_data(test_data)\n\nt1 = datetime.utcnow()\n\nprint 'time to create generator: %s' % (t1-t0)\n</code></pre>\n\n<p>All you've done is created the generator, that won't do any actual work. So you aren't measuring much of anything here. You are still spending much of the time inside the function you've defined after this point.</p>\n\n<pre><code>try:\n while True:\n for channel in channels:\n samples[channel].append(gen.next())\nexcept StopIteration:\n pass\n</code></pre>\n\n<p>It's best to avoid dealing with StopIteration directly if you can. In this case you can do:</p>\n\n<pre><code>for sample, channel in zip(gen, itertools.cycle(channels)):\n samples[channel].append(sample)\n</code></pre>\n\n<p><code>itertools.cycle()</code> will give you a generator that goes repeatedly through all the channels in order.</p>\n\n<pre><code>print 'time to de-interleave data: %s' % (datetime.utcnow()-t1)\n\nprint 'length of channel A is 750: %s' % (len(samples['A']) == 750)\n</code></pre>\n\n<p>You can use numpy, I've done that for you. Basically, numpy lets you do operations over a whole array and that's faster then doing them in your loops. See below:</p>\n\n<pre><code>from datetime import datetime\nimport numpy\n\n\n\ndef unpack_data(data):\n # reads the string in as a sequence of uint8\n data = numpy.fromstring(data, numpy.uint8)\n # figure out if the most significant bit is set\n # for everything\n odds = numpy.logical_not(data & 0x01)\n\n # calculate the interpretation of each number\n # both possible ways\n singles = data.astype(numpy.int8) >> 1\n doubles = singles << 8 + numpy.roll(data, -1)\n\n # I couldn't vectorize this, it fills up the \n # result array with True for every actual starting value\n result = numpy.empty(data.shape, bool)\n current = True\n for index, byte in enumerate(odds):\n # the next bit is a starting bit if\n # if this isn't a starting bit, or the 1 bit wasn't set\n current = not current or byte\n result[index] = current\n\n # where chooses from the single and doubles\n # based on the lsb, and result filters those we actually want\n return numpy.where(odds, singles, doubles)[result]\n\n# generate some test data ...\ntest_data = ''\nfor n in range(500 * 12 * 2 - 1):\n test_data += chr(n % 256)\n\nt0 = datetime.utcnow()\n\n# in this example we have 6000 samples, 8 channels, 750 samples/channel\n# data received is interleaved: A1, B1, C1, ..., A2, B2, C2, ... F750, G750, H750\nchannels = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H')\n\nsamples = { channel : [] for channel in channels}\n\n# call unpack_data(), receive a generator\ndata = unpack_data(test_data)\n\nt1 = datetime.utcnow()\nprint 'time to create generator: %s' % (t1-t0)\n\n# reshape converts 1 dimensional array\n# into two dimensional array\ndata = data.reshape(-1, len(channels))\nfor index, channel in enumerate(channels):\n samples[channel] = data[:,index]\n\nprint 'time to de-interleave data: %s' % (datetime.utcnow()-t1)\n\nprint 'length of channel A is 750: %s' % (len(samples['A']) == 750)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-28T15:20:22.990",
"Id": "33670",
"Score": "0",
"body": "Thank you! That was really helpful. Especially the usage of zip() and itertools.cycle(). (It cut execution time by more than 50% on my target machine.) I'll check out numpy as well, but that will have to wait to another day."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T10:02:17.757",
"Id": "35052",
"Score": "0",
"body": "I've delved deeper into NUMPY and now have a more or less vectorized solution. The question has been updated, in case anyone is interested."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T18:04:13.107",
"Id": "20909",
"ParentId": "20895",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "20909",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T14:16:14.827",
"Id": "20895",
"Score": "3",
"Tags": [
"python",
"numpy"
],
"Title": "A pythonic way of de-interleaving a list (i.e. data from a generator), into multiple lists"
}
|
20895
|
<p>I'm having concerns about the readability of this piece of code:</p>
<pre class="lang-py prettyprint-override"><code> messages_dict = {'error':errors, 'warning':warnings}[severity]
messages_dict[field_key] = message
</code></pre>
<p>and I'm to use this instead:</p>
<pre class="lang-py prettyprint-override"><code> if severity == 'error':
messages_dict = errors
elif severity == 'warning':
messages_dict = warnings
else:
raise ValueError('Incorrect severity value')
messages_dict[field_key] = message
</code></pre>
<p>But it looks too verbose for such a simple thing.</p>
<p>I don't care too much if it's more efficient than constructing a dictionary for just two mappings. Readability and maintainability is my biggest concern here (<code>errors</code> and <code>warnings</code> are method arguments, so I cannot build the lookup dictionary beforehand and reuse it later).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T14:43:51.320",
"Id": "33509",
"Score": "0",
"body": "I don't see the readability concern with the first case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T14:52:20.773",
"Id": "33510",
"Score": "0",
"body": "I thought that it might puzzle an unaware reader..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T15:08:49.243",
"Id": "33511",
"Score": "0",
"body": "Unaware of what? Dictionaries? They are a core Python data structure - if someone can't read that, they don't know Python. You can't write code that is readable for someone who have no idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T17:21:55.510",
"Id": "33519",
"Score": "0",
"body": "I meant unaware of the 'pattern' (using a dict to choose between two options). I've seen complaints in peer reviews about using boolean operators in a similar way (like `x = something or default`, maybe a little bit more complex) because it was _obscure_ :-/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T14:14:55.613",
"Id": "33547",
"Score": "0",
"body": "That's a different situation, as it's relatively unclear what is going on (and is better replaced by the ternary operator). This isn't particularly a pattern, it's just a use of dictionaries."
}
] |
[
{
"body": "<p>Since you mention maintainability I think that the consideration can be taken in terms of what next changes may look like. If further changes will take more statements to be executed with the result of one of those specific options, or if more options will be added, I would stick to the dictionary approach.</p>\n\n<p>Looking into the future can certainly be tricky, but you need to also think how much will the code need to be change to assert a specific new need. If you need to add a new level of reporting, would you prefer to add a new <code>else if</code> or just a value in a dictionary?</p>\n\n<p>Readability then starts to backfire, since <code>if ... else</code> is quite common. What happens when you arrive at 3, 4 or 5 branches?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-01T23:05:01.307",
"Id": "21207",
"ParentId": "20896",
"Score": "3"
}
},
{
"body": "<p>They are not exactly the same, as they behave differently when given an invalid severity. For a fair comparison, the first example code should probably be something like:</p>\n<pre><code>try:\n messages_dict = {'error':errors, 'warning':warnings}[severity]\n\nexcept KeyError:\n raise ValueError(f'Incorrect severity value: {severity}.')\n\nmessages_dict[field_key] = message\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T03:53:41.530",
"Id": "254821",
"ParentId": "20896",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-01-25T14:41:37.067",
"Id": "20896",
"Score": "1",
"Tags": [
"python",
"hash-map",
"lookup"
],
"Title": "Readability concerns with literal dictionary lookup vs if-else"
}
|
20896
|
<p>I am trying to write an idiomatic trim function in C. How does this look? Should I instead malloc the new string and return it?</p>
<pre><code>void trim(const char *input, char *result)
{
int i, j = 0;
for (i = 0; input[i] != '\0'; i++) {
if (!isspace(input[i])) {
result[j++] = input[i];
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T15:12:38.673",
"Id": "33512",
"Score": "4",
"body": "There's a number of problems with that code, it's vulnerable to buffer overflow attacks and it doesn't do what a typical \"trim\" function does. Trim removes leading and trailing whitespace. This strips them all out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T15:44:49.913",
"Id": "33514",
"Score": "0",
"body": "Thanks. Can you please elaborate on how to handle buffer overflow attacks?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T17:05:43.967",
"Id": "33517",
"Score": "2",
"body": "You should never blindly copy data to some buffer when you don't know how much space is allocated to it, that's just asking for trouble. A simple thing to do would be to add a parameter which takes in the size of the buffer. That way it's all on the caller to tell you how big it really is. Then it's up to you to never attempt to read/write beyond the given length. Of course it's not fool proof, the caller can give you bogus lengths, but that would be a problem on their end, not yours."
}
] |
[
{
"body": "<p>As @JeffMercado pointed out, this removes spaces instead of trimming leading and trailing spaces. Assuming you want to keep the current functionality, let's call it <code>remove_spaces</code>.</p>\n\n<p>There's a really subtle bug here:</p>\n\n<pre><code>... isspace(input[i]) ...\n</code></pre>\n\n<p><code>isspace</code> takes the value of an <strong>unsigned char</strong> or <code>EOF</code>. Passing it a <code>char</code>, which is usually signed, will produce undefined behavior. Instead, say:</p>\n\n<pre><code>... isspace((unsigned char) input[i]) ...\n</code></pre>\n\n<p>Another bug: you don't emit a NUL terminator, meaning the caller would have no way of knowing how long the string is (unless it zeroed out the buffer before calling your function).</p>\n\n<p>Fixing these bugs gives us:</p>\n\n<pre><code>void remove_spaces(const char *input, char *result)\n{\n int i, j = 0;\n for (i = 0; input[i] != '\\0'; i++) {\n if (!isspace((unsigned char) input[i])) {\n result[j++] = input[i];\n }\n }\n result[j] = '\\0';\n}\n</code></pre>\n\n<p>@JeffMercado also said this function is vulnerable to buffer overflow. In a sense, this is not true, provided the caller knows to allocate a buffer of at least <code>strlen(input) + 1</code>. But the caller might be lazy and just say <code>char result[100]</code>. Adding an output buffer size parameter will likely guard against such a mistake:</p>\n\n<pre><code>void remove_spaces(const char *input, char *output, size_t output_size);\n</code></pre>\n\n<p>See if you can implement this. Some things to bear in mind:</p>\n\n<ul>\n<li><p>Don't forget about the NUL terminator when checking the output buffer size.</p></li>\n<li><p>Don't be like <a href=\"http://linux.die.net/man/3/strncpy\" rel=\"nofollow\">strncpy</a> and omit the NUL terminator when you have to truncate the string, as it can lead to subtle bugs.</p></li>\n<li><p>If you use <code>int</code> for <code>i</code> and <code>j</code> and <code>size_t</code> for <code>output_size</code>, you should get compiler warnings about comparison between signed and unsigned. If you don't, turn up your compiler warnings. If you're using GCC from the command line, get in the habit of typing <code>gcc -Wall -W</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T21:12:15.493",
"Id": "419142",
"Score": "0",
"body": "`strncpy()` **is not** a string-function, even though some assume. So the result being a string would be happenstance anyway. Which makes the analogy sketchy at best."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T03:46:31.263",
"Id": "513968",
"Score": "0",
"body": "Can't imagine why ` **str** ncpy()` would be confused for a string-function."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T01:02:19.890",
"Id": "20922",
"ParentId": "20897",
"Score": "4"
}
},
{
"body": "<p>We know that we can move a pointer forward and backward, and we also know that we can trim a string from the left. If we increment the pointer and decrement the pointer to trim from the right, then two <code>while</code> loops are enough. You'll notice that the right walk count is less than the left walk count.</p>\n\n<p>Right-trim code:</p>\n\n<pre><code>#include <stdio.h>\n#include <ctype.h>\n\nvoid trim_both(char *, char *);\n\nint main (void) {\n char title[100] = \" My long string \";\n char title_t[100] = \"\";\n\n (void) printf(\"String before left trim is:[%s]\\n\", title);\n trim_both(title, title_t);\n (void) printf(\"String after left trim is:[%s]\\n\", title_t);\n\n}\n\n// trim spaces from left\nvoid trim_both(char *title_p, char *title_tp) {\n int flag = 0;\n\n // from left\n while(*title_p) {\n if(!isspace((unsigned char) *title_p) && flag == 0) {\n *title_tp++ = *title_p;\n flag = 1;\n }\n title_p++;\n if(flag == 1) {\n *title_tp++ = *title_p;\n }\n }\n\n // from right\n while(1) {\n title_tp--;\n if(!isspace((unsigned char) *title_tp) && flag == 0) {\n break;\n }\n flag = 0;\n *title_tp = '\\0';\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-16T01:49:00.923",
"Id": "57147",
"ParentId": "20897",
"Score": "0"
}
},
{
"body": "<p>Easiest way (removes only spaces):</p>\n\n<p>Trim.Start:</p>\n\n<ol>\n<li>Compare chars until they equal <code>' '</code> (space or other chars like <code>\\n</code> or <code>\\t</code>) at the string start and increment temp (<code>i</code>) variable.</li>\n<li>Move pointer about <code>i</code> (<code>str+=i</code>). Now string starts from char which is not a space char (or any other white char).</li>\n</ol>\n\n<p>Trim.End:</p>\n\n<ol>\n<li>Do the same what for Trim.Start but from the end of the string.</li>\n<li>Set last char (last space) as <code>\\0</code>.</li>\n</ol>\n\n<p>The important thing is that function takes pointer to pointer (string). Watch for the function call: <code>StringTrim(&p2);</code></p>\n\n<pre><code>char * StringTrim(char * *pointerToString)\n{\n u8 start=0, length=0;\n\n // Trim.Start:\n length = strlen(*pointerToString);\n while ((*pointerToString)[start]==' ') start++;\n (*pointerToString) += start;\n\n if (start < length) // Required for empty (ex. \" \") input\n {\n // Trim.End:\n u8 end = strlen(*pointerToString)-1; // Get string length again (after Trim.Start)\n while ((*pointerToString)[end]==' ') end--;\n (*pointerToString)[end+1] = 0;\n }\n\n return *pointerToString;\n}\n</code></pre>\n\n\n\n<p>Usage:</p>\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>char str1[] = \" test1 \";\nchar * p1 = str1;\n\nDebug(\"1. before trim: [%s]\", p1);\nStringTrim(&p1);\nDebug(\"1. after trim [%s]\", p1);\n\n\nchar str2[] = \" test2\";\nchar * p2 = str2;\n\nDebug(\"2. before trim: [%s]\", p2);\nStringTrim(&p2);\nDebug(\"2. after trim [%s]\", p2);\n\n\nchar str3[] = \"test3 \";\nchar * p3 = str3;\n\nDebug(\"3. before trim: [%s]\", p3);\nStringTrim(&p3);\nDebug(\"3. after trim [%s]\", p3);\n\n\nchar str4[] = \" \";\nchar * p4 = str4;\n\nDebug(\"4. before trim: [%s]\", p4);\nStringTrim(&p4);\nDebug(\"4. after trim [%s]\", p4);\n\n\nchar str5[] = \"\";\nchar * p5 = str5;\n\nDebug(\"5. before trim: [%s]\", p5);\nStringTrim(&p5);\nDebug(\"5. after trim [%s]\", p5);\n</code></pre>\n</blockquote>\n\n<p>Result:</p>\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>1. before trim: [ test1 ]\n1. after trim [test1]\n2. before trim: [ test2]\n2. after trim [test2]\n3. before trim: [test3 ]\n3. after trim [test3]\n4. before trim: [ ]\n4. after trim []\n5. before trim: []\n5. after trim []\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-01T14:04:21.123",
"Id": "58759",
"ParentId": "20897",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T15:01:34.907",
"Id": "20897",
"Score": "5",
"Tags": [
"c",
"strings"
],
"Title": "Trim function in C"
}
|
20897
|
<p>I have a view model that I'm migrating to RxUI. It exposes a collection of brokers along with a <code>bool</code> indicating whether there is a market (ie. at least one broker). In addition, it has a property for the currently selected broker (the user can choose a broker via a drop-down):</p>
<pre><code>private IReactiveCollection<SourceViewModel> brokers;
public IReactiveCollection<SourceViewModel> Brokers
{
get { return this.brokers; }
private set { this.RaiseAndSetIfChanged(x => x.Brokers, ref this.brokers, value); }
}
private ObservableAsPropertyHelper<bool> isMarket;
public bool IsMarket
{
get { return this.isMarket.Value; }
}
private SourceViewModel selectedBroker;
public SourceViewModel SelectedBroker
{
get { return this.selectedBroker; }
set { this.RaiseAndSetIfChanged(x => x.SelectedBroker, ref this.selectedBroker, value); }
}
</code></pre>
<p>I have these pieces hooked up and working, but I am not convinced I've done this in the most reactive-friendly fashion:</p>
<pre><code>this.WhenAny(x => x.Volatilities, x => x.Value)
.StartWith((ItemObservableCollection<VolatilityViewModel>)null)
.Subscribe(x =>
{
if (x == null)
{
// no volatilities, so definitely no market
this.Brokers = null;
this.SelectedBroker = null;
this.isMarket = Observable.Return(false).ToProperty(this, y => y.IsMarket);
}
else
{
// we have volatilities, so potentially we have a market
// TODO: is there a better means of doing this?
this.Brokers = x.CreateDerivedCollection(y => y.Source);
// TODO: is there a cleaner way to do this?
this.Brokers.Changed
.Select(y => true)
.StartWith(true)
.Subscribe(y =>
{
var volatility = x.FirstOrDefault();
this.SelectedBroker = volatility == null ? null : volatility.Source;
});
// TODO: is there a cleaner way to do this?
this.isMarket = this.Brokers.CollectionCountChanged.Select(y => y > 0).StartWith(x.Count > 0).ToProperty(this, y => y.IsMarket);
}
});
</code></pre>
<p>My <code>Volatilities</code> property is set when the user interacts with a specific set of vols. Everything hinges off of it. It's currently an <a href="https://stackoverflow.com/a/3849454/5380">ItemObservableCollection</a>, but I may change it later to be a reactive collection. I don't believe that's relevant here, but I could be wrong.</p>
<p>The parts I'm concerned about have TODOs in the code, but to summarize:</p>
<ul>
<li>when my <code>Volatilities</code> property changes, so too do the available brokers. I currently create a new derived collection each time <code>Volatilities</code> changes. I couldn't come up with any way to avoid this or implement it more cleanly.</li>
<li>when I recreate my brokers collection, I immediately set up a <code>Changed</code> observer so that any changes result in the first broker being selected. The reasoning is that the first broker will (once I do sorting) be the preferred broker, so any changes in the market should instigate the selection of the preferred broker. I couldn't think of a way to make this logic cleaner and simpler.</li>
<li>in addition, I also recreate my <code>isMarket</code> member, which is <code>true</code> whenever there is at least one broker in the brokers collection. Again, I'm not sure that this is the best approach to achieving this.</li>
</ul>
<p>Can anyone weigh in with their thoughts on this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T08:39:55.993",
"Id": "33540",
"Score": "0",
"body": "Thank you for this question, Kent. I think you just introduced me to Rx :)"
}
] |
[
{
"body": "<blockquote>\n <p>I currently create a new derived collection each time Volatilities changes</p>\n</blockquote>\n\n<p>This was a good idea, but in this case I'd just recreate the brokers list (since it's not a straight <code>volatilities.Select(x => ...)</code>, it's a SelectMany. One thing that's important though, is whether you <em>mutate</em> (i.e. add and remove) items from Volatilities, or you only <em>replace</em> the list (i.e. via an API call, set this.Volatilities to a new collection). </p>\n\n<p>Pick one or the other, don't mix them or else your code will be complicated. Let's assume you're using ReactiveCollection and you're adding/removing to Volatilities.</p>\n\n<pre><code>Volatilities.CollectionCountChanged.StartWith(Volatilities.Count)\n .Select(_ => Volatilities.SelectMany(x => x.BrokerList))\n .ToProperty(this, x => x.Brokers);\n</code></pre>\n\n<p>Then, we can watch when someone changes Brokers - we'll do this in the constructor (along with everything else). Generally, if you're <em>not</em> calling RxUI methods in the constructor, you're Doing Something Wrong. You're wiring up on startup what <em>will</em> happen when various parts of your ViewModel change, those wires typically are constant:</p>\n\n<pre><code>this.WhenAny(x => x.Brokers, x => x.Value)\n .Subscribe(_ => SelectedBroker = Brokers.FirstOrDefault());\n</code></pre>\n\n<p>Now let's set up the IsMarket:</p>\n\n<pre><code>this.WhenAny(x => x.Brokers, x => x.Value)\n .Select(x => x.Count > 0)\n .ToProperty(this, x => x.IsMarket);\n</code></pre>\n\n<h2>What We Can Learn™</h2>\n\n<p>The key point here though, is that IsMarket is directly related to Brokers and nothing else - we should describe that relationship without mentioning Volatilities, then separately describe the relationship between Volatilities and Brokers. We don't want to mix the two. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-28T09:18:51.097",
"Id": "33604",
"Score": "0",
"body": "Thanks Paul - this makes a lot of sense. The situation is that `Volatilities` is set once for the life-span of the dialog interaction, during which time it may also be modified. I am currently re-using the one view model instance for multiple (synchronous) user interactions. Perhaps I'll be better off creating a new instance each time, passing in `Volatilities` to the ctor. I'll look at refactoring this and incorporating your above recommendations. Cheers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-29T17:03:56.890",
"Id": "33766",
"Score": "0",
"body": "Just got to looking at this (was pulled onto something else). I notice your code assumes `Volatilities` is `ReactiveCollection<T>` and not `IReactiveCollection<T>`, since the latter does not have a `Count` property. For obvious reasons I'd prefer to expose the interface, but seem to be in a bit of a bind. Same with `Add`/`Remove`. I can always use `Count()` extension method or add properties & methods to the type that contains the collection, but wondered at your thoughts on this..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-30T14:40:11.497",
"Id": "33832",
"Score": "0",
"body": "You could use IReactiveCollection<T>.Any() instead of .Count()>0"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T10:14:01.820",
"Id": "38083",
"Score": "0",
"body": "To echo Paul's comments, the rx chains should ideally be setup in the viewmodels constructor. You are then functionally defining all the behaviour one time at startup. If you are having to recreate these all the time then its going to get ugly fast. I don't user RX ui at the moment although am considering it as have rewritten rather a lot of it myself, and my preference would be to not blow away the collections each time, but instead reset them to new values so your behaviours don't need recreating. Not sure how you do that for brokers col in rxui, but must be do-able."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T23:47:25.103",
"Id": "20921",
"ParentId": "20900",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "20921",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T12:50:20.390",
"Id": "20900",
"Score": "6",
"Tags": [
"c#",
"wpf",
"mvvm",
"system.reactive"
],
"Title": "Can this reactive code be improved?"
}
|
20900
|
<p>I need to lock on my <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged.aspx" rel="nofollow">AesManaged</a> instance <code>_Aes</code> to call <a href="http://msdn.microsoft.com/en-us/library/bb338332.aspx" rel="nofollow">CreateDecryptor()</a> however the CreateDecryptor() method is not thread safe and this function could be called by multiple threads. Is this the correct way to create a disposable object while needing to use a lock on the parent creating the object?</p>
<pre><code>byte[] encryptedTextBlob = GetEncryptedTextBlob();
ICryptoTransform decryptor = null;
lock(_Aes)
{
decryptor = _Aes.CreateDecryptor();
}
using (decryptor)
using (var encryptedStream = new MemoryStream(encryptedTextBlob))
using (var decrypedStream = new CryptoStream(encryptedStream, decryptor, CryptoStreamMode.Read))
using (var textReader = new StreamReader(decrypedStream))
{
return textReader.ReadToEnd();
}
</code></pre>
|
[] |
[
{
"body": "<p>I would say you're not using AES correctly - don't hold on to an instance of it in your class (guessing by the underscore in the name) but rather create it as needed, while holding AES's parameters (the key and IV) in your class:</p>\n\n<pre><code>using (var aes = new AesManaged() { IV = _IV, Key = _Key })\nusing (var decryptor = aes.CreateDecryptor())\nusing (var encryptedStream = new MemoryStream(encryptedTextBlob))\nusing (var decrypedStream = new CryptoStream(encryptedStream, decryptor, CryptoStreamMode.Read))\nusing (var textReader = new StreamReader(decrypedStream))\n{\n return textReader.ReadToEnd();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T21:11:05.350",
"Id": "33527",
"Score": "0",
"body": "I am getting the data from a 3rd party source that has a fixed IV and Key, that is why I used only the one copy of AesManaged, I thought creating all those copies of AesManaged all to be identical would be expensive."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T22:02:34.530",
"Id": "33532",
"Score": "0",
"body": "Understood, I will use that way. I have asked [a new question](http://codereview.stackexchange.com/questions/20915) without all of that Aes stuff in the way as I still would like to know the answer to my original question in case I need to use it in another situation."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T18:01:21.360",
"Id": "20908",
"ParentId": "20904",
"Score": "4"
}
},
{
"body": "<p>Jesse C. Slicer's answer addresses your main concern, but after seeing those multiple using blocks, you might be interested to know that you can create multiple variables in a single using statement. I think this is a bit easier to read, personally: </p>\n\n<pre><code>using (var aes = new AesManaged() { IV = _IV, Key = _Key },\n var decryptor = aes.CreateDecryptor(),\n var encryptedStream = new MemoryStream(encryptedTextBlob),\n var decrypedStream = new CryptoStream(encryptedStream, decryptor, CryptoStreamMode.Read),\n var textReader = new StreamReader(decrypedStream))\n{\n return textReader.ReadToEnd();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T19:16:57.050",
"Id": "33524",
"Score": "1",
"body": "Interesting, I didn't know you could do this. But personally, I think multiple `using`s are better, because that way, changing the code is easier."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T21:49:50.990",
"Id": "33531",
"Score": "1",
"body": "Awesome. I love this. Addresses the primary concern I had with Jessie's answer (which is great, and readable, but I don't like leaving out braces...in fact, they're required by our coding standards.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T22:11:39.040",
"Id": "33534",
"Score": "0",
"body": "@Beska the best part is it's been part of the standard for a long time: http://msdn.microsoft.com/en-us/library/yh598w02(v=vs.71).aspx"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T22:18:47.447",
"Id": "33535",
"Score": "1",
"body": "@svick I see your point, but I think it would be too easy to accidentally an inject somewhere in the `using` cascades -- still totally valid c#, but altering the meaning of the program:"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-29T20:24:52.547",
"Id": "33783",
"Score": "0",
"body": "@ReacherGilt Unfortunately, this doesn't actually work in older .NET versions. Yes, you can do multiple usings seperated by commas back in VS 2003, like in your example and in the link...but it seems the types have to be the same, which limits the usefulness considerably. I assume this problem isn't encountered in later versions because of the user of the var type for all the variables in your example."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T18:24:51.380",
"Id": "20911",
"ParentId": "20904",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "20908",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T17:30:12.363",
"Id": "20904",
"Score": "4",
"Tags": [
"c#",
"multithreading",
"locking"
],
"Title": "Getting a decryptor object"
}
|
20904
|
<p>Please tell me how bad is the code...in the book he said it's possible with either nested loop, or 1 loop</p>
<p>The user should provide the 8 double numbers for the program to set the cumulative totals in the second array.</p>
<p>This is the code:</p>
<pre><code>#include <stdio.h>
#define ASIZE 8
int main()
{
int index = 0, x, index2;
double cal;
double array1[ASIZE], array2[ASIZE];
printf("Please enter 8 numbers:\n");
for (index = 0; index < ASIZE; index++)//adding the numbers to the first array
{
scanf("%lf", &array1[index]);
}
for (x = 0,index2 = 0,index = 0; x < ASIZE; x++, index2++)//adding the second array the elements
{
cal += array1[index++];
array2[index2] = cal;
}
printf("the first array numbers are:\n");//printing the first array numbers
for (index = 0; index < ASIZE; index++)
{
printf("%.1lf ", array1[index]);
}
printf("\n");
printf("\n");
printf("the second array numbers are:\n");//printing the second array
for (index2 = 0; index2 < ASIZE; index2++)
{
printf("%.1lf ", array2[index2]);
}
}
</code></pre>
<p>I'm a beginner in C, and its important for me to know how to get better. </p>
|
[] |
[
{
"body": "<p>About the only thing I would change is this loop</p>\n\n<pre><code>for (x = 0,index2 = 0,index = 0; x < ASIZE; x++, index2++)//adding the second array the elements\n{\n cal += array1[index++];\n array2[index2] = cal;\n}\n</code></pre>\n\n<p>You don't need <code>x</code> (its really <code>index1</code>. As all the variables are tracking each other you don't need <code>index2</code> as <code>index1</code> is the same value each iteration (and allways do the increment in the <code>for()</code> loop.</p>\n\n<p>The only bug I see is the <code>cal</code> is not initialized to <code>zero</code> and can thus have an indeterminate value.</p>\n\n<p>I would have written it like this:</p>\n\n<pre><code>cal = 0.0;\nfor (index = 0; index < ASIZE; index++)//adding the second array the elements\n{\n cal += array1[index];\n array2[index] = cal;\n}\n</code></pre>\n\n<p>A minor note:</p>\n\n<p>As the code may be changed to have bigger arrays by modifying <code>ASIZE</code>. I would make the user instructions reflect this automaically.</p>\n\n<pre><code>printf(\"Please enter 8 numbers:\\n\");\n\n// Try:\n\nprintf(\"Please enter %d numbers:\\n\", ASIZE);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T21:40:21.870",
"Id": "33528",
"Score": "0",
"body": "Thank you very much fot the detailed answer! It really help :) im only started to learn 2 weeks ago, hope its decent for a newbie, and to get better in my next question :) @Loki Astari"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T17:50:48.667",
"Id": "20907",
"ParentId": "20905",
"Score": "2"
}
},
{
"body": "<p>I'll just comment on a couple minor things that Loki Astari didn't cover.</p>\n\n<p>First thing is that main() returns <code>int</code>, but you never actually return anything. The standard thing to do is return 0 when your program ends successfully.</p>\n\n<p>Your variable names could use some work. You should try to name your variables in such a way that if someone tried to read your code, without knowing what the program does, they would be able to figure it out fairly easily.</p>\n\n<p><code>ASIZE</code> - I could probably guess that this means \"Array Size\", but that doesn't tell me what this really represents in your program - the number of user input numbers. Something like <code>NUM_USER_INPUTS</code> would make this much clearer.</p>\n\n<p><code>array</code> and <code>array2</code> - If I didn't know what your program was for, it would take a while to figure out what these arrays are actually for. If you named them something like <code>userInputs</code> and <code>cumulativeTotals</code>, this would be clear without even having to read the rest of your code what the arrays are for.</p>\n\n<p><code>cal</code> - The most I would be able to say from this name is that it stores some calculation, which doesn't say much. What calculation does it store? How about <code>cumulativeTotal</code>? Combine this with the array name changes, and it's very clear that this single <code>cumulativeTotal</code> is getting added into the <code>cumulativeTotals</code> array - makes this much easier to follow.</p>\n\n<p>Your output could be clearer too. You should make it clear to the user what it is you're outputting assuming they've never seen your program before or the code. If some random person came along and used your program, they'd get asked to enter some numbers, then they'd be told about two arrays... what do these arrays mean? Maybe printing something like <code>Input numbers:</code> and <code>Cumulative totals:</code>. Another thing you could do to make it even nicer is do some output formatting so that the input numbers line up with the totals in columns. Try looking up how to do output formatting with printf into columns.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T23:07:45.633",
"Id": "33538",
"Score": "0",
"body": "Thank you very much for the great points you cleared up..appreciate it! @MahlerFive"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T22:39:34.733",
"Id": "20919",
"ParentId": "20905",
"Score": "0"
}
},
{
"body": "<p>For a beginner, your code is very good. There are some issues, as others have indicated. One extra issue is that you have repeated code. That is usually a undesirable. You can extract the printing loop into a separate function and call that function twice. You can also combine the first two loops so that the output array is computed as the input is read. Below is an example. Even if you haven't covered functions yet, I think it is fairly self evident what this does. Note also that I am not a fan of long variable names. There is a balance to be struck between long descriptive names and short concise names. The rule many people use is that the more local a variable is, the shorter its name may be.</p>\n\n<pre><code>#include <stdio.h>\n#define ASIZE 8\n\nstatic void\nprint_array(const char *msg, const double *d, int n)\n{\n printf(\"%s:\\n\", msg);\n for (int i=0; i < n; i++) {\n printf(\"%.1lf \", d[i]);\n }\n printf(\"\\n\");\n}\n\nint main(int argc, char ** argv)\n{\n double in[ASIZE];\n double out[ASIZE];\n double total = 0.0;\n\n printf(\"Please enter %d numbers:\\n\", ASIZE);\n for (int i=0; i < ASIZE; i++) {\n scanf(\"%lf\", &in[i]);\n total += in[i];\n out[i] = total;\n }\n print_array(\"The input array\", in, ASIZE);\n print_array(\"The output array\", out, ASIZE);\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T02:03:32.933",
"Id": "20923",
"ParentId": "20905",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20907",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T17:32:03.420",
"Id": "20905",
"Score": "1",
"Tags": [
"c"
],
"Title": "Print 2 double arrrays, the second one should be cumulative totals of the elements of the first array"
}
|
20905
|
<p>When the page loads, it checks to see if the user is trying to update an existing book or create a new book.</p>
<p>Something about my code just doesn't seem right. It feels cumbersome and not very logical. Could someone put me out of my misery and let me know that I wrote this bit ok?</p>
<pre><code>Public Property modID As Int32
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim bookID = Request.QueryString("bookID")
If Not String.IsNullOrWhiteSpace(bookID) Then
newBook = False
Else
newBook = True
Create() 'create a new book
bookID = modID.ToString
End If
If Not newBook Then
commitData() 'saves data on form
End If
If Not IsPostBack And Not newBook Then
Page.DataBind()
populateControls() 'populate my dropdown lists and radio/checkbox controls
populateDatasets() 'load datasets to be used later
End If
End Sub
Public Sub Create()
'create a new book
newBook = False
Using dbcon As New SqlConnection(DBUtilities.ConnectionStringDefault)
dbcon.Open()
Dim cmd As New SqlCommand(CreateSQL, dbcon)
cmd.Parameters.Add(New SqlParameter("@authorID", currentUser))
modID = DirectCast(cmd.ExecuteScalar(), Int32)
End Using
navmod = NavbookFactory.Getbook(CInt(modID))
populateNewBook()
End Sub
</code></pre>
|
[] |
[
{
"body": "<p>The only real issue I can see (it's been a while since I worked in VB, so there may be other things) is using a global value to store the ID of the created record. Make your <code>Create()</code> sub a function and return the ID instead of storing it in the property; that will remove a potential source of errors.</p>\n\n<p>Other than that, naming is always important. <code>Create</code> doesn't say much, maybe name it <code>CreateNewBook</code>. Also, what do <code>navmod</code> or <code>modID</code> mean? Generally be more explicit in your naming, it will help others (and you as well a bit later on) understand your code.</p>\n\n<p>This may not exactly compile, as my VB days are a bit in the past as mentioned, but I think you'll get the idea:</p>\n\n<pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n Dim bookID = Request.QueryString(\"bookID\")\n\n If Not String.IsNullOrWhiteSpace(bookID) Then\n newBook = False\n Else\n newBook = True\n bookID = CreateNewBook() 'create a new book\n End If\n\n If Not newBook Then\n commitData() 'saves data on form\n End If\n\n If Not IsPostBack And Not newBook Then\n Page.DataBind()\n populateControls() 'populate my dropdown lists and radio/checkbox controls\n populateDatasets() 'load datasets to be used later\n End If\nEnd Sub\n\nPublic Function CreateNewBook() As String\n 'create a new book\n Using dbcon As New SqlConnection(DBUtilities.ConnectionStringDefault)\n dbcon.Open()\n Dim cmd As New SqlCommand(CreateSQL, dbcon)\n cmd.Parameters.Add(New SqlParameter(\"@authorID\", currentUser))\n modID = DirectCast(cmd.ExecuteScalar(), Int32)\n End Using\n navmod = NavbookFactory.Getbook(CInt(modID))\n populateNewBook()\n\n CreateNewBook = modID.ToString()\nEnd Function\n</code></pre>\n\n<p>Now that I think of it, the <code>modID</code> property I just eradicated may have been used by other methods of yours. If at all possible, try to always pass those values around to any methods that need them. You want to have as little \"global\" state as possible, because that increases the risk of side effects - and such bugs are often pretty hard to track down and fix.</p>\n\n<p>Also, if you need to work in VB (if you don't, my advice would be to consider switching to C#, as it's a much clearer and stricter language, you can often get much better help because many advanced programmers shun VB, and most example code nowadays will also be in C#), <strong>always</strong> call parameterless methods (such as <code>ToString()</code>) with parentheses anyway - method calls that don't look like method calls are always a pain, and it gets worse if that code should ever have to transition to another language.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T19:29:00.343",
"Id": "23337",
"ParentId": "20914",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23337",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T20:13:43.727",
"Id": "20914",
"Score": "1",
"Tags": [
".net",
"asp.net",
"vb.net"
],
"Title": "Creating a new item or updating an existing item on page load"
}
|
20914
|
<p>If I need to create a IDisposeable object from a factory, but if the factory object is not thread safe and requires me to lock on it is this the correct pattern to use?</p>
<pre><code>public void DisposeExample(FactoryClass factoryClass)
{
DispObject dispObject = null;
lock(factoryClass)
{
dispObject = factoryClass.GetDispObject();
}
using(dispObject)
{
dispObject.DoWork();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T22:20:32.367",
"Id": "33536",
"Score": "1",
"body": "CodeReview forum is probably not the best for this type of questions, you'll get more attention on [StackOverflow](http://stackoverflow.com/)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T22:27:08.060",
"Id": "33537",
"Score": "1",
"body": "I realize it's just an example, but I think `factoryClass` is a very bad name for a *variable*."
}
] |
[
{
"body": "<p>If your question is \"will the dispObject get disposed?\", the answer is \"Yes, that's a valid use of using.\" See the <a href=\"http://msdn.microsoft.com/en-us/library/yh598w02%28v=vs.110%29.aspx\" rel=\"nofollow\">using reference</a>, third sample under remarks. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T22:29:11.850",
"Id": "20917",
"ParentId": "20915",
"Score": "0"
}
},
{
"body": "<p>Yes, assuming the factory is shared between threads and the created object doesn't contain any resource that is shared with other objects from the same factory.</p>\n\n<p>But as was already pointed out <a href=\"https://codereview.stackexchange.com/questions/20904/getting-a-decryptor-object\">in your previous question</a>, a better solution might be to have a separate factory for each thread. Factories usually don't use much resources, so it should be fine to have more of them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T04:19:57.513",
"Id": "33539",
"Score": "0",
"body": "Thank you, no one actually answered my question in my previous question so I had to re-ask it without the distraction of the AES implementation as [I already said](http://codereview.stackexchange.com/questions/20904/getting-a-decryptor-object#comment33532_20908) I would be doing it the recommended way (and have already changed my code to do so), but I still wanted to know how to handle the situation if it ever came up again."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T22:30:13.817",
"Id": "20918",
"ParentId": "20915",
"Score": "2"
}
},
{
"body": "<p>It's a common mistake (not present in the code you provided but still possible, warning just in case) that people erroneously think that if you put a lock in some place all other places where object is about to be used will automagically wait until the lock is released. You need ensure you enter the lock in all places that use your factory, that is your object should own the factory (see <a href=\"http://msdn.microsoft.com/en-us/library/c5kehkcz(v=vs.80).aspx\" rel=\"nofollow noreferrer\">lock</a> for more details).</p>\n\n<p>As to your code - technically speaking it is correct because <code>using</code> statement won't throw exceptions if disposable object happens to be null. But since the method is public and factory is passed from outside you break the rule of locking only on objects you own. And also there is no guarantee that other code with access to factory properly locks on it.</p>\n\n<p>And finally, factories are usually objects that are thread safe (can't think of any that is not), so if you own the code for the factory I would recommend to refactor it to make it thread-safe, otherwise create a thread-safe wrapper around original factory.\nOr, if your factory is lightweight just create a separate factory per thread as <a href=\"https://codereview.stackexchange.com/users/2041/svick\">svick</a> suggested.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T12:30:17.507",
"Id": "33543",
"Score": "0",
"body": "Factories are usually used to *create* objects. In that case, the method in question does own the returned object and there is no “other ocde” that can access the same object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T17:31:48.140",
"Id": "33553",
"Score": "1",
"body": "The factory is the object being locked, and the method does not own it since factory is passed as a parameter to public method. The rule (described in the `lock` article referenced above) is that you should lock only on objects you own"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T17:37:02.080",
"Id": "33554",
"Score": "0",
"body": "Hmm, you're right. Somehow, I got confused."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T22:43:28.450",
"Id": "20920",
"ParentId": "20915",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "20918",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T22:00:07.497",
"Id": "20915",
"Score": "1",
"Tags": [
"c#",
"multithreading",
"locking"
],
"Title": "How to correctly get a IDisposeable when you need to lock the factory?"
}
|
20915
|
<p>My recipes model is as follows</p>
<pre><code>has_many :quantities
has_many :ingredients, :through => :quantities, :uniq => true
has_many :sizes, :through => :quantities, :uniq => true
</code></pre>
<p>And the controller action im trying to refactor</p>
<pre><code>class Admin::QuantitiesController < Admin::AdminController
layout 'admin'
authorize_resource :class => :controller
def create
recipe = Recipe.find(params[:recipe_id])
values = params[:quantity][:ingredient]
@quantities = Quantity.find(values.keys)
@quantities_errors = {}
@quantities.each do |quantity|
if quantity.value != values[quantity.id.to_s]
quantity.value = values[quantity.id.to_s]
if quantity.valid?
quantity.save
else
@quantities_errors[quantity.id] = quantity.errors.messages
end
end
end
unless @quantities_errors
redirect_to edit_admin_recipe_path(recipe), notice: 'Ingredients was successfully added.'
else
redirect_to edit_admin_recipe_path(recipe), alert: @quantities_errors
end
end
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T13:39:22.450",
"Id": "33546",
"Score": "0",
"body": "This is confusing. You are editing a recipe, right? (`edit_admin_recipe_path`), then why are you getting the POST in `QuantitiesController#create`? It should be in `RecipesController#update` and use Rails infrastructure (mainly `accepts_nested_attributes_for`), to remove all this boilerplate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-27T18:52:24.580",
"Id": "33589",
"Score": "0",
"body": "Thanks ever so much, after your comment I found http://railscasts.com/episodes/196-nested-model-form-part-1 and managed to get it posting to the recipe model and using accepts_nested_attributes_for. I knew the code was dodgy hence why I posted. I didn't know about accepts_nested_attributes_for before now."
}
] |
[
{
"body": "<p>Some notes:</p>\n\n<ul>\n<li><p>This is a <code>edit_admin_recipe</code> form, so you should POST to <code>Admin::RecipesController#update</code>. </p></li>\n<li><p>Use Rails infrastructure for the models (<a href=\"http://asciicasts.com/episodes/196-nested-model-form-part-1\" rel=\"nofollow\">accepts_nested_attributes_for</a>) to save nested data. Controllers must be kept simple and clean.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-27T19:53:47.800",
"Id": "20964",
"ParentId": "20916",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20964",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-25T22:06:53.157",
"Id": "20916",
"Score": "2",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Updating / validating mass update rails association"
}
|
20916
|
<p>I know there are a few recursive ways to solve this problem but the code below is what came to mind for me.</p>
<pre><code>void create_bst(node *root, vector<int> arr)
{
int len = arr.size();
add_nodes(root,len-1); //Make the tree structure
inorder_traversal(root,arr);
}
void add_nodes(node *n, int len)
{
queue<node *> bfs;
bfs.push(n);
int i = 1;
while(!bfs.empty())
{
node *temp = bfs.front();
bfs.pop();
temp->left = new node(i++);
len--;
if(len == 0)
{
break;
}
bfs.push(temp->left);
temp->right = new node(i++);
len--;
if(len == 0)
{
break;
}
bfs.push(temp->right);
}
}
void inorder_traversal(node *n, vector<int> arr)
{
static int i=0;
if(n->left != NULL)
{
inorder_traversal(n->left,arr);
}
if(n != NULL)
{
n->data = arr[i];
i++;
}
if(n->right != NULL)
{
inorder_traversal(n->right,arr);
}
}
</code></pre>
<p>The add nodes function creates the BST and the inorder traversal function inserts the appropriate values at each node. Is the algorithm above an efficient way to solve this problem?</p>
|
[] |
[
{
"body": "<ol>\n<li><p>Your code will only work one time, because of the <code>static int i</code> in your inorder_traversal function. You have no way to reset <code>i</code> to <code>0</code></p></li>\n<li><p>Splitting creation and filling into two parts is not what I'd call efficient. This way you have to traverse the tree twice: once while creating it and once while filling it. And if you do not depend on a <em>complete binary tree</em>, managing a queue is a wast of time and unnecessary complexity to whom ever is trying to read your code.</p></li>\n</ol>\n\n<p>My advice would be, work recursive on recursive data. The recursive way is much shorter and much easier to read, isn't it?</p>\n\n<pre><code>node* create_bst(vector<int> const& arr)\n{\n return create_bst(arr, 0, arr.size());\n}\n\nnode* create_bst(vector<int> const& arr, int start, int end)\n{\n if (start >= end)\n return null;\n\n int m = (start + end) / 2;\n\n node* root = new node(arr[m]);\n\n root->left = create_bst(arr, start, m);\n root->right = create_bst(arr, m + 1, end);\n\n return root;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T22:02:18.810",
"Id": "33569",
"Score": "2",
"body": "The only difference I would do is use iterators (and not pass the array). It looks more like standard C++ function then."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T18:30:55.337",
"Id": "20939",
"ParentId": "20924",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "20939",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T03:20:45.133",
"Id": "20924",
"Score": "2",
"Tags": [
"c++",
"optimization"
],
"Title": "Given a sorted array in increasing order, create a BST of minimum height"
}
|
20924
|
<p>I am a programming novice. I've written this simple PHP script to run a very basic comment form and would appreciate any feedback, especially on these three topics:</p>
<ol>
<li>Efficiency (not sure the right word for this): basically, am I doing anything in a clearly awkward/inferior/inelegant way, in terms of using significantly more lines of code or blocks to do what I could have done in less, poorly organizing the code, or bypassing functions or techniques that would provide equivalent functionality with simpler code?</li>
<li>Security: this script (and the page that calls it) are currently protected by <code>htpasswd</code> and will only be accessed by trusted individuals. In light of that, does my script have any security weaknesses?</li>
<li>Readability + conventionality: are there any awkward practices that would look strange or confusing to an experienced PHP programmer?</li>
</ol>
<p>To be clear, the code is working exactly as I intend now, which is to display existing comments and to provide two fields (name and comment) for submission, which submit successfully only if both are nonempty and otherwise indicate with CSS which is blank and preserve the POST data. (I do not receive any errors when using <code>ini_set('display_errors', 'On'); error_reporting(E_ALL | E_STRICT);</code>.)</p>
<p>My code, which follows, is included via <code>include</code> from another PHP page that has the surrounding HTML and CSS. (I should also note that I realize that this script does not follow the <a href="http://en.wikipedia.org/wiki/Post/Redirect/Get" rel="nofollow">PRG model</a>.)</p>
<pre><code><?php
/** Function read_comments() takes no arguments. It reads from what it presumes is a correctly formatted (in HTML) comments.txt file. It then prints based on whether the comments file is empty—a default message if so, or otherwise the preformmated contents. */
function read_comments() {
$comments = file_get_contents('comments.txt');
if(empty($comments)) {
echo '<p><i>There are no comments at this time.</i></p>';
} else {
echo $comments;
}
}
/** Function print_form() prints the user submission form, including inline CSS and POST data if a field is left blank. It takes one integer argument that does the following:
* 0 = print blank form
* 1 = mark the textarea border red (to indicate invalid information, defined later as null); also prints POST data
* 2 = mark the text input field border red (to indicate invalid information, defined later as null); also prints POST data
* 3 = mark both fields red */
function print_form($val) {
/* This line is purely stylistic. */
echo '<p><i>Leave a question/comment:</i></p>';
$form = '<form method="post" action="#"><textarea name="comment" id="comment" style="';
/* toggle CSS on textarea based on validation */
if (($val == 1)||($val == 3)) {
$form .= 'border: 1px solid #912; ';
}
$form .= 'width: 80%; height: 10em;">';
/* display post data if any part of the form is invalid */
if ($val != 0) {
$form .= strip_tags($_POST['comment']);
}
$form .= '</textarea><p><i>Your name:</i><br><input type="text" name="name" id="name"';
/* display post data if any part of the form is invalid */
if ($val != 0) {
$form .= 'value="' . strip_tags($_POST['name']) . '"';
}
/* toggle CSS on input block based on validation */
if (($val == 2)||($val == 3)) {
$form .= ' style="border: 1px solid #912;"';
}
$form .= '></p><p><input type="Submit" value="Post comment"></p></form>';
echo $form;
}
/** The role of process_form() is to evaluate whether there is any information to be written; if so, validate it; then call read_comments() and print_form() appropriately */
function process_form() {
$err = 0;
if ($_POST) {
/* validate the comment box */
if (empty($_POST['comment'])) {
$err++;
}
/* validate the name box */
if (empty($_POST['name'])) {
$err = $err + 2;
}
/* if valid, process the form */
if ($err == 0) {
/* create full HTML comment string */
$comment = '<p>“' . strip_tags($_POST['comment']) . '”<br><span style="text-align: right; font-size: 0.75em;">—' . strip_tags($_POST['name']) . ', ' . date('F j\, g\:i A') . '</span></p>';
/* write file to comments page */
file_put_contents('comments.txt', $comment, FILE_APPEND | LOCK_EX);
}
}
/* Run read_comments() to retrieve the comments, including anything new, then print the form with the appropriate validation value */
read_comments();
print_form($err);
}
process_form();
?>
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>separate the HTML/layout from the PHP</li>\n<li>(don't store the resulting HTML of the comments, a CSV/DB with name, comment and date should be more suitable. This is more effort in first instance, but otherwise you will not be able to change the layout in the future. Also see Robs comment in relation to <a href=\"http://lukeplant.me.uk/blog/posts/why-escape-on-input-is-a-bad-idea/\" rel=\"nofollow noreferrer\"> Filter Input - Escape Output</a>)</li>\n<li>rename <code>read_comments()</code> to <code>load_comments_and_display()</code>, but see item 1</li>\n<li>what is <code>val</code>? use descriptive names and don't use any binary encoding</li>\n<li><code>?></code> can be skipped as best practise</li>\n<li>maybe use <code>htmlentities</code> instead of <code>strip_tags</code> if you ever what do add some html in a comment, which should be displayed (see also <a href=\"https://stackoverflow.com/questions/3605629/php-prevent-xss-with-strip-tags\">PHP: Prevent XSS with strip_tags()?</a>)</li>\n</ul>\n\n<p>With separating the layout from the logic there is even no need for additional methods.</p>\n\n<p>comments.tpl.php</p>\n\n<pre><code> <?php\n //$comments - HTML of all current comments\n //$invalidName\n //$invalidComment\n //$comment\n //$name\n <style type=\"text/css\"><!-- move to a css file //-->\n .error {border: 1px solid #912;}\n .comment {text-align: right; font-size: 0.75em;}\n </style>\n <?if empty($comments):?>\n <p><i>There are no comments at this time.</i></p>\n <?else:?>\n <?=$comments?>\n <?endif?>\n\n <p><i>Leave a question/comment:</i></p>\n <form method=\"post\" action=\"#\">\n <textarea \n <?if($invalidComment):?>class=\"error\"<?endif?> \n name=\"comment\" id=\"comment\" style=\"width: 80%; height: 10em;\">\n <?=$comment?>\n </textarea>\n <p><i>Your name:</i><br>\n <input \n <?if($invalidName):?>class=\"error\"<?endif?> \n type=\"text\" name=\"name\" id=\"name\" value=\"<?=$name?>\">\n </p>\n <p><input type=\"Submit\" value=\"Post comment\"></p>\n </form>\n</code></pre>\n\n<p>comments.php you can include in your other file</p>\n\n<pre><code><?php\n$invalidName=false;\n$invalidComment=false;\nif ($_POST) {\n $invalidComment=empty($_POST['comment']);\n $comment=$invalidComment?\"\":strip_tags($_POST['comment']);\n $invalidName=empty($_POST['name']);\n $name=$invalidName?\"\":strip_tags($_POST['name']);\n\n $valid=!$invalidName && !$invalidComment;\n if ($valid)\n {\n $newComment='<p>“' . $comment . '”<br><span class=\"comment\">—' . $name . ', ' . date('F j\\, g\\:i A') . '</span></p>'\n file_put_contents('comments.txt', $comment, FILE_APPEND | LOCK_EX);\n // clear input, so user won't press submit again\n $comment=\"\"; \n $name=\"\"\n }\n}\n\n$comments = file_get_contents('comments.txt');\nrequire \"comments.tpl.php\";\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T20:55:49.833",
"Id": "33557",
"Score": "0",
"body": "please read about filter input escape output"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-27T09:43:25.140",
"Id": "33582",
"Score": "0",
"body": "Of course you're right, but as long as he stores the final html in the comment file (assuming he has no database or csv), this is not really applicable here, as the output is stored in the file and storing a filtered input is not possible."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T14:43:18.020",
"Id": "20936",
"ParentId": "20925",
"Score": "1"
}
},
{
"body": "<ol>\n<li><p><em>Am I doing anything in a clearly awkward/inferior/inelegant way?</em></p>\n\n<p>Yes, coding html as php strings is extremely difficult to read and maintain. Do this (preferably in a separate view file):</p>\n\n<pre><code><span><?php echo htmlspecialchars($foo); ?></span>\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>echo \"<span>\" . htmlspecialchars($foo) . \"</span>\"\n</code></pre></li>\n<li><p><em>In light of that, does my script have any security weaknesses?</em></p>\n\n<p>Two that I can see right off:</p>\n\n<ul>\n<li><p>Your forms are vulnerable to Cross Site Request Forgery. It does not matter that the area is protected by login/password. CSRF does not require a would be attacker to be a registered member of your site. Use a token in your form to guard against csrf.</p></li>\n<li><p>Your markup is vulnerable to Cross Site Scripting. Again, protected by password does not protect you from \"innocent\" mistakes by your users. Always escape (htmlspecialchars) your <strong>output</strong>.</p></li>\n</ul></li>\n<li><p><em>Are there any awkward practices that would look strange or confusing to an experienced PHP programmer?</em></p>\n\n<ul>\n<li>I know you mentioned being aware of PRG, you should absolutely use it. You'll thank yourself later.</li>\n<li>You may eventually experience performance issues if your comments.txt file gets very large. Typically, data like this would be stored in a db and then the results paginated.</li>\n</ul></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T21:22:10.023",
"Id": "20944",
"ParentId": "20925",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "20944",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T05:10:49.047",
"Id": "20925",
"Score": "2",
"Tags": [
"php",
"optimization",
"beginner",
"security"
],
"Title": "Basic PHP comment form"
}
|
20925
|
<p>I was solving the <a href="https://www.facebook.com/hackercup/problems.php?pid=494433657264959&round=185564241586420" rel="nofollow">"Find the Min"</a> problem on Facebook Hacker Cup.</p>
<p>The code below works fine for the sample inputs given there, but for input size as big as 10<sup>9</sup>, this takes hours to return the solution.</p>
<blockquote>
<p><strong>Problem statement</strong>:</p>
<p>After sending smileys, John decided to play with arrays. Did you know
that hackers enjoy playing with arrays? John has a zero-based index
array, <code>m</code>, which contains <code>n</code> non-negative integers. However, only
the first <code>k</code> values of the array are known to him, and he wants to
figure out the rest.</p>
<p>John knows the following: for each index <code>i</code>, where <code>k <= i < n</code>,
<code>m[i]</code> is the minimum non-negative integer which is <em>not</em> contained in
the previous <code>*k*</code> values of <code>m</code>.</p>
<p>For example, if <code>k = 3</code>, <code>n = 4</code> and the known values of <code>m</code> are <code>[2, 3, 0]</code>, he can figure out that <code>m[3] = 1</code>.</p>
<p>John is very busy making the world more open and connected, as such,
he doesn't have time to figure out the rest of the array. It is your
task to help him.</p>
<p>Given the first <code>k</code> values of <code>m</code>, calculate the nth value of this
array. (i.e. <code>m[n - 1]</code>).</p>
<p>Because the values of <code>n</code> and <code>k</code> can be very large, we use a
pseudo-random number generator to calculate the first <code>k</code> values of
<code>m</code>. Given positive integers <code>a</code>, <code>b</code>, <code>c</code> and <code>r</code>, the known values
of <code>m</code> can be calculated as follows:</p>
<pre><code>m[0] = a
m[i] = (b * m[i - 1] + c) % r, 0 < i < k
</code></pre>
<p>Input</p>
<ul>
<li><p>The first line contains an integer T (T <= 20), the number of test cases.</p></li>
<li><p>This is followed by T test cases, consisting of 2 lines each.</p></li>
<li><p>The first line of each test case contains 2 space separated integers,
<code>n</code>, <code>k</code> (\$1 <= k \le 10^5, k < n \le 10^9\$).</p></li>
<li><p>The second line of each test case contains 4 space separated integers
<code>a</code>, <code>b</code>, <code>c</code>, <code>r</code> (\$0 \le a, b, c \le 10^9, 1 \le r <= 10^9\$).</p></li>
</ul>
</blockquote>
<p>My solution:</p>
<pre><code>import sys
cases=sys.stdin.readlines()
def func(line1,line2):
n,k=map(int,line1.split())
a,b,c,r =map(int,line2.split())
m=[None]*n
m[0]=a
for i in xrange(1,k):
m[i]= (b * m[i - 1] + c) % r
#print m
for j in range(0,n-k):
temp=set(m[j:k+j])
i=-1
while True:
i+=1
if i not in temp:
m[k+j]=i
break
return m[-1]
for ind,case in enumerate(xrange(1,len(cases),2)):
ans=func(cases[case],cases[case+1])
print "Case #{0}: {1}".format(ind+1,ans)
</code></pre>
<p>Sample input:</p>
<blockquote>
<pre><code>5
97 39
34 37 656 97
186 75
68 16 539 186
137 49
48 17 461 137
98 59
6 30 524 98
46 18
7 11 9 46
</code></pre>
</blockquote>
|
[] |
[
{
"body": "<p>Untested, but using <code>Counter</code> from <a href=\"http://docs.python.org/2/library/collections.html\" rel=\"nofollow\"><code>collections</code></a> may be quicker than forming a set of the last <code>k</code> values each time.</p>\n\n<pre><code>counter = collections.Counter(m)\nfor j in xrange(n - k):\n i = 0\n while counter[i]:\n i += 1\n counter[m[j]] -= 1\n counter[i] = 1\n m.append(i)\n</code></pre>\n\n<p>If making the <code>counter</code> takes a long time because <code>k</code> is very large, you could consider making it in 'chunks', reading say the smallest 100 values from <code>m</code> initially then reading another 100 only when <code>i</code> gets larger than the smallest 100.</p>\n\n<p>If that's still not fast enough you could try using <code>deque</code> also from <code>collections</code>, and manually updating the set in each cycle of the loop. You can also take advantage of the fact that the number removed from the top of the list on each cycle gives you a clue as to what the next number has to be (higher or lower); and can use a slightly simplified algorithm when dealing with numbers that the programme has added to the list (in which any sequence of <code>k</code> values can contain no duplicates), as opposed to the original pseudo-random list (which may). (Again, the following is untested)</p>\n\n<pre><code>from collections import deque\n\ndef get_next(i):\n while i in set_last_k:\n i += 1\n return i\n\nfor line1, line2 in zip(cases[1::2], cases[2::2]):\n n, k = map(int, line1.split())\n a, b, c, r = map(int, line2.split())\n m = [a]\n for i in xrange(k - 1):\n m.append((b * m[-1] + c) % r)\n last_k = deque(m)\n set_last_k = set(last_k)\n next = get_next(0)\n for j in xrange(min(k, n - k)): # original list - may contain duplicates\n i = next\n removed = last_k.popleft()\n if removed in last_k:\n next = get_next(i+1)\n else:\n set_last_k.remove(removed)\n if removed < i:\n next = removed\n else:\n next = get_next(i+1)\n m.append(i)\n last_k.append(i)\n set_last_k.add(i)\n if n > 2*k:\n for j in xrange(n - 2*k): # extended list - no duplicates\n i = next\n removed = last_k.popleft()\n set_last_k.remove(removed)\n if removed < i:\n next = removed\n else:\n next = get_next(i + 1)\n m.append(i)\n last_k.append(i)\n set_last_k.add(i)\n print len(m), m[-1]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T13:58:56.013",
"Id": "20934",
"ParentId": "20926",
"Score": "3"
}
},
{
"body": "<h3>1. Improving your code</h3>\n\n<ol>\n<li><p>If you used <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"noreferrer\"><code>if __name__ == '__main__':</code></a> to guard the code that should be executed when your program is run as a script, then you'd be able to work on the code (for example, run timings) from the interactive interpreter.</p></li>\n<li><p>The name <code>func</code> is not very informative. And there's no docstring or <a href=\"https://docs.python.org/3/library/doctest.html\" rel=\"noreferrer\">doctests</a>. What does this function do? What arguments does it take? What does it return?</p></li>\n<li><p><code>func</code> has many different tasks: it reads input, it generates pseudo-random numbers, and it computes the sequence in the problem. The code would be easier to read, test and maintain if you split these tasks into separate functions.</p></li>\n<li><p>Reading all the lines of a file into memory by calling the <a href=\"https://docs.python.org/3/library/stdtypes.html#file.readlines\" rel=\"noreferrer\"><code>readlines</code></a> method is usually not the best way to read a file in Python. It's better to read the lines one at a time by iterating over the file or using <a href=\"https://docs.python.org/3/library/functions.html#next\" rel=\"noreferrer\"><code>next</code></a>, if possible.</p></li>\n<li><p>When computing the result, you keep the whole sequence (all \\$n\\$ values) in memory. But this is not necessary: you only need to keep the last \\$k\\$ values (the ones that you use to compute the <a href=\"https://en.wikipedia.org/wiki/Mex_%28mathematics%29\" rel=\"noreferrer\">minimum excluded number, or <em>mex</em></a>). It will be convenient to use a <a href=\"https://docs.python.org/3/library/collections.html#collections.deque\" rel=\"noreferrer\"><code>collections.deque</code></a> for this.</p></li>\n<li><p>Similarly, it's not necessary to build the set of the last \\$k\\$ values every time you want to compute the next minimum excluded number. If you kept this set around, then at each stage, all you'd have to do is to add one new value to the set and remove up to one old value. It will be convenient to use a <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"noreferrer\"><code>collections.Counter</code></a> for this.</p></li>\n</ol>\n\n<p>Applying all of these improvements results in the code shown below.</p>\n\n<pre><code>import sys\nfrom itertools import count, islice\nfrom collections import Counter, deque\n\ndef pseudorandom(a, b, c, r):\n \"\"\"Generate pseudo-random numbers starting with a and proceeding\n according to the linear congruential recurrence\n a -> (b * a + c) % r.\n\n >>> list(islice(pseudorandom(34, 37, 656, 97), 10))\n [34, 71, 82, 4, 28, 43, 16, 84, 78, 50]\n\n \"\"\"\n while True:\n yield a\n a = (b * a + c) % r\n\ndef mex(c):\n \"\"\"Return the \"mex\" (Minimum EXcluded) number in the Counter c.\n\n >>> mex(Counter(range(10)))\n 10\n >>> mex(Counter([2, 3, 0]))\n 1\n\n \"\"\"\n for i in count():\n if c[i] == 0:\n return i\n\ndef iter_mex(k, it):\n \"\"\"Generate the sequence whose first k values are given by the\n iterable `it`, and whose ith value (for i > k) is the \"mex\"\n (minimum excluded number) of the previous k values of the\n sequence.\n\n \"\"\"\n q = deque(islice(it, k))\n for m in q:\n yield m\n c = Counter(q)\n while True:\n m = mex(c)\n yield m\n q.append(m)\n c[m] += 1\n c[q.popleft()] -= 1\n\ndef nth_iter_mex(n, k, a, b, c, r):\n \"\"\"Return the nth value of the sequence whose first k values are\n given by pseudorandom(a, b, c, r) and whose values thereafter\n are the mex of the previous k values of the sequence.\n\n \"\"\"\n seq = iter_mex(k, pseudorandom(a, b, c, r))\n return next(islice(seq, n, None))\n\ndef main(f):\n cases = int(next(f))\n for i in xrange(cases):\n n, k = map(int, next(f).split())\n a, b, c, r = map(int, next(f).split())\n print('Case #{}: {}'.format(i, nth_iter_mex(n - 1, k, a, b, c, r)))\n\nif __name__ == '__main__':\n main(sys.stdin)\n</code></pre>\n\n<h3>2. Timing</h3>\n\n<p>Python comes with the <a href=\"https://docs.python.org/3/library/timeit.html\" rel=\"noreferrer\"><code>timeit</code> module</a> for timing code. Let's have a look at how long the program takes on some medium-sized test instances:</p>\n\n<pre><code>>>> from timeit import timeit\n>>> timeit(lambda:nth_iter_mex(10**5, 10**2, 34, 37, 656, 97), number=1)\n1.6787691116333008\n>>> timeit(lambda:nth_iter_mex(10**5, 10**3, 34, 37, 656, 97), number=1)\n16.67353105545044\n>>> timeit(lambda:nth_iter_mex(10**5, 10**4, 34, 37, 656, 97), number=1)\n143.31502509117126\n</code></pre>\n\n<p>The runtime of the program is approximately proportional to both \\$n\\$ and \\$k\\$, so extrapolating from the above timings, I expect that in the worst case, when \\$n = 10^9\\$ and \\$k = 10^5\\$, the computation will take about five months. So we've got quite a lot of improvement to make!</p>\n\n<h3>3. Speeding up the mex-finding</h3>\n\n<p>In the implementation above it takes \\$Θ(k)\\$ time to find the mex of the last \\$k\\$ numbers, which means that the whole runtime is \\$Θ(nk)\\$. We can improve the mex finding to \\$O(\\log k)\\$ as follows.</p>\n\n<p>First, note that the mex of the last \\$k\\$ numbers is always a number between \\$0\\$ and \\$k\\$ inclusive. So if we keep track of the set of <em>excluded numbers</em> in this range (that is, the numbers between \\$0\\$ and \\$k\\$ inclusive that do not appear in the last \\$k\\$ elements of the sequence), then the mex is the smallest number in this set. And if we keep this set of excluded numbers in a <a href=\"https://en.wikipedia.org/wiki/Heap_(data_structure)\" rel=\"noreferrer\">heap</a> then we can find the smallest in \\$O(\\log k)\\$.</p>\n\n<p>Like this:</p>\n\n<pre><code>import heapq\n\ndef iter_mex(k, it):\n \"\"\"Generate the sequence whose first k values are given by the\n iterable `it`, and whose ith value (for i > k) is the \"mex\"\n (minimum excluded number) of the previous k values of the\n sequence.\n\n \"\"\"\n q = deque(islice(it, k))\n for m in q:\n yield m\n excluded = list(set(xrange(k + 1)).difference(q))\n heapq.heapify(excluded)\n c = Counter(q)\n while True:\n mex = heapq.heappop(excluded)\n yield mex\n q.append(mex)\n c[mex] += 1\n old = q.popleft()\n c[old] -= 1\n if c[old] == 0:\n heapq.heappush(excluded, old)\n</code></pre>\n\n<p>Now the timings are much more satisfactory:</p>\n\n<pre><code>>>> timeit(lambda:nth_iter_mex(10**5, 10**2, 34, 37, 656, 97), number=1)\n0.2606780529022217\n>>> timeit(lambda:nth_iter_mex(10**5, 10**3, 34, 37, 656, 97), number=1)\n0.2634279727935791\n>>> timeit(lambda:nth_iter_mex(10**5, 10**4, 34, 37, 656, 97), number=1)\n0.32929110527038574\n>>> timeit(lambda:nth_iter_mex(10**6, 10**5, 34, 37, 656, 97), number=1)\n3.5652129650115967\n</code></pre>\n\n<p>However, we still expect that when \\$n = 10^9\\$ and \\$k = 10^5\\$, the computation will take around an hour, which is still far too long.</p>\n\n<h3>4. A better algorithm</h3>\n\n<p>Let's have a look at the actual numbers in the sequence generated by <code>iter_mex</code> and see if there's a clue as to a better way to calculate them. Here are the first hundred values from a sequence with \\$k = 13\\$ and \\$r = 23\\$:</p>\n\n<pre><code>>>> list(islice(iter_mex(13, pseudorandom(34, 37, 656, 23)), 100))\n[34, 5, 13, 10, 14, 1, 3, 8, 9, 0, 12, 19, 2, 4, 6, 5, 7, 10, 11, 1,\n 3, 8, 9, 0, 12, 13, 2, 4, 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13,\n 2, 4, 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4, 6, 5, 7, 10,\n 11, 1, 3, 8, 9, 0, 12, 13, 2, 4, 6, 5, 7, 10, 11, 1, 3, 8, 9, 0,\n 12, 13, 2, 4, 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4, 6, 5]\n</code></pre>\n\n<p>You should have noticed a pattern there, but let's lay it out in rows of length \\$k + 1 = 14\\$ to make it obvious:</p>\n\n<pre><code>[34, 5, 13, 10, 14, 1, 3, 8, 9, 0, 12, 19, 2, 4,\n 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4,\n 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4,\n 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4,\n 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4,\n 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4,\n 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4,\n 6, 5]\n</code></pre>\n\n<p>You can see that the first \\$k + 1\\$ values are different, but thereafter each group of \\$k + 1\\$ items from the sequence is identical (and moreover is a permutation of the numbers \\$0, \\ldots, k\\$).</p>\n\n<p>Let's check that this happens for some bigger examples:</p>\n\n<pre><code>>>> it = iter_mex(10**5, pseudorandom(34, 37, 656, 4294967291))\n>>> next(islice(it, 10**5, None))\n0\n>>> s, t = [list(islice(it, 10**5 + 1)) for _ in xrange(2)]\n>>> s == t\nTrue\n>>> sorted(s) == range(10**5 + 1)\nTrue\n</code></pre>\n\n<p>Let's prove that this always happens. First, as noted above, the mex of \\$k\\$ numbers is always a number between \\$0\\$ and \\$k\\$ inclusive, so all numbers in the sequence after the first \\$k\\$ lie in this range. Each number in the sequence is different from the previous \\$k\\$, so each group of \\$k + 1\\$ numbers after the first \\$k\\$ must be a permutation of the numbers from \\$0\\$ to \\$k\\$ inclusive. So if the (\\$k + 1\\$)th last number is \\$j\\$, then the last \\$k\\$ numbers will be a permutation of the numbers from \\$0\\$ to \\$k\\$ inclusive, except for \\$j\\$. So \\$j\\$ is their mex, and that will be the next number. Hence the pattern repeats.</p>\n\n<p>So now it's clear how to solve the problem. If \\$n > k\\$, element number \\$n\\$ in the sequence is the same as element number \\$k + 1 + n \\bmod (k + 1)\\$.</p>\n\n<p>The implementation is straightforward:</p>\n\n<pre><code>def nth_iter_mex(n, k, a, b, c, r):\n \"\"\"Return the nth value of the sequence whose first k values are\n given by pseudorandom(a, b, c, r) and whose values thereafter\n are the mex of the previous k values of the sequence.\n\n \"\"\"\n seq = iter_mex(k, pseudorandom(a, b, c, r))\n if n > k: n = k + 1 + n % (k + 1)\n return next(islice(seq, n, None))\n</code></pre>\n\n<p>and now the timings are acceptable:</p>\n\n<pre><code>>>> timeit(lambda:nth_iter_mex(10**9, 10**5, 34, 37, 656, 4294967291), number=1)\n1.6802959442138672\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-30T10:18:18.000",
"Id": "21055",
"ParentId": "20926",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "21055",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T07:06:50.447",
"Id": "20926",
"Score": "4",
"Tags": [
"python",
"optimization",
"performance",
"programming-challenge"
],
"Title": "\"Find the Min\" challenge on Facebook Hacker Cup"
}
|
20926
|
<p>I have the following example app: <a href="http://dev.driz.co.uk/jsfunction/" rel="nofollow">http://dev.driz.co.uk/jsfunction/</a></p>
<p>Which runs two types of script files with the same outcome.</p>
<p>Script1:</p>
<pre><code>var script1 = {
showMessage: function( message ) {
var el = document.getElementById('example1');
el.innerHTML = message;
}
}
</code></pre>
<p>and script 2:</p>
<pre><code>window.script2 = function() {
function showMessage( message ) {
var el = document.getElementById('example2');
el.innerHTML = message;
}
return {
showMessage: showMessage
}
}();
</code></pre>
<p>They are both namespaced so I can them like:</p>
<pre><code>window.onload = function() {
script1.showMessage('Hello world!');
script2.showMessage('How are you?');
};
</code></pre>
<p>But what's the better way forward? Script1 is the type I would normally write but it requires you to sometimes call a init function first if you have some events that need running on document load.</p>
<p>For example:</p>
<pre><code>var script = {
init: function() {
// some events such as onlick etc..
}
};
script.init();
</code></pre>
<p>Script2 however is a self executing function and therefore would get around this but being a function itself would it allow the same flexibility?</p>
<p>Any thoughts? Suggestions or examples of how people namespace there script files to make them neater and more efficient?</p>
|
[] |
[
{
"body": "<p>Try module-pattern, or somewhat like the module pattern, using an <a href=\"http://benalman.com/news/2010/11/immediately-invoked-function-expression/\" rel=\"nofollow\">IIFE</a></p>\n\n<p>In your case:</p>\n\n<pre><code>(function(ns){\n\n ns.showMessage = function(message){\n var el = document.getElementById('example1');\n el.innerHTML = message;\n }\n\n}(this.script1 = this.script1 || {}));\n\nwindow.onload = function() {\n script1.showMessage('Hello world!');\n};\n</code></pre>\n\n<p>Here's the explanation</p>\n\n<pre><code>//basically, an IIFE is a function that executes itself\n(function(ns){\n\n //in here, ns is a reference to our this.namespace\n\n //also, this IIFE provides us with a local scope\n //we can declare functions and variables that only this scope, by default, sees\n\n //a \"private\" variable\n var priv = \"I can only be seen in the module\";\n\n //a \"private\" function\n function privFn(){\n console.log('I am only usable in the module');\n }\n\n //a \"public\", or more accurately, an \"exposed\" variable\n //we attach it to the namespace\n ns.foo = 'I am an exposed value';\n\n //an exposed function\n ns.bar = function(){\n console.log('exposed!');\n //with an exposed function, we can also call a private function\n privFn();\n }\n\n//this line creates the namespace or uses an existing one\n//it then executes the function, passing the created/existing namespace\n}(this.namespace = this.namespace || {}));\n</code></pre>\n\n<p>And so, using our module:</p>\n\n<pre><code>//we can use the exposed entities\nnamespace.bar(); \n//exposed! \n//I am only usable in the module <- since bar called privFn, it also prints\nnamespace.foo === 'I am an exposed value'\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-27T00:36:38.827",
"Id": "20946",
"ParentId": "20928",
"Score": "2"
}
},
{
"body": "<p>I think it depends on what you need.</p>\n\n<p>For <code>script1</code>, every end point can be accessed. <code>this</code> can be referenced as the object. I like the pattern like:</p>\n\n<pre><code>var Car = {\n name: null,\n init: function (name) {\n this.name = name;\n }\n};\n</code></pre>\n\n<p>For <code>script2</code>, it encapsulates some private variables or functions, which cannot be accessed outside of the anonymous function scope. You can choose what to expose and what to hide.</p>\n\n<pre><code>var Car = (function () {\n var MAX_SPEED = 120; //cannot be referenced\n\n function init() {\n //something cannot be referenced outside the Car\n }\n\n function run() {\n //...\n }\n\n return {\n run: run;\n };\n\n})();\n</code></pre>\n\n<p>These are the ways to create simple namespaces. Because you can also make namespace into a module.</p>\n\n<pre><code>namespace(\"GLOBAL.app.Ticker\");\n</code></pre>\n\n<p><code>namespace</code> will be a simple module to parse the string <code>GLOBAL.app.Ticker</code>, and convert it to a new Object.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-08T06:52:51.163",
"Id": "21457",
"ParentId": "20928",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-26T11:12:31.193",
"Id": "20928",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Namespaced JavasScript code"
}
|
20928
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.