body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I am currently writing a game in C++ and have some variables that I want to be accessible from everywhere. For the examples, I will have the shared variable as an object of the class <code>Input</code>.</p>
<p>At the moment I am implementing it like this:</p>
<p><strong>input.h:</strong></p>
<pre><code>#ifndef INPUT_H
#define INPUT_H
extern Input input;
#endif
</code></pre>
<p><strong>init.cpp:</strong></p>
<pre><code>Input input;
int main(//args){
input.doStuff();
}
</code></pre>
<p>Other files that use the object.cpp:</p>
<pre><code>#include "input.h"
void method(){
input.doStuff();
}
</code></pre>
<p>I've got this nagging doubt that I shouldn't be doing things in this way. Is this doubt correct? What should I be doing and why?</p>
|
[] |
[
{
"body": "<p><strong>Your doubt is correct, don't use global variables.</strong></p>\n\n<p>(Note: For this post, I mean <em>variable</em> in its true meaning, i.e. objects that may change.)</p>\n\n<p>I can't say for sure which technique is the correct one without seeing your code, but normally you want to pass the variable as a parameter to whichever entity needs it:</p>\n\n<pre><code>void foo(Input input)\n{\n input.doSomething();\n}\n\nint main()\n{\n Input input;\n input.doSomething();\n\n foo(input);\n}\n</code></pre>\n\n<p>Or, restrict it to a class as a member variable.</p>\n\n<hr>\n\n<h3>Update: Class examples</h3>\n\n<p>You can do it one or both of these ways:</p>\n\n<pre><code>class Person {\n std::string name_;\npublic:\n explicit Person(std::string const& name) : name_(name) {}\n void set_name(std::string const& name) { name_ = name; }\n}\n\nvoid foo()\n{\n Person p(\"Bob Loblaw\");\n\n p.set_name(\"Slartibartfast\");\n}\n</code></pre>\n\n<hr>\n\n<p>There are two key downsides to using global variables:</p>\n\n<p><strong>1. They can be changed everywhere.</strong></p>\n\n<p>You generally want to enlist the compiler's aid in finding bugs and errors for you. If you allow yourself to modify a variable from all over your code, it is very hard for your compiler and yourself to track down an error. Consider the following scenario:</p>\n\n<pre><code>Input input; // global\n\nvoid foo()\n{\n Input inputt;\n input = someThingWeird;\n}\n</code></pre>\n\n<p>This code will compile. If you're really unlucky, it will even work for a while. If you don't have a global, the code won't compile and the bug will be easy to find.</p>\n\n<p><strong>2. They increase coupling (and reduce testability).</strong></p>\n\n<p>By reading from a global variable, your entity (i.e. function, class, whatever) <em>depends</em> on that global variable. If some day you want to use something else, you'll have to do a lot of refactoring. What's more important, if you change an aspect of the global variable, you will need to update <em>all parts of the code that uses it</em>. This is a great opportunity for suble bugs to infiltrate your code and make your life miserable. A typical example is that <strong>you modify one part of your code, and a completely different part will break</strong>.</p>\n\n<p>Using globals also makes your code hard to unit test, because it depends on the global variable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T14:32:12.460",
"Id": "45928",
"Score": "0",
"body": "So if I wanted an object in my game (say for example an entity) to have access to the input object I should pass it in the constructor?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T14:34:17.747",
"Id": "45929",
"Score": "1",
"body": "If you have a class, and you want that class to be able to use an object, then you will either need to **a)** let the class own the object (create it as a member variable or a local in a function), or **b)** pass it as an argument to the class' constructor or one of the class' functions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T14:35:40.380",
"Id": "45930",
"Score": "0",
"body": "Ok, thanks. I will have to go for the second option as it is important that everything in the game using the input object uses the **same** object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T14:39:20.333",
"Id": "45931",
"Score": "0",
"body": "I updated my answer with an example. Just use an `Input` instead of `std::string`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T14:42:57.113",
"Id": "45932",
"Score": "0",
"body": "\"They can be changed everywhere.\" nope, the fact that they are global doesn't imply this condition, if you declare this statement `static const int a = 42;` globally, you can only read from `a` you will not be able to write in it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T14:43:56.737",
"Id": "45933",
"Score": "0",
"body": "@handuel: You can also combine both options. In other words, one class can pass a member object to another class that needs it. This would be better than using `friend` as you're not giving the receiving class _complete_ access to the sending class' `private` data."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T14:45:26.100",
"Id": "45934",
"Score": "0",
"body": "@user2485710: I've already specified that in my answer. Constants cannot be changed, _even_ in global scope. That's why it's okay to put them there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T15:13:21.520",
"Id": "45938",
"Score": "1",
"body": "@user2485710 Objects with internal linkage are not really global, and *constants* are definitely not *variable*s."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T18:31:57.950",
"Id": "46069",
"Score": "0",
"body": "Your advice is too generic. Global are fine as long as their state does not change. The problem comes from global mutable state (its the `variable` part of `global variable` that is the problem). If your global contains no state that changes (ie only const values (or only methods (that don't change global state)) then you are fine. But passing values is the solution you are correct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T20:05:59.223",
"Id": "46081",
"Score": "0",
"body": "@LokiAstari Thanks for the feedback. However, I write *variable* repeatedly and emphasize that (unexpected) change is the main problem. How is that too generic? In either case, non-mutable globals also have drawbacks, for example reduced flexibility and testability. Also, [this](http://xkcd.com/859/) :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T23:55:25.160",
"Id": "46088",
"Score": "0",
"body": "@Listor. `In either case, non-mutable globals also have drawbacks, for example reduced flexibility and testability.` Not true. If there is no state then they are the same as standalone functions. You can't change them so there is no point in mocking them out (as there result is not dependent on state). Also just because you use the term `variable` is a bit meaningless. It is a common synonym for a named object. `int const test = 5;` That's a global variable by most peoples definition. But its not a problem because its not `global mutable state`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T23:57:00.667",
"Id": "46089",
"Score": "0",
"body": "See: [Google Talk: The Clean Code Talks - \"Global State and Singletons\"](http://www.youtube.com/watch?v=-FRm3VPhseI)"
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T14:05:40.603",
"Id": "29133",
"ParentId": "29130",
"Score": "15"
}
},
{
"body": "<p>@Lstor is absolutely correct. However, I'll like to add some things:</p>\n\n<ul>\n<li><p>If you're using constants (indicated by the <code>const</code> keyword), they're <em>okay</em> as globals. This is because they cannot be changed elsewhere in the code, unlike global variables).</p></li>\n<li><p>I'd recommend <code>class</code>es, especially when writing a game. When used properly, they will allow you to hide your data from entities that should not have access to them. However, it's best not to use them <em>just</em> to avoid globals, especially when they can still be passed around. They should serve some kind of role, even if your program doesn't revolve around <code>class</code>es. In your case, you'll most likely have a Game <code>class</code> and possibly additional <code>class</code>es. More general info about this <a href=\"http://www.cplusplus.com/doc/tutorial/classes/\">here</a>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T14:10:41.027",
"Id": "29134",
"ParentId": "29130",
"Score": "7"
}
},
{
"body": "<p>Using global accessible variables is like handing your wallet to other and hoping they will only take the amount of money you owe them. You don't do this either. </p>\n\n<p>I was confronted with a similar problem while developing a simulation in XNA. There are some properties that have to be public known, but I want to control access to them. So I implemented a generic ItemChangedService. Here a simplified version of it.</p>\n\n<pre><code>public abstract class ItemChangedService<T>{\n //private backing field that holds my value\n private readonly T _current; \n\n //Property Current -> simple a getter and setter\n public virtual T Current {\n get {return _current;}\n set{ \n if(value == current) return; //no change, so we can return\n\n _current = value;\n //Invoke Changed event.\n if(Changed == null) return;\n\n Changed(this, EventArgs.Empty);\n }\n }\n public event EventHandler Changed;\n}\n</code></pre>\n\n<p>This solution has two clear advantages over yours:</p>\n\n<p>First of all your variable is only changeable by getter setter you can redefine in subclasses. The second is that components can register for changes.\nFurther more the behavior while getting/settings is extendable. So I created more *ChangedServices that are able to:</p>\n\n<ul>\n<li>Define what happen it the variable is set to the value it was before. (Define a RefreshBehaviour)</li>\n<li>Validate the input \"value\". (And what should be done? Exeption, LeaveExitingValue,... )</li>\n</ul>\n\n<p>Never the less you can make typedefs in order to give this ItemChangedService meaningful names like CurrentFPSService or CamereaService and so on.</p>\n\n<p><em>Reaction on comments:</em>\nSorry for the C# Code. Unfortunately I can only read C++, but write is a little bit difficult for me. So I try to make an example in pseucode without generics, events and properties:</p>\n\n<pre><code>template <typename T>\nclass ItemChangedService {\n T myVariable;\n\npublic:\n virtual T getValue() const {\n return myVariable;\n }\n\n virtual void setValue(T const& value) {\n if (value == myValue) return; // No change, so we can skip\n\n myValue = value;\n }\n}\n</code></pre>\n\n<p>Because of the fact that the getter and setter are virtual, you can adjust these behavior in subclasses.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T15:12:08.553",
"Id": "45937",
"Score": "1",
"body": "Nice analogy! I'd say it's also like holding out your wallet in public and hoping that no one grabs it without your permission."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T15:17:42.543",
"Id": "45940",
"Score": "1",
"body": "Note that the question is about C++, so posting C# code is not likely to be very helpful to OP."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T16:40:29.170",
"Id": "45946",
"Score": "0",
"body": "@Lstor That is indeed true. I'm afraid I'm having difficulty understanding that code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T17:01:10.807",
"Id": "45949",
"Score": "1",
"body": "There should at least be sufficient comments (if that will even help). I too cannot understand it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T19:37:25.907",
"Id": "45963",
"Score": "1",
"body": "@hichaeretaqua I fixed the C++ so that it's valid. I (re-)introduced templates, since C++ doesn't have a common base class. I did *not* change the variable names (although they should be), and I didn't fix the bug (mixing `myValue` and `myVariable`)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T15:07:44.220",
"Id": "29136",
"ParentId": "29130",
"Score": "5"
}
},
{
"body": "<p>I'm going to go against the current here and suggest that \"no global variables ever\" is unnecessarily dogmatic, and maintaining a small handful of global <em>singleton objects</em> can vastly simplify your code. </p>\n\n<p>For a game in particular, something like an input manager or a graphics system makes sense as a global singleton. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-16T23:49:00.397",
"Id": "234992",
"Score": "0",
"body": "...to which I'd contend that - unless it's being used for its real features like lazy evalutation or to avoid the static initialisation order fiasco - a singleton is often just unnecessary boilerplate, which achieves nothing functionally different from bare globals, other than covering your tracks against the less thorough anti-global crusaders ;-) meaning that imo, sometimes your 1st paragraph is equally true for bare globals... in small doses and unambiguously name[space]d."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T18:18:22.537",
"Id": "29144",
"ParentId": "29130",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "29133",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T13:54:01.423",
"Id": "29130",
"Score": "8",
"Tags": [
"c++"
],
"Title": "Is this code with global variables good practice?"
}
|
29130
|
<p>I have a method that calls a "bridge" for <code>TraderMarketInfo</code>. When info is received, it checks if info <code>IsSet</code> and raises an event. I want to make this method async. C# .NET4.0 VS2012.</p>
<p>Original method:</p>
<pre><code>public void RequestMarketInfo()
{
TraderMarketInfo marketInfo = bridge.GetMarketInfoAll(Data.Symbol);
if (marketInfo.IsSet)
OnMarketInfoUpdated(new MarketInfoUpdateEventArgs(Data.ConnectionId, marketInfo));
}
</code></pre>
<p>My attempt to make it async:</p>
<pre><code>public void RequestMarketInfo()
{
var task = Task<TraderMarketInfo>.Factory.StartNew(() => bridge.GetMarketInfoAll(Data.Symbol));
task.ContinueWith(t =>
{
if (t.Result.IsSet)
OnMarketInfoUpdated(new MarketInfoUpdateEventArgs(Data.ConnectionId, t.Result));
});
}
</code></pre>
<p>Is it done right?</p>
|
[] |
[
{
"body": "<p>You need to be very careful when making code like this multithreaded. Your implementation will compile, and will execute the <code>GetMarketInfoAll()</code> method on another thread, but it may not do what you want. There are at least two things to consider:</p>\n\n<ul>\n<li><p><strong>Synchronization</strong>:<br>\nThe lambda function given to <code>ContinueWith</code> can (and often will) be executed on a different thread from the one that called <code>RequestMarketInfo</code>. The lambda function in your code invokes an event handler, this means that the code inside the event handler may need to synchronize any data it accesses, or you will end up with race conditions and other threading issues.</p></li>\n<li><p><strong>Thread Affinity</strong>:<br>\nSimilar to the first point, it may be necessary for you to ensure that the event handler is invoked on a certain thread. If any of the handlers for the <code>OnMarketInfoUpdated</code> event are updating a UI component in Windows Forms, then you will certainly need to perform those updates on the UI thread using <a href=\"http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx\" rel=\"nofollow\">Invoke</a>.</p></li>\n</ul>\n\n<p>You should also note that depending on the type of application you are developing, it may not actually help you to convert this to async. For example, web applications under heavy load are already using 1 thread per web request, and are often maxed out. However, I suspect you are using this inside a GUI and are trying to make the UI more responsive while it processes this long running query, in which case converting this to async is a good idea.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T04:47:28.020",
"Id": "45996",
"Score": "0",
"body": "Thank you @Gordon Burgett. Bridge uses NamedPipes to communicate with third party app. The code above starts giving \"Cannot connect to client\" error in 50% of the cases. Event risen by OnMarketInfoUpdated causes different calculations on different classes but finally it updates UI (BeginInvoke). Except of the pipe error it works. I'm not sure is it (and other similar calls) creates several clients at a time and break the pipe?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T19:37:06.227",
"Id": "46078",
"Score": "0",
"body": "It is possible that your bridge class is not thread safe. You may try synchronizing the call to the method, ex. `lock(bridge){ return bridge.GetMarketInfoAll(Data.Symbol); }`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T19:42:33.513",
"Id": "46079",
"Score": "0",
"body": "`lock(bridge)...` thank you. Or I have to repair bridge itself. I'll +1 your answers when I can."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T01:30:58.227",
"Id": "29158",
"ParentId": "29137",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29158",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T16:18:09.850",
"Id": "29137",
"Score": "1",
"Tags": [
"c#",
".net",
"task-parallel-library",
"async-await"
],
"Title": "Converting a method to async"
}
|
29137
|
<p>When creating multiple constructors, I usually do the following;</p>
<pre><code>public ConstructorName(int count)
{
this(count, 0);
}
public ConstructorName(String count)
{
this(Integer.parseInt(count), 0);
}
public ConstructorName(int count, int other)
{
// Do something here
}
</code></pre>
<p>However, I can also do it this way;</p>
<pre><code>public ConstructorName(String count)
{
this(Integer.parseInt(count)); // Chain to the constructor that just takes a number
}
public ConstructorName(int count)
{
this(count, 0);
}
public ConstructorName(int count, int other)
{
// Do something here
}
</code></pre>
<p>Is there any actual difference here? Which would be better to use when coding?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T19:24:40.703",
"Id": "45962",
"Score": "1",
"body": "The first option will be slightly more efficient. Less switching scopes = less time wasted unnecessarily popping stuff on and off the stack."
}
] |
[
{
"body": "<p>If there is more than one way to construct an instance, then <em>static factory methods</em> backed by one private constructor, can really help readability, since they can be named differently.</p>\n\n<pre><code>Range halfOpen = Range.largerThan(5);\nRange closed = Range.between(7, 12);\n</code></pre>\n\n<p>If it is really about setting some properties and not others, then the <a href=\"http://en.wikipedia.org/wiki/Builder_pattern\" rel=\"nofollow\">Builder pattern</a> can be what you want. </p>\n\n<pre><code>Person john = Person.named(\"John\")\n .lastName(\"Lennon\")\n .gender(Male)\n .yearOfBirth(1940)\n .build();\n</code></pre>\n\n<p>Both of these approaches also allow for hiding which implementation class is really returned. Our <code>Person</code> instance may be an instance of subclass <code>Man</code>, and the half open <code>Range</code> may be an instance of <code>HalfOpenRange</code>. Both methods allow returning a cached instance, rather than an actual new instance.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T19:18:07.973",
"Id": "29146",
"ParentId": "29142",
"Score": "2"
}
},
{
"body": "<p>Doesn't answer the question directly, but its far more better <em>not</em> to overload constructors/function</p>\n\n<p>Instead of constructor overloading you should make the construtor private and call it from public static functions which do start with \"create\" or something like that.</p>\n\n<p>For example:</p>\n\n<pre><code>class ClassName\n{\n static public ClassName createFromCountString(string count)\n {\n return new ClassName(Integer.parseInt(count), 0);\n }\n\n static public ClassName createFromCount(int count)\n {\n return new ClassName(count, 0);\n }\n\n static public ClassName createFromCountAndOther(int count, int other)\n {\n return new ClassName(count, other);\n }\n\n private ClassName(int count, int other)\n {\n // do something here\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T04:31:24.413",
"Id": "45992",
"Score": "0",
"body": "How can you write `this()` outside a constructor?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T13:53:59.573",
"Id": "46038",
"Score": "0",
"body": "@tintinmj the methods all belong to the ClassName class"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T14:08:40.313",
"Id": "46039",
"Score": "1",
"body": "@Quonux first of all you can't use `this` inside static method. Second you can call a constructor **ONLY** inside from another constructor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T14:20:24.990",
"Id": "46040",
"Score": "0",
"body": "@tintinmj ok i corrected it, and you can't call it this way in *java*, but its possible in *d*, but it wasn't real java so i changed it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T14:27:10.287",
"Id": "46044",
"Score": "0",
"body": "@tintinmj calling the constructor outside of a static function works http://ideone.com/Wawrd1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T14:33:43.307",
"Id": "46046",
"Score": "0",
"body": "@Quonux did you use `this`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T14:36:01.987",
"Id": "46047",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/9883/discussion-between-tintinmj-and-quonux)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T14:09:22.207",
"Id": "46265",
"Score": "0",
"body": "Why is it better?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T16:20:41.813",
"Id": "46268",
"Score": "0",
"body": "@PeterTaylor it is more readable"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T19:19:25.927",
"Id": "29147",
"ParentId": "29142",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29147",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T18:12:13.423",
"Id": "29142",
"Score": "4",
"Tags": [
"java",
"constructor"
],
"Title": "Constructor Chaining in Java"
}
|
29142
|
<p>In a simple webapp I have been using as a playground, I am playing with using rxjava to perform a number of operations in a reactive manner. I have been using reactivemongo to connect to my Mongo database, but I find that for anything more than a trivial CRUD operation I often end up trying to reduce a <code>Future[List[Future[T]]]</code> into a <code>Future[List[T]]</code>. This can happen multiple times in the execution chain, before I finally hand it back to the Play framework.</p>
<p>I am playing with rxjava to try to convert these reactive operations into Observables, so that I can combine them using rxjava's utility methods, but I was wondering if anyone had already solved this problem.</p>
<p>Here is an example from my most complex action:</p>
<pre><code>def import = Action {
//scan the base folder for app IDs (Future[List[UUID]])
val summaries = ftpWrapper.scanUserIdsAsync
//import all the files in each of those folders (Future[List[LogImportResult]])
val processResults = summaries.flatMap(lst => {
//List[Future[List[LogImportResult]]]
val imports = lst.map(user => logProcessor.importLogFolderAsync(user))
//fold together the several lists of insertion results into one list
Future.fold(imports)( List[LogImportResult]() )( _ ++ _ )
})
Async {
//display the insertion results, or throw.
processResults.transform(r => Ok(views.html.logImportResult(r)), ex => throw ex)
}
}
</code></pre>
<p>The above code calls into my services to do the following:</p>
<ul>
<li>Locate all folders on an FTP server whose names are UUIDs</li>
<li>Import all files inside each folder into the Mongo database:
<ul>
<li>check if the file already exists in mongo</li>
<li>if no, then insert the data from the file as a BSONDocument</li>
</ul></li>
<li>combine the results of importing each folder into one giant list</li>
<li>display the results in the view</li>
</ul>
<p>Most of these actions are non-blocking asynchronous, and as such return a future. I have code all over the place in this app to combine these futures together, so I am interested in seeing if rxjava can simplify that. I have already been working on some ideas here: <a href="https://gist.github.com/gburgett/6106724" rel="nofollow">https://gist.github.com/gburgett/6106724</a></p>
<p>So, has anyone encountered something like this? If so, do you have a better way to go about it than simply combining futures like this?</p>
|
[] |
[
{
"body": "<p>It could be the case that using Scala.Rx's reactive variables simplify your use case since they propagate change state as they happen. In particular, chaining those smart Var's together might help you simplify the task. Please have a look at: </p>\n\n<p><a href=\"https://github.com/lihaoyi/scala.rx\" rel=\"nofollow\">https://github.com/lihaoyi/scala.rx</a> </p>\n\n<p>There you also find a link to the underlying publication that elaborates on the concept further.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-15T18:41:03.843",
"Id": "44458",
"ParentId": "29145",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T18:56:01.093",
"Id": "29145",
"Score": "2",
"Tags": [
"scala"
],
"Title": "rxjava observables and scala futures"
}
|
29145
|
<p>I'm using Twitter Bootstrap and I'm working on a page that has several tabs that all have carousels in them (each with a ton of images) I've managed to write an AJAX script that pulls the images from a JSON file I've created (for one of the carousels). I'm planning on making similar JSON file for the rest, but what I'm wondering though is there a way to write the AJAX script so that it grabs the id from the HTML so I don't have to make a unique AJX script for each version of the carousel</p>
<p>Here's how my HTML looks for the carousel:</p>
<pre><code> <div id="ShaluCarousel1b" class="carousel slide"><!-- class of slide for animation -->
<div class="carousel-inner" id="carousel1b">
</div><!-- /.carousel-inner -->
</div>
</code></pre>
<p>And here's my AJAX script:</p>
<pre><code><script>
$.ajaxSetup({
error: function(xhr, status, error) {
alert("An AJAX error occured: " +status + "\nError: " +error);
}
});
$.ajax({
url:'json/carousel1b',
type:'GET',
success: function(data){
console.log('grabbing photos');
var totalPictures = data['totalPictures'];
for (var i=0; i<totalPictures; i++) {
console.log("new image");
if(i<1){
console.log("first image");
var d = "<div class='item active'>";
d += "<a href='" +data.pictures[i]['photo'] +"' rel='prettyPhoto'>";
d += "<img src='" +data.pictures[i]['photo'] +"' >";
d += "</a>";
d += "</div>";
$('#carousel1b').append(d);
}
else {
console.log("image" +i);
var d = "<div class='item'>";
d += "<a href='" +data.pictures[i]['photo'] +"' rel='prettyPhoto'>";
d += "<img src='" +data.pictures[i]['photo'] +"' alt=''>";
d += "</a>";
d += "</div>";
$('#carousel1b').append(d);
$("a[rel^='prettyPhoto']").prettyPhoto();
console.log('pp init');
}
}
}
})
</script>
</code></pre>
<p>I'm basically wondering if there is a way to pull the id (carousel1b) from the htnl and inject it into the AJAX strip in the "url:'jason/<strong>carousel1b</strong> and the "$('<strong>carousel</strong>').append(d)"</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T20:57:22.840",
"Id": "45969",
"Score": "0",
"body": "When do you decide to load the AJAX? Is it when the user clicks on a link? Or when the page loads?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T18:21:52.690",
"Id": "46161",
"Score": "0",
"body": "I was looking to do it when the user clicks on a link - I ended up taking your answer and modifying it a bit. I actually have a bit of a challenge in that there are tabs within tabs... I think I have it mostly working now though"
}
] |
[
{
"body": "<p>Depending on when you want to make the ajax request, you'll need to modify the first line of my example. Currently it just gets all of them. You might want to change it so that it gets only the div that was clicked, or whatever. Anyways here's one way you could do that:</p>\n\n<pre><code>$('div[id*=\"carousel\"]').each(function() { //The *= selector gets all the divs with an id that contains carousel anywhere in the id.\n var $this = $(this), //Here we select the right div\n id = $this.attr('id'); //And grab the id of the div\n\n $.ajax({\n url: 'json/' + id,\n //You don't need to set type: GET, the GET is the default.\n success: function(data) {\n //blah blah blah...\n $this.append(d); //Boom done!\n }\n });\n});\n</code></pre>\n\n<p>The way you have your <code>success</code> function set up, you're appending and changing the DOM each time that <code>for</code> loop goes around, and it goes around for <strong>every</strong> image. That's not good because DOM manipulations are quite expensive performance wise. So if you have 100 images, you're append one at a time - 100 times. The better way to do that would be do all your stuff and save to a variable, string, or object, then append <strong>once</strong> outside the loop.</p>\n\n<p>Here's an example of what I mean:</p>\n\n<pre><code>var totalPictures = data['totalPictures'],\n d = \"\"; //We add \"d\" outside\n\nfor (var i=0; i<totalPictures; i++) {\n if(i<1){\n d = \"<div class='item active'>\";\n d += \"<a href='\" +data.pictures[i]['photo'] +\"' rel='prettyPhoto'>\";\n d += \"<img src='\" +data.pictures[i]['photo'] +\"' >\";\n d += \"</a>\";\n d += \"</div>\";\n } else {\n d += \"<div class='item'>\"; //Added a += here so that it'll add onto the first picture\n d += \"<a href='\" +data.pictures[i]['photo'] +\"' rel='prettyPhoto'>\";\n d += \"<img src='\" +data.pictures[i]['photo'] +\"' alt=''>\";\n d += \"</a>\";\n d += \"</div>\";\n }\n}\n\n$('#carousel1b').append(d); //Here we append a single time outside the loop\n//This cuts our appends down from totalPictures to 1.\n//What may seem like a small change will make a huge difference\n\n$(\"a[rel^='prettyPhoto']\").prettyPhoto(); //I assume you'll need this outside since it depends on the appended content\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T01:23:03.757",
"Id": "45975",
"Score": "0",
"body": "Hey Jonny thanks for the help. One small \"bug\". $('#carousel1b').append(d); should be $('#' +id).append(d); otherwise it worked great. I'd upvote but I can't yet :\\"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T21:07:51.353",
"Id": "29151",
"ParentId": "29150",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29151",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T20:11:52.217",
"Id": "29150",
"Score": "2",
"Tags": [
"ajax",
"html5"
],
"Title": "Simplifying an ajax script in my HTML"
}
|
29150
|
<p>I have a rather simple task in trying to extract keywords from <code>input.dat</code> which looks like:</p>
<pre><code>func1
{
yes true;
keyword123 (1.1 0 -0.3);
gamma (0 1 0);
dir (1 0 0);
func2
{
yes false;
keyword123 (1.1 0 -0.3);
gamma (0 0 1);
dir (1 0 0);
</code></pre>
<p>In this case I want to get the first entry in the vector of <code>keyword123</code>. If the lines containing the keyword aren't identically, the script should stop with an error. I feel that this should be a one- or twoliner in PERL using RegEx but it took me some time to get the following script:</p>
<pre><code>#!/usr/bin/perl -w
use strict;
my $path = "./input.dat";
# array @grepped of lines containing keyword
my @grepped=();
open(FILE,"$path") or die "error on opening $path: $!\n";
while (my $line = <FILE>) {
if ($line=~ /keyword123/i){push(@grepped,"$line")};
}
close(FILE);
# get array @unique of unique lines
my %seen;
my @unique = grep {!$seen{$_}++} @grepped;
# continue with $unique if keyword-line is unique
my $unique;
if (scalar @unique eq 1) {
$unique=$unique[0];
} else {
die "entry not unique, exiting: $!\n";
}
# get string between brackets
$unique =~ /\((.+?)\)/;
my $final = $1;
# cut after first space
$final =~ s/\s.*//s;
print "keyword123: $final\n";
</code></pre>
<p>The script is giving the correct output but this can't be the best work, so any help/hint would be highly appreciated.</p>
|
[] |
[
{
"body": "<p>This is how I would implement it:</p>\n\n<pre><code>#!/usr/bin/perl\nuse warnings;\nuse strict; \n\nmy $file = 'input.dat';\nopen my $IN, '<', $file or die $!;\n\nmy $uniq;\nwhile (my $line = <$IN>) {\n next unless $line =~ /^\\s*keyword123/;\n if (defined $uniq and $line ne $uniq) {\n die \"Entry not unique. Exiting.\\n\";\n }\n $uniq = $line;\n}\n$uniq =~ s/.*\\((.*)\\).*/$1/;\n$uniq =~ s/\\s.*//;\nprint \"keyword123: $uniq\";\n</code></pre>\n\n<p>You can check the uniqueness each time you read the keyword line in. Once you find a non-unique line, you can stop right at the moment, no need to search the rest of the file.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T00:00:41.940",
"Id": "29155",
"ParentId": "29153",
"Score": "1"
}
},
{
"body": "<p>I beat it down to this (below). Since you didn't do anything with the other information you accumulated, I chose the early-out strategy. </p>\n\n<pre><code>my $k123;\nopen( my $fh, '<', './input.dat' ) or die \"error on opening $path: $!\\n\";\nwhile ( my $l = <$fh> ) {\n chomp $l;\n next unless $l =~ m/keyword123/i;\n $k123 //= $l;\n die \"Entry not unique!\" unless $k123 eq $l;\n}\nclose $fh;\nsay \"keyword123: \", ( $k123 =~ /\\(([^)]+)\\)/ );\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T12:52:17.863",
"Id": "29176",
"ParentId": "29153",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T23:47:21.210",
"Id": "29153",
"Score": "0",
"Tags": [
"regex",
"perl"
],
"Title": "Structured instructions for simple extraction script"
}
|
29153
|
<p>I'm doing this in Hadoop Java where I'm reading a String. The string is huge that has been tokenized and put in an array. It has key-value pairs but they are not in any order. I want this order to be rigid so I can load that as a table. So in SQL, if I select a column (after loading this in a table), all the keys of one type should be in colA.</p>
<p>I'm checking each word of the String array and copying them in a new string in a fixed position. The way I thought of doing this is using if else ladder like this:</p>
<pre><code>//row is the tokenized unordered String
String[] newRow = new String[150];
for (int i = 0; i < row.length; ++i) {
if(row[i].equals("token1")){
newRow[0] = row[i]; //key
newRow[1] = row[i+1];//value
}
else if(row[i].equals("token2")){
newRow[2] = row[i];
newRow[3] = row[i+1];
}//...and so on. Elseif ladder at least is at least 100 long.
</code></pre>
<p>I wanted to know if there is a more efficient way to do this?</p>
<p>PS: I'm not sorting the string. Example: <code>row1</code> String is {apple,good,banana,bad}, <code>row2</code> String is {banana,good,apple,bad} where <code>apple</code> and <code>banana</code> are keys. Now in my output I will have two records with say apple as the first key and then banana. So output will be : <code>newRow1</code>: {apple,good,banana,bad}, <code>newRow2</code>: {apple,bad,banana,good}. Essentially I'm rearranging all input to a fixed output.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T06:30:27.350",
"Id": "67669",
"Score": "0",
"body": "I notice that the indentation of your original post has been fixed manually; I have written a bookmarklet to do this automatically. Would you mind if I use the original version as a test sample? It would be part of a jsfiddle and linked from a CR post, but not part of any distributed code."
}
] |
[
{
"body": "<p>I'd put token names and positions in a <code>Map</code> like this:</p>\n\n<pre><code>Map<String, Integer> tokenIndexes = new HashMap<String, Integer>();\ntokenIndexes.put(\"token1\", 0);\ntokenIndexes.put(\"token2\", 2);\ntokenIndexes.put(\"token3\", 4);\n// ...\n</code></pre>\n\n<p>and then in the \"sorting\" part:</p>\n\n<pre><code>String[] newRow = new String[150];\n\nfor (int i = 0; i < row.length; i+=2) { // go two by two as you have keys in even indexes\n if(tokenIndexes.contains(row[i])) {\n int index = tokenIndexes.get(row[i]);\n newRow[index] = row[i];\n newRow[index + 1] = row[i + 1];\n } else {\n // handle missing token\n }\n}\n</code></pre>\n\n<p>This way I would get rid of all \"if-else\" statements, although now I have to maintain a <code>Map</code> (which I think is easier than maintaining a list of \"if-else\").</p>\n\n<p>UPDATE</p>\n\n<p>I'm supposing you just receive that String array and you're unable to change the way the information is retrieved. If you can change the initial array with a Map that would simplify your code even further.</p>\n\n<p>If that's the case then try this to capture your tokens instead of putting everything in an array (I'm supposing a key is the first token to appear):</p>\n\n<pre><code>Map<String, String> info = new HashTable<String, String>();\nboolean isKey = true;\nString lastKey = null;\nString token;\nwhile(tokensAvailable() /* or (token = readToken()) != null */) {\n token = readToken();\n if(isKey) {\n lastKey = token;\n } else {\n info.put(lastKey, token);\n }\n isKey = !isKey;\n}\n</code></pre>\n\n<p>And then when you have to print your table, you can do something like this:</p>\n\n<pre><code>printOut(\"VAL_1 -- VAL_2 -- VAL_3\");\nprintOut(String.format(\"%08d -- %10.2 -- %s\", info.get(\"numericVal1\"), info.get(\"monetaryVal2\"), info.get(\"val3\")));\n</code></pre>\n\n<p><code>String.format()</code> is useful in these cases, you can control the format (like the width) of how every field is printed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T01:12:54.557",
"Id": "45974",
"Score": "0",
"body": "I see... Let me try it.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T01:35:21.443",
"Id": "45976",
"Score": "0",
"body": "Just in case: remember that key's indexes must be even, odd positions are for values"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T02:09:58.483",
"Id": "45977",
"Score": "0",
"body": "Yes, I can change the initial array. So I'm loading it in 'row' in a nested loop using row.append()"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T02:47:36.647",
"Id": "45978",
"Score": "0",
"body": "Updated again, have a try."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T03:00:17.773",
"Id": "45980",
"Score": "0",
"body": "Okay. So I think I need the hard coded HashMap at the top for having a fixed position. I'm putting the key-values in another HashMap. So now instead of comparing the string array row with the position based HashMap, I'll compare the HashMap with the position based HashMap. That way, I still get the fixed order."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T04:07:25.853",
"Id": "45987",
"Score": "0",
"body": "After getting the string array,newRow[], I want to put delimiters between them. I can do 'printOut(newRow[0] + \" -- \" + newRow[1].......' but the problem is the string array is 150 in length. Is there a better way to do this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T04:11:28.277",
"Id": "45990",
"Score": "0",
"body": "Yes, use the static method of String: __String.format(\"format\", args)__, have a look at the [String javadoc](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html). The doc for the format strings can be found here: http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T04:20:19.387",
"Id": "45991",
"Score": "0",
"body": "I updated the answer to give you a hint of how to use String.format()"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T00:43:58.140",
"Id": "29156",
"ParentId": "29154",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "29156",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T23:56:21.573",
"Id": "29154",
"Score": "4",
"Tags": [
"java",
"algorithm",
"strings",
"hadoop"
],
"Title": "Efficient way to copy unordered String into ordered String"
}
|
29154
|
<p>I'd like to get some feedback on whether this is idiomatic elisp, whether it's any good, and any small modifications that would be useful. Thanks</p>
<pre><code>(defun jump-to-register-other-window (register-name)
"Open a register in the other window if file"
;; Should also display register contents if register is text
;; jump-to-register allows it to fail silently if non-legit
;; register is passed in
(interactive "cJump to register: \n")
(let ((cur-buff (buffer-name)))
(jump-to-register register-name)
(let ((register-buffer (buffer-name)))
(switch-to-buffer cur-buff)
(switch-to-buffer-other-window register-buffer))))
(global-set-key (kbd "C-x 4 j") 'jump-to-register-other-window)
</code></pre>
|
[] |
[
{
"body": "<p>The first things which jump into my face are the broken indentation and a dangling parenthesis. Please fix them, otherwise the code is not very readable.</p>\n\n<p>More to the point, I think it is better to replace the body with</p>\n\n<pre><code>(switch-to-buffer-other-window (register-buffer register-name))\n</code></pre>\n\n<p>and define</p>\n\n<pre><code>(defun register-buffer (register-name)\n (save-window-excursion \n (jump-to-register register-name)\n (current-buffer)))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T19:12:14.087",
"Id": "46170",
"Score": "0",
"body": "I fixed the indentation and dangling bracket (I think, perhaps I've missed something). Thanks for `save-excursion` - I think that's what I was looking for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T19:32:59.163",
"Id": "46176",
"Score": "0",
"body": "`save-excursion` does not restore the buffer to the window it was in though (from https://www.gnu.org/software/emacs/manual/html_node/elisp/Excursions.html)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T19:40:58.043",
"Id": "46177",
"Score": "1",
"body": "Edited to use `save-window-excursion` instead, thanks!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T04:59:47.487",
"Id": "29160",
"ParentId": "29157",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29160",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T00:54:49.347",
"Id": "29157",
"Score": "1",
"Tags": [
"lisp",
"elisp",
"emacs"
],
"Title": "A small emacs-lisp snippet for opening a register in another window"
}
|
29157
|
<p>I wanted to write the best implementation I could think of the following really, super simple and stupid <code>OOP</code> model in <code>php</code>.</p>
<p>
<pre><code>class Number {
private $number = false;
function __construct($n) {
if(is_int($n)) {
$this->number = $n;
}
}
public function get() {
return $this->number;
}
}
class Numbers {
public static function multiply(Number $a, Number $b) {
return ($a->get() * $b->get());
}
}
////
// Example
////
$first = new Number(45);
$second = new Number(80);
echo Numbers::multiply($first, $second);
</code></pre>
<p>Anything you guys would change? I was thinking of having <code>Numbers</code> extend <code>Number</code>, but really, the type of operations (functions) Numbers does do not need to extend the Number class. Is there a better object oriented pattern for this model?</p>
|
[] |
[
{
"body": "<p>Here's a few things that caught my eye:</p>\n\n<ul>\n<li>I'm assuming this is just a sketch of an unfinished class, or perhaps a learning excersize? As it stands, your class is unnecessary, and I would advise against using it. Since it just wraps a built in int, built in ints might as well be used. Various functionalities could indeed make it a useful class though (for example, arbitrary precision capabilities).</li>\n<li>If the constructor's argument can't be used, throw an exception. Objects should never exist in an incomplete or meaningless state. What does a false number mean? What does multiply($n1, $n2) mean if one of the numbers is false? Just throw an exception instead.</li>\n<li>I wouldn't bother having <code>Numbers</code> exist. Just have the operations be members of <code>Number</code>. Static methods tend to be regretted down the line. It's always better to have a non-static that could be static than to have a static that you later realize shouldn't be static. Also, having the method be internal to Number would be nice as it would allow you access to <code>Number</code>'s internals without having to expose them to the world.</li>\n<li><code>multiply</code> should return a <code>Number</code>, not an <code>int</code>. Why bother abstracting into an object if you're not going to stick with it?</li>\n<li>Name your argument to the constructor something meaningful. Rather than <code>$n</code> name it <code>$value</code> (or something along those lines).</li>\n<li>Consider expanding your number to handle more than <code>int</code>s. Using the BC Math or GMP extensions, you could write a class that handles arbitrary precision numbers very easily.\n<ul>\n<li>I would probably go with BCM just because it's more commonly available. It's statically linked on Windows and thus always enabled, whereas GMP is bundled in the binary archives, but not enabled by default. I'm not sure what the situation is on linux.</li>\n<li>Since BCM works with ASCII encoded base 10 numeric strings and GMP works with handles, GMP is probably more memory efficient. No idea about general performance though since I'm not very familiar with GMP or BCM's internals or features.</li>\n<li>I belive GMP is limited to integers whereas BC Math is not. That could be good or bad depending on the needs/expectations.</li>\n</ul></li>\n<li>You missed the <code>public</code> in front of your constructor.</li>\n<li>Depending on what you end up doing with the class, I probably wouldn't expose the internal representation. For example, if you ended up using GMP and wanted to switch to BMP, you couldn't if you had previously exposed the internals. Rather than expose them directly, I would implement methods like <code>toString</code>, <code>toInt</code>, <code>toFloat</code>, <code>toBinary</code>, etc. Those methods woud then either do the conversion if possible, or, if precision would be lost (like trying to convert a value to large for an int to an int), an exception would be thrown (or you could return <code>false</code> depending on how you expected to use the methods and if you consider a failure to convert a truly exceptional situation).</li>\n<li>As it is right now, Number is a misnomer. <code>5</code> and <code>5.0</code> are both numbers, but your class only supports <code>5</code>. I might rename it to <code>Integer</code> or something similar.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T12:24:06.220",
"Id": "46208",
"Score": "0",
"body": "+1 for covering everything and explaining"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T06:56:41.140",
"Id": "29164",
"ParentId": "29162",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T05:23:55.193",
"Id": "29162",
"Score": "1",
"Tags": [
"php",
"object-oriented"
],
"Title": "Review a simple PHP OOP model"
}
|
29162
|
<p>I am practising recursion and have written the small code for summing a+b as below:</p>
<pre><code>#include <stdio.h>
int b=6;
static int cnt;
void main(void)
{
int a=9,sum;
sum=succ(a);
printf("Sum returned : %d\n",sum);
}
int succ(x)
{
cnt++;
return(cnt<=b ? succ(x+1) : x++);
}
</code></pre>
<p>I am getting the results fine using this. Can anyone suggest optimization or better code for this? I also want to understand how stacking happens in this case for variables cnt and x. Are they stacking in pairs like 0-9, 1-10 ,2-11,3-12 ,4-13, then at last when cnt is 5 it return x from the post-increment return?</p>
|
[] |
[
{
"body": "<p>First of all, <code>main</code> should be declared <code>int main</code>.</p>\n\n<p>Second, I would advise passing the <code>cnt</code> (which I have called <code>iteration_number</code>) as a parameter as well. Also, you should avoid using a global (<code>b</code>). If you define a helper function, that won't change the signature of your function:</p>\n\n<pre><code>int add_helper(int value, int max, int iteration_number)\n{\n if (iteration_number >= max) return value;\n\n return add_helper(value + 1, max, iteration_number + 1);\n}\n\nint add(int a, int b)\n{\n add_helper(a, b, 0);\n}\n</code></pre>\n\n<p>Note that I have refactored your <code>b</code> to be a parameter, which I have called <code>max</code>. The function can be used like this:</p>\n\n<pre><code>int main(void)\n{\n int start = 9; // Your a\n int count = 6; // Your b\n\n int sum = succ(start, count);\n}\n</code></pre>\n\n<p>(If you are using C89 instead of C99 or C11, there should be a <code>return 0;</code> at the end of <code>main()</code>).</p>\n\n<hr>\n\n<p>However, the \"good\" way to define addition recursively is by increasing one number and decreasing the other:</p>\n\n<pre><code>int add(int a, int b)\n{\n if (b == 0) return a;\n\n return add(a + 1, b - 1);\n}\n</code></pre>\n\n<p>Modifying the function to work with negative numbers is left as an exercise to the reader. </p>\n\n<p>(<strong>Note:</strong> Normally you want to subtract from the lowest number and add to the largest. I left that out to keep the example compact.)</p>\n\n<hr>\n\n<blockquote>\n <p>I also want to understand how stacking happens in this case for variables cnt and x.</p>\n</blockquote>\n\n<p>By \"stacking\", I assume you mean how the variables are pushed onto the stack as the function is called. Your <code>cnt</code> has static linkage, and is not pushed onto the stack at all. In my example, <code>value</code>, <code>max</code> and <code>iteration_number</code> will be pushed onto the stack for each call. (Exactly how is, as far as I know, implementation defined and depends on the calling convention in use.) In other words, assuming no optimization, the arguments will take <code>iteration_number * sizeof(int)</code> bytes on the stack.</p>\n\n<p>If you want to keep track of the values, simply <a href=\"http://codepad.org/Rqfzo3CE\" rel=\"nofollow\">print them in the recursive function like this</a>:</p>\n\n<pre><code>int succ_helper(int value, int max, int iteration_number)\n{\n if (iteration_number >= max) return value;\n\n printf(\"%d: %d - %d\\n\", iteration_number, value, max);\n\n return succ_helper(value + 1, max, iteration_number + 1);\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>Can anyone suggest optimization or better code for this?</p>\n</blockquote>\n\n<pre><code>int sum = 9 + 6;\n</code></pre>\n\n<p>:-)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T09:26:04.160",
"Id": "29168",
"ParentId": "29166",
"Score": "4"
}
},
{
"body": "<blockquote>\n <p>\"I also want to understand how stacking happens in this case for\n variables cnt and x. Are they stacking in pairs like 0-9, 1-10\n ,2-11,3-12 ,4-13\"</p>\n</blockquote>\n\n<p>No, the value from <code>cnt</code> is not on the stack at all. It's global, so it will change along with the recursive execution.</p>\n\n<blockquote>\n <p>\"then at last when cnt is 5 it return x from the post-increment\n return?\"</p>\n</blockquote>\n\n<p>Well, yes it will return the value of <code>x</code>, but the post-increment is pointless as the variable is never used with the incremented value.</p>\n\n<p>By using global variables in the recursive code, it's not using recursion properly. It still works as long as you only have a single branch of recursion, but for a more complex task the branches would mess with each others values.</p>\n\n<p>To use recursion properly, you need to send all the data into the function that it needs:</p>\n\n<pre><code>void main(void) {\n int a = 9, sum, b = 6;\n\n sum = succ(a, b, 0);\n\n printf(\"Sum returned : %d\\n\",sum);\n}\n\nint succ(int x, int y, int cnt) {\n return cnt < y ? succ(x + 1, y, cnt + 1) : x;\n}\n</code></pre>\n\n<p>However, this is not really a good example of how recursion works. Normally a recursive function would divide the work into smaller parts that would each be executed recursively, instead of shaving off a single piece of work and do the rest of the work recursively. A recursive algorithm shouldn't go deeper than perhaps 10 or 20 levels. When you use recursion to just do looping, as in the example, it's inefficient and you will easily run into a stack overflow for larger values.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T10:34:58.083",
"Id": "46009",
"Score": "1",
"body": "`cnt` is guaranteed to be zero-initialized before `main` is executed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T10:47:01.120",
"Id": "46010",
"Score": "0",
"body": "Yes cnt will always be zero as its defined static."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T11:05:56.673",
"Id": "46012",
"Score": "0",
"body": "See [this stackoverflow answer about static variables](http://stackoverflow.com/a/3373159/2235567)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T14:22:09.457",
"Id": "46041",
"Score": "0",
"body": "@Lstor: Ok, I removed that part of the answer, as it's not important anyway as the variable shouldn't be static in the first place."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T10:21:26.943",
"Id": "29170",
"ParentId": "29166",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29168",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T08:48:58.440",
"Id": "29166",
"Score": "4",
"Tags": [
"c",
"recursion"
],
"Title": "Recursive a+b function"
}
|
29166
|
<p>I had made some pages and they work but I'm not sure if I coded it in best way so I want your suggestions and ideas to make my code better.</p>
<p><code>connection.php</code></p>
<pre><code> <?php
$mysql_host = 'localhost';
$mysql_user = 'root';
$mysql_pass = 'root';
$mysql_data = 'project_eye';
$connect = mysql_connect($mysql_host, $mysql_user, $mysql_pass) or mysql_error();
$db_sele = mysql_select_db($mysql_data);
mysql_query("set names 'utf8'");
mysql_query("SET character_set_client=utf8");
mysql_query("SET character_set_connection=utf8");
mysql_query("SET character_set_database=utf8");
mysql_query("SET character_set_results=utf8");
mysql_query("SET character_set_server=utf8");
?>
</code></pre>
<p><code>phpCodes.php</code>:<br>
It's a page that contain the header. I'm using it to call the function to my page.</p>
<pre><code><?php
function headerCode(){
echo '
<div class="header">
<div class="header-top">
<div class="logform">
';
accountLinks();
echo '
</div>
<div class="social-newtork">
<a><img src="images/f.png"></a>
<a><img src="images/t.png"></a>
<a><img src="images/g.png"></a>
</div>
</div>
<div class="menu-content">
<img src="images/eye.jpg">
<img src="images/compelete.jpg" style="width: 78.3%">
<div class="desc">
<span class="first">عينٌـــــــــ</span>
<span class="second">على الحقيقة</span>
</div>
</div>
<div class="menu">
<ul>
<li><a href="">محلية</a></li>
<li><a href="">عالمية</a></li>
<li><a href="">رياضية</a></li>
<li><a href="">طبية</a></li>
<li><a href="">طرائف</a></li>
</ul>
</div>
</div>
';
}
function accountLinks(){
if( !isset($_SESSION['id']) ){
echo '
<form method="post" action="index.php">
<input type="submit" name="submit" value="دخول" class="log">
<input type="password" id="password" name="password" placeholder="كلمة المرور" class="mem-information">
<input type="text" placeholder="اسم المستخدم" id="username" name="username" class="mem-information">
</form> ';
}else{
echo '
<form method="post" action="index.php">
<a href="controlpanel/" class="account">لوحة التحكم</a>
<input type="submit" href="" class="logout" name="logout" onclick="logout(this);" value="تسجيل الخروح">
</form>
';
}
}
?>
</code></pre>
<p><code>con.php</code>:<br>
This page contains simple control panel and it didn't complete yet</p>
<pre><code><?php
ob_start();
session_start();
include('../includes/connect.php');
include('../includes/phpCodes.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>لوحة التحكم</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="../css/mainstyle.css">
<link rel="stylesheet" type="text/css" href="css/controlstyle.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#tabs div').hide();
$('#tabs div:first').show();
$('#tabs ul li:first').addClass('active');
$('#tabs ul li a').click(function(){
$('#tabs ul li').removeClass('active');
$(this).parent().addClass('active');
var currentTab = $(this).attr('href');
$('#tabs div').hide();
$(currentTab).show();
return false;
});
});
</script>
</head>
<body>
<div class="wrapper">
<?php headerCode(); ?>
<div class="content">
<div id="tabs">
<ul>
<li><a href="#add">اضافة موضوع</a></li>
<li><a href="#remove">حذف موضوع</a></li>
<li><a href="#edit">تعديل موضوع</a></li>
<li><a href="#edit">التحكم بالاقسام</a></li>
</ul>
<div id="add">
<form method="POST" action="includes/add.php" dir="rtl" enctype="multipart/form-data">
<br>
حدد القسم : <select name="section">
<?php
$query = "SELECT * FROM `sections`";
$result = mysql_query($query);
while($row=mysql_fetch_array($result, MYSQL_ASSOC)){
echo "<option value='".$row['id']."'>".$row['sectionName']."</option>";
}
?>
</select><br>
عنوان الموضوع :<input type="text" name="title" class="mem-information"/><br>
الموضوع : <br /><textarea name="subject" rows="10" cols="50" class="mem-information" style="width: 500px"></textarea><br /><br>
الصورة :<input type="file" name="image"><br>
<input type="submit" value="إرسال" name="send" class="log" style="color: black">
</form>
</div>
<div id="remove">
<form method="POST" action="includes/remove.php" dir="rtl"><br>
حدد القسم :
<select name ="sectionsName">
<option value="">dd</option>
</select>
<input type="submit" value="حذف" name="send" class="log" style="color: black">
</form>
</div>
<div id="edit">
</div>
<div id="addDep">
</div>
</div>
</div>
</div>
</body>
</html>
</code></pre>
<p><code>add.php</code>:<br>
It's job is to add values to database.</p>
<pre><code><?php
session_start();
include('../../includes/connect.php');
$sectionID = $POST["section"];
$title = $_POST['title'];
$subject = $_POST['subject'];
$visiable = 1;
$imageName = mysql_real_escape_string($_FILES["image"]["name"]);
$imageData = mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["image"]["type"]);
$query = "insert into news (title, subject, visiable, image, section_id) values ('$title','$subject', '$visiable', '$imageData', '$sectionID')";
$result = mysql_query($query);
$id = mysql_insert_id();
$data = array(
'id' => $id
);
$base = '../../show.php';
$url = $base. '?' . http_build_query($data);
header("Location: $url");
exit();
?>
</code></pre>
<p><code>show.php</code>:<br>
After adding to database this page will display the values.</p>
<pre><code><?php
ob_start();
session_start();
include('includes/connect.php');
include('includes/phpCodes.php');
function showNews(){
$id = $_GET['id'];
echo '<img src="includes/getImage.php?id=' . $id . '" class="newsImage">';
echo '
<h1><p class="subjecTitle">هنا العنوان</p></h1>
<div class="newsContent">
hihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihi
</div>
';
}
?>
<!DOCTYPE html>
<html>
<head>
<title>عينٌ على الحقيقة</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/mainstyle.css">
<link rel="stylesheet" type="text/css" href="css/showstyle.css">
<script lang="javascript">
function logout(myFrame){
myFram.submit();
}
</script>
</head>
<body>
<div class="wrapper">
<?php headerCode(); ?>
<div class="content" dir="rtl">
<?php showNews(); ?>
</div>
</div>
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T08:49:40.280",
"Id": "46003",
"Score": "5",
"body": "First of all start using mysqli_* or PDO functions to wrok with database. Mysql_* functions are depracted as of PHP 5.5 and will be removed soon"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T14:28:33.713",
"Id": "46045",
"Score": "2",
"body": "Guiding you towards the _\"perfect\"_ counterpart of this code will take some time, why don't you take yourself from the South-pole to the equater, so we can meet each other half way? because (respectfuly) this code is waaaay off. Oh and BTW: google: TMTOWTDI <= this means that _\"the perfect code\"_ doesn't really exist, it all depends on what you need, and where"
}
] |
[
{
"body": "<p>Ok, where to start.</p>\n\n<p>mysql_* functions are bad. Burn them, throw them away but don't use them. Use mysqli_ instead or even better PDO.</p>\n\n<p>Ever heard of SQL injections? I think so since you are using <code>mysql_real_escape_string</code>. A simple search on the interwebz for <code>how to bypass mysql_real_escape_string</code> shows its weaknesses.</p>\n\n<p>That being said, let's look at your code.</p>\n\n<p>The mysql_* left aside your code isn't bad at all. Everything works and at the end of the day that is all that matter. But after that day come other days. And in 2 month times you might need to change certain parts in your code, fix a bug, add some functionality,...</p>\n\n<p>With that in our minds lets look at the code:</p>\n\n<p>There is no real seperation of concern. Every file has multiple functionalities and knows way to much.</p>\n\n<ul>\n<li><strong>connection.php</strong> only handles the database connection. So this is good!</li>\n<li><strong>phpCodes.php</strong> supplies functions that handle presentation (I'll come to this later)</li>\n<li><strong>con.php</strong> handles presentation, sql queries, sessions and buffering</li>\n<li><strong>add.php</strong> knows about sessions AND how to add an Image.</li>\n<li><strong>show.php</strong> knows about session, buffers, other functional files AND it knows about presentation. Now that is a lot for a simple file.</li>\n</ul>\n\n<p>I don't think I need to tell you what is wrong ;)</p>\n\n<p>One of the important programming rules (imo) is DRY, Don't repeat yourself.\nYet somehow you repeat the HTML in 2 files. So if you want to make a change to the html you will have to check all files that have html and change it there. So make sure that you don't write duplicate code. Not for 'increased performace' because of a smaller filesize but because it is way easier to maintain.</p>\n\n<p>So, a little todo list for you:\nSeperate business logic from presentation. In your presentation files there sould only be html with some <code>echo $someVar</code> statements. In your business logic there should be no html and plain stupid code. Code that does the job without having to know about other parts of the system.</p>\n\n<p>Then create a 'controller' file that includes the correct files, starts the session and the buffer, ...</p>\n\n<p>This way you can easily add functionality, change presentation, ...</p>\n\n<p>Always think <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\" rel=\"nofollow\">SOLID</a></p>\n\n<p>One last remark on the <strong>phpCodes.php</strong>. Don't use functions to output html. Functions should give some sort of functionality. You give it something and it does something to that thing. But you are simply using it as a glorified variable holding some HTML.</p>\n\n<p>A part from that a function should best be stateless. But your function returns different things depending on a variable that doesn't even get passed in.</p>\n\n<p>If a function changes its output depending on a variable, that variable should be passed in into the function. Not hard coded in it. If the sole purpose of the function is to return html. Don't use a function, simply include the correct template in the controller.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T12:48:39.250",
"Id": "29265",
"ParentId": "29167",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "29265",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T08:48:16.907",
"Id": "29167",
"Score": "1",
"Tags": [
"php",
"mysql"
],
"Title": "Basic news/blog post system"
}
|
29167
|
<p>I have the following condition statement in Groovy:</p>
<pre><code>if ( condition_1 ) {
//some actions
} else if ( condition_2 ) {
//some another actions
} else {
assert false, 'Assertion description'
}
</code></pre>
<p>Code Narc gives me a warning about using boolean <code>false</code> constant in the assertion. I'm not sure if it is real issue, so please share your thoughts about it.</p>
<p>I thought about using exceptions in this code instead of <code>assert false</code> but it looks too heavy (exception handling is too heavy I think) for my particular case.</p>
|
[] |
[
{
"body": "<p>Throwing an assert error is probably heavier than throwing an Exception (as Groovy will parse the assert inputs to give you a pretty output string)</p>\n\n<p>And unless you are going to be running this hundreds of times per second, I wouldn't worry about it either way...</p>\n\n<p>A way of using assert that gets round the warning (and provides a nice error message) might be to do:</p>\n\n<pre><code>assert condition_1 || condition_2, 'Expected at least condition_1 or condition_2 to be true'\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T11:15:11.037",
"Id": "46013",
"Score": "0",
"body": "Good! It is exactly what I want! Probably `condition_1 && condition_2` should be `condition_1 || condition_2`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T11:18:12.697",
"Id": "46014",
"Score": "0",
"body": "Whoops...yeah, updated :-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T11:11:40.423",
"Id": "29173",
"ParentId": "29171",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29173",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T10:22:59.430",
"Id": "29171",
"Score": "1",
"Tags": [
"groovy",
"constants"
],
"Title": "Boolean constant for assert in if..else block"
}
|
29171
|
<p>I am trying to download files using jsp but then downloaded files are not readable.
Suppose if i download pdf files then it can not opened,if i download jpg files then it can not opened and similarily for the video files too.</p>
<p>Please point out the mistakes where i have made</p>
<pre><code> <%@ page import = "java.sql.*"%>
<%@ page import = "java.util.*" %>
<%@ page import= "java.io.*" %>
<%
try{
String txtFileNameVariable="movie.mp4";
String locationVariable="../webapps/y/";
String PathVariable="";
//txtFileNameVariable = request.getParameter("fileVariable");
//locationVariable = request.getParameter("locationVariable");
PathVariable = locationVariable+txtFileNameVariable;
BufferedReader bufferedReader = null;
try{
bufferedReader = new BufferedReader(new FileReader(PathVariable));
}
catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}
File f=new File(locationVariable, txtFileNameVariable);
String fileType = txtFileNameVariable.substring(txtFileNameVariable.indexOf(".")+1,txtFileNameVariable.length());
if (fileType.trim().equalsIgnoreCase("txt")) {
response.setContentType( "text/plain" );
} else if (fileType.trim().equalsIgnoreCase("doc")) {
response.setContentType( "application/msword" );
} else if (fileType.trim().equalsIgnoreCase("xls")) {
response.setContentType( "application/vnd.ms-excel" );
} else if (fileType.trim().equalsIgnoreCase("pdf")) {
response.setContentType( "application/pdf" );
} else {
response.setContentType( "application/octet-stream" );
}
String original_filename = txtFileNameVariable;
response.setHeader( "Content-Disposition", "attachment; filename=\"" + original_filename + "\"" );
try{
int anInt=0;
while((anInt=bufferedReader.read())!=-1)
out.write(anInt);
}catch(IOException ioe){
ioe.printStackTrace();
}
}catch(Exception e){
out.println("This is the Error " +e.getMessage());
}
%>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T12:08:42.730",
"Id": "46019",
"Score": "4",
"body": "Locate the errors yourself, then report them on Stack Overflow. We (and them) don't serve as a compiler."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T12:12:36.980",
"Id": "46021",
"Score": "0",
"body": "One think I can say [don't use Java code in JSP](http://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T12:16:58.483",
"Id": "46022",
"Score": "0",
"body": "@Jamal i have already compiled"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T12:19:49.850",
"Id": "46023",
"Score": "0",
"body": "@javaprogrammer: Okay, but it still belongs on SO since the code is not working. If you have specific errors, then those should be mentioned to better assist you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T12:21:22.453",
"Id": "46024",
"Score": "0",
"body": "@Jamal no compile time error,no runtime error,no errors at all just the file is not readable"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T12:26:01.560",
"Id": "46025",
"Score": "0",
"body": "@javaprogrammer: That's fine, then. Just be aware that they may not be so willing to just search your code for the error."
}
] |
[
{
"body": "<p>Some observations:</p>\n\n<ul>\n<li><p>Don't use <code>FileReader</code>, that's meant to be used for char streams, where undesireable transformations could happen due to default charsets and the like. Binary streams are the correct choice for your case.</p></li>\n<li><p>Your first try-catch sentence doesn't handle the error apropriately, you only print the stacktrace, but your code will probably throw a NullPointerException at the first reference to bufferedReader.</p></li>\n<li><p>Maybe this is a simplified version of your JSP, but just in case: have you noticed that you are not validating the user input? (I guess you get the filename from a request parameter, as you have commented a line where the filename is taken from the request) what if, say, you receive something like \"../../../etc/passwd\"? this is a security issue.</p></li>\n<li><p>Scriptlets are deprecated, consider using JSTL tags or custom ones.</p></li>\n<li><p>You are opening a stream (bufferedReader) but you never close it.</p></li>\n</ul>\n\n<p>Anyway, this is a version of your JSP using <code>InputStream</code> instead of <code>Reader</code>, I haven't fixed the other issues I mentioned (that is your task):</p>\n\n<pre><code><%@ page import = \"java.sql.*\"%>\n<%@ page import = \"java.util.*\" %>\n<%@ page import= \"java.io.*\" %>\n<%\ntry{\n String txtFileNameVariable=\"movie.mp4\";\n String locationVariable=\"../webapps/y/\";\n String PathVariable=\"\";\n //txtFileNameVariable = request.getParameter(\"fileVariable\");\n //locationVariable = request.getParameter(\"locationVariable\");\n PathVariable = locationVariable+txtFileNameVariable;\n BufferedInputStream bufferedInputStream = null;\n try{\n bufferedInputStream = new BufferedInputStream(new FileinputStream(PathVariable));\n }\n catch(FileNotFoundException fnfe){\n fnfe.printStackTrace();\n }\n File f=new File(locationVariable, txtFileNameVariable);\n String fileType = txtFileNameVariable.substring(txtFileNameVariable.indexOf(\".\")+1,txtFileNameVariable.length());\n if (fileType.trim().equalsIgnoreCase(\"txt\")) {\n response.setContentType( \"text/plain\" );\n } else if (fileType.trim().equalsIgnoreCase(\"doc\")) {\n response.setContentType( \"application/msword\" );\n } else if (fileType.trim().equalsIgnoreCase(\"xls\")) {\n response.setContentType( \"application/vnd.ms-excel\" );\n } else if (fileType.trim().equalsIgnoreCase(\"pdf\")) {\n response.setContentType( \"application/pdf\" );\n } else {\n response.setContentType( \"application/octet-stream\" );\n }\n String original_filename = txtFileNameVariable;\n response.setHeader( \"Content-Disposition\", \"attachment; filename=\\\"\" + original_filename + \"\\\"\" );\n try{\n int anInt=0;\n OutputStream output = response.getOutputStream();\n while((anInt=bufferedInputStream.read())!=-1)\n output.write(anInt);\n output.flush();\n } catch(IOException ioe) {\n ioe.printStackTrace();\n }\n} catch(Exception e) {\n out.println(\"This is the Error \" +e.getMessage());\n}\n\n%>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T12:34:24.813",
"Id": "46026",
"Score": "0",
"body": ",i do not find any errors either compile time or runtime."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T12:36:25.383",
"Id": "46027",
"Score": "0",
"body": "@javaprogrammer Sorry, I didn't understand your comment"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T12:42:56.363",
"Id": "46029",
"Score": "0",
"body": "i dont have any errors while compiling or running. Just the downloaded files are not readable"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T12:46:41.340",
"Id": "46030",
"Score": "0",
"body": "No one is saying that you have compilation errors, I just reviewed your code and commented my observations (and BTW fixed your original problem)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T12:49:16.337",
"Id": "46031",
"Score": "2",
"body": "... and the fact that you have no compilation problems doesn't mean that your code doesn't have issues."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T04:43:09.587",
"Id": "46101",
"Score": "0",
"body": "i dont think your answer is useful"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T12:26:51.460",
"Id": "29175",
"ParentId": "29174",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29175",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T11:44:55.140",
"Id": "29174",
"Score": "-2",
"Tags": [
"java",
"servlets",
"file",
"jsp"
],
"Title": "file downloading using jsp but not readable"
}
|
29174
|
<p>I am trying to write up a pixel interpolation (binning?) algorithm (I want to, for example, take four pixels and take their average and produce that average as a new pixel). I've had success with stride tricks to speed up the "partitioning" process, but the actual calculation is really slow. For a 256x512 16-bit grayscale image I get the averaging code to take 7s on my machine. I have to process from 2k to 20k images depending on the data set. The purpose is to make the image less noisy (I have used median filter and various other in-built filters, but it was suggested that I should try pixel binning also).</p>
<pre><code>import numpy as np
from numpy.lib.stride_tricks import as_strided
from scipy.misc import imread
import matplotlib.pyplot as pl
import time
def sliding_window(arr, footprint):
""" Construct a sliding window view of the array"""
t0 = time.time()
arr = np.asarray(arr)
footprint = int(footprint)
if arr.ndim != 2:
raise ValueError("need 2-D input")
if not (footprint > 0):
raise ValueError("need a positive window size")
shape = (arr.shape[0] - footprint + 1,
arr.shape[1] - footprint + 1, footprint, footprint)
if shape[0] <= 0:
shape = (1, shape[1], arr.shape[0], shape[3])
if shape[1] <= 0:
shape = (shape[0], 1, shape[2], arr.shape[1])
strides = (arr.shape[1]*arr.itemsize, arr.itemsize,
arr.shape[1]*arr.itemsize, arr.itemsize)
t1 = time.time()
total = t1-t0
print "strides"
print total
return as_strided(arr, shape=shape, strides=strides)
def binning(w,footprint):
#the averaging block
#prelocate memory
binned = np.zeros(w.shape[0]*w.shape[1]).reshape(w.shape[0],w.shape[1])
#print w
t2 = time.time()
for i in xrange(w.shape[0]):
for j in xrange(w.shape[1]):
binned[i,j] = w[i,j].sum()/(footprint*footprint + 0.0)
t3 = time.time()
tot = t3-t2
print tot
return binned
Output:
5.60283660889e-05
7.00565886497
</code></pre>
<p>Is there some built-in/optimized function that would to the same thing I want, or should I just try and make a C extension (or even something else)?</p>
<p>Here is the additional part of the code just for completeness, since I think the functions are the most important here. Image plotting is slow, but I think there is a way to improve it <a href="https://stackoverflow.com/questions/8955869/why-is-plotting-with-matplotlib-so-slow">for example here</a>.</p>
<pre><code>for i in range(2000):
arr = imread("./png/frame_" + str("%05d" % (i + 1) ) + ".png").astype(np.float64)
w = sliding_window(arr,footprint)
binned = binning(w,footprint)
pl.imshow(binned,interpolation = "nearest")
pl.gray()
pl.savefig("binned_" + str(i) + ".png")
</code></pre>
<p>What I am looking for could be called interpolation. I just used the term the person who advised me to do this used. Probably that is the reason why I was finding histogram related stuff!</p>
<p>Apart from the <code>median_filter</code>, I tried <code>generic_filter</code> from scipy.ndimage but those did not give me the results I wanted (they had no "valid" mode).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T13:49:30.533",
"Id": "46037",
"Score": "0",
"body": "Are you sure that what you are doing is binning? Sounds more like interpolation to me. In any case, ``numpy`` and ``scipy`` have both binning and interpolation functions of different kinds, have you tried them?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T14:40:30.100",
"Id": "46048",
"Score": "0",
"body": "I should probably post this to stack overflow then ? Since this is now probably a \"which function\" question...Thanks anyway!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T18:16:05.300",
"Id": "46067",
"Score": "0",
"body": "OK, it's official - I am an idiot, the solution was stuff I used a couple of weeks ago.\n\nAll I needed was a simple scipy.signal.convolve function, with the 2x2 kernel, mode = \"valid\" and the result divided by 4...(Or fft convolve for speed, but there could be problems with zero padding, not sure yet).\n\nAnd from whay I have read - median filter should always win, but it is something particular I want to test.\n\nThanks for your help guys!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T13:24:55.880",
"Id": "29178",
"Score": "1",
"Tags": [
"python"
],
"Title": "Pixel interpolation (binning?) algorithm"
}
|
29178
|
<p>I want to use the enum on the client for a dropdown list. Does this make sense, or is there a smarter way of doing this?</p>
<pre><code>public class clientEnum
{
public string Value { get;set;}
public int Key { get; set; }
}
public static List<clientEnum> EnumToclientEnum <T>(T enumType) where T : Type
{
List<clientEnum> list = new List<clientEnum>();
foreach (var value in Enum.GetValues(enumType))
{
var name = value.ToString();
var number = (byte)Enum.Parse(enumType, name);
list.Add(new clientEnum { Key = (int)number, Value = value.ToString() });
}
return list;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T13:21:42.997",
"Id": "46263",
"Score": "0",
"body": "I assume localization is no problem for this application?"
}
] |
[
{
"body": "<p>Your code won't work, I get an error at following line:</p>\n\n<pre><code>var number = (byte)Enum.Parse(enumType, name);\n</code></pre>\n\n<p>This is the error:</p>\n\n<blockquote>\n <p>InvalidCastException: Specified cast is not valid.</p>\n</blockquote>\n\n<p>You should leave the cast to a byte away. I'm no expert at enumerations so I went looking on the internet a bit and I think I found a solution. Also, I replaced the second <code>value.ToString()</code> with <code>name</code> when adding it to the list. No need for doing the same things twice.</p>\n\n<pre><code>public static List<clientEnum> EnumToclientEnum <T>(T enumType) where T : Type\n{\n List<clientEnum> list = new List<clientEnum>();\n\n foreach (var value in Enum.GetValues(enumType))\n {\n var name = value.ToString(); \n var number = Enum.Parse(enumType, name);\n list.Add(new clientEnum { Key = (int)number, Value = name });\n }\n return list;\n}\n</code></pre>\n\n<p>Taking things a bit further I'd make the method an <code>IEnumerable<T></code> using <a href=\"http://msdn.microsoft.com/en-us/library/vstudio/9k7k7cf0.aspx\" rel=\"nofollow\"><strong><em>yield return ...</em></strong></a> and when needed you can convert it to a <code>List<T></code> when needed. Here, I left out putting the number in a variable as it used only once.</p>\n\n<pre><code>public static IEnumerable<clientEnum> EnumToclientEnum <T>(T enumType) where T : Type\n{\n foreach (var value in Enum.GetValues(enumType))\n {\n var name = value.ToString(); \n yield return new clientEnum { Key = (int)Enum.Parse(enumType, name), Value = name };\n }\n}\n</code></pre>\n\n<p>And if you care for short code:</p>\n\n<pre><code>public static IEnumerable<clientEnum> EnumToclientEnumShort <T>(T enumType) where T : Type\n{\n foreach (var value in Enum.GetValues(enumType))\n yield return new clientEnum { Key = (int)Enum.Parse(enumType, value.ToString()), Value = value.ToString() };\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>public enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }\nvar result = EnumToclientEnum(typeof(Days)); //IEnumerable\nvar listified = result.ToList(); //List\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T00:27:20.473",
"Id": "46092",
"Score": "0",
"body": "the underlying type for the enum i am using is a byte not an int. i guess checking for underlying type will make this better. thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T08:03:11.640",
"Id": "46109",
"Score": "0",
"body": "Ok didn't know that :) But the rest of the code might still be of help. ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T14:18:53.543",
"Id": "29181",
"ParentId": "29179",
"Score": "1"
}
},
{
"body": "<p>If you are open to use a framework you can use <a href=\"http://james.newtonking.com/projects/json-net.aspx\" rel=\"nofollow\">json.net</a> and use the StringEnumConverter Class.</p>\n\n<p>Or you could manually create it like this too.</p>\n\n<pre><code>string.Join(\", \", Enum.GetNames(typeof(Days )).ToList().ConvertAll(key =>\n{\n return string.Format(\"{0}: {1}\", key, (int)((Days )Enum.Parse(typeof(Days ), key)));\n}).ToArray()));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T14:50:15.580",
"Id": "29182",
"ParentId": "29179",
"Score": "1"
}
},
{
"body": "<p>Yes, use linq extensions:</p>\n\n<pre><code>public static List<clientEnum> EnumToclientEnum<T>()\n{\n var type = typeof(T);\n if (!type.IsEnum) throw new NotSupportedException();\n return Enum.GetValues(type).Select(x => new clientEnum { Key = (int)x, Value = x.ToString() }).ToList();\n}\n</code></pre>\n\n<p>In your original code (as well as in Abbas's answer) enum value is being converted to string and then this string is parsed back to get the value. That makes no sense.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T13:28:04.100",
"Id": "29222",
"ParentId": "29179",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "29181",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T13:50:27.517",
"Id": "29179",
"Score": "2",
"Tags": [
"c#",
"json",
"enum",
"converting"
],
"Title": "Converting a c# enum into a list to be sent to the client"
}
|
29179
|
<p>This question has become long after many updates. <a href="https://codereview.stackexchange.com/questions/29183/review-implementation-of-stack-by-using-array-in-c#comment46116_29183">Click here</a> to go down.
<hr>
I have implemented stack using arrays in C. Please give me suggestions on how to improve it. The purpose of writing it is practice-only.</p>
<p>I'll be implementing it by using pointers soon so please leave the part about using pointers instead of arrays for implementing stack.</p>
<p><strong>I'll keep adding updated code so please review the latest one.</strong></p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
#define MAX_SIZE 100
#define MIN 1
#define MAX 3
void intro();
void push(int *arr, int *length, int data);
int pop(int* arr, int *length);
int main()
{
int arr[MAX_SIZE];
int length = 0;
int choice = MAX + 1;
int data;
while (1)
{
while (MAX < choice || choice < MIN)
{
system("cls");
intro();
printf("Enter your choice -> ");
scanf("%d", &choice);
}
system("cls");
switch (choice)
{
case 1:
printf("\nEnter data to be pushed -> ");
scanf("%d", &data);
push(arr, &length, data);
printf("\nData pushed");
break;
case 2:
printf("\nPopped Data is %d", pop(arr, &length));
break;
case 3:
return 0;
}
printf("\nLength is %d", length);
getchar();
getchar();
choice = MAX + 1;
}
}
void intro()
{
printf("1 Push data\n");
printf("2 Pop Data\n");
printf("3 Exit this program\n\n");
}
void push(int *arr, int *length, int data)
{
if (*length == MAX_SIZE){
printf("Stack Overflow\n");
exit(1);
}
arr[(*length)++] = data;
}
int pop(int *arr, int *length)
{
if (*length == 0){
printf("Stack Underflow\n");
exit(2);
}
return arr[--(*length)];
}
</code></pre>
<p><strong>Update 1 after Lstor gave suggestions</strong></p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
static const int MAX_SIZE = 100;
static const int MIN = 1;
static const int MAX = 4;
void intro();
void push(int *, int *, int);
int pop(int *, int *);
int top(int *, int *);
int main()
{
int arr[MAX_SIZE];
int length = 0;
for (;;)
{
int choice = MAX + 1;
while (MAX < choice || choice < MIN)
{
system("cls");
intro();
printf("Enter your choice -> ");
scanf("%d", &choice);
}
system("cls");
int data;
errno = 0;
switch (choice)
{
case 1:
printf("\nEnter data to be pushed -> ");
scanf("%d", &data);
push(arr, &length, data);
if (errno == 1){
printf("\nStack overflow");
}
break;
case 2:
data = pop(arr, &length);
if (errno == 2){
printf("\nStack underflow");
}
else{
printf("\nThe data is %d", data);
}
break;
case 3:
data = top(arr, &length);
if (errno == 1){
printf("\nStack overflow");
}
else if (errno == 2){
printf("\nStack underflow");
}
else{
printf("\nThe data at top is %d", data);
}
break;
case 4:
return 0;
}
printf("\nLength is %d", length);
getchar();
getchar();
}
}
void intro()
{
printf("1 Push data\n");
printf("2 Pop Data\n");
printf("3 See the top of the stack\n");
printf("4 Exit this program\n\n");
}
void push(int *arr, int *length, int data)
{
if (*length == MAX_SIZE){
errno = 1;
return;
}
arr[(*length)++] = data;
}
int pop(int *arr, int *length)
{
if (*length == 0){
errno = 2;
return -1;
}
return arr[--(*length)];
}
int top(int *arr, int *length)
{
if (*length == 0){
errno = 2;
return -1;
}
else if (*length == MAX_SIZE){
errno = 1;
return -1;
}
return arr[*length - 1];
}
</code></pre>
<p><strong>Update 2</strong> - Includes the suggestions by Lstor given in comments and William Morris's suggestions. I changed a few things and didn't implement William Morris's suggestion about user experience.</p>
<pre><code>#include<assert.h>
#include<errno.h>
#include<stdio.h>
#include<stdlib.h>
static const int MAX_SIZE = 100;
enum action {PUSH = 1, POP, TOP, QUIT};
void clear_screen(void)
{
system("cls");
}
static enum action get_user_action(void)
{
int choice = 0;
do
{
clear_screen();
printf("%d Push data\n"
"%d Pop Data\n"
"%d See the top of the stack\n"
"%d Exit\n\n"
"Enter your choice -> ", PUSH, POP, TOP, QUIT);
scanf("%d", &choice);
} while (choice != PUSH && choice != POP && choice != TOP && choice != QUIT);
return (enum action) choice;
}
void push(int *arr, int *length, int data)
{
if (*length == MAX_SIZE){
errno = PUSH;
return;
}
arr[(*length)++] = data;
}
int pop(int *arr, int *length)
{
if (*length == 0){
errno = POP;
return -1;
}
return arr[--(*length)];
}
int top(int *arr, int *length)
{
if (*length == 0){
errno = POP;
return -1;
}
else if (*length == MAX_SIZE){
errno = PUSH;
return -1;
}
return arr[*length - 1];
}
int main(void)
{
int arr[MAX_SIZE];
int length = 0;
enum action choice;
while ((choice = get_user_action()) != QUIT)
{
clear_screen();
int data;
errno = 0;
switch (choice)
{
case PUSH:
printf("Enter data to be pushed -> ");
scanf("%d", &data);
push(arr, &length, data);
if (errno == PUSH){
printf("Stack overflow\n");
}
break;
case POP:
data = pop(arr, &length);
if (errno == POP){
printf("Stack underflow\n");
}
else{
printf("The data is %d\n", data);
}
break;
case TOP:
data = top(arr, &length);
switch (errno)
{
case PUSH:
printf("Stack overflow\n");
break;
case POP:
printf("Stack underflow\n");
break;
default:
printf("The data at top is %d\n", data);
}
break;
default:
assert(!"You should not have reached this.");
}
printf("Length is %d\n", length);
getchar();
getchar();
}
}
</code></pre>
<p><strong>Update 3</strong> Includes William Morris's suggestions to Update 2</p>
<pre><code>#include<assert.h>
#include<stdio.h>
#include<stdlib.h>
static const int MAX_SIZE = 100;
enum action {PUSH = 1, POP, TOP, QUIT};
void clear_screen(void)
{
system("cls");
}
static enum action get_user_action(void)
{
int choice = PUSH - 1;
do
{
clear_screen();
printf("%d Push data\n"
"%d Pop Data\n"
"%d See the top of the stack\n"
"%d Exit\n\n"
"Enter your choice -> ", PUSH, POP, TOP, QUIT);
scanf("%d", &choice);
} while (choice != PUSH && choice != POP && choice != TOP && choice != QUIT);
return (enum action) choice;
}
void push(int *arr, int *length, int *status, int data)
{
*status = PUSH - 1;
if (*length == MAX_SIZE){
*status = PUSH;
return;
}
arr[(*length)++] = data;
}
int pop(int *arr, int *length, int *status)
{
*status = PUSH - 1;
if (*length == 0){
*status = POP;
return -1;
}
return arr[--(*length)];
}
int see_top(int *arr, int *length, int *status)
{
*status = PUSH - 1;
if (*length == 0){
*status = POP;
return -1;
}
return arr[*length - 1];
}
int main(void)
{
int arr[MAX_SIZE];
int length = 0;
enum action choice;
while ((choice = get_user_action()) != QUIT)
{
clear_screen();
int status;
int data;
switch (choice)
{
case PUSH:
printf("Enter data to be pushed -> ");
scanf("%d", &data);
push(arr, &length, &status, data);
if (status == PUSH){
printf("Stack overflow\n");
}
else{
printf("%d pushed onto the stack\n", data);
}
break;
case POP:
data = pop(arr, &length, &status);
if (status == POP){
printf("Stack underflow\n");
}
else{
printf("The data is %d\n", data);
}
break;
case TOP:
data = see_top(arr, &length, &status);
switch (status)
{
case POP:
printf("Nothing in the stack\n");
break;
default:
printf("The data at top is %d\n", data);
}
break;
default:
assert(!"You should not have reached this.");
}
printf("Length is %d\n", length);
getchar();
getchar();
}
}
</code></pre>
<p><strong>Update 4</strong> After William Morris's comments on Update 3. I also made the whole thing use consistent bracing style suggested by Lstor in my question about <a href="https://codereview.stackexchange.com/questions/29213/review-implementation-of-stack-by-using-pointers-in-c">stack implementation by pointers</a></p>
<pre><code>#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
static const int MAX_SIZE = 100;
enum action {START, PUSH, POP, TOP, QUIT, END};
void clear_screen(void)
{
system("cls");
}
static enum action get_user_action(void)
{
int choice = START;
do {
clear_screen();
printf("%d Push data\n"
"%d Pop Data\n"
"%d See the top of the stack\n"
"%d Exit\n\n"
"Enter your choice -> ", PUSH, POP, TOP, QUIT);
scanf("%d", &choice);
} while (!(START < choice && choice < END));
return (enum action) choice;
}
void push(int *arr, int *length, int *status, int data)
{
*status = START;
if (*length == MAX_SIZE) {
*status = PUSH;
return;
}
arr[(*length)++] = data;
}
int pop(int *arr, int *length, int *status)
{
*status = 0;
if (*length == 0) {
*status = 1;
return -1;
}
return arr[--(*length)];
}
int peek(int *arr, int *length, int *status)
{
*status = 0;
if (*length == 0) {
*status = 1;
return -1;
}
return arr[*length - 1];
}
int main(void)
{
int arr[MAX_SIZE];
int length = 0;
enum action choice;
while ((choice = get_user_action()) != QUIT) {
clear_screen();
int status;
int data;
switch (choice) {
case PUSH:
printf("Enter data to be pushed -> ");
scanf("%d", &data);
push(arr, &length, &status, data);
if (status == 1) {
printf("Stack overflow\n");
} else {
printf("%d pushed onto the stack\n", data);
}
break;
case POP:
data = pop(arr, &length, &status);
if (status == 1) {
printf("Stack underflow\n");
} else {
printf("The data is %d\n", data);
}
break;
case TOP:
data = peek(arr, &length, &status);
if (status == 1) {
printf("Nothing in the stack\n");
} else {
printf("The data at top is %d\n", data);
}
break;
default:
assert(!"You should not have reached this.");
}
printf("Length is %d\n", length);
getchar();
getchar();
}
}
</code></pre>
<p><strong>Update 5</strong> After discussing things <a href="http://chat.stackexchange.com/transcript/message/10569957#10569957">in chat</a> William Morris suggested other things. I have included Lstor's suggestion about using enum for status and suggestion in the chat.</p>
<pre><code>#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
static const int MAX_SIZE = 100;
enum action {START, PUSH, POP, TOP, QUIT, END};
enum status {SUCCESS, FAILURE};
void clear_screen(void)
{
system("cls");
}
static enum action get_user_action(void)
{
int choice = START;
do {
clear_screen();
printf("%d Push data\n"
"%d Pop Data\n"
"%d See the top of the stack\n"
"%d Exit\n\n"
"Enter your choice -> ", PUSH, POP, TOP, QUIT);
scanf("%d", &choice);
} while (!(START < choice && choice < END));
return (enum action) choice;
}
enum status push(int *arr, int *length, int data)
{
if (*length == MAX_SIZE) {
return FAILURE;
}
arr[(*length)++] = data;
return SUCCESS;
}
enum status pop(int *arr, int *length, int *data)
{
if (*length == 0) {
return FAILURE;
}
*data = arr[--(*length)];
return SUCCESS;
}
enum status peek(int *arr, int *length, int *data)
{
if (*length == 0) {
return FAILURE;
}
*data = arr[*length - 1];
return SUCCESS;
}
int main(void)
{
int arr[MAX_SIZE];
int length = 0;
enum action choice;
while ((choice = get_user_action()) != QUIT) {
clear_screen();
int data;
switch (choice) {
case PUSH:
printf("Enter data to be pushed -> ");
scanf("%d", &data);
if (push(arr, &length, data) == SUCCESS) {
printf("%d pushed onto the stack\n", data);
} else {
printf("Stack overflow\n");
}
break;
case POP:
if (pop(arr, &length, &data) == SUCCESS) {
printf("The data is %d\n", data);
} else {
printf("Stack underflow\n");
}
break;
case TOP:
if (peek(arr, &length, &data) == SUCCESS) {
printf("The data at top is %d\n", data);
} else {
printf("Nothing in the stack\n");
}
break;
default:
assert(!"You should not have reached this.");
}
printf("Length is %d\n", length);
getchar();
getchar();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Most of the code is a driver program. The only really interesting part here is</p>\n\n<pre><code>arr[(*length)++] = data;\n</code></pre>\n\n<p>and</p>\n\n<pre><code>return arr[--(*length)];\n</code></pre>\n\n<p>as well as the range-checking. I won't look too closely at the driver code.</p>\n\n<p>My key advice is: <strong>Make your data structure reusable.</strong> Put it in a header and implementation file, and use that. The next step is to dynamically allocate the array in a <code>create</code> type of function and use that instead.</p>\n\n<h3>Some general style notes:</h3>\n\n<ul>\n<li>Use (<code>static</code>) <code>const int</code> instead of <code>#define</code> for constants.</li>\n<li>In C99 and C11, you don't have to declare variables at the beginning of a block. Use C99 or C11 and declare variables as late as possible. (You are already using one of them, otherwise your <code>main</code> would require a <code>return 0;</code> at the end.)</li>\n<li>Don't pass <code>length</code> as a pointer. There's no need to, and makes the code more error-prone.</li>\n<li>I like <code>for (;;)</code> better than <code>while (1)</code>. Think \"forever\". It's just a matter of taste, though.</li>\n<li>Avoid platform-dependent code. If you must, at least wrap it up in a function.</li>\n<li>Your <code>push</code> and <code>pop</code> should neither do IO nor exit the program. The C way is to return a status code (or set <code>errno</code>).</li>\n<li>Your interface is incomplete: It does not provide a way to <em>peek</em> at the top of the stack without popping it.</li>\n<li>In terms of variable names, indentation, whitespace and so on your program is pretty okay. That is good! (But I would have written the extra <code>ay</code>.)</li>\n</ul>\n\n<p>These points are mostly nitpicking. Don't bother to improve your program. Write a new one, and take it all the way: <strong>Call <code>malloc</code>.</strong></p>\n\n<h3>Update: Key points from comments.</h3>\n\n<ul>\n<li><p>Use a <code>default</code> branch in your <code>switch</code>. If you don't expect the <code>default</code> to ever be entered, then put an assertion in it:</p>\n\n<pre><code>switch (condition) {\ncase firstCase:\n // ...\ndefault:\n assert(!\"Should never be reached.\");\n}\n</code></pre>\n\n<p>String literals are always truthy. By reversing the value (with <code>!</code>), the assertion will always trigger if the line is executed.</p></li>\n<li><p><code>see_top</code> is often called <code>peek</code>.</p></li>\n<li><p>The condition in the <code>do...while</code> in <code>get_user_action</code> can be <code>choice < PUSH && choice > QUIT</code>. If you add dummy elements at the beginning and end of the enum and test against them instead, you won't need to update the code when you add more options:</p>\n\n<pre><code>enum action { BEGIN, PUSH, /* ... */ END };\n\ndo {\n // ...\n} while (choice <= BEGIN && choice >= END);\n</code></pre></li>\n<li><p>I'd put an empty line below each case block, and a space before <code><</code> in the <code>#include</code>s.</p></li>\n<li>Sort your <code>#include</code>s alphabetically. </li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T17:33:43.607",
"Id": "46052",
"Score": "0",
"body": "I am going to make it reusable by using pointers. Just wanted to get some basic things out of the way first. If I shouldn't pass the `length` as pointer then how do you propose to update that in the functions? About platform-dependent code, which one? `system('cls')`? The extra `ay`? I am ignoring your advice about `malloc` for now and updating my question with updated code. Please comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T17:37:39.057",
"Id": "46054",
"Score": "0",
"body": "I am ignoring the `malloc` part only because I'll be implementing that after I understand completely how to implement stack by arrays. I have been told that my basic concepts are bad so just trying to think everything again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T17:38:04.123",
"Id": "46055",
"Score": "0",
"body": "Oh, right. I'm too used to having a `struct` to operate on, which would carry the length with it. I mean `system(\"cls\")`, yes. The extra `ay` after `arr`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T17:41:10.400",
"Id": "46056",
"Score": "0",
"body": "Are there any other suggestions? Also about not having `return 0;` at the end, I have a `return` at the logical end of the program in the `switch` statement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T17:45:49.880",
"Id": "46058",
"Score": "1",
"body": "I don't have anything further to add to the updated code, except to put `#include <errno.h>` at the top (to keep them sorted alphabetically). Also, I recommend having a `default` branch in your `switch`. In C89, there is no implicit return from `main()`, and therefore you need it right before the end of the scope, unless that is unreachable. But you should prefer C99 or C11 anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T17:49:48.860",
"Id": "46060",
"Score": "0",
"body": "Why use the `default` branch? There doesn't seem to be any use."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T17:57:23.033",
"Id": "46061",
"Score": "1",
"body": "Exactly. Put `assert(!\"Should never be reached.\");` (or something like that) there, so you will know if you have made a mistake."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T07:11:21.890",
"Id": "46105",
"Score": "0",
"body": "Any comments on update 3?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T07:26:14.860",
"Id": "46106",
"Score": "1",
"body": "Nothing really substantial. `see_top` is often called `peek`. The condition in the `do...while` in `get_user_action` can be `choice < PUSH && choice > QUIT)`. If you add dummy elements at the beginning and end of the `enum` and test against them instead, you won't need to update the code when you add more options. Finally, I'd put an empty line below each `case` block, and a space before `<` in the `#include`s."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T07:38:35.240",
"Id": "46107",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/9892/discussion-between-aseem-bansal-and-lstor)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T18:18:02.717",
"Id": "46483",
"Score": "0",
"body": "When I asked [this question](http://programmers.stackexchange.com/questions/207272/use-of-const-and-macro-definition-to-declare-constants-in-c-in-what-situations) I came upon [this](http://stackoverflow.com/questions/1674032/static-const-vs-define-in-c) and [this](http://stackoverflow.com/questions/2308194/shall-i-prefer-constants-over-defines) regarding constants in C. The 2nd one has a better accepted answer but the first one has a better answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T06:04:34.673",
"Id": "46507",
"Score": "0",
"body": "They are talking about compile-time constants. In short, if you need the constant at compile-time, use the enum hack. If not, use (`static`) `const`."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T16:56:21.303",
"Id": "29185",
"ParentId": "29183",
"Score": "3"
}
},
{
"body": "<p>In a simple practice program like this, the user experience is perhaps not\nsomething you considered much (more interesting is getting it to work :-) But\nyou should think about it in general. Try using your program and consider\nwhether it is comfortable to use. For example, if I want to enter many\nnumbers into the array, I have to repeatedly select <code>1</code> then enter the number,\nselect <code>1</code> then enter the number, etc. This is tedious. Added to that your\n<code>getchar</code> calls at the end of each loop mean the user must type enter again,\nwithout any purpose, the \"Data pushed\" message seems like noise, and if the\nuser has the patience to enter 100 numbers and dares enter another, the\nprogram exits!</p>\n\n<p>A better approach might be to allow several numbers to be entered at a time.\nOr perhaps change the interface so that if the user types a number it is\npushed, if 'p' is typed, a number is popped and if 'q' the program exits. If\nthe array is full, print a warning but don't exit. These are just examples,\nthe point being that you should always think of the user.</p>\n\n<hr>\n\n<p>One criticism I have of the coding is that your input choices are spread\nthroughout the file. From <code>MIN</code>/<code>MAX</code> at the top through the choice-entry loop\nand the switch statement to the <code>intro</code> function at the bottom. There is\nnothing tying these together and so if a change is made in one place you have\nto remember to change every other location.</p>\n\n<p>Adding an enum (or #defines) and using it everywhere would help:</p>\n\n<pre><code>enum action {PUSH, POP, QUIT};\n\nstatic enum action get_user_action(void)\n{\n int choice = 0;\n do {\n printf(\"%d Push data\\n\"\n \"%d Pop Data\\n\"\n \"%d Exit\\n\\n\"\n \"Enter your choice -> \", PUSH, POP, QUIT);\n scanf(\"%d\", &choice);\n } while (choice != PUSH && choice != POP && choice != QUIT);\n return (enum action) choice;\n}\n</code></pre>\n\n<p>and in <code>main</code></p>\n\n<pre><code>enum action choice;\nwhile ((choice = get_user_action()) != QUIT) {\n if (choice == PUSH) {\n // do the push\n } else {\n // do the pop\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Some minor points:</p>\n\n<ul>\n<li><p>Your <code>printf</code> statements often put a '\\n' at the beginning of the text to be\nprinted. This is unusual - it would be better if you put the \\n at the end.</p></li>\n<li><p>Your switch statement has no <code>default</code> case, which is generally bad practice.\nAlways use a default. In this case the switch is arguably not needed.</p></li>\n<li><p>Move <code>main</code> to the end to avoid the need for prototypes. Although at first it\nmight seem odd, this is a common pattern.</p></li>\n<li><p>Both <code>main</code> and <code>intro</code> need <code>void</code> parameter list</p></li>\n</ul>\n\n<p><hr>\n<strong>Comments</strong> on your 2nd update</p>\n\n<p>I'm not keen on your setting <code>errno</code> as an error value. And certainly not\nwith the PUSH/POP values you have used. Values written to <code>errno</code> are defined\nin errno.h - or more probably sys/errno.h and you should never conflict with\nthose numbers. Moreover, <code>errno</code> is used by system and library functions and\nI'm not happy extending that for your own private use.</p>\n\n<p>Error handling is often the most difficult part of C (which is perhaps why\nexceptions seem at first glance to be such a boon in C++ - although they seem\nto cause more problems than they cure from my ignorant perspective). The\ngeneral pattern for library and system functions is to return -1 or NULL to\nthe caller and maybe set <code>errno</code> to show the reason. Often -1/NULL is\nreturned in place of the normal return value, which is not ideal. In your\ncase, the reason for failure is clear and <code>errno</code> is not needed. As you have\nused it, the caller must be sure to set <code>errno</code> to zero before calling one of\nyour functions, as the functions do not indicate failure (even <code>pop</code> and <code>top</code>\ndon't, as -1 is a valid number to find on the stack).</p>\n\n<p>So since we don't have exceptions and I'm saying not to use <code>errno</code> as you\nhave, what should you do?</p>\n\n<p>Since you cannot mix the return value and the data (-1 is a valid number for\nthe stack), there are two alternatives. Return status and add a return\nparameter for the value (pop/top). </p>\n\n<pre><code>int push(int *arr, int *length, int data) \n{\n if (*length == MAX_SIZE) {\n return -1;\n }\n arr[(*length)++] = data;\n return 0;\n}\n\nint pop(int *arr, int *length, int *data)\n{\n if (*length == 0){\n return -1;\n }\n *data = arr[--(*length)];\n return 0;\n}\n</code></pre>\n\n<p>Or return the data (pop/top) and add a return parameter for the status:</p>\n\n<pre><code>void push(int *arr, int *length, int data, int *status) \n{\n if (*length == MAX_SIZE) {\n *status -1;\n }\n arr[(*length)++] = data;\n *status = 0;\n}\n\nint pop(int *arr, int *length, int *status)\n{\n if (*length == 0){\n *status -1;\n }\n *status = 0;\n return arr[--(*length)];\n}\n</code></pre>\n\n<p>Take your pick and be consistent within the app. In this case I think I'd go\nfor returning status.</p>\n\n<p>In the case of your <code>top</code> function, you don't need to pass <code>length</code> as a\npointer, <code>arr</code> could and should be <code>const</code> and it is surely not an error if\n<code>length == MAX_SIZE</code>.</p>\n\n<p><hr>\n<strong>Comments</strong> on 3rd update.</p>\n\n<p>No, as I said before in relation to <code>errno</code>, don't use PUSH and POP as error\nstatus. And using <code>PUSH-1</code> as a synonym for 0 is horribly wrong. When you\nhave defined some constants (with enum or #define etc) you must treat their\nvalue as unknown - <strong>nothing</strong> is permitted to assume the value of an enum or\ndefine - which is what you have done in using <code>PUSH-1</code>. If you assume the\nvalue of such a constant you negate the purpose of using the constant instead\nof the raw value.</p>\n\n<p>As I said before, you don't need different status values. Just use 0 for good\nand -1 for bad (or in other circumstances, a valid pointer and NULL, or 1 for true and 0 for false\netc). If at some point you did need to differentiate between errors, you\ncould define some error constants. <code>PUSH</code> is not an error constant it is one\nof your actions. <code>STACK_FULL</code> or <code>STACK_EMPTY</code> would be meaningful. But you\n<strong>don't</strong> need that here. Your statements in <code>main</code> should just check for\n<code>if (status < 0) {...}</code> or <code>if (status != 0) {...}</code> or even <code>if (status)\n{...}</code> .</p>\n\n<p><strong>Comment</strong> on 5th update</p>\n\n<p>That looks much better, don't you think? I hope you agree because a lot of the process of improving code is self criticism. Once you get a feeling for what looks good and what is just not quite right (the 'yuk' feeling), you have made the biggest leap to improving your code. </p>\n\n<p>When I look at your latest update, I now have only minor 'yuk' moments. One is the START/END tags of the enum, which stick out somehow. I have trouble explaining why - I think it is just at the level of \"I wouldn't do that\", which is a danger when reviewing - separating objective comments from personal preference.</p>\n\n<p>Another minor point is in your use of START/END. </p>\n\n<pre><code>...\n} while (!(START < choice && choice < END));\n</code></pre>\n\n<p>This would be more naturally expressed as </p>\n\n<pre><code>...\n} while (choice <= START || choice >= END);\n</code></pre>\n\n<p>The <code>peek</code> function still needs a <code>const</code> on <code>arr</code> and <code>length</code> should not be a pointer. </p>\n\n<p>A final minor point is the return of <code>enum status</code> by the functions. This is perfectly ok. Nothing wrong at all. It is just unusual to see functions returning such an enum rather than just an int (0/-1). Arguably what you have is \"better\" in that it is clear from the enum what is good/bad. It is just not normally done :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T18:13:45.580",
"Id": "46066",
"Score": "0",
"body": "Many thanks for the suggestion of `enum`. I always knew that this structure, which I used regularly, was bad but didn't knew any remedy or what to ask for. I'll update my code and post the updated one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T18:33:22.507",
"Id": "46070",
"Score": "0",
"body": "I added the updated code. Update 2. I haven't taken care of the user experience but I think other things should be good. One thing that I am not sure is the `while` in `get_user_input`. If the things in `enum` become large would checking individually be a good idea? Same goes for using if...else structure in the `main` function. Wouldn't switch work? After all `enum` have `int` associated with them. Please comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T18:48:09.400",
"Id": "46072",
"Score": "0",
"body": "I hope you didn't have the time to read the last comment because I tried and the `switch` version worked. I tweaked some more checks and I think the readability increased. Any suggestions?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T04:00:12.637",
"Id": "46099",
"Score": "0",
"body": "About `length == MAX_SIZE` not being an error, in case we are pushing and stack is filled then isn't that an error? I was mistaken in case of function `top` but in case of `push` it is an error. Also I am doing Update 3. Please comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T07:09:47.337",
"Id": "46104",
"Score": "0",
"body": "Any comments on update 3?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T14:03:16.740",
"Id": "46136",
"Score": "0",
"body": "Here I don't need more than 1 error state but in the general case if I need to get more than one error states like `Underflow`, `Overflow` then using another `enum` for that is fine?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T14:16:28.773",
"Id": "46138",
"Score": "0",
"body": "@AseemBansal Yes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T14:22:12.583",
"Id": "46139",
"Score": "1",
"body": "Although I missed the `PUSH - 1` part when I read your code, @WilliamMorris is making a very important point here. `enum`s provide an abstraction, and you should *not* break that abstraction by assuming values. However, as long as the values are contiguous I think it's fine to test if a value is inside the range or not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T16:18:32.720",
"Id": "46149",
"Score": "0",
"body": "@Lstor I think I fixed it in Update 4. Anything I did wrong in Update 4?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T16:21:58.920",
"Id": "46150",
"Score": "0",
"body": "Your `status` should be an `enum` even though it is just two states. That makes it easier to see if the status means success or failure. In `push`, you are using `START` and `PUSH`, but you should be using status code enums instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T16:24:20.197",
"Id": "46151",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/9892/discussion-between-aseem-bansal-and-lstor)"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T18:07:04.887",
"Id": "29195",
"ParentId": "29183",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29195",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T16:28:47.550",
"Id": "29183",
"Score": "0",
"Tags": [
"c",
"array",
"stack"
],
"Title": "Review implementation of stack by using array in C"
}
|
29183
|
<p>Could you tell me how to make it quality code?</p>
<pre><code><?php
class Game {
public function __construct() {
session_start();
}
public function play(){
return '<input type="button" value="Play" onclick="window.location = \'?play=1\'">';
}
public function start($msg=null) {
unset($_SESSION['bees']);
$bee = new Bee();
$bee->setType('queen');
$this->addBee($bee,1);
$bee->setType('worker');
$this->addBee($bee,5);
$bee->setType('drone');
$this->addBee($bee,8);
if($msg)
return $msg;
else {
var_dump($_SESSION['bees']); // debug
return 'Game started <input type="button" value="Hit" onclick="window.location = \'?hit=1\'">';
}
}
public function hit() {
$msg = '';
if($_SESSION['bees'])
$rd = array_rand($_SESSION['bees'],1);
else
$this->start('Game will start again');
$_SESSION['bees'][$rd]['lifespan'] = $_SESSION['bees'][$rd]['lifespan'] - $_SESSION['bees'][$rd]['hit'];
if($_SESSION['bees'][$rd]['lifespan']<1) {
$_SESSION['bees'][$rd]['bees'] -=1;
$_SESSION['bees'][$rd]['lifespan'] = $_SESSION['bees'][$rd]['life'];
switch($rd)
{
case 'queen': $msg .= $this->start('Game start again, the Queen is dead.'); break;
default: $msg .= 'One \'' . $rd . '\' is gone';
}
}
if($_SESSION['bees'][$rd]['bees']<1){
unset($_SESSION['bees'][$rd]);
$msg = 'The \'' . $rd . '\' team is gone';
}
var_dump($_SESSION['bees']); // debug
return '<input type="button" value="Hit" onclick="window.location = \'?hit=1\'"> ' . $msg;
}
public function addBee(Bee $newbee, $number = 1) {
$tipo = $newbee->getType();
$bee = $newbee->get();
$_SESSION['bees'][$tipo] = $bee;
$_SESSION['bees'][$tipo]['bees'] = $number;
$_SESSION['bees'][$tipo]['life'] = $newbee->getLifespan($tipo);
}
}
class Bee
{
protected $_type = null;
protected $_types = array(
'queen' => array(
'hit' => 8,
'lifespan' => 100
),
'worker' => array(
'hit' => 10,
'lifespan' => 75
),
'drone' => array(
hit' => 12,
'lifespan' => 50
)
);
public function setHit(){}
public function setLifespan(){}
public function addNewType(){}
protected function _set_hit(){}
protected function _set_lifespan(){}
protected function _add_new_type(){}
public function getLifespan($type){
if(array_key_exists($type,$this->_types))
return $this->_types[$this->_type]['lifespan'];
else
throw new Exception('The Bee need to be a Queen, Worker or Drone');
}
public function getTypes() {
return $this->_types;
}
public function getType() {
return $this->_type;
}
public function setType($type) {
if(array_key_exists($type,$this->_types))
$this->_type = $type;
else
throw new Exception('The Bee need to be a Queen, Worker or Drone');
}
public function get() {
return $this->_types[$this->_type];
}
}
?>
<html>
<head>
<title>play Bee</title>
</head>
<body>
<?php
$game = new Game();
if(isset($_GET['play']) && $_GET['play']) {
echo $game->start();
} else if(isset($_GET['hit']) && $_GET['hit']) {
echo $game->hit();
} else {
echo $game->play();
}
?>
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T17:41:25.337",
"Id": "46057",
"Score": "0",
"body": "One point I know is about the non-existence of documentation (comments) on it, but was a test for 1 hour which I didn't give the concern for it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T10:48:16.753",
"Id": "46203",
"Score": "0",
"body": "MVC, that's all you need to _really_ know, but I need 15 chars in a comment. Also _Single Responsabilitiy_ (which comes naturally when using the MVC pattern), and declare classes in separate files..."
}
] |
[
{
"body": "<ul>\n<li>Indentation is important</li>\n<li>dont use the same bee object again and again</li>\n<li>embrace braces (after every if, else, and so on keyword comes a brace pair)</li>\n<li><p>after if or switch should be a space or/and there should bespaces inside e.g.<br>\n<code>if( X ) {</code> or <code>if ( X ) {</code></p></li>\n<li><p>controversial point, don't use nondescriptive names, use names with meaning, e.g. don't use names like <code>$msg</code>, <code>$rd</code></p></li>\n<li><p>you can cache the value of <code>$_SESSION['bees'][$rd]</code> into a variable and give it a good name, this healps <em>a lot</em></p>\n\n<pre><code>class Game {\n public function __construct() {\n session_start();\n }\n\n public function play(){\n return '<input type=\"button\" value=\"Play\" onclick=\"window.location = \\'?play=1\\'\">';\n }\n\n public function start($msg=null) {\n unset($_SESSION['bees']);\n\n $bee = new Bee();\n $bee->setType('queen');\n $this->addBee($bee,1);\n\n $bee = new Bee();\n $bee->setType('worker');\n $this->addBee($bee,5);\n\n $bee = new Bee();\n $bee->setType('drone');\n $this->addBee($bee,8);\n\n if($msg) {\n return $msg;\n }\n else {\n var_dump($_SESSION['bees']); // debug\n return 'Game started <input type=\"button\" value=\"Hit\" onclick=\"window.location = \\'?hit=1\\'\">';\n }\n }\n\n public function hit() {\n $msg = '';\n\n if ($_SESSION['bees']) {\n $rd = array_rand($_SESSION['bees'],1); \n } \n else {\n $this->start('Game will start again');\n }\n\n $_SESSION['bees'][$rd]['lifespan'] = $_SESSION['bees'][$rd]['lifespan'] - $_SESSION['bees'][$rd]['hit'];\n\n if ($_SESSION['bees'][$rd]['lifespan']<1) {\n $_SESSION['bees'][$rd]['bees'] -=1;\n $_SESSION['bees'][$rd]['lifespan'] = $_SESSION['bees'][$rd]['life'];\n\n switch($rd)\n {\n case 'queen':\n $msg .= $this->start('Game start again, the Queen is dead.');\n break;\n\n default:\n $msg .= 'One \\'' . $rd . '\\' is gone';\n }\n }\n\n if ($_SESSION['bees'][$rd]['bees']<1) {\n unset($_SESSION['bees'][$rd]);\n $msg = 'The \\'' . $rd . '\\' team is gone';\n }\n\n var_dump($_SESSION['bees']); // debug\n\n return '<input type=\"button\" value=\"Hit\" onclick=\"window.location = \\'?hit=1\\'\"> ' . $msg;\n }\n\n public function addBee(Bee $newbee, $number = 1) {\n\n $tipo = $newbee->getType();\n $bee = $newbee->get();\n\n $_SESSION['bees'][$tipo] = $bee;\n $_SESSION['bees'][$tipo]['bees'] = $number;\n $_SESSION['bees'][$tipo]['life'] = $newbee->getLifespan($tipo);\n }\n}\n\n\nclass Bee {\n protected $_type = null;\n\n protected $_types = array( 'queen' => array(\n 'hit' => 8,\n 'lifespan' => 100\n ),\n 'worker' => array(\n 'hit' => 10,\n 'lifespan' => 75\n ),\n 'drone' => array(\n 'hit' => 12,\n 'lifespan' => 50\n ));\n\n public function setHit(){}\n public function setLifespan(){}\n public function addNewType(){}\n\n protected function _set_hit(){}\n protected function _set_lifespan(){}\n protected function _add_new_type(){}\n\n public function getLifespan($type) {\n if (array_key_exists($type,$this->_types)) {\n return $this->_types[$this->_type]['lifespan'];\n }\n else {\n throw new Exception('The Bee need to be a Queen, Worker or Drone');\n }\n }\n\n public function getTypes() {\n return $this->_types;\n }\n\n public function getType() {\n return $this->_type;\n }\n\n public function setType($type) {\n if(array_key_exists($type,$this->_types)) {\n $this->_type = $type;\n }\n else {\n throw new Exception('The Bee need to be a Queen, Worker or Drone');\n }\n }\n\n public function get() {\n return $this->_types[$this->_type];\n }\n}\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T23:50:28.213",
"Id": "29202",
"ParentId": "29190",
"Score": "7"
}
},
{
"body": "<p>One big issue with this code is that you've got a tight coupling between the business logic and the presentation. For example, the method <code>play()</code> really jumps out: </p>\n\n<pre><code>public function play(){\n\n return '<input type=\"button\" value=\"Play\" onclick=\"window.location = \\'?play=1\\'\">';\n\n}\n</code></pre>\n\n<p>From its name I'd think that this method plays something (a game? A piece of music? A role in a play? Another issue is clear, unambiguous naming of classes, methods and variables). I wouldn't expect it to output the HTML markup for a button with a JavaScript event attached to it. </p>\n\n<p>This might not seem like a big deal, and in this particular case it probably isn't. But ask yourself this, how much work would you need to do if whoever set you this project decided half way though that it should run through the command line instead of a web browser? </p>\n\n<p>Ideally, your PHP classes should contain no presentation logic at all. They should return data structures (arrays, scalar types, simple data transfer objects, etc) to the outside world, and then a separate process should take that information and render it to the user in a suitable presentation. The classes that do the actual work (the business objects) should implement all the logic and rules needed to accomplish a task without any concern as to how the results of that task are presented. </p>\n\n<p>This concept is known as separation of concerns. A concern is a particular part of the software package you're developing which shouldn't be tightly bound (coupled in the lingo) to other parts of your package (sorry I can't really word it better than that). Implementing the rules and maintaining the state of the game is one concern, getting user input and displaying output to the user is a different concern. While there obviously has to be some coupling you should try to minimize the degree that one is bound to the other. Additionally, it's generally considered preferable for the part of the program responsible for presentation (which will typically be unique to that program) to know something about the business objects than it is for the business objects (which may get used across a wide range of applications) to know something about the presentation. </p>\n\n<p>A related issue is reliance on <code>$_SESSION</code> inside your class. Again this has to do with separation of concerns. The <code>$_SESSION</code> array and its associated methods (<code>session_start ()</code>, etc) are a data storage mechanism. Data storage is a separate concern from the business logic, so again you should try to separate the code that handles storing the game state out from the code that implements the business logic. In the case of <code>$_SESSION</code> there's the additional problems of it being tightly coupled to HTTP and that the <code>session_start ()</code> function can't be called once headers have been sent to the client. Again, ask yourself how hard would it be to adapt your code to work in a command line or to use a database instead of the PHP session to store state? </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T22:25:13.963",
"Id": "29248",
"ParentId": "29190",
"Score": "8"
}
},
{
"body": "<h2>Inheritance, ever heard of it?</h2>\n\n<p>A good rule I tend to use a lot is the following:\nIs there an <code>if</code> in my class function? Does the outcome of the function depend on the <code>if</code>? Then it is often a good idea to create a Sub class.</p>\n\n<p>Your Bee classes look really messy without even looking at the code. For every Bee you set a 'type'. So what if I forget to set a type? Errors? is there a default? No way to know unless you dive into the code = Bad.</p>\n\n<p>So better would be:</p>\n\n<pre><code>new Bee('worker');\n</code></pre>\n\n<p>By passing in the type in the construct we are now sure that the Bee is of a certain type, it also makes it easier to read.</p>\n\n<p>But then remains the question. Does the type of the bee change it behaviour? I guess it does. A queen can lay eggs but the other beers can't.\nThis would give you an '<code>abstract class Bee</code>' with all default functions. Then you would create 3 different subclasses: <code>WorkerBee</code>, <code>QueenBee</code> and <code>DroneBee</code></p>\n\n<p>Then again, to much tight coupling. Say I want to test the 'Game' class, but no I have no idea what it needs. It needs session, it needs 'Bee',...</p>\n\n<p>A really good place to start is <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\" rel=\"nofollow\">SOLID</a></p>\n\n<p>Apply that to your code and it will not be as messy anymore</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T08:26:55.047",
"Id": "29256",
"ParentId": "29190",
"Score": "5"
}
},
{
"body": "<p>I had to take this test a couple of days ago during an interview process. I wrote mine as procedural and paid the price (didn't get selected for the next stage). </p>\n\n<p>Looking at your effort, I've spent a couple of hours on it and have adapted it. Here is my offering:</p>\n\n<pre><code>class bee\n{\n private $type = NULL;\n private $qty = 0;\n private $life = 0;\n\n public static $available_types = array('queen' => array(\n 'hit' => 8,\n 'lifespan' => 100\n ),\n 'worker' => array(\n 'hit' => 10,\n 'lifespan' => 75\n ),\n 'drone' => array(\n 'hit' => 12,\n 'lifespan' => 50\n ));\n\n public function __construct($type, $qty) \n {\n //create new bee set collection\n\n //does this bee type exist?\n if (array_key_exists($type, self::$available_types)) \n {\n //set default properties\n $this->type = $type;\n $this->qty = $qty;\n $this->life = self::$available_types[$type]['lifespan'];\n }\n else \n {\n throw new Exception('The Bees need to be a Queen, Worker or a Drone');\n } \n\n }\n\n public function get_type()\n {\n return $this->type;\n }\n\n public function get_life()\n {\n return $this->life;\n }\n\n public function get_qty()\n {\n return $this->qty;\n } \n\n}\n\nclass game \n{\n public $message;\n\n public function __construct() \n {\n session_start();\n }\n\n public function reset_game($supress_message = FALSE)\n {\n //reset each type of bees\n $bee = new bee('queen', 1);\n $this->add_bees($bee);\n\n $bee = new bee('worker', 5);\n $this->add_bees($bee); \n\n $bee = new bee('drone', 8);\n $this->add_bees($bee); \n\n if (! $supress_message)\n {\n $this->message = 'Game has been reset. All bees have been respawned.';\n };\n }\n\n public function add_bees(bee $new_bee) \n {\n $_SESSION['bees'][$new_bee->get_type()] = array('qty' => $new_bee->get_qty(),\n 'life' => $new_bee->get_life(),\n 'hit_points' => bee::$available_types[$new_bee->get_type()]['hit']\n ); \n } \n\n public function hit()\n {\n $bees = (array) $_SESSION['bees'];\n\n //is the session object still valid?\n if ($bees) \n {\n //get random bee from session\n $seed = array_rand($bees, 1); \n\n //check if there are any bees of selected type actually left\n if ($bees[$seed]['life'] == 0 && $bees[$seed]['qty'] == 0)\n {\n //apply hit again\n $this->hit();\n };\n\n //deduct appropriate hit points from selected bee\n $bees[$seed]['life'] -= $bees[$seed]['hit_points'];\n\n //if this bee has no life left\n if ($bees[$seed]['life'] < 0)\n {\n //then reset its life to designated lifespan\n $bees[$seed]['life'] = bee::$available_types[$seed]['lifespan']; \n\n //reduce bee quantity by 1\n $bees[$seed]['qty'] -= 1; \n };\n\n //how many bees are remaining for this type\n if ($bees[$seed]['qty'] >0 )\n { \n //there is at least one bee still left\n $this->message = $seed.' bee has been hit. There are '.$bees[$seed]['qty'].' bees left.'; \n }\n else //no, either the queen is dead, or all workers are dead, or all drones are dead\n {\n switch ($seed)\n {\n case 'queen': //the queen is dead, end game\n $this->message = 'The queen is dead, therefore all bees are dead. The game has been reset';\n $this->reset_game(TRUE);\n return;\n break;\n\n default: \n $bees[$seed]['life'] = 0;\n $this->message = $seed.' bee has been hit and killed. There are no more '.$seed.' bees left.';\n break;\n };\n };\n\n //update session data with changes\n $_SESSION['bees'][$seed] = $bees[$seed];\n\n } \n else //session no longer exists\n {\n $this->reset_game();\n }\n }\n\n public function show_view()\n {\n //set view data \n $view = new stdClass();\n $view->message = $this->message;\n $view->queen = $_SESSION['bees']['queen'];\n $view->worker = $_SESSION['bees']['worker'];\n $view->drone = $_SESSION['bees']['drone'];\n\n ?>\n <!DOCTYPE html>\n <html>\n <body>\n\n <h1>Bee Test</h1>\n <p><?=$view->message?></p>\n\n <form name=\"input\" action=\"beetest_revised.php\" method=\"post\">\n <input type=\"submit\" name =\"action\" value=\"hit\">\n </form>\n\n <p>Queen Bees</p>\n <?=var_dump($view->queen)?>\n\n <p>Worker Bees</p>\n <?=var_dump($view->worker)?>\n\n <p>Drone Bees</p>\n <?=var_dump($view->drone)?>\n\n </body>\n </html>\n <?\n }\n\n}\n\n$controller = new game();\n\nif ($_POST)\n{\n $controller->hit();\n $controller->show_view();\n}\nelse\n{ \n $controller->message = 'Game has been reset.';\n $controller->reset_game();\n $controller->show_view();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T17:21:47.330",
"Id": "80821",
"Score": "4",
"body": "Could you explain how this can benefit the asker's code? Code-only answers aren't considered reviews and are subject to deletion."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T17:18:51.230",
"Id": "46300",
"ParentId": "29190",
"Score": "-2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T17:37:04.600",
"Id": "29190",
"Score": "4",
"Tags": [
"php",
"game"
],
"Title": "Basic \"bee game\" labeled as messy"
}
|
29190
|
<p><strong>A little background</strong><br/>
I'm an intern at a large engineering company, and I'm also the only CS major in the entire building. The people on my team don't have technical backgrounds, but hired me to start developing an internal application. </p>
<p><strong>About my program</strong><br/>
I'm trying to read two part numbers as input, search through a CSV file to find them, and then extract all of the associated parts into two separate lists that can then be compared. </p>
<p>Currently I can enter part numbers and then read the associated parts into an ArrayList. However </p>
<ul>
<li>things feel kind of hacked together at this point </li>
<li>I don't exactly have a solid grasp on OOP </li>
<li>The two classes that "smell" to me are my FileInput.java and PartList.java classes (although for all I know the whole thing may stink, it's difficult without a developer to mentor me). </li>
</ul>
<p>Ideally, I want to have two PartList objects that can then be compared in another class.</p>
<p>My main issue is how I'm instantiating the PartList within the FileInput. I was essentially fiddling around with Eclipse and its built in refactoring features to get it to work, and that's what I got. </p>
<p>I just don't think things are organized logically, and I'm unsure how to continue. I omitted the PartNumber class because it's twice as long as the others and I don't think it's necessary to understand my problem. Any advice is appreciated!</p>
<p><code>FileInput.java</code></p>
<pre><code>public class FileInput {
// Just a test file
public final static String strFile = "C:\\Users\\hamlib1\\Projects\\HVC_Project\\TestData\\TT524S-FinalV1.csv";
public void readCSV(String input) throws IOException {
CSVReader reader = new CSVReader(new FileReader(strFile));
String[] row;
while ((row = reader.readNext()) != null) {
int limit = row.length;
for (int i = 0; i < limit; i++) {
if (row[i].contains(input)) {
// The way I'm instantiating and calling from PartList here seems off to me
PartList partList = new PartList();
partList.setList(reader, row);
}
}
}
reader.close();
PartList.printList();
System.out.println("Reader Closed");
}
}
</code></pre>
<p><code>PartList.java</code></p>
<pre><code>public class PartList {
private static ArrayList<String[]> partList = new ArrayList<String[]>();
// Not sure what to even put here
public PartList() {
}
// Algorithm for filling the list works, but it smells to me
// Mainly passing the CSVreader and row, but when I start reading I want
// to be at the row that matches the input
public void setList(CSVReader reader, String[] row) throws IOException {
String levelString = row[0];
int levelInt = Integer.parseInt(levelString);
if (levelInt == 2) {
partList.add(row); // Add the first row to the list
row = reader.readNext();
String nextLevelString = row[0];
int nextLevelInt = Integer.parseInt(nextLevelString);
while (nextLevelInt > 2) { // Add subsequent rows
partList.add(row);
row = reader.readNext();
nextLevelString = row[0];
nextLevelInt = Integer.parseInt(nextLevelString);
}
}
}
// Just so I can check if I'm filling the list correctly
public static void printList() {
for (int i = 0; i < partList.size(); i++) {
String[] strings = partList.get(i);
for (int j = 0; j < strings.length; j++) {
System.out.print(strings[j] + " | ");
}
System.out.println();
}
}
}
</code></pre>
<p><code>RunProgram.java</code></p>
<pre><code>public class RunProgram {
public static void main(String[] args) {
PartNumber part1 = new PartNumber();
PartNumber part2 = new PartNumber();
FileInput file = new FileInput();
part1.readInput();
part2.readInput();
String partString1 = part1.getPartNumber();
String partString2 = part2.getPartNumber();
try {
System.out.println(part1.toString());
file.readCSV(partString1);
System.out.println(part2.toString());
file.readCSV(partString2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
</code></pre>
<p><img src="https://i.stack.imgur.com/vrzeE.png" alt="Example of CSV file"></p>
<p>Here's an example of the CSV. The one I pulled this from is about 35,000 lines, but they all follow the same format. I deleted some irrelevant columns for simplicity, but the important information are the levels and part numbers. They won't change position, and searching through an entire CSV only takes a few seconds. To pull a group of parts I first check if its level is 2 (denoting a "top" level) then I pull all subsequent parts until the next 2.</p>
<p><strong>Edit</strong></p>
<p>I decided to create create a PartList object and pass it to my readCSV method. This appeared to work when I printed the list. Then I created a second PartList, and tried to print both lists. What should have happened is each list printed separately. Instead, it printed both lists merged together, twice. Somehow I'm adding the parts for two separate lists into a single list. I think this comes down to my PartList class (and lack of appropriate constructors, getters & setters?). I think this problem is now more suited for Stack Overflow, but if anyone has general refactoring help I'll still greatly appreciate it.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T21:51:35.813",
"Id": "46085",
"Score": "0",
"body": "How big is the CSV file (# of lines)? How often does the CSV change? Can the part number show up in any \"column\" in the file? It also looks like there is some sort of hierarchy to the csv file based on how you are searching. Perhaps post a few lines as an example. You can change names, codes, etc. if needed as long as the structure / columns are intact."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T12:48:22.747",
"Id": "46129",
"Score": "0",
"body": "I can't seem to find an email listed on your profile. Mine is brianhamlin14@gmail.com if you have any advice. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T20:50:34.617",
"Id": "46181",
"Score": "0",
"body": "@RobertSnyder: It would be great if that advice were to be shared for everyone. :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T20:58:28.830",
"Id": "46183",
"Score": "0",
"body": "@DaveJarvis yeah I have a soft spot for that type of situation. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T13:24:46.470",
"Id": "46246",
"Score": "0",
"body": "If it were me, I would load the files into http://hsqldb.org/ and then do a SQL statement. This way, if they ask for a new report I could re-use the code and deliver quickly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T00:54:16.953",
"Id": "46247",
"Score": "0",
"body": "My original plan was to use some sort of database to load the file into. I did some research but ultimately decided I didn't know enough about databases to start fiddling around with them. I figured the CSV files were small enough that it wouldn't be an issue but in retrospect maybe it would have been a good idea..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T19:56:06.717",
"Id": "46492",
"Score": "0",
"body": "Unless this is for the sake of the exercise, you could also simply use a csv parsing library, such as openCSV and spend your time on the specific parts of your application."
}
] |
[
{
"body": "<p><strong>Some beginner mistakes...</strong></p>\n\n<p>The functionality of the classes should make sense logically. Instead of bringing out the terminologies, I prefer to think from a layman's interpretation of a class. Why should your <code>PartList</code> know what is a <code>CSVReader</code>? And why should your <code>PartNumber</code> know how to read an input?</p>\n\n<p><strong>Other pointers</strong></p>\n\n<p>You also need to learn how to accurate translate the rules and requirements of your work into programming logic. For example, the identification of non-\"top level\" parts. Are they identified by a model level number greater than two, as written in your code? Or just when they are not equal to two, as you have written in your question? This is also where validation of values and \"business requirements\" come in to play, to ensure your code functions as per expectations.</p>\n\n<p><strong>Gotcha</strong></p>\n\n<p>Looking at your code again, there is a glaring bug between the <code>for</code> loop below and the <code>setList</code> method of <code>PartList</code>, which is called in the same loop too:</p>\n\n<pre><code>for (int i = 0; i < limit; i++) {\n if (row[i].contains(input)) {\n // The way I'm instantiating and calling from PartList here seems off to me\n PartList partList = new PartList();\n partList.setList(reader, row);\n }\n }\n</code></pre>\n\n<p><code>setList</code> is actually modifying the state of your <code>reader</code> object, i.e. when this method returns and there is the slim chance that the next column matches the input (I know it's not intentional, so probably bug #2?), you wouldn't be looping through the same lines of the <code>reader</code> object. Instead, you will be starting from the next line which the first invocation of <code>setList</code> left off. In fact, your code will also be reading in one extra line when <code>setList</code> exits upon encountering the next top-level part, and the flow goes into the next iteration of the outer <code>while</code> loop which calls <code>reader.readNext()</code> again. Last but not least, <code>PartList</code> is instantiated within the <code>for</code> loop, meaning it can't be used outside at all.</p>\n\n<p><strong>Suggested solution</strong></p>\n\n<pre><code>package com.myproject.se;\n\npublic class Part {\n\n enum Serviceability {\n SERVICEABLE(\"SVCBLE\"), NOT_SERVICEABLE(\"NOT SVC\"), UNDEFINED(\"\");\n\n private String value;\n\n Serviceability(String value) {\n this.value = value;\n }\n\n public String toString() {\n return value;\n }\n\n static Serviceability fromValue(String value) {\n if (value != null) {\n String valueToCompare = value.toUpperCase();\n for (Serviceability current : Serviceability.values()) {\n if (current.value.equals(valueToCompare)) {\n return current;\n }\n }\n }\n return UNDEFINED;\n }\n }\n\n enum PartType {\n PART(\"PART\"), ASSEMBLY(\"ASSEMBLY\"), UNDEFINED(\"\");\n\n private String value;\n\n PartType(String value) {\n this.value = value;\n }\n\n public String toString() {\n return value;\n }\n\n static PartType fromValue(String value) {\n if (value != null) {\n String valueToCompare = value.toUpperCase();\n for (PartType current : PartType.values()) {\n if (current.value.equals(valueToCompare)) {\n return current;\n }\n }\n }\n return UNDEFINED;\n }\n }\n\n private int modelLevel;\n private String partNumber;\n private String name;\n private Serviceability serviceability;\n private int quantity;\n private PartType partType;\n\n public Part(String[] values) {\n // TODO: sanity checking for desired number of columns\n setModelLevel(Integer.parseInt(values[0]));\n setPartNumber(values[1]);\n setName(values[2]);\n setServiceability(values[3]);\n setQuantity(Integer.parseInt(values[4]));\n setPartType(values[5]);\n }\n\n public int getModelLevel() {\n return modelLevel;\n }\n\n public void setModelLevel(int modelLevel) {\n this.modelLevel = modelLevel;\n }\n\n public String getPartNumber() {\n return partNumber;\n }\n\n public void setPartNumber(String partNumber) {\n // normalize to upper case\n this.partNumber = partNumber.toUpperCase();\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n // normalize to upper case\n this.name = name.toUpperCase();\n }\n\n public Serviceability getServiceability() {\n return serviceability;\n }\n\n public void setServiceability(Serviceability serviceability) {\n this.serviceability = serviceability;\n }\n\n public void setServiceability(String serviceability) {\n this.serviceability = Serviceability.fromValue(serviceability);\n }\n\n public int getQuantity() {\n return quantity;\n }\n\n public void setQuantity(int quantity) {\n this.quantity = quantity;\n }\n\n public PartType getPartType() {\n return partType;\n }\n\n public void setPartType(PartType partType) {\n this.partType = partType;\n }\n\n public void setPartType(String partType) {\n this.partType = PartType.fromValue(partType);\n }\n\n public boolean isTopLevelPart() {\n return modelLevel == 2;\n }\n\n public boolean hasPartNumberContains(String value) {\n return partNumber.contains(value);\n }\n\n public boolean isServiceable() {\n return serviceability == Serviceability.SERVICEABLE;\n }\n\n public String toString() {\n return modelLevel + \" | \" + partNumber + \" | \" + name + \" | \" + serviceability + \" | \" + quantity + \" | \"\n + partType;\n }\n}\n</code></pre>\n\n<p>I used two <code>Enums</code> to represent valid values for serviceability and part type, in case I need to compare these values often and I want to avoid any typos in doing <code>String</code> comparisons. I also normalize String inputs to upper case for this exercise. By right, I can also have a <code>PartFactory</code> class to take in the six <code>String</code> inputs and construct a <code>Part</code> for me, but I have decided to keep it simple and just implemented a constructor for this purpose. Feel free to add useful methods that is related to a <code>Part</code> and will aid in your work here, for example I have the <code>isTopLevelPart</code> method that will return <code>true</code> if the model number is 2.</p>\n\n<pre><code>package com.myproject.se;\n\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\n\npublic class PartList implements Iterable<Part> {\n private List<Part> partList = new ArrayList<Part>();\n\n public PartList(Part part) {\n addPart(part);\n }\n\n public void addPart(Part part) {\n // simple constraint\n if (partList.isEmpty() && !part.isTopLevelPart()) {\n throw new RuntimeException(\"This is not a top-level part.\");\n }\n partList.add(part);\n }\n\n @Override\n public Iterator<Part> iterator() {\n return partList.iterator();\n }\n\n public Part getTopLevelPart() {\n return partList.get(0);\n }\n\n public int size() {\n return partList.size();\n }\n\n public List<Part> getServiceableParts() {\n List<Part> result = new ArrayList<Part>();\n for (Part part : partList) {\n if (part.isServiceable()) {\n result.add(part);\n }\n }\n return result;\n }\n}\n</code></pre>\n\n<p><code>PartList</code> is a simple wrapper class that stores <code>Part</code> objects in an <code>ArrayList</code>. The only enhancement I have added is a constraint on the first element of the <code>List</code>, which must be a top-level part (see above). Other than that, feel free to once again introduce methods related to what a <code>PartList</code> should know, in my case here I added a simple <code>getServiceableParts</code> method for illustration.</p>\n\n<pre><code>package com.myproject.se;\n\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\n\npublic class RecordSupplier implements Iterable<Part>, Closeable {\n private static final List<String[]> testValues = new ArrayList<String[]>();\n\n static {\n testValues.add(new String[] { \"2\", \"ABC\", \"NAME 1\", \"\", \"1\", \"\" });\n testValues.add(new String[] { \"3\", \"DEF\", \"NAME 2\", \"SVCBLE\", \"2\", \"PART\" });\n testValues.add(new String[] { \"4\", \"GHI\", \"NAME 3\", \"NOT SVC\", \"3\", \"ASSEMBLY\" });\n testValues.add(new String[] { \"2\", \"JKL\", \"NAME 4\", \"\", \"1\", \"\" });\n testValues.add(new String[] { \"3\", \"MNO\", \"NAME 5\", \"SVCBLE\", \"5\", \"PART\" });\n }\n\n @Override\n public void close() throws IOException {\n // do nothing\n }\n\n @Override\n public Iterator<Part> iterator() {\n return new Iterator<Part>() {\n private Iterator<String[]> innerIterator = testValues.iterator();\n\n @Override\n public boolean hasNext() {\n return innerIterator.hasNext();\n }\n @Override\n public Part next() {\n return new Part(innerIterator.next());\n }\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n }\n };\n }\n\n}\n</code></pre>\n\n<p>I needed a mock class here to simulate a <code>CSVReader</code>, so here's a <code>RecordSupplier</code> using the iteration pattern of providing input. What is crucial to note here is that <code>RecordSupplier</code>, or more specifically its <code>iterator</code>, supplies <code>Part</code> objects, instead of a <code>String</code> array. Generally, you will want a well-behaved input provider that passes only types that can appropriately encapsulate the raw underlying values to caller methods that need the data. The other minor benefit of wrapping your <code>CSVReader</code> in such a class is that you can easily replace the actual input in the future by a database, or XML file reader etc, and all the caller methods see are still <code>Part</code> objects.</p>\n\n<pre><code>package com.myproject.se;\n\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Scanner;\n\npublic class Main {\n\n public static void main(String[] args) {\n @SuppressWarnings(\"unused\")\n Scanner scanner = new Scanner(System.in);\n String partNumber1;\n String partNumber2;\n System.out.println(\"Enter first part number:\");\n // partNumber1 = scanner.next();\n partNumber1 = \"JKL\";\n System.out.println(\"Enter second part number:\");\n // partNumber2 = scanner.next();\n partNumber2 = \"ABC\";\n Map<String, PartList> result = getPartLists(partNumber1, partNumber2);\n for (Entry<String, PartList> entry : result.entrySet()) {\n System.out.println(\"Part number search term: \" + entry.getKey());\n Iterator<Part> iterator = entry.getValue().iterator();\n while (iterator.hasNext()) {\n System.out.println(iterator.next());\n }\n System.out.println(\"====================\");\n }\n }\n\n public static Map<String, PartList> getPartLists(String... partNumbers) {\n // only searching for two parts now, easily extensible\n if (partNumbers.length != 2) {\n throw new RuntimeException(\"Only two part numbers needed.\");\n }\n Map<String, PartList> result = new HashMap<String, PartList>();\n RecordSupplier supplier = new RecordSupplier();\n Iterator<Part> iterator = supplier.iterator();\n PartList partList = null;\n while (iterator.hasNext()) {\n Part part = iterator.next();\n if (part.isTopLevelPart()) {\n String match = partNumberMatches(part, partNumbers);\n if (match.isEmpty()) {\n partList = null;\n } else {\n // match belongs to a new PartList\n partList = new PartList(part);\n // add the new PartList to result\n result.put(match, partList);\n }\n } else if (partList != null) {\n // keep adding current Part to existing PartList\n partList.addPart(part);\n }\n }\n try {\n supplier.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n // returning just a List of PartList should be good enough actually\n return result;\n }\n\n public static String partNumberMatches(Part part, String... partNumbers) {\n for (String partNumber : partNumbers) {\n if (part.hasPartNumberContains(partNumber)) {\n return partNumber;\n }\n }\n return \"\";\n }\n}\n</code></pre>\n\n<p>Finally, the main class. I have commented out the parts that read in user input (see the use of the <code>Scanner</code> class) and hard-coded two test values. The bulk of the work is done in <code>getPartLists</code>.</p>\n\n<pre><code>Map<String, PartList> result = new HashMap<String, PartList>();\nRecordSupplier supplier = new RecordSupplier();\nIterator<Part> iterator = supplier.iterator();\nPartList partList = null;\n</code></pre>\n\n<p>Create our <code>result</code> object and the <code>RecordSupplier</code>.</p>\n\n<pre><code>while (iterator.hasNext()) {\n Part part = iterator.next();\n</code></pre>\n\n<p>Get a <code>Part</code> object representing the current row.</p>\n\n<pre><code> if (part.isTopLevelPart()) {\n String match = partNumberMatches(part, partNumbers);\n</code></pre>\n\n<p>If this is a top-level part, check if it matches our inputs or not (I think <code>partNumberMatches</code> is pretty self-explanatory and will not go there).</p>\n\n<pre><code> if (match.isEmpty()) {\n partList = null;\n</code></pre>\n\n<p>If there is no match, we set our <code>partList</code> to <code>null</code>, using this as some sort of a flag afterwards to know we are ignoring subsequent lines until the next top-level part.</p>\n\n<pre><code> } else {\n // match belongs to a new PartList\n partList = new PartList(part);\n // add the new PartList to result\n result.put(match, partList);\n }\n</code></pre>\n\n<p>We have a match, lets set <code>partList</code> as a new <code>PartList</code> with this top-level part and add it to our <code>result</code>.</p>\n\n<pre><code> } else if (partList != null) {\n // keep adding current Part to existing PartList\n partList.addPart(part);\n }\n}\n</code></pre>\n\n<p>For other non-top-level parts, we will just check if <code>partList</code> is <code>null</code> or not. If it isn't, it means we have just matched a top-level part to our inputs and we need to add the current part to <code>partList</code>.</p>\n\n<p>Implicit assumptions:</p>\n\n<ol>\n<li>We are only matching part number names with the second column, <code>Part Number Breakdown</code> (see <code>partNumberMatches</code> and <code>Part.hasPartNumberContains</code>)</li>\n<li>One top-level part will only match one input.</li>\n</ol>\n\n<p>I hope this is informative enough...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T21:17:03.167",
"Id": "46237",
"Score": "0",
"body": "I am impressed. +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T03:21:23.773",
"Id": "46248",
"Score": "1",
"body": "Probably one of the most useful suggestions I have seen in a long time. Very well written and orgainized. Very thorough. Good job. +1"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T19:18:56.020",
"Id": "29285",
"ParentId": "29191",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "29285",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T17:39:57.037",
"Id": "29191",
"Score": "7",
"Tags": [
"java",
"object-oriented",
"csv"
],
"Title": "Intern with no mentor struggling with refactoring and OOP"
}
|
29191
|
<p>We are working to translate our site into different languages. Currently, we pull 80% of a page from a database that is already translated. We drop in a language id and output the appropriate content. </p>
<p>What I need to store and access are the bits and pieces of text that need to appear on every page, but won't be stored in a database. For example, a save button might say "click to save" in English, or "clique acqui" in French, or "clicken zie here" in German. </p>
<p>We might have 10 - 20 different pages (templates) on our site that will require this hard coded translated text. There might be 20 - 40 bits of text on a single page that need to be output into any of ten languages.</p>
<p>My solution is to create a global array (or structure) that contains all of the text pieces in different languages. We will populate the array with hard coded strings. When a person changes their language id, we will just access a different part of the array and output the appropriate text.</p>
<p>Below, I have a working page that that enables you to toggle your language and access different text pieces. </p>
<p>My question is, is there a major pitfall I am overlooking or is there an easier way to get this done? </p>
<pre><code><html>
<head>
<title>EJ's Test Page</title>
<!--- JQUERY --->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<cfscript>
// SET LANGUAGE
if (structKeyExists(FORM, "LanguageID")) {
LanguageID = FORM.LanguageID;
} else {
LanguageID = 1;
}
</cfscript>
<form method="post">
<select name="LanguageID" onchange="javascript:form.submit();">
<option value="1" <cfif LanguageID eq 1>selected="selected"</cfif> >American</option>
<option value="2" <cfif LanguageID eq 2>selected="selected"</cfif> >German</option>
<option value="3" <cfif LanguageID eq 3>selected="selected"</cfif> >French</option>
</select>
</form>
<cfscript>
// GET PAGE CONTENT
PageContent = getPageContent(LanguageID);
</cfscript>
<cfoutput>
<h1>#PageContent.Text1#</h1>
<p><b>#PageContent.Text3#</b> - #PageContent.Text4#</p>
<button id="MyButton">#PageContent.Text2#</button>
</cfoutput>
<!--- GET PAGE CONTENT --->
<cffunction name="getPageContent">
<cfscript>
makeLanguageArray();
PC = APPLICATION.PageContent[LanguageID];
return PC;
</cfscript>
</cffunction>
<!--- MAKE LANGUAGE ARRAY --->
<cffunction name="makeLanguageArray">
<cfscript>
if (not structKeyExists(APPLICATION, "PageContent")) {
APPLICATION.PageContent = structNew();
// ENGLISH
i = 1;
APPLICATION.PageContent[i] = structNew();
APPLICATION.PageContent[i].Text1 = "What a fine day!";
APPLICATION.PageContent[i].Text2 = "The flowers are in bloom.";
APPLICATION.PageContent[i].Text3 = "Follow the money";
APPLICATION.PageContent[i].Text4 = "Save to List";
// GERMAN
i++;
APPLICATION.PageContent[i] = structNew();
APPLICATION.PageContent[i].Text1 = "Einen Augenblick, bitte!";
APPLICATION.PageContent[i].Text2 = "Wie teuer ist das?";
APPLICATION.PageContent[i].Text3 = "Kommen Sie mit!";
APPLICATION.PageContent[i].Text4 = "Gute Nacht!";
// FRENCH
i++;
APPLICATION.PageContent[i] = structNew();
APPLICATION.PageContent[i].Text1 = "Je ne l'ai pas fait intentionnellement.";
APPLICATION.PageContent[i].Text2 = "C’est lui l’agresseur.";
APPLICATION.PageContent[i].Text3 = "Je viens d’être victime de vol.";
APPLICATION.PageContent[i].Text4 = "Ce n’est pas ma faute.";
}
</cfscript>
</cffunction>
<script>
<cfoutput>
var ButtonText = '#PageContent.Text4#';
</cfoutput>
$MyButton = $("#MyButton");
throwAlert = function() {
alert(ButtonText);
}
$MyButton.click(throwAlert);
</script>
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T05:24:18.017",
"Id": "62421",
"Score": "0",
"body": "There are several i18n packages out there.\n\nhttps://github.com/jmohler1970/PHP-Language-File-in-ColdFusion\n\nis one of them.\n\n**Disclaimer:** I wrote it"
}
] |
[
{
"body": "<p>You could create a language layer and the code only knows the reference. PHPBB has a good example of this in their templating system.</p>\n\n<p>That way the button on a form, for example, is always something like template_var['login']. There is a replace going on based on a language pack file. The user selected preferences define which language pack to use. In the end you're just dumping the language file definition into a template variable that never changes. </p>\n\n<p>This route might be easier to manage than an huge structure that keeps growing as you expand?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T20:06:36.953",
"Id": "29201",
"ParentId": "29197",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T19:17:27.577",
"Id": "29197",
"Score": "0",
"Tags": [
"i18n",
"coldfusion",
"cfml"
],
"Title": "How to store and access translated language text pieces?"
}
|
29197
|
<p>I created this small function just to practice C code. It's a simple random string generator.</p>
<pre><code>#include <string.h>
#include <time.h>
char *randstring(int length) {
static int mySeed = 25011984;
char *string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.-#'?!";
size_t stringLen = strlen(string);
char *randomString = NULL;
srand(time(NULL) * length + ++mySeed);
if (length < 1) {
length = 1;
}
randomString = malloc(sizeof(char) * (length +1));
if (randomString) {
short key = 0;
for (int n = 0;n < length;n++) {
key = rand() % stringLen;
randomString[n] = string[key];
}
randomString[length] = '\0';
return randomString;
}
else {
printf("No memory");
exit(1);
}
}
</code></pre>
<p>The code seems to work ok.
Any ideas, improvements or bugs?</p>
<p>I added the <code>mySeed</code> var so that if I call it twice with the same length it doesn't give me the same exact string.</p>
<p><strong>EDIT:</strong></p>
<p>I have changed the code to this:</p>
<pre><code>char *randstring(size_t length) {
static char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.-#'?!";
char *randomString = NULL;
if (length) {
randomString = malloc(sizeof(char) * (length +1));
if (randomString) {
for (int n = 0;n < length;n++) {
int key = rand() % (int)(sizeof(charset) -1);
randomString[n] = charset[key];
}
randomString[length] = '\0';
}
}
return randomString;
}
</code></pre>
<p>I know that in the <code>sizeof(charset)</code> you don't have to use the <code>()</code>. You only need them when using sizeof with types, but it's just out of habit.</p>
|
[] |
[
{
"body": "<p>the code doesn't look that wrong, but</p>\n\n<ul>\n<li>the caller should allways check for errors</li>\n<li><code>if (length < 1)</code> test unnecessary</li>\n<li><code>srand(time(NULL)</code> should be done outside</li>\n<li>error catching (<code>malloc</code>) should open no new block</li>\n<li><code>short</code> isn't really at the high of the time, use it only for serilizing/deserilizing raw binary files/network data</li>\n<li>use <code>unsigned</code> if it makes sense, <strong>the counter can't be negative</strong> and this is not lala-java-land (besides it can be a bit faster but most times it doesn't matter) (side note, yes i am damaged from looking at the assembler output of the compilers)</li>\n<li><p>you don't need to recalculate the <code>string</code> length everytime, with <em>C++0x</em> you can maybe let it calculate from the compiler on compiletime</p>\n\n<pre><code>#include <string.h>\n#include <time.h>\n\nchar *randstring(int length) { \n char *string = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.-#'?!\";\n size_t stringLen = 26*2+10+7; \n char *randomString;\n\n randomString = malloc(sizeof(char) * (length +1));\n\n if (!randomString) {\n return (char*)0;\n }\n\n unsigned int key = 0;\n\n for (int n = 0;n < length;n++) { \n key = rand() % stringLen; \n randomString[n] = string[key];\n }\n\n randomString[length] = '\\0';\n\n return randomString;\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T20:01:49.890",
"Id": "46080",
"Score": "0",
"body": "The `unsigned` (`size_t` to be more specific) applies to the `size` parameter as well."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T19:56:28.093",
"Id": "29199",
"ParentId": "29198",
"Score": "3"
}
},
{
"body": "<p>Your function is nice but has a few issues, the main one being that it\n should not call <code>srand</code>. <code>srand</code> should be called elsewhere (eg in <code>main</code>)\n just once. This seeds the random number generator, which need only be done\n once.</p>\n\n<p>A minor issue is that <code>string</code> is badly named - <code>charset</code> might be better.\n It should be <code>const</code> and you then need not call <code>strlen</code> to find its length\n <code>sizeof charset -1</code> is enough. For me, randomString is an unnecessarily\n long name.</p>\n\n<p>On failing to allocate memory for the string, I would prefer to see a NULL\n return than an <code>exit</code>. If you want an error message, use <code>perror</code>, but\n perhaps in the caller, not here. I would be inclined to avoid the\n possibility of such an error but passing in the buffer and its length\n instead of allocating.</p>\n\n<p>Some minor points: sizeof(char) is 1 by definition and using <code>short</code> for\n <code>key</code> is pointless - just use <code>int</code>. Also <code>key</code> should be defined where it\n is used and I would leave a space after the ; in the for loop definition.</p>\n\n<p>Note also that using <code>rand() % n</code> assumes that the modulo division\n is random - that is not what <code>rand</code> promises.</p>\n\n<p>Here is how I might do it:</p>\n\n<pre><code>static char *rand_string(char *str, size_t size)\n{\n const char charset[] = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJK...\";\n if (size) {\n --size;\n for (size_t n = 0; n < size; n++) {\n int key = rand() % (int) (sizeof charset - 1);\n str[n] = charset[key];\n }\n str[size] = '\\0';\n }\n return str;\n}\n</code></pre>\n\n<p><strong>Edit</strong> July 31 23:07UTC</p>\n\n<p>Why would I write the function to take a buffer instead of allocating the\nstring inside the function? </p>\n\n<p>Returning dynamically allocated strings works fine. And if the memory is\nlater freed there is no problem. But writing this sort of function is a great\nway to leak memory, for example if the caller doesn't know the memory must be\nfreed or forgets to free memory, or even if he frees it in the main path but\nforgets to free it in other paths etc.</p>\n\n<p>Memory leaks in a desktop applications might not be fatal, but leaks in an\nembedded system will lead eventually to failure. This can be serious,\ndepending upon the system involved. In many embedded systems, dynamic\nallocation is often not allowed or is at least best avoided.</p>\n\n<p>Although it certainly is common <strong>not</strong> to know the size of strings or buffers\nat compile time, the opposite is also often true. It is often possible to\nwrite code with fixed buffer sizes. I always prefer this option if possible\nso I would be reluctant to use your allocating function. Perhaps it is better\nto add a wrapper to a non-allocating function for those cases where you really\nmust allocate dynamically (for example when the random string has to outlive the calling context):</p>\n\n<pre><code>char* rand_string_alloc(size_t size)\n{\n char *s = malloc(size + 1);\n if (s) {\n rand_string(s, size);\n }\n return s;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T20:09:48.337",
"Id": "46082",
"Score": "0",
"body": "note that you don't need to return any result because the str parameter is mutable"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T20:12:20.077",
"Id": "46083",
"Score": "1",
"body": "That is true but many standard library functions do this too. It can make life easier, eg in `printf(\"%s\\n\", rand_string(buf, sizeof buf));`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T20:17:14.803",
"Id": "46084",
"Score": "0",
"body": "your right, if you speak of easy life you grab c++,java,go,python,haskell,ruby or d unless your really need the last 100%-20% performance or your forced to use c"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T00:50:33.613",
"Id": "46093",
"Score": "1",
"body": "The questioner is asking specifically about C, not C++, not Java, not go, python etc. Thanks for your input."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T20:56:24.817",
"Id": "46182",
"Score": "0",
"body": "@WilliamMorris Could you provide some more insight on why you pass the buffer and not just create the buffer in the string with malloc and return it? Is it because this way it would be easier to free the memory? Is it not possible to free the returned pointer? Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T00:09:25.570",
"Id": "46188",
"Score": "0",
"body": "Added some notes to my answer on allocating vs passing a buffer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-02-02T13:14:55.097",
"Id": "356019",
"Score": "0",
"body": "Just to point out (I'm sure you know, but you didn't make it explicit), `sizeof charset` works for `const char charset[]` but is wrong for `const char *charset`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T20:26:16.177",
"Id": "387160",
"Score": "0",
"body": "On the note of using `int`, everywhere you use `int` you include the possibility that a compiler for a given architecture might introduce sign handling overhead... probably best to use `size_t` for things like sizes or indexes of arrays. It'll all end up in a register, at the end of the day anyway, but this way it might end up in a *better* register in some cases."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T19:56:37.863",
"Id": "29200",
"ParentId": "29198",
"Score": "12"
}
},
{
"body": "<p>Wanted to also give a small input. I had to implement a very similar function for a project of mine. I can't disclose the algorithm, however. But let me try to give you a couple small hints as to how you could further improve yours. I'm foremost concerned with stability and performance (low latency and high throughput) of code.</p>\n\n<p>Let's start with this (profiled for a <strong>1024-byte long string for 10,000 iterations</strong> with gprof):</p>\n\n<pre><code>Each sample counts as 0.01 seconds.\n % cumulative self self total \n time seconds seconds calls us/call us/call name \n 67.16 0.02 0.02 10000 2.01 2.01 randstring\n 33.58 0.03 0.01 10000 1.01 1.01 mkrndstr\n 0.00 0.03 0.00 10000 1.01 1.01 mkrndstrperf\n</code></pre>\n\n<p>The difference is here really thin as on a few repetitions gprof gives random data, so let's take callgrind instead.</p>\n\n<p>The total cost is then more precisely calculated in function calls:</p>\n\n<pre><code> 7,986,402,268 ???:randstring [~perf/t/mkrndstr-notmine]\n 6,655,222,307 ???:mkrndstr [~perf/t/mkrndstr-notmine]\n 6,653,436,779 ???:mkrndstr_ipa [~perf/t/mkrndstr-notmine]\n 6,653,436,778 ???:mkrndstr_ipd [~perf/t/mkrndstr-notmine]\n</code></pre>\n\n<p>For a <strong>10-byte long string and 10,000 calls</strong>, the relative difference is even bigger:</p>\n\n<pre><code> 9,968,042 ???:randstring [~perf/t/mkrndstr-notmine]\n 8,646,775 ???:mkrndstr [~perf/t/mkrndstr-notmine]\n 6,716,774 ???:mkrndstr_ipa [~perf/t/mkrndstr-notmine]\n 6,716,774 ???:mkrndstr_ipd [~perf/t/mkrndstr-notmine]\n</code></pre>\n\n<p>Here, <code>mkrndstr_ip{a,d}</code> means: in-place for automatically stored and dynamically stored data (different calls, identical functions), respectively.</p>\n\n<hr>\n\n<p>Some key take-aways beforehand:</p>\n\n<ol>\n<li><p>down-casting</p>\n\n<pre><code>size_t l = (sizeof(charset) -1); // uncast\n</code></pre>\n\n<p>versus</p>\n\n<pre><code>int l = (int)(sizeof(charset) -1); // cast to int as suggested in William Morris' reply\n</code></pre>\n\n<p>makes on that scale a big difference--you avoid passing around loads of superfluous bytes.</p></li>\n<li><p>The static set of chars is a good idea, saves many cycles and calls, I'd prefix it with a const qualifier.</p></li>\n<li><p>It's a bad idea to do per-cycle/per-iteration instantiations and identical calculations for the same reasons as in 2 above, make the value, loosely speaking, sticky as Quonux demonstrates it.</p></li>\n<li><p>Considering randomness. I guess you know libc's <code>rand()</code> is an implementation of a PRNG. It's useless for anything serious. If your code gets executed too quickly, i.e., when there's too little interval between any two successive calls to <code>rand()</code>, you'll get the same character from the set. So make sure to pause for a couple CPU cycles. You could also simply read chunks from <code>/dev/urandom</code> (with the <code>u</code> prefix, otherwise my \"simply\" wouldn't hold) or similar on a UNIX derivative. Don't know how to access the random device on Windows.</p></li>\n<li><p><code>strlen</code> is indeed slower than <code>sizeof</code> for clear reasons (expects complex strings), see the implementation in glibc sources, for example, in <code>string/strlen.c</code>.</p></li>\n<li><p>The rest is in the comments.</p></li>\n</ol>\n\n<hr>\n\n<p>Let's get to the code:</p>\n\n<ol>\n<li><p><strong>Yours, final</strong>:</p>\n\n<pre><code>char *randstring(size_t length) { // length should be qualified as const if you follow a rigorous standard\n\nstatic char charset[] = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.-#'?!\"; \nchar *randomString; // initializing to NULL isn't necessary as malloc() returns NULL if it couldn't allocate memory as requested\n\nif (length) {\n randomString = malloc(length +1); // I removed your `sizeof(char) * (length +1)` as sizeof(char) == 1, cf. C99\n\n if (randomString) { \n for (int n = 0;n < length;n++) { \n int key = rand() % (int) (sizeof(charset) -1);\n randomString[n] = charset[key];\n }\n\n randomString[length] = '\\0';\n }\n}\n\nreturn randomString;\n}\n</code></pre></li>\n<li><p><strong>Mine</strong> (only slight optimizations):</p>\n\n<pre><code>char *mkrndstr(size_t length) { // const size_t length, supra\n\nstatic char charset[] = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.-#'?!\"; // could be const\nchar *randomString;\n\nif (length) {\n randomString = malloc(length +1); // sizeof(char) == 1, cf. C99\n\n if (randomString) {\n int l = (int) (sizeof(charset) -1); // (static/global, could be const or #define SZ, would be even better)\n int key; // one-time instantiation (static/global would be even better)\n for (int n = 0;n < length;n++) { \n key = rand() % l; // no instantiation, just assignment, no overhead from sizeof\n randomString[n] = charset[key];\n }\n\n randomString[length] = '\\0';\n }\n}\n\nreturn randomString;\n}\n</code></pre></li>\n<li><p>Now considering your question regarding <strong>dynamic versus automatic data storage</strong>:</p>\n\n<pre><code>void mkrndstr_ipa(size_t length, char *randomString) { // const size_t length, supra\n\nstatic char charset[] = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.-#'?!\";\n\nif (length) {\n if (randomString) {\n int l = (int) (sizeof(charset) -1);\n for (int n = 0;n < length;n++) {\n int key = rand() % l; // per-iteration instantiation\n randomString[n] = charset[key];\n }\n\n randomString[length] = '\\0';\n }\n}\n}\n</code></pre>\n\n<p>There's also an identical function with the modified name as stated way above. Both are called like this:</p>\n\n<pre><code>char *c = malloc(SZ_STR +1); // dynamic, in C on the heap\nchar d[SZ_STR +1]; // \"automatic,\" in C on the stack\nmkrndstr_ipd(SZ_STR, c);\nmkrndstr_ipa(SZ_STR, d);\n</code></pre>\n\n<ol>\n<li><a href=\"https://stackoverflow.com/a/6500497/2579089\">Here's a short note on memory allocation in C++</a></li>\n<li><a href=\"https://stackoverflow.com/a/662454/2579089\">Here's a more visual note</a></li>\n</ol></li>\n</ol>\n\n<hr>\n\n<p>Now the more interesting part:</p>\n\n<pre><code> .globl randstring\n .type randstring, @function\nrandstring:\n.LFB0:\n .cfi_startproc\n pushq %rbp\n .cfi_def_cfa_offset 16\n .cfi_offset 6, -16\n movq %rsp, %rbp\n .cfi_def_cfa_register 6\n pushq %rbx\n subq $40, %rsp\n .cfi_offset 3, -24\n call mcount\n movq %rdi, -40(%rbp)\n cmpq $0, -40(%rbp)\n je .L2\n movq -40(%rbp), %rax\n addq $1, %rax\n movq %rax, %rdi\n call malloc\n movq %rax, -24(%rbp)\n cmpq $0, -24(%rbp)\n je .L2\n movl $0, -28(%rbp)\n jmp .L3\n.L4:\n call rand\n movl %eax, %ecx\n movl $1991868891, %edx\n movl %ecx, %eax\n imull %edx\n sarl $5, %edx\n movl %ecx, %eax\n sarl $31, %eax\n movl %edx, %ebx\n subl %eax, %ebx\n movl %ebx, %eax\n movl %eax, -32(%rbp)\n movl -32(%rbp), %eax\n imull $69, %eax, %eax\n movl %ecx, %edx\n subl %eax, %edx\n movl %edx, %eax\n movl %eax, -32(%rbp)\n movl -28(%rbp), %eax\n movslq %eax, %rdx\n movq -24(%rbp), %rax\n addq %rax, %rdx\n movl -32(%rbp), %eax\n cltq\n movzbl charset.1808(%rax), %eax\n movb %al, (%rdx)\n addl $1, -28(%rbp)\n.L3:\n movl -28(%rbp), %eax\n cltq\n cmpq -40(%rbp), %rax\n jb .L4\n movq -40(%rbp), %rax\n movq -24(%rbp), %rdx\n addq %rdx, %rax\n movb $0, (%rax)\n.L2:\n movq -24(%rbp), %rax\n addq $40, %rsp\n popq %rbx\n popq %rbp\n .cfi_def_cfa 7, 8\n ret\n .cfi_endproc\n.LFE0:\n .size randstring, .-randstring\n</code></pre>\n\n<p>compared with:</p>\n\n<pre><code> .globl mkrndstr\n .type mkrndstr, @function\nmkrndstr:\n.LFB1:\n .cfi_startproc\n pushq %rbp\n .cfi_def_cfa_offset 16\n .cfi_offset 6, -16\n movq %rsp, %rbp\n .cfi_def_cfa_register 6\n subq $48, %rsp\n call mcount\n movq %rdi, -40(%rbp)\n cmpq $0, -40(%rbp)\n je .L7\n movq -40(%rbp), %rax\n addq $1, %rax\n movq %rax, %rdi\n call malloc\n movq %rax, -8(%rbp)\n cmpq $0, -8(%rbp)\n je .L7\n movl $69, -16(%rbp)\n movl $0, -12(%rbp)\n jmp .L8\n.L9:\n call rand\n movl %eax, %edx\n sarl $31, %edx\n idivl -16(%rbp)\n movl %edx, -20(%rbp)\n movl -12(%rbp), %eax\n movslq %eax, %rdx\n movq -8(%rbp), %rax\n addq %rax, %rdx\n movl -20(%rbp), %eax\n cltq\n movzbl charset.1818(%rax), %eax\n movb %al, (%rdx)\n addl $1, -12(%rbp)\n.L8:\n movl -12(%rbp), %eax\n cltq\n cmpq -40(%rbp), %rax\n jb .L9\n movq -40(%rbp), %rax\n movq -8(%rbp), %rdx\n addq %rdx, %rax\n movb $0, (%rax)\n.L7:\n movq -8(%rbp), %rax\n leave\n .cfi_def_cfa 7, 8\n ret\n .cfi_endproc\n.LFE1:\n .size mkrndstr, .-mkrndstr\n</code></pre>\n\n<p>I believe an interpretation is not necessary here, the disassembly is then only for visualisation. Compare the different number of instructions.</p>\n\n<p>What I wanted to show is that just a couple of tiny nip'n'tucks does wonders. We sure could go memmove the string into an external buffer at a fixed address or do n-byte-wise assignments. We could also put the set in a macro or use even more static allocation. But let's not exaggerate and go write this outright in ASM, and when we'd be done with it, do the same in pure machine code.</p>\n\n<p>I hope this helps and if it's not a real-time system, then don't do much hassle with the optimizations, stability and reliability (like <code>rand()</code>) should go first. If you optimize this and that out, something else somewhere else could break. There are a few open-source projects online that show how to optimize excessively but at the cost of an unmaintanable code for newcomers to their teams and sheer complexity for the more accustomed developers.</p>\n\n<p>Last thing I'd like to point you at is that </p>\n\n<blockquote>\n <p>error: ‘for’ loop initial declarations are only allowed in C99 mode</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T01:38:31.480",
"Id": "46306",
"Score": "1",
"body": "I would not expect either putting the size into a variable or defining the `key` variable outside the loop to make any difference. The compiler can optimise this away. With `gcc` using `-O2` the two functions (randstring, mkrndstr) give identical assembler. The same is true of `clang`. How are you compiling (which compiler/options)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T16:28:02.897",
"Id": "46336",
"Score": "0",
"body": "Wow. Thanks for such an in-depth analysis of my code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T12:59:53.970",
"Id": "46377",
"Score": "0",
"body": "@William: I generally test performance without any compiler optimizations. `-O2`, in my opinion, does not always produce stable binaries, it's more about compatibility of your code and the optimizations specified to the compiler. That was an assembly by `gcc`. Besides, not always do I run my code on x86 machines, so it may differ again. When I do fine-tuning, I manually pick optimizations instead of the predefined bundles. I prefer to get my code as I want it instead of trusting some compiler that it would improve it. By the way, this also applies to interpreted languages like Perl and Python."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T13:05:08.600",
"Id": "46378",
"Score": "0",
"body": "@Antonio: hope you'll find even more ways to improve your code, there really is always room for improvement, for everyone, at any step in your program. You never stop learning -- that's what I love most about programming."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T19:31:37.867",
"Id": "46402",
"Score": "2",
"body": "The thing is, code that looks shorter in assembly is not necessarily quicker. Your optimisation of moving the size of the character set to a variable causes the compiler (gcc on IA32) to emit an `idiv` instruction instead of using its most efficient method of dividing by `sizeof charset - 1` (69). Testing just this division with gcc on OS-X and Linux, your code, which uses `idiv`, is shorter but takes twice as long. With -O2 and with or without a separate variable for the size, the code is shorter still and takes a quarter of the time of the unoptimised `idiv` code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T19:39:14.617",
"Id": "46403",
"Score": "2",
"body": "@AntinioCS, note that worrying about performance of any particular function is best avoided unless you find you have performance problems. In that case you should find the performance bottlenecks and optimise just those."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T18:50:46.633",
"Id": "29276",
"ParentId": "29198",
"Score": "5"
}
},
{
"body": "<p>There is one problem with this code: it doesn't generate a random string each time the program is run. The code is missing <code>srand(time(0));</code>. The <code>srand()</code> function sets the starting point for producing a series of pseudo-random integers. If <code>srand()</code> is not called, the <code>rand()</code> seed is set as if <code>srand(1)</code> were called at program start. Any other value for seed sets the generator to a different starting point.</p>\n\n<p>For more details, read <a href=\"https://www.geeksforgeeks.org/rand-and-srand-in-ccpp/\" rel=\"nofollow noreferrer\"><strong>rand() and srand() in C/C++</strong></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-02-09T14:15:07.817",
"Id": "357149",
"Score": "0",
"body": "[As William Morris points out](/a/29200) (first paragraph), it does call `srand()` - unfortunately it does so on each call of the function, rather than once in the `main()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-02-09T15:31:44.597",
"Id": "357172",
"Score": "0",
"body": "Yeah William pointed that out, and it doesn't need to call `srand()` every function call once in `main()` is fine."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-02-07T16:02:11.410",
"Id": "187019",
"ParentId": "29198",
"Score": "0"
}
},
{
"body": "<p>I have a suggestion. It's ok to use a charset but I would recommend using ASCII values to save some memory (not that it matters too much). You can check out ASCII values here, for example, <a href=\"https://www.asciitable.com/\" rel=\"nofollow noreferrer\">https://www.asciitable.com/</a> and then you set the interval of numbers you want. In the example below I will use 32-126. Also, as it was already said, you should call <code>srand</code> on <code>main</code> or something, since it should be called only once.</p>\n\n<p>What I mean is something like:</p>\n\n<pre><code>#define ASCII_START 32\n#define ASCII_END 126\n\nchar* generateRandomString(int size) {\n int i;\n char *res = malloc(size + 1);\n for(i = 0; i < size; i++) {\n res[i] = (char) (rand()%(ASCII_END-ASCII_START))+ASCII_START;\n }\n res[i] = '\\0';\n return res;\n}\n//srand is not visible, as I said it could be on main.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-05-14T18:27:55.467",
"Id": "194388",
"ParentId": "29198",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "29200",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T19:30:21.933",
"Id": "29198",
"Score": "9",
"Tags": [
"c",
"strings",
"random",
"generator"
],
"Title": "Random String generator in C"
}
|
29198
|
<p>I have two solutions (in Jython) to take two pictures and copy and paste alternate sections of one picture to the other, like so:</p>
<p><img src="https://i.stack.imgur.com/dp427.png" alt="pic1"><img src="https://i.stack.imgur.com/BJlty.png" alt="pic2"><img src="https://i.stack.imgur.com/XihbZ.jpg" alt="newpic"></p>
<pre><code>for x in range (0,w):
for y in range (0,h):
sourcePx=getPixel(pic1,x,y)
targetPx=getPixel(pic2,x,y)
if (y>=0 and y<20) or (y>=40 and y<60)or (y>=80 and y<=100):
setColor(targetPx, getColor(sourcePx))
repaint (pic2)
</code></pre>
<hr>
<pre><code>for y in range(0,h):
leaf = (y>=0 and y<20) or (y>=40 and y<60)or (y>=80 and y<=100):
if leaf:
for x in range(width):
sourcePx = getPixel(pic1, x, y)
targetPx = getPixel(pic2, x, y)
setColor(targetPx, getColor(sourcePx))
repaint(pic2)
</code></pre>
<hr>
<p>I have been trying to work this out and have two questions about this:</p>
<ol>
<li>Which is the more efficient way to loop through the pixels and why?</li>
<li>Does it make any difference to efficiency (and if so how), creating the variable leaf and then using that in the <code>if</code> statement?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T20:15:57.143",
"Id": "46180",
"Score": "3",
"body": "Minor point (not worth an answer): You an rewrite `(y>=0 and y<20)` to `0 <= y < 20`."
}
] |
[
{
"body": "<p>The second one is more efficient. Simply because in the first one you are calculating the <code>if</code> <code>w * h</code> times but in the second you are calculating it <code>h</code> times.</p>\n\n<p>Also it can be made more readable and efficient just by using this. It eliminates <code>leaf</code> which you aren't using anywhere. Readability doesn't need explaining. </p>\n\n<pre><code>for y in range(0,h):\n if (20 > y >= 0) or (60 > y >= 40)or (100 >= y >= 80):\n for x in range(width):\n sourcePx = getPixel(pic1, x, y)\n targetPx = getPixel(pic2, x, y)\n setColor(targetPx, getColor(sourcePx))\n repaint(pic2)\n</code></pre>\n\n<p><strong>Update 1</strong></p>\n\n<p>As limelights has suggested, use of <code>xrange</code> is better than use of <code>range</code> in Python2. If your <code>h</code> or <code>w</code> are big then using <code>range</code> would return a list which occupies memory while use of <code>xrange</code> returns a generator which is much more memory efficient. Performance might suffer a bit but in most cases it is worth it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T04:37:25.763",
"Id": "46100",
"Score": "0",
"body": "ty Aseem, yes I can see what you are saying about the loops, for some reason I can stare at something and it's like a brain jam and I can't figure out the simplest of concepts.. cheers"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T13:29:09.240",
"Id": "46130",
"Score": "0",
"body": "This could be optimised even further, just FYI. The use of `xrange()` for example if width is massive would speed the program up."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T13:30:48.353",
"Id": "46131",
"Score": "0",
"body": "@limelights I have been using Python 3 for some time and forgot that unless Python3 tag is used questions are about 2 not 3. I'll add that. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T21:39:18.960",
"Id": "46185",
"Score": "1",
"body": "Not worth an answer but... I would start it with `for y in range(20) + range(40, 60) + range(80, 100)` which seems cleaner than having an if condition."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T04:31:45.880",
"Id": "29207",
"ParentId": "29206",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29207",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T04:25:12.210",
"Id": "29206",
"Score": "2",
"Tags": [
"image",
"jython"
],
"Title": "Copying sections of one picture to another"
}
|
29206
|
<p>Here is my code for removing duplicated values from an array. I think I tested it with the most possible cases. Any suggestions or bugs? </p>
<pre><code>class duplicate {
public static int[] removeDuplicates(int[] arr) {
int end = arr.length;
for (int i = 0; i < end; i++) {
for (int j = i + 1; j < end; j++) {
if (arr[i] == arr[j]) {
int shiftLeft = j;
for(int k = j + 1; k < end; k++, shiftLeft++) {
arr[shiftLeft] = arr[k];
}
end--;
j--;
}
}
}
int[] whitelist = new int[end];
for (int i = 0; i < end; i++) {
whitelist[i] = arr[i];
}
return whitelist;
}
}
</code></pre>
<p>After some tests, it appears really inefficient because an array with 1,000,000 elements takes a very long time to end. Is there any better way to implement this on arrays?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T09:59:02.837",
"Id": "46113",
"Score": "2",
"body": "Use Set(Eg HashSet). Duplicate values are not allowed in it. Just iterate over the array and add it to the Set.If you want result in an array copy the set to the target array."
}
] |
[
{
"body": "<p>Suggestion: </p>\n\n<pre><code>public static Integer[] removeDuplicates(Integer[] arr) {\n return new HashSet<Integer>(Arrays.asList(arr)).toArray(new Integer[0]);\n}\n</code></pre>\n\n<p>Another solution might be:</p>\n\n<pre><code>public static int[] removeDuplicates(int[] arr) {\n Set<Integer> alreadyPresent = new HashSet<Integer>();\n int[] whitelist = new int[0];\n\n for (int nextElem : arr) {\n if (!alreadyPresent.contains(nextElem)) {\n whitelist = Arrays.copyOf(whitelist, whitelist.length + 1);\n whitelist[whitelist.length - 1] = nextElem;\n alreadyPresent.add(nextElem);\n }\n }\n\n return whitelist;\n}\n</code></pre>\n\n<p>Here you only iterate once via <code>arr</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T11:26:38.610",
"Id": "46118",
"Score": "1",
"body": "You could avoid copying the whitelist for every unique element, and start it off by having the same size as the original, then only copy the subarray with unique lements just before returning."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T19:47:47.767",
"Id": "46818",
"Score": "1",
"body": "Incrementally increasing `whitelist` by 1 creates a time complexity of **`O(N^2)`**. Consider using `ArrayList` which expands dynamically, and returning `arraylist.toArray();` That would run in **`O(N)`**."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-06T03:06:34.763",
"Id": "54384",
"Score": "0",
"body": "@awashburn if targeting >= .NET 2.0, one should use `List<T>` instead of `ArrayList`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T09:07:10.540",
"Id": "29212",
"ParentId": "29210",
"Score": "12"
}
},
{
"body": "<p>You're following the same philosophy as the bubble sort, which is very, very, very slow. Have you tried this?:</p>\n\n<ul>\n<li>Sort your unordered array with <a href=\"http://en.wikipedia.org/wiki/Quicksort\">quicksort</a>. Quicksort is much faster than bubble sort (I know, you are not sorting, but the algorithm you follow is almost the same as bubble sort to traverse the array).</li>\n<li>Then start removing duplicates (repeated values will be next to each other). In a <code>for</code> loop you could have two indices: <code>source</code> and <code>destination</code>. (On each loop you copy <code>source</code> to <code>destination</code> unless they are the same, and increment both by 1). Every time you find a duplicate you increment source (and don't perform the copy).</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T09:57:10.900",
"Id": "29216",
"ParentId": "29210",
"Score": "11"
}
},
{
"body": "<p>A slight improvement on Dr H's </p>\n\n<pre><code>public static int[] removeDuplicates(int[] arr) {\n Set<Integer> alreadyPresent = new HashSet<>();\n int[] whitelist = new int[arr.length];\n int i = 0;\n\n for (int element : arr) {\n if (alreadyPresent.add(element)) {\n whitelist[i++] = element;\n }\n }\n\n return Arrays.copyOf(whitelist, i);\n}\n</code></pre>\n\n<p>This does only one array copy at the end. It also takes advantage of the fact that <code>Set.add()</code> returns a boolean that indicated if the Set changed, and so avoids an explicit <code>contains()</code> check.</p>\n\n<p><strong>Java 8 update</strong></p>\n\n<p>In java 8 the code is a lot simpler :</p>\n\n<pre><code>public static int[] removeDuplicates(int[] arr) {\n return Arrays.stream(arr)\n .distinct()\n .toArray();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-11T11:55:55.523",
"Id": "190908",
"Score": "0",
"body": "why you are copying whitelist ? Can't we just return whitelist ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-11T14:07:15.923",
"Id": "190937",
"Score": "0",
"body": "@PrabhatSubedi copy because the size will (most likely) be smaller than the original. And whitelist has the original size."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T15:30:15.153",
"Id": "29231",
"ParentId": "29210",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "29216",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T08:40:45.660",
"Id": "29210",
"Score": "11",
"Tags": [
"java",
"array"
],
"Title": "Removing duplicate values from an array"
}
|
29210
|
<p>After I had my <a href="https://codereview.stackexchange.com/questions/29183/review-implementation-of-stack-by-using-array-in-c">code for stack implementation by array</a> reviewed I wrote stack implementation by using pointers. Here's my code. Any suggestions for improvement are welcome. </p>
<p><strong>I'll be adding updated code so please review the latest one.</strong> Obviously you are free to ignore this also. To skip reading this long question you can <a href="https://codereview.stackexchange.com/questions/29213/review-implementation-of-stack-by-using-pointers-in-c#comment46114_29213">click here</a>.</p>
<p>Here's my implementation of stack by using pointers. If someone prefers github <a href="https://github.com/anshbansal/general/tree/master/C/Data_Structures/Stack" rel="nofollow noreferrer">here is github</a></p>
<pre><code>#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
enum action {START, PUSH, POP, TOP, QUIT, END};
typedef struct node
{
int data;
struct node *lower;
}stack_node;
void clear_screen(void)
{
system("cls");
}
static enum action get_user_action(void)
{
int choice = START;
do
{
clear_screen();
printf("%d Push data\n"
"%d Pop Data\n"
"%d See the top of the stack\n"
"%d Exit\n\n"
"Enter your choice -> ", PUSH, POP, TOP, QUIT);
scanf("%d", &choice);
} while (!(START < choice && choice < END));
return (enum action) choice;
}
void push(stack_node **top_stack, int *status, int data)
{
*status = START;
stack_node *node = malloc(sizeof(node));
if (node == NULL)
{
*status = PUSH;
return;
}
node -> data = data;
if (*top_stack == NULL){
node -> lower = NULL;
}
else{
node -> lower = *top_stack;
}
*top_stack = node;
}
int pop(stack_node **top_stack, int *status)
{
*status = START;
if (*top_stack == NULL){
*status = POP;
return -1;
}
stack_node *node = *top_stack;
int data = node -> data;
*top_stack = node -> lower;
free(node);
return data;
}
int peek(stack_node **top_stack, int *status)
{
*status = START;
if (*top_stack == NULL){
*status = POP;
return -1;
}
return (*top_stack) -> data;
}
int main(void)
{
enum action choice;
int status;
stack_node *top = NULL;
while ((choice = get_user_action()) != QUIT)
{
clear_screen();
int data;
switch (choice)
{
case PUSH:
printf("Enter data to be pushed -> ");
scanf("%d", &data);
push(&top, &status, data);
if (status == PUSH){
printf("Not enough memory\n");
}
else{
printf("%d pushed onto the stack", data);
}
break;
case POP:
data = pop(&top, &status);
if (status == POP){
printf("Stack underflow\n");
}
else{
printf("The data is %d\n", data);
}
break;
case TOP:
data = peek(&top, &status);
switch (status)
{
case POP:
printf("Nothing in the stack\n");
break;
default:
printf("The data at top is %d\n", data);
}
break;
default:
assert(!"You should not have reached this.");
}
getchar();
getchar();
}
}
</code></pre>
<p><strong>Update 1</strong></p>
<p>I think I have made the stack able to use any data type. This is what I have made. I also added a function for deleting the stack <code>stack_delete</code>.</p>
<pre><code>#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum action {START, PUSH, POP, TOP, LENGTH, QUIT, END};
enum status {SUCCESS, FAILURE};
typedef struct node {
void *data;
struct node *lower;
} stack_node;
typedef struct stack {
size_t elem_size;
size_t stack_size;
stack_node *top;
} stack_struct;
void clear_screen(void)
{
system("cls");
}
static enum action get_user_action(void)
{
int choice = START;
do {
clear_screen();
printf("%d Push data\n"
"%d Pop Data\n"
"%d See the top of the stack\n"
"%d See the length of the stack\n"
"%d Exit\n\n"
"Enter your choice -> ", PUSH, POP, TOP, LENGTH, QUIT);
scanf("%d", &choice);
} while (!(START < choice && choice < END));
return (enum action) choice;
}
enum status stack_create(stack_struct **stack, size_t elem_size)
{
(**stack).elem_size = elem_size;
(**stack).stack_size = 0;
(**stack).top = NULL;
return SUCCESS;
}
enum status push(stack_struct **stack, void *data)
{
stack_node *node = malloc(sizeof(node));
if (node == NULL) {
return FAILURE;
}
node->data = malloc(sizeof((**stack).elem_size));
if (node->data == NULL) {
return FAILURE;
}
memcpy(node->data, data, (**stack).elem_size);
node->lower = (**stack).top;
(**stack).top = node;
(**stack).stack_size += 1;
return SUCCESS;
}
enum status pop(stack_struct **stack, void *data)
{
if ((**stack).top == NULL) {
return FAILURE;
}
stack_node *node = (**stack).top;
memcpy(data, node->data, (**stack).elem_size);
(**stack).top = node->lower;
free(node->data);
free(node);
(**stack).stack_size -= 1;
return SUCCESS;
}
enum status peek(stack_struct **stack, void *data)
{
if ((**stack).top == NULL) {
return FAILURE;
}
memcpy(data, (**stack).top->data, (**stack).elem_size);
return SUCCESS;
}
void stack_delete(stack_struct **stack)
{
while ((**stack).top != NULL)
{
stack_node *node = (**stack).top;
(**stack).top = (**stack).top->lower;
free(node->data);
free(node);
}
free(*stack);
}
int main(void)
{
enum action choice;
stack_struct *stack = malloc(sizeof(stack_struct));
if (stack == NULL)
{
printf("Not enough memory\n");
return 1;
}
stack_create(&stack, sizeof(int));
while ((choice = get_user_action()) != QUIT) {
clear_screen();
int data;
switch (choice) {
case PUSH:
printf("Enter data to be pushed -> ");
scanf("%d", &data);
if (push(&stack, &data) == SUCCESS) {
printf("%d pushed onto the stack\n", *(int *)stack->top->data);
} else {
printf("Not enough memory\n");
}
break;
case POP:
if (pop(&stack, &data) == SUCCESS){
printf("The data is %d\n", data);
} else {
printf("Stack underflow\n");
}
break;
case TOP:
if (peek(&stack, &data) == SUCCESS){
printf("The data at top is %d\n", data);
} else {
printf("Nothing in the stack\n");
}
break;
case LENGTH:
printf("Length is %d\n", stack->stack_size);
break;
default:
assert(!"You should not have reached this.\n");
}
getchar();
getchar();
}
stack_delete(&stack);
}
</code></pre>
<p><strong>Update 3</strong></p>
<p>I added it after Corbin's review of my Update 2. So far I have just left the use of linked list for implementing the stack. </p>
<p>I haven't made 2 files yet but I have placed stack implementation at the top of the file for showing the logical separation of implementation code and client code. As this isn't a very big implementation I think the logical separation is what is needed here.</p>
<p>Here is my updated code.</p>
<pre><code>#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum status {STACK_SUCCESS, STACK_FAILURE};
typedef struct node {
void *data;
struct node *lower;
} stack_node;
typedef struct stack {
size_t elem_size;
size_t stack_size;
stack_node *top;
} STACK;
enum status stack_init(STACK *stack, size_t elem_size)
{
stack->elem_size = elem_size;
stack->stack_size = 0;
stack->top = NULL;
return STACK_SUCCESS;
}
stack_node * stack_node_create(STACK *stack)
{
stack_node *node = malloc(sizeof(stack_node));
if (node == NULL) {
return NULL;
}
node->data = malloc(stack->elem_size);
if (node->data == NULL) {
free(node);
return NULL;
}
return node;
}
enum status stack_push(STACK *stack, void *data)
{
stack_node *node = stack_node_create(stack);
if (node == NULL) {
return STACK_FAILURE;
}
memcpy(node->data, data, stack->elem_size);
node->lower = stack->top;
stack->top = node;
stack->stack_size += 1;
return STACK_SUCCESS;
}
enum status stack_pop(STACK *stack, void *data)
{
if (stack->top == NULL) {
return STACK_FAILURE;
}
stack_node *node = stack->top;
memcpy(data, node->data, stack->elem_size);
stack->top = node->lower;
free(node->data);
free(node);
stack->stack_size -= 1;
return STACK_SUCCESS;
}
enum status stack_peek(STACK *stack, void *data)
{
if (stack->top == NULL) {
return STACK_FAILURE;
}
memcpy(data, stack->top->data, stack->elem_size);
return STACK_SUCCESS;
}
void stack_cleanup(STACK *stack)
{
while (stack->top != NULL) {
stack_node *node = stack->top;
stack->top = stack->top->lower;
free(node->data);
free(node);
}
}
//Stack Implementation before this.
//Things that are used to use the stack are placed after this.
enum action {START, PUSH, POP, TOP, LENGTH, QUIT, END};
void clear_screen(void)
{
system("cls");
}
static enum action get_user_action(void)
{
int choice = START;
do {
clear_screen();
printf("%d Push data\n"
"%d Pop Data\n"
"%d See the top of the stack\n"
"%d See the length of the stack\n"
"%d Exit\n\n"
"Enter your choice -> ", PUSH, POP, TOP, LENGTH, QUIT);
scanf("%d", &choice);
} while (!(START < choice && choice < END));
return (enum action) choice;
}
int main(void)
{
enum action choice;
STACK stack;
stack_init(&stack, sizeof(int));
while ((choice = get_user_action()) != QUIT) {
clear_screen();
int data;
switch (choice) {
case PUSH:
printf("Enter data to be pushed -> ");
scanf("%d", &data);
if (stack_push(&stack, &data) == STACK_SUCCESS) {
printf("%d pushed onto the stack\n", *(int *)stack.top->data);
} else {
printf("Not enough memory\n");
}
break;
case POP:
if (stack_pop(&stack, &data) == STACK_SUCCESS){
printf("The data is %d\n", data);
} else {
printf("Stack underflow\n");
}
break;
case TOP:
if (stack_peek(&stack, &data) == STACK_SUCCESS){
printf("The data at top is %d\n", data);
} else {
printf("Nothing in the stack\n");
}
break;
case LENGTH:
printf("Length is %d\n", stack.stack_size);
break;
default:
assert(!"You should not have reached this.\n");
}
getchar();
getchar();
}
stack_cleanup(&stack);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T10:40:52.117",
"Id": "46114",
"Score": "0",
"body": "Is this meant to be reviewed as library style code or as a one-off intellectual oversize? In other words, would you like for us to critique the external-developer usability of this, or just critique it for being a simple implementation and demo?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T10:49:52.747",
"Id": "46115",
"Score": "0",
"body": "@Corbin Review according to reusability. I think that would mean external-developer usability."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T02:25:54.683",
"Id": "46245",
"Score": "0",
"body": "You might find [this code of mine](https://groups.google.com/d/msg/comp.unix.programmer/GtN3XqArc5s/mCKFA-w59pEJ) interesting. It implements a stack with a very generic interface. The *client code* which uses the stack, just passes a `void*` and saves the result on every call. This `void*` points to the stack state, but the client code cannot access it because the definition is not in the header file, just the functions that can be used. $0.02. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T14:41:46.033",
"Id": "46380",
"Score": "2",
"body": "Isn't it better to start a new review for the updated code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T15:31:23.330",
"Id": "46384",
"Score": "0",
"body": "@Lstor Just wanting to know whether it is good or not. Starting a new one each time I update it would lead to something like 7 copies of the same thing. Also if I have missed something then people will be repeating themselves. That might be annoying for the reviewers as well as any readers. Also for iterative reviews the only thing that can successfully work in the current structure without making a mess of this website would be adding the code. [Meta discussion](http://meta.codereview.stackexchange.com/questions/41/iterative-code-reviews-how-can-they-happen-successfully)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T16:05:14.687",
"Id": "46391",
"Score": "0",
"body": "@Lstor Please comment/add answer in the meta discussion if you think there is a better alternative to this method without making this website a mess. I would like to hear your thoughts as almost all the answers there are 2 years old."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T05:12:29.983",
"Id": "46439",
"Score": "0",
"body": "@Lstor After seeing corbin add another answer I realized that it is possible for the reviewer to add more than one answer. I think that would keep the reviews clean and separate from one another if that is your concern."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T06:04:28.553",
"Id": "46443",
"Score": "0",
"body": "That is a good point, I haven't considered that before. Too bad it's not possible to fold the code in the question too -- I think that would be the cleanest solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T06:36:23.307",
"Id": "46444",
"Score": "0",
"body": "@Lstor If you haven't started Update 1's review I made Update 2 according to Corbin's suggestion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T06:43:53.433",
"Id": "46446",
"Score": "0",
"body": "@Lstor Another reason why we need this website out of beta. I don't think the people at SE would consider custom features for a beta website. But for a live website it could be possible."
}
] |
[
{
"body": "<p>First of all, you should put the implementation in a separate implementation file and expose access to it through a header.</p>\n\n<p>Second, your <code>stack_node</code> is an implementation detail and should not be exposed to client code. Instead, create a <code>struct stack</code> that contains bookkeeping data and a pointer to the top node:</p>\n\n<pre><code>typedef struct {\n size_t length;\n stack_node *top;\n} stack_t;\n</code></pre>\n\n<p>Make functions to create and delete (free) such <code>stack_t</code>s. All your functions should take a pointer to the <code>stack_t</code> they operate on, and should not take any further bookkeeping data.</p>\n\n<p><strong>Usage example:</strong></p>\n\n<pre><code>stack_t *values = stack_create();\n\nstack_push(values, 42);\nint ultimate_answer = stack_peek(values);\nstack_push(values, 9*6);\n\nint no_jokes_in_base_thirteen = stack_pop(values);\n\nstack_delete(values);\n</code></pre>\n\n<p>I would also make a helper function to create nodes. It should not be used by client code, and therefore it should have internal linkage (i.e. be declared <code>static</code>) in the stack implementation file.</p>\n\n<h3>Other comments:</h3>\n\n<ul>\n<li><p>Don't have spaces when using <code>-></code>, just like you wouldn't use spaces when using <code>.</code>:</p>\n\n<pre><code>node->lower = *top_stack; // node is pointer\nnode.lower = *top_stack; // node is not pointer\n</code></pre></li>\n<li><p>Be consistent with your style. You are mixing K&R-style and Allman/BSD-style, i.e.</p>\n\n<pre><code>if (kernighan_and_ritchie) {\n}\n</code></pre>\n\n<p>vs.</p>\n\n<pre><code>if (bsd_style)\n{\n}\n</code></pre>\n\n<p>Pick one and stick to it. I personally prefer clean K&R style, which also uses \"cuddled <code>else</code>\":</p>\n\n<pre><code>if (cuddly) {\n} else {\n}\n</code></pre>\n\n<p>But having a newline before the <code>else</code> is also fine.</p></li>\n<li><p>I'd rename <code>top_stack</code> to <code>top_of_stack</code>, <code>stack_top</code> or simply <code>top</code>, otherwise it can give the impression of being a stack.</p></li>\n</ul>\n\n<h3>Edit:</h3>\n\n<p>A few things I forgot:</p>\n\n<ul>\n<li><p>To be useful to other developers, the stack would need to take other types than just <code>int</code>s.</p></li>\n<li><p>Your <code>stack</code> is really a singly linked list with some limitations. It would be a good exercise to implement a complete implementation of a singly (and later, doubly) linked list.</p></li>\n<li><p>Your implementation does not have a way to get the size of the stack. <code>size</code> should be O(1). That means that the stack should keep track of its own size, like I indicated in the <code>stack_t</code> example above.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T11:24:36.503",
"Id": "46117",
"Score": "0",
"body": "I think can take care of everything except one. How do I make the stack to take different data types? Data types are decided at compile time, if I am correct. I know that `stdlib.h` has `qsort` and `bsearch` which can take any type but I don't know how that could be implemented. Can you provide some hint about how to implement that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T11:31:19.593",
"Id": "46120",
"Score": "0",
"body": "Use `void*`. Dennis Ritchie said that \"C is a strongly typed, weakly checked language\", and `void*` is very weakly checked. But that increases the complexity, so I recommend you wait until you are comfortable with `void*`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T11:48:47.663",
"Id": "46375",
"Score": "0",
"body": "I think I have made the stack able to use any data type. Please have a look."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T09:55:19.190",
"Id": "29215",
"ParentId": "29213",
"Score": "5"
}
},
{
"body": "<p>Lstor has most of these, but I'd like to go into more detail on a few things and also suggest a few new things.</p>\n\n<hr>\n\n<p>As Lstor said, separate your declarations and your implementation. Declarations go in a header file (.h), and definitions go in a source file (.c). Consuming code then includes the header and doens't have to even know the source file exists. In fact, for non-trivial libraries, the source is rarely used directly. Instead, the header is used and the consuming code is linked against a library. You don't need to go that far since your library is small and has a trivial compilation process, but the separation of declaration and implementation is definitely worth keeping in mind.</p>\n\n<hr>\n\n<p>Create a naming scheme and go with it. I suggest <code>library_component_function</code>, like <code>ab_stack_push</code> (<code>ab</code> being for <code>Aseem Bansal</code> in this example). In a way, it's essentially namespacing via name. Provided you pick a reasonable prefix, no other library is going to have used it yet, meaning you'll have the entire space of <code>name_</code> to yourself. (Avoid well know libraries' prefixes like <code>curl_</code>, <code>apr_</code>, <code>ev_</code>, etc).</p>\n\n<p>Even if you don't do a library prefix, you should prefixing the functions with <code>stack_</code>. Not only does any kind of reusable code need a prefix or risk an inevitable name clash, it's also just simpler to know that all stack related functions start with stack. It makes it easier to find and remember the functions.</p>\n\n<hr>\n\n<p>As Lstor hinted at, I would create a different, more versatile data structure and implement your stack in terms of that. While a pure stack is going to be a bit more efficient memory-wise, using a different data structure to implement it means less code to manage and ease of design. I would implement a stack as either a vector or a doubly linked list. In either situation, you're basically taking a more complete data type and removing functionality. That means that all of your stack code can just be thin wrappers.</p>\n\n<hr>\n\n<p>I'm always tempted to impelement data structures as an opaque pointer. By only exposing the struct as a pointer, you can ensure that client code never touches the internals of it. It's quite handy for completely hiding an implementation, and it has a few other minor benefits, but it also comes at a cost of the struct always having to be dynamically allocated. (Well, technically it doesn't have to be, but it's quite a pain otherwise).</p>\n\n<p>The basic idea is to forward declare a struct in the header and only actually define it in the implementation file. Forward declared types can have a pointer to them (since the size of a pointer is always known), but the plain type cannot be used until the full declaration has been provided. This means that only your implementation can use the contents of the struct since consuming code won't know what's in it. Consuming code can only see a pointer to the struct.</p>\n\n<p>This is a pattern you've probably actually seen before if you've used anything that works like a handle. For example, <code>FILE</code> is an opaque pointer in GNU's libc. Consuming code only ever works with <code>FILE</code> in the sense of <code>FILE*</code>. You would never have a plain <code>FILE</code>, and, in fact, it's not possible with GNU's libc.</p>\n\n<hr>\n\n<p>Rather than a human driven test, consider a semi-rigourous, programmatic test (think unit testing). Yeah, it's cool to have a little program that lets you use your hard work and see it in action, but in terms of actual bug catching, you want something you can instantly reproduce, not go \"wait... how many elements had I inserted? And what were they?\" Rather, it'd be nice if your test found a bug in your stack if you could simply run it again to recreate said bug. If you haven't looked into unit testing, I'm essentially recommending a simplified version of that.</p>\n\n<hr>\n\n<p>From a usability perspective, genericness is crucial. A stack that can only store ints is pretty useless. I'd like to expand on Lstor's advice to use <code>void*</code>. A good introduction to it is here <a href=\"http://www.youtube.com/watch?v=iyLNYXcEtWE&feature=PlayList&p=9D558D49CA734A02&index=5\" rel=\"nofollow\">http://www.youtube.com/watch?v=iyLNYXcEtWE&feature=PlayList&p=9D558D49CA734A02&index=5</a>. </p>\n\n<p>The basics of it are pretty simple though once you wrap your head around it. By using a <code>void*</code>, you essentially treat blocks of memory as blocks of memory and nothing more. </p>\n\n<p>A good example of this is <code>void* memcpy(void* dest, const void* src, std::size_t count);</code> in the standard. <code>memcpy</code> doesn't care what the memory is. It doesn't care if it's an <code>int*</code>, a <code>char**</code> or whatever. It just knows that you've handed it a chunk of memory and told it to copy <code>count</code> bytes of it to another block of memory. </p>\n\n<p>Your stack implementation would be similar: you just hand it a chunk of memory and tell it to push it. By keeping size of each element in the <code>stack_t</code> struct, your method won't require the size. In other words, <code>void stack_push(stack_t* stack, int val);</code> becomes <code>int stack_push(stack_t* stack, void* val);</code> and <code>stack_t* stack_create();</code> becomes <code>stack_t* stack_create(size_t elem_size);</code>. The reason the size is stored internally rather than provided each time is two fold. First is for usability purposes, but second is that you want to see your instance as a stack of <code>something</code>. You want <code>stack_t a* = stack_create(sizeof(int));</code> to be a stack of ints and your <code>stack_t* b = stack_create(sizeof(char*));</code> to be a stack of <code>char*</code> (example names, not a suggested naming scheme :p). Ideally they'd be tied to that one type and that one type only. Ideally they'd be part of the actual type of the object (<em>looks longingly at C++</em>). That can't happen in C though, so instead, we leave the sizing business to the internals and we trust ourselves to only ever pass it the type it is containing.</p>\n\n<p>As for the acutal usuage, the main confusion with <code>void*</code> is \"what the hell do I do with a <code>void*</code>?\". <code>void*</code> is just used to accept or return a pointer of unknown type. To actually work with it, you will cast it to a <code>char*</code> and use it. Casting it to a <code>char*</code> allows you to do single-byte arithmetic on it. Since you already know the size of each element, you can use that to multiply out single byte arithmetic. This is essentially what the compiler does for you when you use typed pointers. With <code>int* ints</code>, <code>ints + 3</code> is the same thing as <code>((char*) ints) + sizeof(int) * 3</code>. Since pointer is still typed, it actually is still inserting the size for you. It just happens that <code>sizeof(char)</code> is always 1.</p>\n\n<p>Imagine you have a <code>void* ptr</code> that you know holds 20 elements that are each 4 bytes. This means that element n is at <code>void* elem_n = ((char*) ptr) + (4 * n);</code>. This is really the entire concept. You know how to find addresses, and you know what the sizes are. That's all you need :). In fact, if you're working with linked structures, you don't even need to know how to find offset addresses. You just need to know to use the stored size.</p>\n\n<p>An example:</p>\n\n<pre><code>typedef struct {\n stack_node_t* prev;\n void* data;\n} stack_node_t;\n\ntypedef struct {\n size_t elem_size;\n size_t size;\n stack_node_t* top;\n} stack_t; //_t suffixed names are all reserved by POSIX. \n //In reality, that won't matter for a type \n //like `stack_t`, but worth keeping in mind.\n\nstack_t* stack_create(size_t elem_size)\n{\n stack_t* stack = malloc(sizeof(*stack));\n if (stack == NULL) { return NULL; }\n stack->elem_size = elem_size;\n stack->size = 0;\n stack->top = NULL;\n return stack;\n}\n\nint stack_push(stack_t* stack, void* elem)\n{\n stack_node_t* node = malloc(sizeof(*node));\n\n if (node == NULL) {\n return STACK_ERR_ALLOC;\n }\n\n node->data = malloc(stack->elem_size);\n\n if (node->data == NULL) {\n return STACK_ERR_ALLOC;\n }\n\n memcpy(node->data, elem, stack->elem_size);\n\n node->prev = stack->top;\n stack->top = node;\n\n return STACK_SUCCESS;\n}\n</code></pre>\n\n<p>An example that uses an array might be a bit more helpful, so if you'd like one of those, let me know (or, watch the earlier linked video -- it implements an array based stack).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T20:12:53.287",
"Id": "46179",
"Score": "0",
"body": "Hats off! I particularly liked forcing use of pointers, I haven't thought of or seen that approach before. I also didn't know `_t` is reserved by POSIX."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T21:47:44.313",
"Id": "46186",
"Score": "0",
"body": "@Lstor it has a few downsides, especially in certain scenarios (embedded systems come to mind where mallocing a pointer might be more than a minor inconvenience), but it can be nice to completely hide implementation. And yeah, `_t` is reserved by POSIX. I can't imagine POSIX would ever add a stack, so it's likely fine in this context, but by the letter of the law, it's technically wrong on any POSIX system."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T11:49:06.273",
"Id": "46376",
"Score": "0",
"body": "I think I have made the stack able to use any data type. Please have a look."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T20:02:11.023",
"Id": "29242",
"ParentId": "29213",
"Score": "3"
}
},
{
"body": "<p>A few things with regards to your new code:</p>\n\n<hr>\n\n<p><code>SUCCESS</code> and <code>ERROR</code> are very risky enum identifiers. Since enums share a global scope, this means that no code that your code is used with can ever use either of those identifiers in an enum or your code won't compile. That's a big risk to take. Just be to on the safe side, you could prefix them <code>STACK_SUCCESS</code>/<code>STACK_ERROR</code>.</p>\n\n<hr>\n\n<p>Some functions have <code>stack_</code> prefix and some don't. All of them should have the prefix.</p>\n\n<hr>\n\n<p>There's still no separation of declaration and implementation (header/source). Normally this wouldn't be an issue since it's such a small script, but you said that you'd like it reviewed according to reusability. Reusability hinges on a well defined separation.</p>\n\n<hr>\n\n<p>All of your <code>stack**</code> should just be <code>stack*</code>.</p>\n\n<p>None of your double pointers are actually being used a double pointer, so there's no purpose to have the confusion/indirection overhead.</p>\n\n<p>Also, once it's a <code>stack*</code>, you main will just need a <code>stack</code> so you won't have to <code>malloc</code> it.</p>\n\n<hr>\n\n<p><code>stack_create</code> should be named <code>stack_init</code>. <code>create</code> implies that memory is allocated. <code>init</code> implies that a structure is initialized. new and create tend to imply that both memory is allocated and initialized. init implies that initialization is done on existing memory.</p>\n\n<hr>\n\n<p>There's a mismatch in memory semantics. The consuming code allocates the stack, but the stack_delete method destroy it. If the client <code>malloc</code>s it, the client should <code>free</code> it. Either stack_create needs to malloc the stack, or stack_delete needs to not free it (and if it doesn't free, it should be renamed to something like stack_dispose or stack_cleanup).</p>\n\n<hr>\n\n<p>I don't like <code>stack_struct</code> for two reasons: it's obvious by intuition/IDE inspection/reading the header that it's a struct. You never see x_int or x_char for a reason: it's useless.</p>\n\n<p>The more important reason though is that the end user doesn't need to know that it's a struct. In fact, if the end user could just see it as a black-box style little object, that would be for the best. It being a struct is an implementation detail, and you typically want to hide implementation details from consumers of your code.</p>\n\n<hr>\n\n<p><code>stack_node *node = malloc(sizeof(node));</code> is probably a typo. This is the same as <code>stack_node *node = malloc(sizeof(stack_node*));</code> since it's not <code>struct node</code>. It should likely be <code>stack_node *node = malloc(sizeof(*node));</code></p>\n\n<hr>\n\n<p>You have a potential memory leak in <code>push</code>. What happens if the <code>node</code> is successfully <code>malloc</code>d, but the <code>node->data</code> malloc fails? Once <code>push</code> returns, you no longer have a pointer to <code>node</code> which means that there's now memory that is allocated but not pointed to. There's a lot of ways you can handle code flows like this. In this particular situation, I would do something like this:</p>\n\n<pre><code>enum status push(stack_struct *stack, void *data)\n{\n stack_node *node = malloc(sizeof(*node));\n\n if (!node) {\n return FAILURE;\n }\n\n node->data = malloc(sizeof(stack->elem_size));\n if (node->data) {\n memcpy(node->data, data, stack->elem_size);\n node->lower = stack->top;\n stack->top = node;\n stack->stack_size += 1;\n return SUCCESS;\n }\n\n free(node);\n\n return FAILURE;\n}\n</code></pre>\n\n<hr>\n\n<p>I'd be tempted to pull the node management out into its own functions. At the moment it doesn't really matter since the code is so small. It might simplify certain things though (like the example above). The node management would of course be implemented as internal linkage only inside of the stack source so external code can't see it (static functions).</p>\n\n<p>As an example of simplification, consider a new implementation of <code>push</code>:</p>\n\n<pre><code>static stack_node* stack_node_create(void* data, size_t elem_size)\n{\n stack_node* node = malloc(sizeof(*node));\n if (!node) { return NULL; }\n node->data = malloc(elem_size);\n if (!node->data) {\n free(node);\n return NULL;\n }\n memcpy(node->data, data, elem_size);\n return node;\n}\n\nstatic void stack_node_destroy(stack_node* node)\n{\n free(node->data);\n free(node);\n}\n\nenum status push(stack_struct *stack, void *data)\n{\n stack_node* node = stack_node_create(data, stack->elem_size);\n if (!node) {\n return FAILURE;\n }\n node->lower = stack->top;\n stack->top = node;\n stack->stack_size += 1;\n return SUCCESS;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T05:43:44.083",
"Id": "46440",
"Score": "0",
"body": "I didn't like `stack_struct` either but as you told `x_t` is reserved for POSIX and I didn't want to form a bad habit even though it is valid in this case. I guess I'll use `STACK` instead of `stack_struct`(Inspiration from `FILE`). Other than that my focus currently was to make it work. The next time I update I'll take care of everything said so far(except the use of linked list for stack as I have reserved that for future)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T05:56:47.733",
"Id": "46442",
"Score": "0",
"body": "I just noticed that your example's `stack_node_destroy` is redundant. The function `stack_node_create` actually takes care of everything. There is no memory to be freed if `node == NULL`. But good point about pulling out node management into a separate function. Also about your `stack_create_function` [I was suggested](http://chat.stackexchange.com/transcript/message/10570024#10570024) that returning status would be a better idea compared to returning the data(I think that data here is the pointer). Is this better for functions called by the client or is it useful practice in libraries also?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T06:37:45.953",
"Id": "46445",
"Score": "0",
"body": "I made Update 2 according to suggestions given. I haven't made 2 files but I have shown a clear logical separation of the implementation and the client code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T07:59:18.153",
"Id": "46453",
"Score": "0",
"body": "@AseemBansal I would just stick would `stack` or even the old `stack_struct` in favor of `STACK`. All caps seems odd and is a pain to type. How is `stack_node_destroy` redundant? It's meant to be used when destroying the list. It has nothing to do with cleanup when allocating the nodes (it just encapsulates allocation of the node and the data as a pseudo-atomic operation from the outside)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T08:03:35.453",
"Id": "46455",
"Score": "0",
"body": "As for the return being a pointer... Since it's an internal function it doesn't matter. If you really wanted, you could pass a `stack_node**` and return a status flag instead of returning a pointer. At the end of the day though, the function will either succeed in allocating or fail. A pointer can conveniently encode this flag as NULL or non-NULL. If it were external linkage, there might be an argument for a status return (in future, more than 1 error reason might exist for failure). Since it's internal though, I wouldn't bother. Internal things can be easily-ish changed if/when necessary."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T16:47:37.380",
"Id": "46481",
"Score": "0",
"body": "You have used `stack_node_destroy(node);` in the `push` function. I was referring to that. In case of failure of `stack_node_create` which is the first statement of the `push` function there is no memory allocated to the stack's node so calling `stack_node_destory` in the `push` is redundant. Having that as an atomic operation is actually a good idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T20:19:10.807",
"Id": "46496",
"Score": "0",
"body": "@AseemBansal Ah, whoops. You're right. No idea why I put that in push :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T04:33:09.793",
"Id": "46506",
"Score": "0",
"body": "Any other improvement in Update 2 other than choice of name of the struct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T00:01:00.710",
"Id": "46612",
"Score": "0",
"body": "@AseemBansal Hmmmm, I really just looked at the method signatures for the most part. I'll look over everything in a bit more detail later and post a review for update 3 if I see anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T07:02:51.247",
"Id": "46864",
"Score": "0",
"body": "Any comments for [this about designing a generic doubly linked list around which I want to make wrapers for implementing stack](http://programmers.stackexchange.com/questions/207899/better-design-for-a-generic-doubly-linked-list-around-which-i-plan-to-make-diffe)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T07:03:17.420",
"Id": "46865",
"Score": "0",
"body": "@Lstor Any comments on the above?"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T21:41:59.490",
"Id": "29380",
"ParentId": "29213",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29242",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T09:23:56.027",
"Id": "29213",
"Score": "1",
"Tags": [
"c",
"stack",
"pointers"
],
"Title": "Review implementation of stack by using pointers in C"
}
|
29213
|
<p>The following code makes jQuery trigger a new <code>target</code> event on elements when they become the target of the <a href="http://en.wikipedia.org/wiki/Fragment_identifier" rel="nofollow">fragment identifier</a>.</p>
<p>For a very basic example, the following <code>target</code> event handler:</p>
<pre><code>$('.question-page .answer').on('target', function highlight(){
$(this).stop().css({'background':'orange'}).animate({'background':'white'}, 300);
});
</code></pre>
<p>…Would emulate what following CSS would express with the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/%3atarget" rel="nofollow"><code>:target</code> pseudo-selector</a>:</p>
<pre><code>.question-page .answer:target {
animation: 0.3s highight;
}
@keyframes highlight {
from {
background: orange;
}
to {
background: white;
}
}
</code></pre>
<p>The plugin code follows. My concerns are mostly on the sanity of the event triggering, particularly the <code>handleHashChange</code> and <code>ignoreHashChange</code> functions which attempt to mitigate a <code>click</code> triggering a <code>target</code> event for an element, and that same <code>click</code> bubbling up to cause a <code>hashchange</code> (which without this code, would trigger another <code>target</code> event — although it is holistically the same <code>target</code> event).</p>
<p>I'm also interested in style and integration with jQuery API — I have doubts as to whether passing the <code>originalEvent</code> as a second argument is a good idea or not (should I just fold that event's <code>preventDefault</code> into the <code>target</code> event?), particularly in the case of the fake ready event constructor.</p>
<p>Any other criticism more than welcome.
</p>
<pre><code>void function jQueryTargetEventClosure($){
// Returns a 'ready' event to pass when 'target' is triggered by initial hash state on document load:
// Prevents critical failure when attempting to invoke event methods on 'target' handlers
var readyEventConstructor = (function readyEventConstructorClosure() {
var history = window.history;
var historySupport = history.replaceState && typeof history.replaceState === 'function';
return function readyEventConstructor() {
var location = window.location;
var readyEvent = $.Event( 'ready' );
// In case of history support, allow preventDefault to remove the window location's hash
if( historySupport && location.hash ){
readyEvent.preventDefault = function preventDomReadyTargetDefault() {
history.replaceState( void 0, void 0, location.href.split( location.hash )[ 0 ] );
// ...but then hand over to jQuery's own preventDefault for internal statefulness etc
return ( $.Event.prototype.preventDefault || $.noop ).call( readyEvent );
};
}
return readyEvent;
};
}());
// Utility: removes the hash from any passed URI(-component)-like string
function unHash( uriString ) {
// String.prototype.link converts a string into an anchor, allowing us to use the DOM's URI abstraction properties
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/link
var link = $( ''.link( uriString ))[ 0 ];
// Splitting with an empty string (no hash) is not what we want. Replace falsy with null:
return link.href.split( link.hash || void 0 )[ 0 ];
}
// Hashchange event handlers:
// Alternate to prevent duplicates (otherwise a click will bubble to trigger a hashchange - creating another target)
function filterHashChangeTarget( hashChangeEvent ) {
var $subject = $( window.location.hash );
$subject.trigger( 'target', [ hashChangeEvent ]);
}
// Bind the above handler
function handleHashChange( hashChangeEvent ) {
$( window )
.off( 'hashchange.ignore' )
.on( 'hashchange.handle', filterHashChangeTarget );
}
// Unbind the next instance
function ignoreHashChange( hashChangeEvent ){
$( window )
.off( 'hashchange.handle' )
.on( 'hashchange.ignore', handleHashChange );
}
// For link clicks
$( 'body' ).on( 'click', 'a[href*=#]', function filterClickTarget( clickEvent ) {
var link = this;
// The hash is effectively a selector for the targetted element
var $subject = $( link.hash );
void function handlePropagation(){
// noop, in case preventDefault is not available
var originalPreventDefault = clickEvent.preventDefault || $.noop();
// Don't handle the next hash change
ignoreHashChange();
// ...Unless default's prevented
clickEvent.preventDefault = function hashChangeInterrupt(){
// Reinstate the hash change handler
handleHashChange();
return originalPreventDefault();
};
}();
// Only apply to in-page links: minus the hash, link & location must match
if ( unHash( link.href ) === unHash( window.location.href )) {
$subject.trigger( 'target', [ clickEvent ]);
}
});
// On DOM ready
$(function readyTargetCheck(){
$( window.location.hash ).trigger( 'target', readyEventConstructor() );
});
}(jQuery);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-26T12:14:26.957",
"Id": "67357",
"Score": "0",
"body": "No, probably not — you could use a straight transition. The question's about the jQuery plugin."
}
] |
[
{
"body": "<p>to start with a terrible pun; I would avoid <code>void</code> where possible,<br> <code>history.replaceState( '', '', location.href.split( location.hash )[ 0 ] );</code> makes more sense to me. Also for your return statements I would rather see</p>\n\n<pre><code>return link.hash ? link.href.split( link.hash )[ 0 ] : link.href;\n</code></pre>\n\n<p>Furthermore, it seems that a <strong>lot</strong> of your code could be replaced with jQuery's <code>event.stopPropagation()</code>, am I missing something?</p>\n\n<p>Other than that the code is very well documented, and teaches the reader some new tricks.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T18:07:46.203",
"Id": "47165",
"ParentId": "29214",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T09:42:36.427",
"Id": "29214",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"css",
"plugin",
"dom"
],
"Title": "Custom event to match CSS :target pseudo-class"
}
|
29214
|
<p>I have a question about the best way to design / redesign my software. I have a program that uses a web services to perform certain tasks. Each task is a different set of request / response classes on the server end and a general function call from the Main Hook.</p>
<pre><code>RequestObject req = new RequestObject("SomeVal");
ResponseObject rsp = new ResponseObject();
rsp = WebServiceHook.Method1(RequestObject); //Returns ResponseObject
</code></pre>
<p>Each Method takes a different request object and returns a different type of response object.</p>
<p>As it stands, I have a class for each of these methods. Each class has a public method <code>Process()</code> that does the interaction. I am trying to determine the best way to group all this code together using OO techniques without sacrificing functionality. I would like just one <code>ProcessMethod</code> in one class that will handle the interaction with the web service for all the different web methods.</p>
<p>From reading about the OO patterns, it would appear the one I need to use is the abstract factory pattern with the adapter and strategy pattern thrown in too.</p>
<p>Am I going about this the right way?</p>
<p>I have a COM Library created in C#, with <code>COMVisible</code> set to true. This library talks to a 3rd party <code>WebService</code> calling various methods depending on the task at hand. For each <code>Request</code> / <code>Response</code> class exposed by the 3rd party DLL I have a Request / Response Pair (Class and Interface) to Marshal variables specifically for a VC6 application.</p>
<p>Mainly using:</p>
<pre><code>MarshalAs(UnmanagedType.LPStr)]
</code></pre>
<p>I have added a C# project to the solution to test this code, see test method below:</p>
<pre><code>static void Main(string[] args)
{
ICOMReq iReq = new CCOMReq();
ICOMRsp iRsp = new CCOMRsp();
Link l = new Link();
iReq.Date_Time = DateTime.UtcNow;
iReq.Var2 = "1023758145865";
l.DoMethod1(iReq, out iRsp);
//Handle COM Response here
}
</code></pre>
<p>The link class looks like so at the moment, but will have all the methods created once the design is correct:</p>
<pre><code>public class Link
{
public bool DoMethod1(ICOMReq _COMReq, out ICOMRsp COMRsp)
{
Method1 WebServiceMethod = new Method1(new Method1Request(), new Method1Response(), (CCOMReq)_COMReq, new CCOMRsp());
WebServiceMethod.Process();
//Just test code at the moment
COMRsp = null;
return true;
}
}
</code></pre>
<p>Each <code>DoMethod(N)</code> that will be in the link class will look the same performing its task with identical code to the other <code>DoMethod</code>s. The key differences between the methods is the Param Types Passed in and the <code>Method1</code> (<code>Method1Request</code>/<code>Method1Response</code>) type will vary depending on the webmethod to be called.</p>
<p>Class <code>Method1</code> (There will be one of these for every method I need to implement on the <code>WebService</code>) looks like so:</p>
<pre><code>public class Method1 : WebServiceInterfaceBridge<Method1Request, Method1Response, ICOMReq, ICOMRsp>
{
public Method1(Method1Request WEB_Req, Method1Response WEB_Rsp, CCOMReq COM_Req, ICOMRsp COM_Rsp)
: base(WEB_Req, WEB_Rsp, CBE_Req, CBE_Rsp)
{
WEB_Req.SOME_DATE_TIME = COM_Req.Date_Time;
}
public new void Process()
{
base.Process();
}
public override void LOG()
{
Console.WriteLine(this.WebMethod_Request.MEMBER_VAR_HERE);
}
//There will be additional methods here in the end as well as a mapping method to convert the WEBMethodResponse to a COMResponse and pass it back to the caller
}
</code></pre>
<p>The class (<code>WebServiceInterfaceBridge</code>) that all <code>Method(N)</code> classes will inherit from is shown below:</p>
<pre><code>public abstract class WebServiceInterfaceBridge <T,U,V,W> : WebServiceInterface
where T : class
where U : class
where V : class
where W : class
{
protected T WebMethod_Request;
protected U WebMethod_Response;
protected V COM_Request;
protected W COM_Response;
public WebServiceInterfaceBridge(T tPHSReq, U uPHSRsp, V vCBEReq, W wCBERsp)
{
WebMethod_Request = tPHSReq;
WebMethod_Response = uPHSRsp;
COM_Request = vCBEReq;
COM_Response = wCBERsp;
}
public abstract void LOG();
public void CallWebServiceMethod()
{
WebMethod_Response = CallWebMethod<T, U>(WebMethod_Request);
}
public void Process()
{
LOG();
CallWebServiceMethod();
}
}
</code></pre>
<p>And finally, here is the class that actually calls the Web service that the <code>WebServiceBridge</code> Class inherits from:</p>
<pre><code>public class WebServiceInterface
{
private ServiceClient WEBSVC = new ServiceClient();
public U CallWebMethod<T, U>(T tRequest)
where T:class
where U:class
{
if (tRequest.GetType() == typeof(Method2Request))
{
Method2Request Req = (Method2Request)(object)tRequest;
Method2Response Rsp = WEBSVC.Method2(Req);
return (U)(object)Rsp;
}
else if (tRequest.GetType() == typeof(Method1Request))
{
Method1Request Req = (Method1Request)(object)tRequest;
Method1Response Rsp = WEBSVC.Method1(Req);
return (U)(object)Rsp;
}
else
{
throw new NullReferenceException();
}
}
}
</code></pre>
<p>I have left out my internal classes for marshaling the Req/Rsp's, they are just classes with Member Vars and Get/Sets.</p>
<p>Before I carry on with my design, I am wondering, from an OO point of view, if I am approaching this task in the right way or if what I am doing is overkill and could be greatly simplified?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T11:46:36.527",
"Id": "46121",
"Score": "2",
"body": "Is this the real example? If it is, then i fail to see what is the purpose of `Method1`, `Method2`, etc. and why cant you have a single `WebServiceInterface`, which will handle all the requests/responses."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T11:49:17.303",
"Id": "46122",
"Score": "2",
"body": "Also classes like `WebServiceInterfaceBridge <T,U,V,W>` is almost always an indication, that you are not going the right way :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T11:52:55.893",
"Id": "46123",
"Score": "0",
"body": "Hi Nik, Yes this is a real example with sensitive code obscured, Method1 & Method2 of the webservice actually performs tasks like updating databases or creating tickets etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T11:53:40.457",
"Id": "46124",
"Score": "0",
"body": "\"Also classes like WebServiceInterfaceBridge <T,U,V,W> is almost always an indication, that you are not going the right way :) \" - Ok how do i achieve what i need without generic types?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T12:00:30.310",
"Id": "46125",
"Score": "0",
"body": "By using interfaces/baseclasses. I mean, there is nothing wrong with generics, its just that in your case using 4 generic parameters looks like an overkill."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T12:03:13.397",
"Id": "46126",
"Score": "0",
"body": "In your example, your `Method1` simply calls `base.Process`, which makes me question what exactly it does, what base class cant do?"
}
] |
[
{
"body": "<p>I think what you should do, is instead of spawning those <code>Method</code> classes you should implement a proper wrappers for com requests/responses, and then find the way to treat those wrappers the same way without the need to know, whats inside them. From the code you provided, i cant quite see whats stopping you. Off the bat, why cant you do something like:</p>\n\n<pre><code>interface IComWrapper\n{\n object GetComObject();\n //something else? \n}\n\nabstract class ComWrapperBase<T> : IComWrapper\n{\n public virtual object GetComObject()\n {\n return BaseObject;\n }\n\n protected ComWrapperBase(T baseObject)\n {\n BaseObject = baseObject;\n }\n\n protected T BaseObject { get; private set; }\n}\n\nclass Request1 : ComWrapperBase<CCOMReq>\n{\n public Request1(CCOMReq baseObject) : base(baseObject)\n {}\n\n public DateTime DateTime\n {\n get { return BaseObject.Date_Time; }\n set { BaseObject.Date_Time = value; }\n }\n\n public override string ToString()\n {\n return \"Something you might want to log?\";\n }\n\n //mapping\n}\n\nclass Response1 : ComWrapperBase<ICOMRsp>\n{\n public Response1(ICOMRsp baseObject) : base(baseObject)\n {}\n\n //mapping\n}\n\ninterface IComService\n{\n object Send(object comRequest);\n}\n\ninterface ILogging\n{\n void Log(object sender, string message);\n}\n\ninterface IWrappersFactory\n{\n T CreateWrapper<T>(object comObject);\n}\n\nclass WebServiceInterface\n{\n private readonly IComService _service;\n private readonly ILogging _log;\n private readonly IWrappersFactory _factory;\n\n public WebServiceInterface(IComService service, ILogging log, IWrappersFactory factory)\n {\n _service = service;\n _log = log;\n _factory = factory;\n }\n\n public TResponse Send<TRequest, TResponse>(TRequest request) \n where TRequest : IComWrapper \n where TResponse : IComWrapper\n {\n _log.Log(GetType(), request.ToString());\n var res = _service.Send(request.GetComObject());\n return _factory.CreateWrapper<TResponse>(res);\n }\n}\n\n//an example of how ComService implementation might look like (there is probably a better way)\nclass ComService : IComService\n{\n private readonly ServiceClient WEBSVC = new ServiceClient();\n\n //depending on ServiceClient implementation, this probably can be simplified\n public object Send(object comRequest)\n {\n var r1 = comRequest as CCOMReq;\n if (r1 != null)\n {\n return WEBSVC.Method1(r1);\n }\n //handle other messages\n //.....\n //.....\n throw new NotSupportedException();\n }\n}\n</code></pre>\n\n<p>Basically, what you are trying to do in you application is to ipmlement the same f**d up design that your ClientService has. What you should try to do instead is hide this design behind a bridge, and work with it dotNet-way using common OOP practices (meaning you should try to implement single generic method which sends all requests).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T12:48:57.470",
"Id": "29219",
"ParentId": "29217",
"Score": "0"
}
},
{
"body": "<p>You're definitely going in a wrong direction. Instead of trying to synthesize some weird generic classes in attempt to find a common general pattern in \"I send request and receive a reply, in each case requests and replies are different classes\", you should start from designing the interface of your communication, so that other layers of your system are abstracted from technical implementation of COM/Web service/whatever protocol you have to deal with.</p>\n\n<p>Based on your comment:</p>\n\n<blockquote>\n <p>Method1 & Method2 of the webservice actually performs tasks like updating databases or creating tickets etc</p>\n</blockquote>\n\n<p>we can define an interface like this:</p>\n\n<pre><code>public interface ITicketManager //bad name, just as an example\n{\n Ticket CreateTicket(string ticketName, string project /*, etc*/);\n bool TryMoveTicket(Ticket ticket, string newProject);\n Ticket CreateSubTicket(Ticket parent, string ticketName);\n}\n</code></pre>\n\n<p>As you see users of this interface don't know about those request-reply wrappers that you have in the underlying communication protocol, they are dealing with business entities. And implementation of this interface may look like this (just as example):</p>\n\n<pre><code>public class TicketManager: ITicketManager\n{\n public Ticket CreateTicket(string ticketName, string project)\n {\n CreateTicketRequest request = new CreateTicketRequest\n {\n Name = ticketName,\n Project = project\n };\n var response = WebServiceHook.Method1(request);\n return new Ticket\n {\n Id = response.Id,\n Name = response.TicketName,\n Project = response.Project\n }\n }\n\n public bool TryMoveTicket(Ticket ticket, string newProject)\n {\n MoveTicketRequest request = new MoveTicketRequest\n {\n Id = ticket.Id,\n FromProject = ticket.Project,\n NewProject = newProject\n };\n var response = WebServiceHook.Method2(request);\n\n if (response.Successful)\n ticket.Project = newProject;\n\n return response.Successful;\n }\n\n public Ticket CreateSubTicket(Ticket parent, string ticketName)\n {\n CreateTicketRequest request = new CreateTicketRequest\n {\n ParentId = parent.Id,\n Name = ticketName,\n Project = project\n };\n var response = WebServiceHook.Method1(request);\n\n return new Ticket\n {\n Id = response.Id,\n Parent = parent,\n Name = response.TicketName,\n Project = response.Project\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T05:55:55.620",
"Id": "29254",
"ParentId": "29217",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T09:58:54.873",
"Id": "29217",
"Score": "1",
"Tags": [
"c#",
"object-oriented",
".net"
],
"Title": "Web service performing different tasks"
}
|
29217
|
<p>I wrote this Jqeury to make it work with asp.net update panel. I know i do little bit of hacking to make it work just. I want to get some help in how to optimize and remove the hacks from my script.</p>
<pre><code><script type="text/javascript">
//get all elemnt with class .resource-download
$.each($(".resource-download"), function () {
var fileExtension = getFileExtension(this.href);
if (fileExtension == "" || fileExtension != "pdf") {
$(this).addClass("hideLinke");
}
});
//load script agine
function init() {
$.each($(".resource-download"), function () {
var fileExtension = getFileExtension(this.href);
if (fileExtension == "" || fileExtension != "pdf") {
$(this).addClass("hideLinke");
}
});
}
// getFileExtension
function getFileExtension(fileURL) {
if (fileURL.indexOf('.') === -1) { return ""; } //check for no extension
return fileURL.split('.').pop();
}
//loadGridLayout
function loadGridLayout() {
$('#grid-wrapper').masonry();
$('.selectpicker').selectpicker();
$('.btn-hamburger').click(function () {
$('.lts-nav').toggleClass('expanded');
$('.wrapper').toggleClass('wrapper-expanded');
});
/* iPhone Site Search Styling */
var searching = false;
$('.search-add-on').click(function () {
if ($(window).width() < 480) {
$('.section-1 .search-hideable').toggle();
$('.section-1 .site-search').focus();
searching = true;
}
});
$('.site-search').blur(function () {
if ($(window).width() < 480) {
$('.section-1 .search-hideable').toggle();
searching = false;
}
});
$(window).resize(function () {
if ((searching || !$('.site-search').is(':visible')) && $(window).width() > 480) {
$('.section-1 .search-hideable').toggle(true);
$('.section-1 .search-hideable').removeAttr('style');
searching = false;
}
});
}
//add script to script manager
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(init);
prm.add_endRequest(loadGridLayout);
</script>
</code></pre>
|
[] |
[
{
"body": "<p>Some notes in no particular order:</p>\n\n<p><strong>1</strong></p>\n\n<pre><code>//get all elemnt with class .resource-download\n$.each($(\".resource-download\"), function () {\n var fileExtension = getFileExtension(this.href);\n if (fileExtension == \"\" || fileExtension != \"pdf\") {\n $(this).addClass(\"hideLinke\");\n }\n});\n\n//load script agine \nfunction init() {\n $.each($(\".resource-download\"), function () {\n var fileExtension = getFileExtension(this.href);\n if (fileExtension == \"\" || fileExtension != \"pdf\") {\n $(this).addClass(\"hideLinke\");\n }\n });\n}\n</code></pre>\n\n<p>better to define the function and call it rather than copy paste the code. </p>\n\n<pre><code>function init() {\n $.each($(\".resource-download\"), function () {\n var fileExtension = getFileExtension(this.href);\n // see point 2\n if (fileExtension == \"\" || fileExtension != \"pdf\") {\n $(this).addClass(\"hideLinke\");\n }\n });\n}\n\ninit();\n</code></pre>\n\n<p><strong>2</strong></p>\n\n<pre><code>if (fileExtension == \"\" || fileExtension != \"pdf\") {\n</code></pre>\n\n<p>Is pointless, <code>\"\" !== \"pdf\"</code> so you should just have the second condition.</p>\n\n<pre><code>if (fileExtension !== \"pdf\") {\n</code></pre>\n\n<p><strong>3</strong><br>\nIt's better to be in the habit of using <code>===</code> and <code>!==</code> to avoid subtle bugs caused by type coercion.</p>\n\n<p><strong>4</strong></p>\n\n<p><code>$.each($(\".resource-download\"), function () {});</code> is better written as <code>$(\".resource-download\").each(function() {});</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T14:22:22.413",
"Id": "29228",
"ParentId": "29223",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29228",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T13:45:48.477",
"Id": "29223",
"Score": "0",
"Tags": [
"javascript",
"jquery",
"asp.net"
],
"Title": "How to optimize jQuery to run on asp.net web form updatepanel?"
}
|
29223
|
<p>To get more familiar with Java, I decided to make a Tetris clone.</p>
<p>As I finished the <code>Tiles</code> beans class, I went to the <a href="http://en.wikipedia.org/wiki/Tetromino" rel="nofollow noreferrer"><code>Tetromino</code></a> class, which is basically made of different sets of 4 <code>Tiles</code> objects (I'm grouping them with <code>ArrayLists</code>). Each <code>Tetromino</code> has a different colour and shape.</p>
<p>Would it be better practice to identify what Tetromino I'm trying to make right in the <code>Tetromino</code> class, or should I make a different class for each different kind of Tetromino available, probably extending the <code>Tetromino</code> class?</p>
<hr />
<p><strong>Example</strong></p>
<p>(Please note that these are just design-illustrative made to represent my question)</p>
<p>Instead of something like:</p>
<pre><code>public class Tetromino {
private ArrayList<Tiles> tiles = new ArrayList<Tiles>();
public Tetromino(char shape) {
switch(shape) {
case 'L':
createLShapedTetr();
break;
/* etcetera */
}
}
private void createLShapedTetr(){
/*
Sets color for bricks
Adds each brick (with their X and Y coordinates) to the arrayList
*/
}
/* other methods, such as spinPiece() */
}
</code></pre>
<p>Do something like this:</p>
<pre><code>public class Tetromino {
private ArrayList<Tiles> tiles = new ArrayList<Tiles>();
/* Tetrominoes basic methods that every Tetr does */
}
public class TetrominoShapeJ extends Tetromino {
/* sets colour, space and spin-method in here */
}
</code></pre>
|
[] |
[
{
"body": "<p>From an Object Oriented perspective, it's better to create extending classes, as in your second suggestion. This makes it easier to add more implementations in the future, to override existing implementations to create even more specialized behavior, etc.</p>\n\n<p>In your case, however, since there is a mathematical limit to the number of one-sided tetrominos, I think your first approach is fine.</p>\n\n<p>Do you plan on making lots of different types of tetrominos, different colors, textures, or other highly customizable things? I have a feeling <a href=\"http://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow\">YAGNI</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T17:13:56.940",
"Id": "46153",
"Score": "0",
"body": "Thank you for your answer. The only customizable things that I'm planning to do are outside the Tetromino scope."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T15:33:04.353",
"Id": "29232",
"ParentId": "29224",
"Score": "1"
}
},
{
"body": "<p>I think that the principle which applies here is <strong>favour composition over inheritance</strong>.</p>\n\n<p>Java provides a straightforward implementation of the lightweight pattern via <code>enum</code>. You can set up an enum <code>TetrominoShape</code> with 7 possible values:</p>\n\n<pre><code>public enum TetrominoShape {\n I,\n O,\n etc.\n}\n</code></pre>\n\n<p>Then each <code>Tetromino</code> instance would have a <code>final TetrominoShape</code> field, a position, an orientation, etc.</p>\n\n<p>I don't see any need for <code>Tiles</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T17:00:40.257",
"Id": "29235",
"ParentId": "29224",
"Score": "1"
}
},
{
"body": "<p>Go for static factory methods : allow creation only through static methods on your class, keep the constructor private.</p>\n\n<p>(also keep that List of Tiles private)</p>\n\n<pre><code>public class Tetromino {\n private ArrayList<Tiles> tiles;\n\n private Tetromino(List<Tile> tiles) {\n this.tiles = new ArrayList<Tiles>(tiles)\n }\n\n public static Tetromino createLShaped(){ \n // create tiles\n // call private constructor \n }\n\n /* other methods... */\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T20:05:20.883",
"Id": "29243",
"ParentId": "29224",
"Score": "1"
}
},
{
"body": "<p>You should only create subclasses for the different shapes if they are going to behave differently. If I were implementing it, I don't think they would behave differently, so I would not make subclasses for them. I think in my case every method would be the same, and each instance might have a different set of points with the blocks it covered. So an example method called public boolean canMoveDown might check the shapes points against any points on the game board below it, which would be the same implementation for each shape.</p>\n\n<p>I don't think you should be passing a char to the constructor, though. I'd prefer an enum, or barring that, the set of points the particular shape you are creating covers, with that set kept in a factory. That keeps all of that data out of the class and the class is just responsible for processing the set of points it takes up. When coding try to follow the single responsibility principle where each class has one thing to do. This keeps everything much simpler and much easier to test and maintain.</p>\n\n<p>Studies on software development have shown that systems with a large amount of inheritance are tougher to work on, tougher to maintain, and have more bugs. It's basically hidden functionality when you are looking at any class and it has a whole set of classes above it in an inheritance chain. So using inheritance for no reason is very bad.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T18:05:07.240",
"Id": "29272",
"ParentId": "29224",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29272",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-07-31T13:55:08.153",
"Id": "29224",
"Score": "0",
"Tags": [
"java",
"object-oriented",
"design-patterns"
],
"Title": "Creating tetrominoes in game"
}
|
29224
|
<p>Given a table, I want to explore all possible <strong>transition</strong> between the elements in the table.
ex: for a table with size 3 [0,1,2], the output of the algorithm should be 0->1, 1->0, 0->2, 2->1, 1->2, 2->0.
I guess this can be regarded as traversing a complete graph.</p>
<p>I have an implementation of an algorithm doing this in Python:</p>
<pre><code>def test1(n):
theList=[]
theList.append(0)
for x in range(0,n+1):
for y in range(n,x+1,-1):
theList.append(y)
theList.append(x)
if x!=n:
theList.append(x+1)
for x in range(n,0,-1):
theList.append(x-1)
return theList
</code></pre>
<p>This code always start at element 0, and return a list of all the transitions.</p>
<p>But I need my algorithm i Prolog. So I have done an attempt to port the Python-code to Prolog. My main focus has been on writing readable and maintainable code. But I guess there is great room for improvement wrt. performance of the Prolog code:</p>
<pre><code>:- use_module(library(clpfd)).
:- use_module(library(between)).
:- use_module(library(lists)).
dynappend( List, X ) :-
(
foreach( Item, List ),
param(X,T)
do
var( Item ), var(T) ->
Item = X ,
T = 1
;
true
).
s3(List,N):-
LSize is N*(N+1)+1,
length(List,LSize),
dynappend( List, 0 ),
(
for(X1, 0, N ),
param( N, List )
do
X1T is X1+2,
( between:numlist( X1T, N, YList ) -> true ; YList=[] ) ,
lists:reverse(YList,RYList),
(
foreach(Y, RYList ),
param( X1, List )
do
dynappend( List, Y ),
dynappend( List, X1 )
),
( X1 #\= N -> X1T2 is X1+1, dynappend( List, X1T2 ) ; true )
),
N1 is N-1,
numlist( 0, N1, XList ),
lists:reverse(XList,RXList),
(
foreach(X2, RXList ),
param(List)
do
dynappend( List, X2 )
).
</code></pre>
<p>Running the code: </p>
<pre><code>| ?- s3(L, 2).
L = [0,2,0,1,2,1,0] ?
yes
</code></pre>
<p>Any suggestions for improvements of the Prolog code?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T09:30:32.147",
"Id": "46140",
"Score": "0",
"body": "if you get the habit to use 'yield' in Python, you will end with much more Prolog like code, very similar to what @Mat shows"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T14:31:34.797",
"Id": "46141",
"Score": "0",
"body": "If someone suggests that a question belongs to codereview.SE please flag/ask a moderator to move it next time. Make a comment to move the question if you can't see the flag button and someone else will flag it. Posting the same question on both sites isn't considered good. Just wait a bit."
}
] |
[
{
"body": "<p>Consider describing what a transition is:</p>\n\n<pre><code>list_transition(List, (E1->E2)) :-\n select(E1, List, Rest),\n member(E2, Rest).\n</code></pre>\n\n<p>Example query:</p>\n\n<pre><code>?- list_transition([0,1,2], T).\nT = (0->1) ;\nT = (0->2) ;\nT = (1->0) ;\nT = (1->2) ;\nT = (2->0) ;\nT = (2->1) ;\nfalse.\n</code></pre>\n\n<p>And to get all transitions:</p>\n\n<pre><code>?- findall(T, list_transition([0,1,2], T), Transitions).\nTransitions = [ (0->1), (0->2), (1->0), (1->2), (2->0), (2->1)].\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T09:24:43.340",
"Id": "29230",
"ParentId": "29229",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "29230",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T08:14:13.307",
"Id": "29229",
"Score": "5",
"Tags": [
"algorithm",
"graph",
"prolog"
],
"Title": "Complete graph traversal algorithm in Prolog"
}
|
29229
|
<p>I had posted <a href="https://salesforce.stackexchange.com/questions/14324/recursive-functions-apex">a question</a> some time back for the best way of doing an account hierarchy, and this is the way implemented at last.</p>
<p>Can someone point out any obvious flaw in this (other than SOQL)?</p>
<p>The use case is to find the first account which has IS VGE flag checked, or if no IS VGE ones in hierarchy get the topmost one.</p>
<p>Once you get the record, update some fields with this records' value. If no parent is present, don't bother. There's no business limit in hierarchy levels.</p>
<p>The below method is called by a before insert and before update triggers:</p>
<pre><code> public with sharing class Find {
//Static variable to make sure method is called only once
public static boolean firstRun_GlobalUltimate = true;
public static void findGlobal(list<account>Triggerlist)
{
map<Integer,id> Treemap = new map<Integer,ID>();
account a = new account();
set<ID> parentIdSet = new set<ID>();
Map<ID,Account>parentRec= new map<ID,Account>();
Id accid;
account gm;
map<ID,Account>queryMap = new map<ID,Account>();
//Forming a map of current Account indexes and their parents,if there is any
for (integer n=0; n< TriggerList.size(); n++)
{
//Checking if Parent is missing for the record
If (TriggerList[n].ParentId != null)
{
//Add key for map as index of item in list,Value as Parent ID present for Account
treeMap.put(n, TriggerList[n].ParentId);
//Add parent id to parentIdset to be used in account heirarchy loop
parentIdSet.add(TriggerList[n].ParentId);
}
}//End of main for loop
//Account hierarchy traversy Loop:Applicable only to accounts with a parent
//Once loop is executed Treemap will be updated with either
//first VGE account it met in hierarchy or the top most account in heirarchy
do
{
//Clear the querymap
querymap.clear();
//Select parent record with Is vge account and its parentid
queryMap = new map<ID,Account>([select Is_VGE_Account__c ,Segment__c,Public_sector__c,parentid from account where id in :parentidset]);
//Clear parentidset
parentidset.clear();
//check whether map is empty
if(!querymap.isempty())
{
//Traverse through the treemap
for(integer i:treemap.keyset())
{
accid = treemap.get(i);
if(querymap.containskey(accid) )
{ //Get the parent record
gm = querymap.get(accid);
//Form a map of all parent record
parentRec.put(gm.id,gm);
//If Parent is not a VGE Account add its parent id to parentid set for next fetch and update treemap
if((!gm.is_vge_account__c) && (gm.parentID!=null))
{
parentIdSet.add(gm.parentID);
treemap.put(i,gm.parentid);
}
}//end of checking whether querymap returned record
}//end of traversing through keymap
}//End of querymap empty checking
}while((!querymap.isempty()) && Limits.getQueries()<50);//Making sure SOQL Limit of 100 is not hit
//Updating incoming Accounts
for (integer n=0; n< TriggerList.size(); n++)
{
//Check if the account has a parent and has an entry in treemap,if so update the Global
//Ultimate value to the value in Treemap.For accounts without parent ,Global Ultimate remains null
if(Treemap.containskey(n))
{
Triggerlist[n].Global_Ultimate__c = Treemap.get(n);
}
//Check if Customer Account and whether without a Global Ultimate
if(GEN_Utilities.recordType(Triggerlist[n].recordTypeId) == 'Customer Account' && (Triggerlist[n].Global_Ultimate__c!=null) )
{
//Get the record from parentRecmap
gm = parentRec.get(Triggerlist[n].Global_Ultimate__c);
//Update the account with Global ultimate's segment and public sector
Triggerlist[n].Segment__c = gm.Segment__c;
Triggerlist[n].Public_sector__c = gm.Public_sector__c;
}
}//End of updating incoming accounts loop
}//End of method
}//End of Class
</code></pre>
|
[] |
[
{
"body": "<p>Nothing jumps out at me as a huge problem since you are checking the number of queries executed in the trigger's context. I do agree with the original suggestion of preferring batch Apex, though scheduling Apex from within a trigger can be dangerous. If you don't need these values updated immediately, I would suggest trying scheduled Apex (perhaps a job that runs 1-3x daily?) You could use a custom field on the object to flag it be evaluated during the batch.</p>\n\n<p>I do have one concern: what happens if you hit your self-imposed 50 query limit before you finish traversing the tree? What's the fallback in that case? Potentially other triggers could activate and use at least 50 SOQL queries before even getting to your method.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T11:30:08.263",
"Id": "29262",
"ParentId": "29245",
"Score": "2"
}
},
{
"body": "<p>I'd be tempted to traverse the relationships in the queries bit more. In any given query you can use up to 5 dots to go \"up\" and 1 subquery to go down (to a related list if you like).</p>\n\n<p>So - while this looks bit crazy and would mean some restructuring - you could end up with some massive savings in the amount of queries:</p>\n\n<pre><code>SELECT Id, Name,\n Parent.Id, Parent.Name,\n Parent.Parent.Id, Parent.Parent.Name,\n Parent.Parent.Parent.Id, Parent.Parent.Parent.Name, \n Parent.Parent.Parent.Parent.Id, Parent.Parent.Parent.Parent.Name,\n Parent.Parent.Parent.Parent.Parent.Id, Parent.Parent.Parent.Parent.Parent.Name,\n Parent.Parent.Parent.Parent.Parent.ParentId /* Can't go further, needs new query */\nFROM Account\nWHERE ParentId != null\n</code></pre>\n\n<p>You would still have to take uniqueness into account (if 2 records with same parent will be processed with your trigger, that parent will appear once for each of them), so it still needs something like <code>Map<Id, Account></code>.</p>\n\n<p>And a small variant if you need something that lists all \"level 3 parents\" for example:</p>\n\n<pre><code>SELECT Parent.Parent.Parent.Id, Parent.Parent.Parent.Name\nFROM Account\nWHERE Parent.Parent.Parent.Id != null\nGROUP BY Parent.Parent.Parent.Id, Parent.Parent.Parent.Name\n</code></pre>\n\n<p>(without <code>GROUP BY</code> the list will contain duplicates)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T13:38:15.777",
"Id": "37412",
"ParentId": "29245",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T21:28:43.500",
"Id": "29245",
"Score": "2",
"Tags": [
"salesforce-apex"
],
"Title": "Account hierarchy"
}
|
29245
|
<p>For a university project I'm trying to build a system that has a general architecture of:</p>
<p>Client app <=====> Client library < - - > Server library <=====> Server app</p>
<p>I'm trying to make the client and server as general (in the context of a java application, cross-platform compatibility is a concern for later) as possible, so the client library serializing objects from the client app to send to the server and deserializing objects from the server as responses. </p>
<p>I have the client library written, and a simple test application that just sends String objects to the client library for sending to the server. I've gotten cleanup code which (I believe) works fairly well in the client library, but the cleanup code in the test app doesn't seem to work, even though it's quite similar. It leaves its threads running and doesn't shut down. The TestApp.UpstreamThread remains in the running state, while the TestApp.DownstreamThread remains in the waiting state forever. As you can see from the code, when one thread ends it's supposed to interrupt() the other. </p>
<p>The code for the test app is as follows: </p>
<pre><code>public class TestApp {
private UpstreamChannel upstream = null;
private DownstreamChannel downstream = null;
private Thread upstreamThread = null;
private Thread downstreamThread = null;
private Client <String> client = null;
private boolean ending = false;
/**
*
*/
private class UpstreamChannel implements Runnable {
private TestApp outer = null;
/**
*
*/
@Override
public void run () {
Thread.currentThread ().setName ("TestApp.UpstreamChannel");
try (BufferedReader inReader = new BufferedReader (new InputStreamReader (System.in))) {
while (!this.outer.ending) {
this.outer.client.acceptMessage (inReader.readLine ());
}
} catch (IOException ex) {
Logger.getLogger (this.getClass ().getName ()).log (Level.SEVERE, null, ex);
} finally {
this.outer.ending = true;
this.outer.downstreamThread.interrupt ();
Thread.currentThread ().interrupt ();
return;
}
}
/**
*
* @param app
*/
public UpstreamChannel (TestApp app) {
this.outer = app;
}
}
/**
*
*/
private class DownstreamChannel implements Runnable {
private TestApp outer = null;
/**
*
*/
@Override
public void run () {
Thread.currentThread ().setName ("TestApp.DownstreamChannel");
try {
while (!this.outer.ending) {
System.out.println (this.outer.client.getMessage ());
}
} catch (InterruptedException ex) {
Logger.getLogger (this.getClass ().getName ()).log (Level.INFO, null, ex);
} finally {
this.outer.ending = true;
this.outer.upstreamThread.interrupt ();
Thread.currentThread ().interrupt ();
return;
}
}
/**
*
* @param app
*/
public DownstreamChannel (TestApp app) {
this.outer = app;
}
}
/**
*
*/
public void run () {
if ((null == this.upstreamThread)
&& (null == this.downstreamThread)) {
this.upstreamThread = new Thread (this.upstream);
this.downstreamThread = new Thread (this.downstream);
this.upstreamThread.start ();
this.downstreamThread.start ();
}
}
/**
*
*/
public TestApp (Client <String> client) {
this.upstream = new UpstreamChannel (this);
this.downstream = new DownstreamChannel (this);
this.client = client;
Logger.getLogger (this.getClass ().getName ()).log (Level.INFO, "Class instantiated");
}
}
</code></pre>
<p>And this is the client library: </p>
<pre><code>public class Client <T> {
private String hostname = "localhost";
private Integer port = 8113;
private Socket connection = null;
private DownstreamChannel downstream = null;
private UpstreamChannel upstream = null;
private Thread upstreamThread = null;
private Thread downstreamThread = null;
/**
* This thread handles waiting for messages from the attached app and
* sending them to the server
*/
private class UpstreamChannel <T> implements Runnable {
private Client outer = null;
private BlockingQueue <T> inputQueue = null;
/**
* Send messages to server
*
* This method waits for input from the attached app and writes it to
* the server's socket as a serialized object.
*/
@Override
public void run () {
Thread.currentThread ().setName ("Client.UpstreamChannel");
try (ObjectOutputStream outWriter = new ObjectOutputStream (this.outer.connection.getOutputStream ())) {
while (true) {
// Get last input line from the user
outWriter.writeObject (this.inputQueue.take ());
outWriter.flush ();
}
} catch (IOException | InterruptedException ex) {
Logger.getLogger (this.getClass ().getName ()).log (Level.SEVERE, null, ex);
} finally {
this.outer.downstreamThread.interrupt ();
return;
}
}
/**
* Accept a message to send upstream
*
* @param message
* @return
*/
public UpstreamChannel acceptMessage (T message) {
this.inputQueue.add (message);
return this;
}
/**
* Initialize the upstream channel
*
* @param outer
*/
public UpstreamChannel (Client outer) {
this.outer = outer;
this.inputQueue = new LinkedBlockingQueue ();
}
}
/**
* This thread handles waiting for messages from the server and sending them
* to the connected client
*/
private class DownstreamChannel <T> implements Runnable {
private Client outer = null;
private BlockingQueue <T> outputQueue = null;
/**
* Get messages from server
*
* This loop waits for messages from the server and pushes them into
* the downstream queue
*/
@Override
public void run () {
Thread.currentThread ().setName ("Client.DownstreamChannel");
try (ObjectInputStream inReader = new ObjectInputStream (this.outer.connection.getInputStream ())) {
while (true) {
this.outputQueue.add ((T) inReader.readObject ());
}
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger (this.getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
this.outer.upstreamThread.interrupt ();
return;
}
}
/**
* Get the first unprocessed message from the downstream queue
*
* @return
* @throws InterruptedException
*/
public T getMessage () throws InterruptedException {
return this.outputQueue.take ();
}
/**
* Initialize the downstream channel
*
* @param outer
*/
public DownstreamChannel (Client outer) {
this.outer = outer;
this.outputQueue = new LinkedBlockingQueue ();
}
}
/**
* Start the main loop
*/
public void run () throws IOException, InterruptedException {
if ((null == this.upstreamThread)
&& (null == this.downstreamThread)) {
this.upstreamThread = new Thread (this.upstream);
this.downstreamThread = new Thread (this.downstream);
this.upstreamThread.start ();
this.downstreamThread.start ();
}
}
/**
* Send a message to the server
*
* @param message
* @return
*/
public Client acceptMessage (T message) {
this.upstream.acceptMessage (message);
return this;
}
/**
* Get the next unprocessed message from the server
*
* @return
* @throws InterruptedException
*/
public T getMessage () throws InterruptedException {
return (T) this.downstream.getMessage ();
}
/**
* Initialize the client
*
* @param hostname
* @param port
*/
public Client (String hostname, Integer port) throws UnknownHostException, IOException {
this.hostname = hostname;
this.port = port;
this.connection = new Socket (this.hostname, this.port);
this.upstream = new UpstreamChannel (this);
this.downstream = new DownstreamChannel (this);
}
}
</code></pre>
<p>The class that runs the code is basically just a stub but I've included it for completeness. </p>
<pre><code>public class TestClient {
/**
*
* @param args
* @throws Exception
*/
public static void main (String[] args) throws UnknownHostException, IOException, InterruptedException {
Client <String> clientInstance = new Client ("localhost", 8113);
TestApp app = new TestApp (clientInstance);
clientInstance.run ();
app.run ();
}
}
</code></pre>
<p>Whilst the test app is obviously a fairly disposable bit of code, I would like it to clean up properly as it will form the skeleton on which the actual client applications will be built. </p>
<p>I'm also curious as to the quality of the code I've produced (which I think this is better suited to a code review than a question on Stack Exchange). I've been trying to follow recommendations as regards cleaning up after yourself, and it does seem to work, but I'm wondering if it's sufficiently robust. Any input on the cleanup code quality would be appreciated. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T10:11:27.283",
"Id": "46201",
"Score": "0",
"body": "I suspect the issue is one of the client library needing to notify the application that it's ceased talking to the server. I just need to figure out a decent mechanism for doing it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T16:06:16.997",
"Id": "46267",
"Score": "0",
"body": "Currently you have no code or interface that even tries to initiate a clean shutdown. The Socket is never closed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T20:16:57.683",
"Id": "46278",
"Score": "0",
"body": "It's a try-with-resource block. `try (ObjectOutputStream outWriter = new ObjectOutputStream (this.outer.connection.getOutputStream ()))` means that Java should automatically close the inputstreamreader when the try block exits so you don't have to put it there explicitly. It's a java 7 feature."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T22:30:35.300",
"Id": "46303",
"Score": "0",
"body": "I know, the point is : nothing ever triggers it to close."
}
] |
[
{
"body": "<p>Tidbits for you:</p>\n\n<pre><code>private UpstreamChannel upstream = null;\nprivate boolean ending = false;\n</code></pre>\n\n<p>Instance variables are initialized to <code>null</code> by default, and boolean values are set to <code>false</code> by default. </p>\n\n<p>Without applying <a href=\"http://whitemagicsoftware.com/encapsulation.pdf\" rel=\"nofollow noreferrer\">self-encapsulation</a>, the classes will not be as extensible as they could be.</p>\n\n<p>The following lines:</p>\n\n<pre><code> Logger.getLogger (this.getClass ().getName ()).log (Level.SEVERE, null, ex);\n Logger.getLogger (this.getClass ().getName ()).log (Level.INFO, \"Class instantiated\");\n</code></pre>\n\n<p>Have duplicate code that could be eliminated using:</p>\n\n<pre><code> getLogger().log( ... );\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>private void Logger getLogger() {\n return Logger.getLogger( this.getClass ().getName () );\n}\n</code></pre>\n\n<p>This method can be eliminated altogether using a static LOGGER instance variable and obtaining the <a href=\"https://stackoverflow.com/a/2971457/59087\">class name dynamically</a>. And it can be simplified even more by using <a href=\"http://en.wikipedia.org/wiki/Aspect-oriented_programming\" rel=\"nofollow noreferrer\">aspects</a> to inject logging when required.</p>\n\n<p>An empty <code>return</code> line from the <code>finally</code> block is superfluous.</p>\n\n<p>Avoid code such as:</p>\n\n<pre><code> this.outer.ending = true;\n</code></pre>\n\n<p>Instead:</p>\n\n<pre><code> getOuter().endDownstream();\n</code></pre>\n\n<p>The <code>endDownstream()</code> method would resemble:</p>\n\n<pre><code>public void end() {\n setEnding( true );\n}\n\npublic void endDownstream() {\n end();\n getDownstreamThread().interrupt();\n}\n</code></pre>\n\n<p>The corresponding <code>endUpstream()</code> method:</p>\n\n<pre><code>public void enUpstream() {\n end();\n getUpstreamThread().interrupt();\n}\n</code></pre>\n\n<p>This can be refactored further, to merge both methods into a single call (note that the <code>end()</code> method can be eliminated, as well, since <code>setEnding(true)</code> now only exists once in the code):</p>\n\n<pre><code>public void endStream() {\n setEnding( true );\n getStreamThread().interrupt();\n}\n</code></pre>\n\n<p>There is a bit of duplication between <code>UpstreamChannel</code> and <code>DownstreamChannel</code>. The duplication can be abstracted using a common <code>AbstractChannel</code> class via polymorphism. For example, it appears as though all channels have a name, which leads to duplicate code such as:</p>\n\n<pre><code> Thread.currentThread ().setName (\"Client.UpstreamChannel\");\n</code></pre>\n\n<p>This can be written, instead, as:</p>\n\n<pre><code>public class AbstractChannel <T> implements Runnable {\n public void run() {\n Thread.currentThread().setName (getName());\n }\n\n protected abstract String getName();\n}\n\nprivate class UpstreamChannel <T> extends AbstractChannel {\n protected String getName() {\n return \"Client.UpstreamChannel\";\n }\n\n public void run () {\n super.run();\n // ...\n</code></pre>\n\n<p>Now the superclass isolates how the name is set in a single location for all subclasses. The subclasses simply change <code>getName()</code> to return their name.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T04:00:31.857",
"Id": "35660",
"ParentId": "29247",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T22:04:57.093",
"Id": "29247",
"Score": "2",
"Tags": [
"java",
"multithreading",
"socket"
],
"Title": "Proper cleanup in multithreaded client/server code"
}
|
29247
|
<p>I am new to JavaScript. I know that many inheritance and initialization methods have been written and use some advance features like <code>Object.create</code>:</p>
<p><a href="http://ejohn.org/blog/simple-javascript-inheritance/" rel="nofollow">Simple JavaScript Inheritance</a></p>
<p><a href="http://aaditmshah.github.io/why-prototypal-inheritance-matters/" rel="nofollow">Why Prototypal Inheritance Matters</a></p>
<p>For practice, I wrote my own methods for inheritance and initialization. I have no idea if my code is good or if it could be improved. Could someone help me and give me some advice?</p>
<pre><code>function Class() {};
Class.prototype.create = function () {
var constr = this.constructor;
var instance = new constr();
for (var i = 0; i < arguments.length; i++) {
var props = arguments[i];
for (var name in props){
instance[name] = props[name];
}
}
return instance;
}
Class.prototype.extend = function () {
var constr = this.constructor;
var proto = this.constructor.prototype;
function ProtoClas() {};
var prototype = ProtoClas.prototype = (function (proto) {
function F() {};
F.prototype = proto;
return new F();
})(proto);
ProtoClas.prototype.constructor = ProtoClas;
for (var i = 0; i < arguments.length; i++) {
var props = arguments[i];
for (var name in props){
prototype[name] = props[name];
}
}
return new ProtoClas();
}
Class.extend = function () {
var args = Array.prototype.slice.call(arguments);
return this.prototype.extend.apply(new this(), args);
}
Class.create = function () {
var args = Array.prototype.slice.call(arguments);
return this.this.prototype.create.apply(this, args);
}
</code></pre>
<p>I then generate a new Class and an instance through this Class:</p>
<pre><code>var Person = Class.extend({
say: function () {
console.log("Hello");
},
walk: function () {
console.log("walk");
}
});
var person = Person.create({
name:'lee'
})
console.log(Person);
console.log(person);
</code></pre>
|
[] |
[
{
"body": "<p>I'm the author of <a href=\"http://aaditmshah.github.io/why-prototypal-inheritance-matters/\" rel=\"nofollow noreferrer\">Why Prototypal Inheritance Matters</a>. It's good that you're taking an interest in prototypal inheritance. So let's review your code. I'll start with your use case and then discuss the implementation.</p>\n<h1>The Use Case</h1>\n<pre><code>var Person = Class.extend({\n say: function () {\n console.log("Hello");\n },\n walk: function () {\n console.log("walk");\n }\n});\n\nvar person = Person.create({\n name:'lee'\n});\n\nconsole.log(Person);\nconsole.log(person);\n</code></pre>\n<p>This code looks good. It's very similar to what I wrote in my aforementioned article. I would like to point out one thing though: you don't need two separate methods <code>extend</code> and <code>create</code>. Object creation and extension may be <a href=\"http://aaditmshah.github.io/why-prototypal-inheritance-matters/#combining_object_creation_and_extension\" rel=\"nofollow noreferrer\">combined into a single function</a>. Hence you could do:</p>\n<pre><code>var Person = Class.extend({\n say: function () {\n console.log("Hello");\n },\n walk: function () {\n console.log("walk");\n }\n});\n\nvar person = Person.extend({\n name: "lee"\n});\n\nconsole.log(Person);\nconsole.log(person);\n</code></pre>\n<h1>The Implementation</h1>\n<p>Since you only require one method for prototypal inheritance I'll primarily focus on your <code>extend</code> function. First, your <code>Class.extend</code> method is needlessly complicated. I would rewrite it as:</p>\n<pre><code>function Class() {}\n\nvar extend = Class.prototype.extend = function () {\n //...\n};\n\nClass.extend = function () {\n return extend.apply(new Class, arguments);\n};\n</code></pre>\n<p>As you can see you don't need to call <code>Array.prototype.slice</code> on <code>arguments</code>. It may be directly passed to <code>apply</code>. In addition try keeping things in variables as much as possible. Avoid expressions like <code>this.prototype.extend</code>. Also be explicit: write <code>new Class</code> instead of <code>new this()</code>.</p>\n<hr />\n<p>Your <code>Class.prototype.extend</code> function is not only confusing but also wrongly implemented. It doesn't extend the given object <code>this</code>. Instead it extends <code>ProtoClas.prototype</code> which is actually just <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create\" rel=\"nofollow noreferrer\" title=\"Object.create - JavaScript | MDN\"><code>Object.create</code></a>. I would implement <code>Class</code> as follows:</p>\n<pre><code>function Factory() {}\n\nvar CLASS = {\n extend: function () {\n Factory.prototype = this;\n var instance = new Factory;\n var length = arguments.length;\n var index = 0;\n\n while (index < length) {\n var prototype = arguments[index++];\n\n for (var property in prototype)\n if (instance[property] !== prototype[property])\n Object.defineProperty(instance, property,\n Object.getOwnPropertyDescriptor(prototype, property));\n }\n\n return instance;\n }\n};\n</code></pre>\n<p>You may now use <code>CLASS.extend</code> as follows:</p>\n<pre><code>var PERSON = CLASS.extend({\n say: function () {\n console.log("Hello");\n },\n walk: function () {\n console.log("walk");\n }\n});\n\nvar person = PERSON.extend({\n name: "lee"\n});\n\nconsole.log(PERSON);\nconsole.log(person);\n</code></pre>\n<p>Note that instead of doing <code>var instance = Object.create(this)</code> I used a function called <code>Factory</code> instead. The reason for doing this is performance: <code>Object.create</code> creates a new constructor every time. Here I'm simply reusing a single <code>Factory</code> constructor.</p>\n<p>In addition for each argument supplied to <code>extend</code> I copy all the properties of the argument to the instance only if it doesn't already exist. This check speeds up the process because every object inherits from <code>Object.prototype</code> and copying is a very expensive operation.</p>\n<p>Also instead of copying the properties using <code>instance[property] = prototype[property]</code> I'm using <code>Object.defineProperty</code> and <code>Object.getOwnPropertyDescriptor</code>. The allows you to copy properties as is allowing you to use getters/setters, etc.</p>\n<h1>The Alternative</h1>\n<p>On a concluding note I would like to mention that true prototypal inheritance is slow in JavaScript because JavaScript <a href=\"http://aaditmshah.github.io/why-prototypal-inheritance-matters/#constructors_vs_prototypes\" rel=\"nofollow noreferrer\">favors the constructor pattern of prototypal inheritance</a> instead. Hence if you wish to write fast code then I suggest you read the following article which describes prototype-class isomorphism: <a href=\"https://stackoverflow.com/a/17893663/783743\">https://stackoverflow.com/a/17893663/783743</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T07:18:21.443",
"Id": "47627",
"Score": "0",
"body": "Thank you very much, as you say recently I am interested in javascript inheritance, again I do an improved job on John Resig's Simple JavaScript Inheritance, inspired by your `Object.create` method, could help check it good or bad? http://codereview.stackexchange.com/questions/30018/i-do-an-improvement-job-on-john-resigs-simple-javascript-inheritance-please-ch"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T15:48:26.273",
"Id": "29956",
"ParentId": "29251",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29956",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T03:32:34.223",
"Id": "29251",
"Score": "1",
"Tags": [
"javascript",
"inheritance"
],
"Title": "Please check if these two methods for inheritance and initialization are good or bad"
}
|
29251
|
<p>I have written this big function to do some formatting in my python code. Would you be able to suggest anyways to make this smaller ? </p>
<pre><code>def disfun(String1,String2,String3):
if String3 == "A" or String3 == "B":
if String3 == "A":
pass
elif String3 == "B":
print "#"*54
print "##"," "*48,"##"
print "##",'{0:^48}'.format(String2),"##"
print "##",'{0:^48}'.format(String1),"##"
print "##"," "*48,"##"
print "#"*54
elif String3 == "C":
print "-"*40
print "--",'{0:^34}'.format(String2),"--"
print "-"*40
elif String3 == 'D':
String2 = ' * '.join(String2)
print "#"*54
print "##",'{0:^48}'.format(String2),"##"
print "##",'{0:^48}'.format(String1),"##"
print "#"*54
elif String3 == 'E':
print "*"*54
print "**",'{0:^48}'.format(String2),"**"
print "**",'{0:^48}'.format(String1),"**"
print "*"*54
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T12:26:42.750",
"Id": "46209",
"Score": "0",
"body": "I am at a loss why you'd call \"String3\" something that's clearly the type of banner, and \"String2\" to something that on one of the branches is `join`ed (so it's in fact a collection). Very cryptic."
}
] |
[
{
"body": "<p>Ok, the first thing is that the names are not at all descriptive. <code>disfun</code>? What does that mean? Maybe something like <code>generateReport</code>? What are the purposes of <code>String1</code> and <code>String2</code>? Why does <code>String2</code> get printed before <code>String1</code>? Why does <code>String1</code> not get printed at all when <code>String3</code> is <code>\"C\"</code>? Also, python variables tend to begin with a lowercase letter, not an uppercase letter.</p>\n\n<p>As to shortening the function, there's a rule of thumb called DRY: Don't Repeat Yourself. If you see the same code written several times, extract it into a function.</p>\n\n<p>Here's a first shot at improving your code:</p>\n\n<pre><code>def __printBannerEdge(char, width):\n assert len(char) == 1\n print char * width\n\n\ndef __printBannerContent(char, width, content):\n assert len(char) == 1\n print char * 2, ('{0:^' + str(width - 6) + '}').format(content), char * 2\n\n\ndef __printBanner(char, width, lines):\n __printBannerEdge(char, width)\n for line in lines:\n __printBannerContent(char, width, line)\n __printBannerEdge(char, width)\n\n\ndef generateReport(content, title, selection):\n if selection == \"A\" or selection == \"B\":\n if selection == \"B\":\n __printBannerEdge('#', 54)\n __printBannerContent('#', 54, '')\n __printBannerContent('#', 54, title)\n __printBannerContent('#', 54, content)\n __printBannerContent('#', 54, '')\n __printBannerEdge('#', 54)\n\n elif selection == \"C\":\n __printBanner('-', 40, [title])\n\n elif selection == 'D':\n __printBanner('#', 54, [' * '.join(title), content])\n\n elif selection == 'E':\n __printBanner('#', 54, [title, content])\n</code></pre>\n\n<p>Some commentary: </p>\n\n<ul>\n<li>The names I use (<code>content</code>, <code>title</code>, <code>selection</code>) are guess from context. There may be better names possible.</li>\n<li>I'm a little confused as to why the output is so different for each report type. I'm guessing that <code>selection</code> is set by user input from a menu of some sort? You should separate the function that parses user input from this function, and have 5 separate functions (eg <code>generatePartList</code>).</li>\n<li>One of the oddest thing about the function as written is that sometimes <code>title</code> is a single string, and sometimes it seems to be a list of strings (or maybe the <code>join</code> statement is meant to \"bold\" the title name?).</li>\n<li>Better than printing in these functions is to return a string, and let the caller print the string (that makes it easier to write your output to a file instead of standard output, for instance, if you decide later that's something you want to do).</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T05:18:02.117",
"Id": "29253",
"ParentId": "29252",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29253",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T04:43:04.800",
"Id": "29252",
"Score": "1",
"Tags": [
"python"
],
"Title": "python function compression"
}
|
29252
|
<p>I'm trying to improve my functional skills and seeing where it fits and where it might not. Please review the code and see where functional practices might be applied. I'm specifically looking at trying to get rid of the state variables.</p>
<pre><code>private int GetFirstLineFrameCount(XDocument doc)
{
var subElement = (from res in doc.Descendants(_xmlns + "subelements")
where res.Element(_xmlns + "object")
.Element(_xmlns + "metadata")
.Element(_xmlns + "identifier").Value == "1"
select res).FirstOrDefault();
var offsetElement = subElement.Descendants(_xmlnsEc + "start").Select(x => x.Element(_xmlnsEc + "editUnitNumber")).FirstOrDefault();
if (offsetElement == null)
{
Logger.Error<SubtitleNormalizer>("no offset found");
return 0;
}
return Int32.Parse(offsetElement.Value);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T19:32:10.837",
"Id": "46232",
"Score": "0",
"body": "do you mean get rid of _xmlns and _xmlnsEc? If so just pass them in as parameters to the method."
}
] |
[
{
"body": "<p>A refactored functional programming that is <code>evil</code>.</p>\n\n<pre><code>public static class ObjectExtension\n{\n public static Tout IfNotNull<Tin, Tout>(this Tin source, Func<Tin, Tout> func)\n where Tout : class\n where Tin : class\n {\n if (source == null)\n {\n return null;\n }\n else\n {\n return func(source);\n }\n }\n}\n\npublic static class stringExtension\n{\n public static int ToIntDefault(this string str, Func<int> def)\n {\n if (!string.IsNullOrEmpty(str))\n {\n return int.Parse(str);\n }\n return def();\n }\n}\n</code></pre>\n\n<p>Consumer:</p>\n\n<pre><code>private int GetFirstLineFrameCount(XDocument doc, string _xmlns, string _xmlnsEc)\n{\n int result = 0;\n var subElement = (from res in doc.Descendants(_xmlns + \"subelements\")\n where res.Element(_xmlns + \"object\")\n .Element(_xmlns + \"metadata\")\n .Element(_xmlns + \"identifier\").Value == \"1\"\n select res)\n .FirstOrDefault()\n .IfNotNull(k =>\n k.Descendants(_xmlnsEc + \"start\").Select(x => x.Element(_xmlnsEc + \"editUnitNumber\")).FirstOrDefault()\n )\n .IfNotNull(k =>\n {\n result = k.Value.ToIntDefault(\n () => {\n Logger.Error<SubtitleNormalizer>(\"no offset found\");\n return 0;\n }\n );\n return (object)null;\n }\n );\n return result;\n}\n</code></pre>\n\n<h2>No, don't follow this. It is evil.</h2>\n\n<p>I just demonstrate something that can be done with functions. What you can do is as <code>dreza</code>'s suggest to accept <code>_xmlns</code> and <code>_xmlnsEc</code> as parameter. Otherwise, I found that both of the variable is legal to exists, just make them readonly and do constructor injection. Otherwise, create a configuration for both variable so you can use <code>myXmlConfiguration.Xmlns</code> and <code>myXmlConfiguration.XmlnsEc</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T02:23:19.777",
"Id": "29292",
"ParentId": "29264",
"Score": "1"
}
},
{
"body": "<p>If you really want to make this functional, it looks like a case for the \"Maybe monad\". See</p>\n\n<ul>\n<li><a href=\"http://devtalk.net/csharp/chained-null-checks-and-the-maybe-monad/\" rel=\"nofollow\">Chained null checks and the Maybe monad</a></li>\n<li><a href=\"http://smellegantcode.wordpress.com/2008/12/11/the-maybe-monad-in-c/\" rel=\"nofollow\">The Maybe Monad in C#</a></li>\n</ul>\n\n<p>Unfortunately the dichotomy of <code>class</code> vs <code>struct</code> limits the elegance of Maybe monads in C#, but with the following:</p>\n\n<pre><code>public static class Maybe\n{\n public static Maybe<TElement> ToMaybe<TElement>(this TElement value) where TElement : class\n {\n return new Maybe<TElement>(value);\n }\n}\n\npublic struct Maybe<TElement> where TElement : class\n{\n private readonly TElement _Wrapped;\n\n public bool HasValue { get { return _Wrapped != null; } }\n\n public TElement Value\n {\n get\n {\n if (_Wrapped == null) throw new InvalidOperationException();\n return _Wrapped;\n }\n }\n\n public Maybe(TElement value)\n {\n _Wrapped = value;\n }\n\n public TResult? SelectStruct<TResult>(Func<TElement, TResult> fn) where TResult : struct\n {\n return _Wrapped == null ? default(TResult?) : fn(_Wrapped);\n }\n\n // Returns \"this\" for fluent usage\n public Maybe<TElement> Exec(Action<TElement> ifAction, Action elseAction)\n {\n if (_Wrapped != null) ifAction(_Wrapped);\n else elseAction();\n return this;\n }\n}\n</code></pre>\n\n<p>you can refactor</p>\n\n<pre><code> var subElement = (from res in doc.Descendants(_xmlns + \"subelements\")\n where res.Element(_xmlns + \"object\")\n .Element(_xmlns + \"metadata\")\n .Element(_xmlns + \"identifier\").Value == \"1\"\n select res).FirstOrDefault();\n\n var offsetElement = subElement.Descendants(_xmlnsEc + \"start\").Select(x => x.Element(_xmlnsEc + \"editUnitNumber\")).FirstOrDefault();\n\n if (offsetElement == null)\n {\n Logger.Error<SubtitleNormalizer>(\"no offset found\");\n return 0;\n }\n\n return Int32.Parse(offsetElement.Value);\n</code></pre>\n\n<p>to</p>\n\n<pre><code> return (from res in doc.Descendants(_xmlns + \"subelements\")\n where res.Element(_xmlns + \"object\")\n .Element(_xmlns + \"metadata\")\n .Element(_xmlns + \"identifier\").Value == \"1\"\n select res).\n FirstOrDefault().\n Descendants(_xmlnsEc + \"start\").\n Select(x => x.Element(_xmlnsEc + \"editUnitNumber\")).\n FirstOrDefault().\n ToMaybe().\n Exec(val => {}, () => { Logger.Error<SubtitleNormalizer>(\"no offset found\"); }).\n SelectStruct(elt => Int32.Parse(elt.Value)).\n GetValueOrDefault();\n</code></pre>\n\n<p>A fuller <code>Maybe</code> implementation might have a <code>Where</code> method, a <code>Select<TResult>(Func<TElement, TResult>) where TResult : class</code> method, and a <code>GetValueOrDefault()</code> method, and extension methods to do the same for <code>Nullable<TStruct></code>, but I've simplified it to just support what's needed for this answer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T14:41:43.257",
"Id": "29305",
"ParentId": "29264",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T12:44:00.207",
"Id": "29264",
"Score": "6",
"Tags": [
"c#",
"functional-programming"
],
"Title": "Getting the first line frame count"
}
|
29264
|
<p>I'm cloning a fairly complex div/ page and changing various things in it before appending it to the DOM. The current method seems long-winded, and I was hoping if there was a simpler way of doing it?</p>
<pre><code>$.each(results.jobs, function(i, result){
var theID = result.id,
theTitle = result.title,
theDescription = result.description,
theLocation = result.location,
theType = result.type,
thePosted = posted[2]+'-'+posted[1]+'-'+posted[0],
theAgency = result.company,
theRef = result.reference,
theSalary = '',
theApps = result.number_of_applications,
hasApplied = result.applied,
theFeatured = result.featured,
theJobNo = pages*i +1;
if(result.hasOwnProperty('salary')){
var theSalary = result.salary.information.replace(/Â/g, '');
}
var jobContainer = $('#job-container').clone(true, true).attr('data-jobno', theJobNo);
jobContainer.find('h1').text(theTitle);
jobContainer.find('#job-location').text(theLocation);
jobContainer.find('#job-type').text(theType);
jobContainer.find('#job-date').text(thePosted);
jobContainer.find('#job-agency').text(theAgency);
jobContainer.find('#job-description').html(theDescription.replace(/£/gi, '&pound;'));
jobContainer.find('#job-ref').text(theRef);
jobContainer.find('#job-id').text(theID);
jobContainer.find('.apply-btn, .email-btn, .save-btn').attr('id', theID);
jobContainer.find('.save-btn').text('Save Job').removeClass('job-saved');
if(localStorage["saved"]!=null && localStorage["saved"]!= '[]'){
if(localStorage["saved"].indexOf(theID)>= 0){
jobContainer.find('.save-btn').addClass('job-saved').text('Job Saved');
}
}
if(theFeatured === '1'){
jobContainer.find('#job-featured').show();
}else{
jobContainer.find('#job-featured').hide();
}
if(localStorage["applied"]!=null && localStorage["applied"]!= '[]'){
if(localStorage["applied"].indexOf(theID)>= 0){
jobContainer.find('.job-alert').show();
}
}
if(theSalary != null){
jobContainer.find('#job-row-salary').show();
jobContainer.find('#job-salary').text(theSalary);
}else{
jobContainer.find('#job-row-salary').hide();
}
if(theApps === '0'){
jobContainer.find('#job-apps').html('<span style="color:#219a00">Be first to apply!</span>');
}else{
jobContainer.find('#job-apps').html(theApps);
}
viewJobList.push(jobContainer)
});
$('#slider').html('').append(viewJobList)
</code></pre>
<p>This is inside an Ajax success function which is made to an API. I'm cloning an existing page in the HTML and adding new information, adding it to an array/ list then appending to the DOM just the once.</p>
|
[] |
[
{
"body": "<p>This seems a textbook case for using Angular.</p>\n\n<p>Assuming you do not have the time to invest in Angular, you could consider the following:\nIf you named all your divs after your <code>result</code> properties ( for example <code>'#job-agency'</code> -> <code>#job-company</code> ), then you would have to do far less extraction work and far fewer <code>text()</code> calls.</p>\n\n<p>You could do something like: </p>\n\n<pre><code>$.each(results.jobs, function(i, result){\n\n var key;\n\n //Enhance your result object with some calculated values\n result.thePosted = posted[2]+'-'+posted[1]+'-'+posted[0];\n result.theJobNo = pages*i +1,\n\nif(result.hasOwnProperty('salary')){\n result.theSalary = result.salary.information.replace(/Â/g, '');\n}\n\nvar jobContainer = $('#job-container').clone(true, true).attr('data-jobno', theJobNo);\n\nfor( key in result )\n{\n jobContainer.find( '#job-' + key ).text( result[key] );\n}\n\njobContainer.find('.apply-btn, .email-btn, .save-btn').attr('id', theID);\njobContainer.find('.save-btn').text('Save Job').removeClass('job-saved');\n</code></pre>\n\n<p>etc. etc.</p>\n\n<p>The rest of the code is ok once you apply consistent indenting.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T21:58:59.437",
"Id": "39421",
"ParentId": "29266",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T13:28:24.160",
"Id": "29266",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"ajax"
],
"Title": "DOM cloning in a loop"
}
|
29266
|
<p>I'm trying to clean some incoming <code>$_GET</code> parameters. I've not done this before, so I'd love feedback.</p>
<p>I'm especially concerned with the array. While all the other parameters control simple logic, the array will be saved into the database and potentially output to users.</p>
<p>Please also feel free to point out any redundancies.</p>
<pre><code><?php
// int: only want a positive value
// array: wont know what this could be but it could be anything urlencoded
// string: three possible outcomes: foo, bar, fudge
( isset( $_GET["val1"] ) ? (bool) $val1 = true : (unset) $val1 );
( isset( $_GET["val2"] ) ? (int) $val2 = sanitize_absint( $_GET["val2"] ) : (unset) $val2 );
( isset( $_GET["val3"] ) ? (array) $val3 = sanitize_array($_GET["val3"]) : (unset) $val3 );
( isset( $_GET["val4"] ) ? (string) $val4 = sanitize_string($_GET["val4"]) : (unset) $val4 );
// further refine val4 string
val4_strip($val_4);
// sanitize
function gfahp_sanitize_absint( $int ) {
$int = filter_var( $int, FILTER_SANITIZE_NUMBER_INT );
$int = abs( intval( $int ) ); // positive number
return $int;
}
function gfahp_sanitize_string( $string ) {
// is this enough to prevent anything icky?
$string = filter_var( $string, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW );
return $string;
}
function gfahp_sanitize_array( $array ) {
$array = array_walk_recursive( $array, "gfahp_sanitize_string" );
return $array;
}
function val4_strip($val_4){
// strip down val4
if (!empty($val4){
switch ($val4) {
case 'foo':
$val4 = 'foo';
break;
case 'bar':
$val4 = 'bar';
break;
case 'fudge':
$val4 = 'fudge';
break;
default:
$val4 = (unset) $val4
break;
}
}
return $val4;
}
</code></pre>
|
[] |
[
{
"body": "<p>My 2 cents:</p>\n\n<p><code>$int = abs( intval( $int ) ); // positive number</code></p>\n\n<p>Silently fixing input values is evil, perhaps required, but still evil.</p>\n\n<pre><code>function gfahp_sanitize_array( $array ) {\n $array = array_walk_recursive( $array, \"gfahp_sanitize_string\" );\n return $array;\n}\n</code></pre>\n\n<p>You assign and then return, I would just return immediately</p>\n\n<pre><code>function gfahp_sanitize_array( $array ) \n{\n return array_walk_recursive( $array, \"gfahp_sanitize_string\" );\n}\n</code></pre>\n\n<p>Also, what is up with gfahp ? Hungarian notation of functions with acronyms is a slappable offence.</p>\n\n<p>As for</p>\n\n<pre><code>function val4_strip($val_4){\n// strip down val4\n if (!empty($val4){\n switch ($val4) {\n case 'foo':\n $val4 = 'foo';\n break;\n case 'bar':\n $val4 = 'bar';\n break;\n case 'fudge':\n $val4 = 'fudge';\n break; \n default:\n $val4 = (unset) $val4\n break;\n }\n }\n\n}\n</code></pre>\n\n<p>You should probably go for a generic function that can look up a value in a set and assign it if found, otherwise return blank. ( Also that function does not return anything? ) (Also you are unsetting var4 in places ). Something like</p>\n\n<pre><code>$val4_set = array( \"foo\" , \"bar\" , \"fudge\" );\n\n( isset( $_GET[\"val4\"] ) ? (string) $val4 = sanitize_string_from_set($_GET[\"val4\"], $val4_set) : (unset) $val4 );\n\nfunction sanitize_string_from_set( $string , $set )\n{\n return array_key_exists( $string, $set )?$string:\"\"; \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T19:02:25.813",
"Id": "46227",
"Score": "0",
"body": "Hungarian?, slapable? buuuuhahahahahah -- sorry I may have passed my Balmer peak. Wonderfull feedback truly many thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T19:10:10.690",
"Id": "46228",
"Score": "0",
"body": "As for `$int = abs( intval( $int ) );` how would you do it differently? Mind you someone could try to submit a neg number and it would still fail."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T19:12:56.863",
"Id": "46230",
"Score": "0",
"body": "I would catch it in the UI before submitting, if someone tries to hack I would check whether the value < 0 and throw an error in that case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T19:17:44.013",
"Id": "46231",
"Score": "0",
"body": "good point re `<0`. No ui on this, its a service that returns GravityForms output via get params. Im just tring to keep script kiddies from imputing undeseriable XSS."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T09:01:07.233",
"Id": "46255",
"Score": "0",
"body": "Oh just to round trip your comments re Hungairian Notaion, those are actually [function prefixes](http://nacin.com/2010/05/11/in-wordpress-prefix-everything/) - which are a good thing, no?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T14:03:50.247",
"Id": "46264",
"Score": "0",
"body": "Go for classes instead, I'd say. Function prefixes are really Hungarian notations."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T18:23:54.277",
"Id": "29274",
"ParentId": "29269",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T16:49:15.593",
"Id": "29269",
"Score": "0",
"Tags": [
"php",
"url"
],
"Title": "Am I sufficiently cleaning incoming $_GET parameters, especially in the array?"
}
|
29269
|
<p>Are there any ways I could improve speed and less code? The elevator that uses this script works fine. Could anything be better?</p>
<pre><code>print(" Teknikk xPower 9700 PRE DEV V1 Intialised")
-- Develoment sample, May have functions added or removed. --
local Floor = script.Parent.Floor
local Floors = script.Parent.Floors
local FireLock = false
local Alarm = false
local Open = false
local Closed = true
local IsOpening = false
local IsClosing = false
local Moving = false
local Busy = false
local Locked = false
local DoorSpeed = 0.00001
local MotorStartSpeed = 0.13
local MotorStopSpeed = 0.13
local MotorSpeed = 12
local MotorCurrentSpeed = 8
local MoveDirection = "None"
local CallDirection = "None"
local FloorIndicatorOffset = 6
local LevelOffset = 3
local TargetFloor = 0
local TotalFloors = 0
local Car = script.Parent.Car.Control
local duck = false
local WaitCall = false
local CallQuene = {}
local CardLock = true
local CardNumber = {0,1}
local LockedFloors = {2,3,4,5,6,7,8}
function ProcessCall(xFloor, xDest)
if TargetFloor == 0 and xFloor ~= xDest then
if xDest > xFloor then
TargetFloor = xDest
Car.DirectionalIndicator.Decal.Texture = "http://www.roblox.com/asset/?id=119917350"
Start("Up")
end
if xDest < xFloor then
TargetFloor = xDest
Car.DirectionalIndicator.Decal.Texture = "http://www.roblox.com/asset/?id=119917359"
Start("Down")
end
end
end
function Start(xDirection)
Busy = true
if Open or IsOpening then
repeat DoorClose(Floor.Value) wait(0.1) until Closed == true and IsOpening == false
end
Moving = true
-- Some code for just 1 floor up, not too fast --
if (Floors:FindFirstChild("Floor"..TargetFloor).FloorLevel.Position - script.Parent.Car.Control.FloorLevel.Position).Magnitude < 14 then
MotorCurrentSpeed = 5
MotorStopSpeed = 0.05
LevelOffset = 5
else
MotorCurrentSpeed = MotorSpeed
MotorStopSpeed = 0.05
LevelOffset = 6.5
end
Car.Platform.BodyPosition.P = 0
Car.Platform.BodyPosition.D = 0
Car.Platform.BodyVelocity.P = 5000
if xDirection == "Up" then
MoveDirection = "Up"
for i = 0, MotorCurrentSpeed, 1 do
Car.Platform.BodyVelocity.velocity = Vector3.new(0,i,0)
wait(MotorStartSpeed)
end
end
if xDirection == "Down" then
MoveDirection = "Down"
for i = 0, MotorCurrentSpeed, 1 do
Car.Platform.BodyVelocity.velocity = Vector3.new(0,-i,0)
wait(MotorStartSpeed)
end
end
end
function Stop(TF)
if TargetFloor ~= TF then return end
Btn(TargetFloor,0)
Car.DirectionalIndicator.Decal.Texture = "http://www.roblox.com/asset/?id=0"
FPos = script.Parent.Floors:FindFirstChild("Floor"..TF).FloorLevel.Position.Y
Car.Platform.BodyPosition.position = Vector3.new(Car.Platform.BodyPosition.position.X,FPos,Car.Platform.BodyPosition.position.Z)
Car.Platform.BodyVelocity.P = 0
Car.Platform.BodyPosition.P = 10000
Car.Platform.BodyPosition.D = 6000
Car.Platform.BodyVelocity.velocity = Vector3.new(0,0,0)
repeat
print((script.Parent.Floors:FindFirstChild("Floor"..TF).FloorLevel.Position - script.Parent.Car.Control.FloorLevel.Position).Magnitude)
wait(0.1)
until (script.Parent.Floors:FindFirstChild("Floor"..TF).FloorLevel.Position - script.Parent.Car.Control.FloorLevel.Position).Magnitude < 0.4
wait(1)
TargetFloor = 0
if Floor.Value == TotalFloors then
MoveDirection = "Down"
end
if Floor.Value == 1 then
MoveDirection = "Up"
end
DirInd(TF,MoveDirection)
Moving = false
wait(1)
DoorOpen(TF)
print("Waiting 4 sec before delete and check")
Quene(TF,"Remove")
Busy = false
wait(4)
Quene(0,"Check")
end
function DoorOpen(TF)
if Closed and not IsOpening and TF ~= nil and not Moving then
IsOpening = true
if Car:FindFirstChild("DoorOpen") ~= nil then
Car:FindFirstChild("DoorOpen").BrickColor = BrickColor.New("Lime green")
end
if MoveDirection == "Up" then
Car.FloorIndicator.Ding.Pitch = 0.5
Car.FloorIndicator.Ding:Play()
end
if MoveDirection == "Down" then
Car.FloorIndicator.Ding.Pitch = 0.5
Car.FloorIndicator.Ding:Play()
wait(0.5)
Car.FloorIndicator.Ding.Pitch = 0.3
Car.FloorIndicator.Ding:Play()
end
CarRight = script.Parent.Car.Control.DoorRight
CarLeft = script.Parent.Car.Control.DoorLeft
DoorRight = script.Parent.Floors:FindFirstChild("Floor"..TF).DoorRight
DoorLeft = script.Parent.Floors:FindFirstChild("Floor"..TF).DoorLeft
if DoorRight == nil and DoorLeft == nil then print("Cant open doors, No shaft doors") return end
CarRight.Anchored = true
CarLeft.Anchored = true
for i=0, 51 do
CarRight.CFrame = CarRight.CFrame * CFrame.new(0, 0, 0.05)
CarLeft.CFrame = CarLeft.CFrame * CFrame.new(0, 0, -0.05)
DoorRight.CFrame = DoorRight.CFrame * CFrame.new(0, 0, 0.05)
DoorLeft.CFrame = DoorLeft.CFrame * CFrame.new(0, 0, -0.05)
wait(DoorSpeed)
end
CarRight.Anchored = true
CarLeft.Anchored = true
Closed = false
Open = true
if Car:FindFirstChild("DoorOpen") ~= nil then
Car:FindFirstChild("DoorOpen").BrickColor = BrickColor.New("Institutional white")
end
IsOpening = false
end
end
function DoorClose(TF)
if Open and not IsClosing and TF ~= nil and not Moving then
IsClosing = true
DirInd(TF,"None")
if Car:FindFirstChild("DoorClose") ~= nil then
Car:FindFirstChild("DoorClose").BrickColor = BrickColor.New("Lime green")
end
CarRight = script.Parent.Car.Control.DoorRight
CarLeft = script.Parent.Car.Control.DoorLeft
DoorRight = script.Parent.Floors:FindFirstChild("Floor"..TF).DoorRight
DoorLeft = script.Parent.Floors:FindFirstChild("Floor"..TF).DoorLeft
if DoorRight == nil and DoorLeft == nil then print("Cant open doors, No shaft doors") return end
CarRight.Anchored = true
CarLeft.Anchored = true
for i=0, 51 do
CarRight.CFrame = CarRight.CFrame * CFrame.new(0, 0, -0.05)
CarLeft.CFrame = CarLeft.CFrame * CFrame.new(0, 0, 0.05)
DoorRight.CFrame = DoorRight.CFrame * CFrame.new(0, 0, -0.05)
DoorLeft.CFrame = DoorLeft.CFrame * CFrame.new(0, 0, 0.05)
wait(DoorSpeed)
end
CarRight.Anchored = false
CarLeft.Anchored = false
Closed = true
Open = false
if Car:FindFirstChild("DoorClose") ~= nil then
Car:FindFirstChild("DoorClose").BrickColor = BrickColor.New("Institutional white")
end
IsClosing = false
end
end
function Btn(xFloor,xMode)
local xCar = Car.FloorBtn:FindFirstChild("F"..xFloor)
local xCall = Floors:FindFirstChild("Floor"..xFloor):FindFirstChild("CallButton")
local xDual = script.Parent.Parent:FindFirstChild("CallFloor")
if xMode == 1 then
if xCar ~= nil then
xCar.BrickColor = BrickColor.new("Lime green")
end
if xCall ~= nil then
xCall.BrickColor = BrickColor.new("Lime green")
end
if xDual ~= nil then
if xDual:FindFirstChild("F"..xFloor) ~= nil then
xDual:FindFirstChild("F"..xFloor).CallButton.BrickColor = BrickColor.new("Lime green")
end
end
end
if xMode == 0 then
if xCar ~= nil then
xCar.BrickColor = BrickColor.new("Institutional white")
end
if xCall ~= nil then
xCall.BrickColor = BrickColor.new("Institutional white")
end
if xDual ~= nil then
if xDual:FindFirstChild("F"..xFloor) ~= nil then
xDual:FindFirstChild("F"..xFloor).CallButton.BrickColor = BrickColor.new("Institutional white")
end
end
end
end
function DirInd(xFloor,xDir)
local Dup = Floors:FindFirstChild("Floor"..xFloor):FindFirstChild("DirIndUp")
local Ddn = Floors:FindFirstChild("Floor"..xFloor):FindFirstChild("DirIndDown")
if xDir == "Up" then
Dup.BrickColor = BrickColor.new("Bright green")
end
if xDir == "Down" then
Ddn.BrickColor = BrickColor.new("Really red")
end
if xDir == "None" then
Dup.BrickColor = BrickColor.new("Really black")
Ddn.BrickColor = BrickColor.new("Really black")
end
end
function Quene(xFloor,Mode,isCall)
if Mode == "Check" then
for i = 1, #CallQuene do
if CallQuene[i] ~= nil then
ProcessCall(Floor.Value, CallQuene[i])
end
end
end
if Mode == "Add" then
Btn(xFloor,1)
local IgnoreCall = false
if isCall ~= true then
for i = 1, #LockedFloors do
if LockedFloors[i] == xFloor then
print("Call is in Lock list.")
if CardLock then
IgnoreCall = true
end
end
end
end
for i = 1, #CallQuene do
if CallQuene[i] == xFloor then
print("Call exist, Not adding floor: "..CallQuene[i])
IgnoreCall = true
end
end
if not IgnoreCall and xFloor ~= Floor.Value and not Locked or not IgnoreCall and xFloor ~= Floor.Value and xFloor == 1 then
table.insert(CallQuene,xFloor)
print("Floor added, Value: "..xFloor)
Btn(xFloor,1)
if not Busy then Quene(0,"Check") end
else
if xFloor == Floor.Value and not Locked or IgnoreCall then
wait(0.2)
Btn(xFloor,0)
end
if Locked then
wait(0.2)
Btn(xFloor,0)
end
end
end
if Mode == "Remove" then
for i = 1, #CallQuene do
if CallQuene[i] == xFloor then
print("Removed: "..CallQuene[i])
table.remove(CallQuene,i)
end
end
Btn(xFloor,"Off")
end
end
function FireMode(Player)
if not FireLock then
Car.LockInd.BrickColor = BrickColor.new("Really red")
Floors.Floor1:FindFirstChild("FireService").Key.Texture = "http://www.roblox.com/asset/?id=121879581"
FireLock = true
Locked = true
for i = 1, #CallQuene do
print("Removed: "..CallQuene[i])
table.remove(CallQuene,i)
end
Car.DirectionalIndicator.Decal.Texture = "http://www.roblox.com/asset/?id=0"
if Floor.Value ~= 1 then
DoorClose(Floor.Value)
Moving = true
Car.Platform.BodyVelocity.P = 2560
Car.Platform.BodyVelocity.velocity = Vector3.new(0,0,0)
TargetFloor = 1
MoveDirection = "Down"
wait(1)
Car.Platform.BodyVelocity.velocity = Vector3.new(0,-6,0)
end
elseif FireLock then
Car.LockInd.BrickColor = BrickColor.new("Really black")
Floors.Floor1:FindFirstChild("FireService").Key.Texture = "http://www.roblox.com/asset/?id=121879579"
FireLock = false
Locked = false
end
end
if Car:FindFirstChild("DoorOpen") ~= nil then
Car:FindFirstChild("DoorOpen").ClickDetector.MouseClick:connect(function() if not FireLock then DoorOpen(Floor.Value) end end)
end
if Car:FindFirstChild("DoorClose") ~= nil then
Car:FindFirstChild("DoorClose").ClickDetector.MouseClick:connect(function() if not FireLock then
local Close = false
for i = 1, #CallQuene do
if CallQuene[i] ~= nil then
Close = true
end
end
if Close then
DoorClose(Floor.Value) Quene(0,"Check")
else
Car:FindFirstChild("DoorClose").BrickColor = BrickColor.New("Lime green")
wait(0.2)
Car:FindFirstChild("DoorClose").BrickColor = BrickColor.New("Institutional white")
end
end
end)
end
CarCalls = Car.FloorBtn:GetChildren()
x = script.Parent.Floors:GetChildren()
for i = 1, #x do
TotalFloors = TotalFloors + 1
if x[i]:FindFirstChild("CallButton") ~= nil then
local fRep = string.gsub(x[i].Name, "Floor", "")
local fFloor = tonumber(fRep)
x[i].CallButton.ClickDetector.MouseClick:connect(function() Quene(fFloor,"Add",true) end)
end
end
if game.CreatorId ~= 0 then if game.CreatorId ~= 6623575 then x = Instance.new("Hint",Workspace) x.Text = "This place is using a Stolen Teknikk elevator. We apperiate the No support." script.Parent:Remove() end end
for i = 1, #CarCalls do
local bRep = string.gsub(CarCalls[i].Name, "F", "")
local cFloor = tonumber(bRep)
CarCalls[i].ClickDetector.MouseClick:connect(function() Quene(cFloor,"Add",false) end)
end
script.Parent.ScriptCall.Changed:connect(function ()
if script.Parent.ScriptCall.Value ~= 0 then
Quene(script.Parent.ScriptCall.Value,"Add",true)
script.Parent.ScriptCall.Value = 0
end
end)
script.Parent.FireMode.Changed:connect(function ()
if script.Parent.FireMode.Value == true then
FireMode()
script.Parent.FireMode.Value = false
end
end)
Car.Alarm.ClickDetector.MouseClick:connect(function ()
if not Alarm then
Alarm = true
for i=0,20 do
Car.FloorIndicator.Alarm:Play()
wait(0.1)
end
Alarm = false
end
end)
if Car:FindFirstChild("ElevatorLock") ~= nil then
Car.ElevatorLock.ClickDetector.MouseClick:connect(function (Player)
if Player ~= nil and Player.Name == "Heisteknikk" then
if not Locked then
Locked = true
Car.ElevatorLock.BrickColor = BrickColor.new("Really red")
else
Locked = false
Car.ElevatorLock.BrickColor = BrickColor.new("Dark stone grey")
end
end
end)
end
if Car:FindFirstChild("RFID") ~= nil then
Car:FindFirstChild("RFID").Touched:connect(
function (Card)
local Accepted = false
if Card.Parent:FindFirstChild("CardNumber") ~= nil and CardLock then
for id=1, #CardNumber do
if Card.Parent.CardNumber.Value == CardNumber[id] then
Car.RFID.BrickColor = BrickColor.new("Bright green")
CardLock = false
wait(5)
CardLock = true
Car.RFID.BrickColor = BrickColor.new("New Yeller")
Accepted = true
end
wait()
end
if not Accepted then
Car.RFID.BrickColor = BrickColor.new("Really red")
wait(1)
Car.RFID.BrickColor = BrickColor.new("New Yeller")
end
end
end)
end
if Floors.Floor1:FindFirstChild("FireService") ~= nil then
Floors.Floor1:FindFirstChild("FireService").ClickDetector.MouseClick:connect(function(Player) if Player ~= nil and Player.Name == "Heisteknikk" then FireMode() end end)
end
print("Floor served: "..TotalFloors)
while true do
wait()
for i = 1, #x do
local xs = string.gsub(x[i].Name, "Floor", "")
local xx = tonumber(xs)
if (x[i].FloorLevel.Position - script.Parent.Car.Control.FloorLevel.Position).Magnitude < LevelOffset then
if Floor.Value ~= xx then
Floor.Value = xx
Stop(xx) -- InCase f stops
end
end
if duck == false then
if (x[i].FloorLevel.Position - script.Parent.Car.Control.FloorLevel.Position).Magnitude < 0.5 then
duck = true
DirInd(1,"Up")
DoorOpen(1)
end
end
end
end
</code></pre>
|
[] |
[
{
"body": "<h1>Indentation</h1>\n\n<p>It's in some places, but in the places it's not in, it's pretty bad.</p>\n\n<p>You should always make sure your code is indented so, when looking over your code, you can see what goes where.</p>\n\n<p>For example, your <code>Start</code> function has bad indentation. Generally, all function code between the signature and the <code>end</code> keyword of the function should have <strong>at least</strong> one indent (more if there are other structures like <code>if</code>)</p>\n\n<p>How the beginning <code>Start</code> function should look:</p>\n\n<pre><code>function Start(xDirection)\n Busy = true\n if Open or IsOpening then\n repeat DoorClose(Floor.Value) wait(0.1) until Closed == true and IsOpening == false\n end\n\n ...\n</code></pre>\n\n<p>Also, I'm not sure if this is just personal preference, but you have a lot of \"one-liners\". By that, I mean that in a lot of places, you tend to try to put things on one line. While this does make your code look a bit more tidy, it might be harder for someone else to read it (or maybe even you, if you stepped away from the code for a while)</p>\n\n<p>For example, I would change this line:</p>\n\n<pre><code>Car:FindFirstChild(\"DoorOpen\").ClickDetector.MouseClick:connect(function() if not FireLock then DoorOpen(Floor.Value) end end)\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>Car:FindFirstChild(\"DoorOpen\").ClickDetector.MouseClick:connect(function()\n if not FireLock then\n DoorOpen(Floor.Value)\n end\nend\n</code></pre>\n\n<p>Other than that, your code is very difficult to read, making it hard for people to give you a good review. Since this is a lot of code, I recommend finding an online program that can indent your LUA for you, as if you did it by hand, it could take a long time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-17T16:10:39.190",
"Id": "77814",
"ParentId": "29275",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T18:47:12.433",
"Id": "29275",
"Score": "4",
"Tags": [
"game",
"lua"
],
"Title": "Elevator code for a game called ROBLOX"
}
|
29275
|
<p>I have been working to create an easy-to-use set of methods to encrypt configuration objects for my client application. It will contain username and passwords to databases and similar vaults of data, so it's rather important that I've got the fundamentals correct.</p>
<p>I'm fairly new to this form of encryption, and I certainly haven't done this in .NET before. So I am curious - is there any given, open caveats in the attached code? I'll greatly appreciate your comments!</p>
<p>Also, please don't mind the comments <em>in the code</em>. This is a late-night side-project for me, and I'll look into sprucing it all up once I've got it all examined.</p>
<pre><code> public byte[] CalculatePasswordHash(byte[] salt)
{
var hash = Encoding.UTF8.GetBytes(Password);
var hashing = SHA256.Create();
var iterations = 10000;
while (iterations > 0)
{
// Compute the hash
hash = hashing.ComputeHash(hash);
// Apply the salt
for (int position = 0, cursor = 0; position < hash.Length; position += 1)
{
hash[position] ^= salt[cursor];
cursor += 1;
if (cursor >= salt.Length)
cursor = 0;
}
iterations -= 1;
}
return hash;
}
public byte[] CreateSalt()
{
return CreateSalt(SaltLength);
}
public byte[] CreateSalt(int size)
{
var random = new RNGCryptoServiceProvider();
var buf = new byte[size];
random.GetBytes(buf);
return buf;
}
public void Lock(string filePath, byte[] source)
{
// Ensure that the path is rooted
filePath = RootPath(filePath);
// Generate salt as well as the encryption key
var salt = CreateSalt();
var key = CalculatePasswordHash(salt);
// Initialize the Rijndael encryption tool
var crypto = Rijndael.Create();
var iv = CreateSalt(crypto.BlockSize / 8);
using (var mem = new MemoryStream())
{
// Encrypt the source array
crypto.Key = key;
crypto.IV = iv;
var desc = crypto.CreateEncryptor();
using (var cryptoStream = new CryptoStream(mem, desc, CryptoStreamMode.Write))
{
cryptoStream.Write(source, 0, source.Length);
}
desc.Dispose();
// Append the salt and iv to the end of the file
using (var fs = new FileStream(filePath, FileMode.Create))
{
var encrypted = mem.ToArray();
fs.Write(encrypted, 0, encrypted.Length);
fs.Write(salt, 0, salt.Length);
fs.Write(iv, 0, iv.Length);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p><code>CalculatePasswordHash</code> is inadvertently reimplementing (and probably not as well) a standard primitive. You should use <code>System.Security.Cryptography.Rfc2898DeriveBytes</code> instead.</p></li>\n<li><p>The code</p>\n\n<pre><code> var desc = crypto.CreateEncryptor();\n ...\n desc.Dispose();\n</code></pre>\n\n<p>raises a red flag. Why isn't it using <code>using</code>?</p></li>\n<li><p>You write to a memory stream and then write the contents of the memory stream unmodified to a file. It seems that you could simplify this just skipping the middle-man.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T10:53:59.523",
"Id": "46463",
"Score": "0",
"body": "Yes, I found out about Rfc2898DeriveBytes after I had implemented my solution. I'll definitely replace my own with that. Thank you so much for your help and time! :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T14:20:22.693",
"Id": "29304",
"ParentId": "29278",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29304",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T18:58:13.213",
"Id": "29278",
"Score": "1",
"Tags": [
"c#",
".net",
"security",
"cryptography"
],
"Title": "Am I interfacing in a secure manner with rijndael?"
}
|
29278
|
<p>Apex is a language native to force.com/Salesforce and has a lot of common ground with Java. It is a case insensitive, object oriented language. </p>
<ul>
<li><a href="http://apexdevnet.com/page/Apex_Code%3a_The_World%27s_First_On-Demand_Programming_Language" rel="nofollow">The World's First On-Demand Programming Language</a></li>
<li><a href="http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_intro_what_is_apex.htm" rel="nofollow">What is apex?</a></li>
<li><a href="http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#StartTopic=Content/apex_intro.htm" rel="nofollow">APEX developer's guide</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T19:03:00.137",
"Id": "29279",
"Score": "0",
"Tags": null,
"Title": null
}
|
29279
|
A proprietary Java-like programming language for the Force.com Platform.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T19:03:00.137",
"Id": "29280",
"Score": "0",
"Tags": null,
"Title": null
}
|
29280
|
<p>Excerpt from <a href="http://www.force.com/why-force.jsp" rel="nofollow">Force.com website</a>:</p>
<blockquote>
<p><strong>What is Force.com?</strong></p>
<p>Force.com is a platform for creating and deploying applications for the social enterprise. Because there are no servers or software to buy or manage, you can focus solely on building apps that include built-in social and mobile functionality, business processes, reporting, and search. Your apps run on a secure, proven service that scales, tunes, and backs up data automatically.</p>
</blockquote>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T19:06:23.853",
"Id": "29281",
"Score": "0",
"Tags": null,
"Title": null
}
|
29281
|
A platform for creating and deploying applications for the social enterprise. Essentially Salesforce.com without CRM.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T19:06:23.853",
"Id": "29282",
"Score": "0",
"Tags": null,
"Title": null
}
|
29282
|
<p>Salesforce as a company provides multiple cloud-based systems, but are mainly known for their CRM system. Their main products are built on the Force.com platform, which is an MVC-style framework that can be extended through custom <a href="http://codereview.stackexchange.com/tags/apex-code/info">Apex code</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T19:09:56.240",
"Id": "29283",
"Score": "0",
"Tags": null,
"Title": null
}
|
29283
|
A Platform-as-a-Service development environment delivered on Salesforce.com - the platform is more correctly referred to as Force.com. A dedicated Salesforce Stack Exchange public beta is available for all your Salesforce questions at http://salesforce.stackexchange.com/.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T19:09:56.240",
"Id": "29284",
"Score": "0",
"Tags": null,
"Title": null
}
|
29284
|
<p>I've been working with jQuery, mostly consuming plugins and using bits and pieces here and there for other functionality. Anyways, I wrote some standalone functionality in jQuery for a project and decided to convert it to a plugin as an exercise for myself. Note, it's not a full blown plugin, I don't inject markup or CSS at run-time around a specified element; as it stands the plugin code is just acting on markup it expects to be in the specified container in order to work. For now and ease of review.</p>
<p>The plugin source, with full working contrived example, can be accessed at this <a href="http://jsfiddle.net/emgee/PVKse/" rel="nofollow">Fiddle</a> for your review.</p>
<p>Any constructive feedback is welcome, naming conventions, optimizations, general code improvement, do's/don't's, etc...</p>
<p>I've included just the plugin source below, although it is a bit lengthy. </p>
<p>I would appreciate a review of this code.</p>
<pre><code>(function ($) {
$.wwSmoothScroll = function (element, options) {
var timer; // holds timer for continuous scroll functionality
var scrollOffset; // how many pixels the content is scrolled on each scroll action
var continuousScrollSpeed; // affects speed of scrolling when mouse/finger held down on a scroll button
// settings for auto-scroll feature
var autoScroll;
var autoScrollSpeed;
var autoScrollTimer;
var autoScrollHandler;
var autoScrollDirectionChangeDelay;
var $container;
var $content;
var $btnLeftScroll;
var $btnRightScroll;
// used to reference the current instance of the object
var plugin = this;
var defaults = {
"scrollOffset": 10,
"continuousScrollSpeed": 25,
"autoScroll": false,
"autoScrollSpeed": 50,
"autoScrollDirectionChangeDelay": 500
};
// used to hold the merged defaults and user provided options
// within plugin code use: plugin.settings.propertyName
// outside the plugin use: element.data('pluginName').settings.propertyName, where
// [element] is the element the plugin has been attached to.
plugin.settings = {};
plugin.init = function () {
// merge default and user-provided settings
plugin.settings = $.extend({}, defaults, options);
// store references to various jQuery objects
$container = $(element);
$btnLeftScroll = $container.find(".scroller-left.button");
$btnRightScroll = $container.find(".scroller-right.button");
$content = $container.find("ul");
$btnRightScroll.on("mousedown touchstart", function () {
Scroll(ScrollRight)
})
.on("mouseup touchend", ScrollStop);
$btnLeftScroll.on("mousedown touchstart", function () {
Scroll(ScrollLeft)
})
.on("mouseup touchend", ScrollStop);
$content.on("mouseenter", Content_OnMouseEnter)
.on("mouseleave", Content_OnMouseLeave);
if ($content[0].scrollWidth > $content.outerWidth()) $btnRightScroll.fadeIn("slow");
if (plugin.settings.autoScroll) {
autoScrollHandler = ScrollRight;
autoScrollTimer = setTimeout(RunAutoScroll, plugin.settings.autoScrollSpeed);
}
};
// *** PUBLIC METHODS ***
plugin.scrollRight = function () {
ScrollRight();
return plugin;
}
plugin.scrollLeft = function () {
ScrollLeft();
return plugin;
}
plugin.scrollStop = function () {
ScrollStop();
return plugin;
}
plugin.exitPlugin = function () {
return $container;
}
// *** PRIVATE METHODS ***
var RunAutoScroll = function () {
var isDirectionChanged = false;
// check for visibility of the main container, don't want this and scroll code executing if the container has been hidden
if ((plugin.settings.autoScroll) && ($container.is(":visible"))) {
// if the right button is still visible and the scroll direction is to the right, continue scrolling right
if ($btnRightScroll.is(":visible") && autoScrollHandler === ScrollRight) {
// do nothing for now...
} else {
var isLeftScrollButtonVisible = $btnLeftScroll.is(":visible");
if (isLeftScrollButtonVisible && autoScrollHandler === ScrollRight) {
isDirectionChanged = true;
autoScrollHandler = ScrollLeft;
} else if (!isLeftScrollButtonVisible && autoScrollHandler === ScrollLeft) {
isDirectionChanged = true;
autoScrollHandler = ScrollRight;
}
}
// if direction has been swapped, wait the defined period of time before actually scrolling
if (isDirectionChanged) autoScrollTimer = setTimeout(RunAutoScroll, plugin.settings.autoScrollDirectionChangeDelay);
else {
autoScrollHandler();
autoScrollTimer = setTimeout(RunAutoScroll, plugin.settings.autoScrollSpeed);
}
}
};
var Content_OnMouseEnter = function () {
if (plugin.settings.autoScroll) clearTimeout(autoScrollTimer);
};
var Content_OnMouseLeave = function () {
if (plugin.settings.autoScroll) autoScrollTimer = setTimeout(RunAutoScroll, plugin.settings.autoScrollSpeed);
};
var Scroll = function (scrollHandler) {
if (scrollHandler !== undefined) {
/* disable autoscroll once the user has clicked on a scroll button */
clearTimeout(autoScrollTimer);
plugin.settings.autoScroll = false;
scrollHandler();
timer = setInterval(scrollHandler, plugin.settings.continuousScrollSpeed);
}
};
var ScrollRight = function () {
console.log("ScrollRight()");
var maxScrollOffsetLeft = $content[0].scrollWidth - $content.outerWidth();
if ($content.scrollLeft() < maxScrollOffsetLeft) {
$content.scrollLeft($content.scrollLeft() + plugin.settings.scrollOffset);
$btnLeftScroll.fadeIn("slow");
} else {
if (timer !== undefined) clearInterval(timer);
$btnRightScroll.fadeOut("slow");
}
};
var ScrollLeft = function () {
console.log("ScrollLeft()");
if ($content.scrollLeft() > 0) {
$content.scrollLeft($content.scrollLeft() - plugin.settings.scrollOffset);
$btnRightScroll.fadeIn("slow");
} else {
if (timer !== undefined) clearInterval(timer);
$btnLeftScroll.fadeOut("slow");
}
};
var ScrollStop = function () {
clearInterval(timer);
};
// Call the "constructor" for the plugin
plugin.init();
};
// add the plugin to the jQuery.fn object
$.fn.wwSmoothScroll = function (options) {
return this.each(function () {
if (undefined == $(this).data("wwSmoothScroll")) {
// create a new instance of the plugin
var plugin = new $.wwSmoothScroll(this, options);
// store a reference to the plugin object
$(this).data("wwSmoothScroll", plugin);
}
});
};
})(jQuery);
</code></pre>
<p><strong>UPDATE:</strong> I changed the jQuery to 1.9 in the Fiddle as under IE10 it wasn't working. Wasn't using anything specific to jQuery 2.x</p>
<p><strong>UPDATE:</strong> Changed the defaults variable to use string literals to avoid collisions.</p>
|
[] |
[
{
"body": "<p>Overal, I think this is very good code, I only have a few pointers.</p>\n\n<ul>\n<li><p>Unused variables ( <a href=\"http://www.jshint.com/\">jshint</a> ).</p>\n\n<ul>\n<li>scrollOffset</li>\n<li>continuousScrollSpeed</li>\n<li>autoScroll</li>\n<li>autoScrollSpeed</li>\n<li>autoScrollDirectionChangeDelay</li>\n</ul></li>\n<li><p>Yoda conditions :</p>\n\n<ul>\n<li><code>(undefined == $(this).data(\"wwSmoothScroll\"))</code></li>\n<li><code>(scrollHandler !== undefined)</code></li>\n<li>Either have all Yoda conditions or no Yoda conditions, also compare to <code>undefined</code> with <code>===</code>. Or use/try falsey conditions.</li>\n</ul></li>\n<li><p>Chaining event handlers, it looks ugly. The problem is that I dont like what beautifiers do either. I counter propose the following formatting, which I can grok in a split second, feel free to ignore:</p></li>\n</ul>\n\n<blockquote>\n<pre><code>$btnRightScroll.on(\"mousedown touchstart\", function () { Scroll(ScrollRight) })\n .on(\"mouseup touchend\", ScrollStop);\n\n$btnLeftScroll.on(\"mousedown touchstart\", function () { Scroll(ScrollLeft) })\n .on(\"mouseup touchend\", ScrollStop);\n\n$content.on(\"mouseenter\", Content_OnMouseEnter)\n .on(\"mouseleave\", Content_OnMouseLeave);\n</code></pre>\n</blockquote>\n\n<ul>\n<li>Finally, it is considered best practice to have one chained var statement, so</li>\n</ul>\n\n<blockquote>\n<pre><code>var timer, // holds timer for continuous scroll functionality\n scrollOffset, // how many pixels the content is scrolled on each scroll action\n continuousScrollSpeed, // affects speed of scrolling when mouse/finger held down on a scroll button\n\n // settings for auto-scroll feature\n autoScroll,\n autoScrollSpeed,\n etc.\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T19:02:45.193",
"Id": "63179",
"Score": "2",
"body": "Some comments: Unused Variables: whoops! I changed the implementation and neglected the clean-up (not good practice). YODA: Thank you for pointing those out. Formatting: Thank you for the suggestions, and I prefer the formatting you provided. Chained VAR: I've been away from JavaScript for a while, thank you for the best practice pointer. Again, thank you for taking the time to review!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T15:57:42.003",
"Id": "37965",
"ParentId": "29288",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "37965",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T23:20:23.390",
"Id": "29288",
"Score": "9",
"Tags": [
"javascript",
"jquery",
"plugin"
],
"Title": "First jQuery Plugin - SmoothSlider"
}
|
29288
|
<p>I am writing a unit test for a Dispatcher that will route a HTTP request to a specific Controller and invoke a specific method on that Controller. It will also trigger various events at different steps of the process. The majority of what is going on is carried out by dependencies injected at construction time; the Dispatcher is just wiring everything together in the proper order.</p>
<p>I have gotten to where I am testing the events being triggered appropriately during processing. There are three "primary" steps of the process:</p>
<ul>
<li>Routing</li>
<li>Controller Invocation</li>
<li>Response being sent to user</li>
</ul>
<p>Before each primary step is carried out a "before" event is triggered and after the step is finished an "after" event is triggered. The problem I am encountering is with unit testing that the appropriate <em>after</em> event is not triggered before the <em>before</em> event. I have attempted to mock this dependency with PHPUnit for these tests and use the Mock object's <code>$this->at($methodInvokeIndex)</code> but this is, to be blunt, a royal PITA. Every time you invoke a new method on the object you have to go readjust indexes all over the place. For the sake of this review this method of mocking objects is not feasible and will not be implemented.</p>
<p>Below are the test helpers and unit test I have for testing the before routing event is triggered. The reason I ask for the review is that the test is, well, a bit hacky. I'm getting this huge red warnings about the test and typically I see that as a failure in the design but I'm not seeing how.</p>
<p>Anyway, to the code. Everything in this question is related to a project available at <a href="https://github.com/cspray/SprayFire/tree/restful-dispatcher" rel="nofollow">cspray/SprayFire:restful-dispatcher</a>.</p>
<p><code>MediatorHelper</code></p>
<pre><code><?php
/**
* An abstract \SprayFire\Mediator\Mediator that will cache all triggered events
* for detailed inspection during unit testing.
*
* @author Charles Sprayberry
* @license See LICENSE in source root
*/
namespace SprayFireTest\Helpers\DispatcherMediator;
use \SprayFire\Mediator;
abstract class MediatorHelper implements Mediator\Mediator {
/**
* A collection of info related to triggered events; each element in the numerically
* indexed array is the info for a triggered event, each one of these arrays
* will have the following keys:
*
* 'name' => event name,
* 'target' => event Target,
* 'args' => event args
*
* @property array
*/
private $events = [];
/**
* @property array
* @type \SprayFire\Mediator\Callback
*/
protected $callbacks = [];
/**
* Will cache each triggered event for later inspection.
*
* @param string $eventName
* @param object $Target
* @param array $args
* @return bool|void
*/
public function triggerEvent($eventName, $Target, array $args = []) {
$this->events[] = [
'name' => $eventName,
'target' => $Target,
'args' => $args
];
}
/**
* Will return an array representing the info for each triggered event before
* getTriggeredEvents() was called.
*
* @return array
*/
public function getTriggeredEvents() {
return $this->events;
}
/**
* Will return an array of \SprayFire\Mediator\Callback objects or an empty
* array if no callbacks are added for the given event.
*
* @param string $eventName
* @return array
*/
public function getCallbacks($eventName) {
return $this->callbacks;
}
/**
* Should add a callback to a collection of callbacks for a specific event
* based on the event name returned from the passed $Callback.
*
* @param \SprayFire\Mediator\Callback $Callback
* @return boolean
*/
public function addCallback(Mediator\Callback $Callback) {
$this->callbacks[] = $Callback;
}
/**
* Should remove a callback from the collection of callbacks for the event
* name.
*
* @param \SprayFire\Mediator\Callback $Callback
*/
public function removeCallback(Mediator\Callback $Callback) {
return false;
}
}
</code></pre>
<hr>
<p><code>TriggerBeforeRoutingEvent</code></p>
<pre><code><?php
/**
* A test helper that ensures the appropriate \SprayFire\Events::BEFORE_ROUTING
* event is triggered one time and that \SprayFire\Events::AFTER_ROUTING is not
* triggered when the event is triggered.
*
* @author Charles Sprayberry
* @license See LICENSE in source root
*/
namespace SprayFireTest\Helpers\DispatcherMediator;
use \SprayFire\Mediator;
use \SprayFire\Events;
use \PHPUnit_Framework_AssertionFailedError as TestFailedException;
class TriggerBeforeRoutingEvent extends MediatorHelper {
/**
* @param string $eventName
* @param object $Target
* @param array $args
* @return bool|void
* @throws \PHPUnit_Framework_AssertionFailedError
*/
public function triggerEvent($eventName, $Target, array $args = []) {
if ($eventName === Events::BEFORE_ROUTING) {
$alreadyTriggered = $this->getTriggeredEvents();
foreach($alreadyTriggered as $eventInfo) {
if ($eventInfo['name'] === Events::BEFORE_ROUTING) {
throw new TestFailedException('The ' . Events::BEFORE_ROUTING . ' event was triggered multiple times');
}
if ($eventInfo['name'] === Events::AFTER_ROUTING) {
throw new TestFailedException('The ' . Events::AFTER_ROUTING . ' event was triggered before the ' . Events::BEFORE_ROUTING . ' event');
}
}
}
// we store the event after we check already triggered events
// otherwise the first call to BEFORE_ROUTING will cause test to fail on first check
parent::triggerEvent($eventName, $Target, $args);
}
}
</code></pre>
<hr>
<p><code>DispatcherTest</code></p>
<p>This is just the one test related to above code. The references to <code>$MockObject</code> properties are mock objects that will satisfy the dependency injection contract.</p>
<pre><code><?php
/**
* @author Charles Sprayberry
* @license Subject to the terms of the LICENSE file in the project root
* @version 0.3
* @since 0.1
*/
namespace SprayFireTest\Dispatcher\FireDispatcher;
use \SprayFire\Events;
use \SprayFire\Dispatcher\FireDispatcher;
use \SprayFireTest\Helpers;
use \PHPUnit_Framework_TestCase as PHPUnitTestCase;
class DispatcherTest extends PHPUnitTestCase {
public function testDispatcherInvokesBeforeRoutingOneTimeAndBeforeAfterRouting() {
$this->MockRouter->expects($this->once())
->method('getRoute')
->will($this->returnValue($this->getMock('\\SprayFire\\Router\\Route')));
$this->MockFactory->expects($this->once())
->method('makeObject')
->will($this->returnValue($this->getMock('\\SprayFire\\Controller\\Controller')));
$Mediator = new Helpers\DispatcherMediator\TriggerBeforeRoutingEvent();
$Dispatcher = new FireDispatcher\Dispatcher($this->MockRouter, $this->MockFactory, $Mediator);
$Dispatcher->dispatch($this->MockRequest, $this->MockResponse);
$testPassed = false;
$triggeredEvents = $Mediator->getTriggeredEvents();
foreach($triggeredEvents as $eventInfo) {
if ($eventInfo['name'] === Events::BEFORE_ROUTING) {
$testPassed = true;
}
}
if (!$testPassed) {
$this->fail('The ' . Events::BEFORE_ROUTING . ' event was not triggered');
}
}
}
</code></pre>
<p>So, the hackiness is pretty apparent. To go over the problems I see:</p>
<ul>
<li>Some of the testing is actually taking place in the Helpers. If the Helper throws a <code>PHPUnit_Framework_AssertionFailedError</code> it is ultimately doing something the actual unit testing test case should be doing.</li>
<li>The actual unit test requires a foreach loop and I've always found that this "seems" wrong.</li>
</ul>
<p>The pros are that I don't have to work with trying to mock out something that is extremely difficult to do so.</p>
<p>Is there something horribly wrong here? Are my fears justified and this is more indicative of a problem with the design? I've come to the conclusion that I don't believe the design is necessarily a problem; I can't come up with any way to perform these actions in a way that makes this test easier to implement.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T09:28:26.323",
"Id": "384186",
"Score": "0",
"body": "Yes you’re right about your fears. Your user land code should not have test exceptions, and your code shouldn’t need any mock really. You should be able to set it up easily by creating an empty dispatcher, adding a route and events to it, and then do assertions on those events. As far as I know nothing lets you do this right now and that’s your design problem. Make this test using TDD and imagine how you’d like to use and test it without thinking about the real implementation, you’ll find a much better design since you don’t have a choice to test it properly."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T23:59:37.127",
"Id": "29289",
"Score": "3",
"Tags": [
"php",
"object-oriented",
"unit-testing"
],
"Title": "Unit testing event triggering"
}
|
29289
|
<p>I am currently writing my first actual C++ project. I like Chess and I would like to see how good I'm doing on a monthly basis, so the idea is to read the log files (.pgn files) from the games and tell me how many games I won and such.</p>
<p>My question specially relates to Games.cpp where I'm not sure I have done the right thing in having both a <code>getMonths()</code> returning a list of all the months I have played a game and a <code>getGamesByMonth(std::string month)</code> returning all the games played on a given month. Seems like too much work - maybe a simpler solution is available.</p>
<p>Also, looking at <code>wonAsBlack()</code>, <code>wonAsWhite()</code>, <code>lostAsWhite()</code>, etc, seems like too much work as well - there might be a better solution to this as well. You can see the actual way it works in main.cpp where I have made a test case.</p>
<p>The code is <a href="https://github.com/madsravn/PGNHelper" rel="nofollow">here</a>.</p>
<p><strong>Games.cpp:</strong></p>
<pre><code>#include "Games.hpp"
#include "Parser.hpp"
Games::Games() {
}
Games::Games(std::vector<Game> games) {
pgames = games;
}
void
Games::openFile(std::string tfile) {
Parser parser;
parser.parse(tfile);
pgames = parser.games();
}
size_t
Games::getSize() {
return pgames.size();
}
Games
Games::getGamesWonBy(std::string winner) {
std::vector<Game> games;
for(Game &game : pgames) {
if(game.getWinner().find(winner) == 0) {
games.push_back(game);
}
}
return games;
}
Games
Games::getGamesLostBy(std::string loser) {
std::vector<Game> games;
for(auto &game : pgames) {
if(game.getLoser().find(loser) == 0) {
games.push_back(game);
}
}
return games;
}
std::vector<std::string>
Games::getMonths() {
std::vector<std::string> months;
for(Game &game : pgames) {
std::string month = game.getMonth();
auto index = std::find(months.begin(), months.end(), month);
if(index == months.end()) {
months.push_back(month);
}
}
return months;
}
Games
Games::getGamesByMonth(std::string month) {
std::vector<Game> games;
for(auto &game : pgames) {
if(game.getMonth() == month) {
games.push_back(game);
}
}
Games rgames(games);
return rgames;
}
Games
Games::getDrawGames() {
std::vector<Game> games;
for(auto &game : pgames) {
if(game.getDraw() == true) {
games.push_back(game);
}
}
Games rgames(games);
return rgames;
}
Games
Games::getGamesByType(std::string type) {
std::vector<Game> games;
for(auto &game : pgames) {
if(game.getType() == type) {
games.push_back(game);
}
}
Games rgames(games);
return rgames;
}
Games
Games::wonAsBlack() {
std::vector<Game> games;
for(auto &game : pgames) {
if(game.getResult() == "0-1") {
games.push_back(game);
}
}
Games rgames(games);
return rgames;
}
Games
Games::wonAsWhite() {
std::vector<Game> games;
for(auto &game : pgames) {
if(game.getResult() == "1-0") {
games.push_back(game);
}
}
Games rgames(games);
return rgames;
}
Games
Games::lostAsBlack() {
return wonAsWhite();
}
Games
Games::lostAsWhite() {
return wonAsBlack();
}
Games
Games::drawAsWhite(std::string name) {
std::vector<Game> games;
for(auto &game : pgames) {
if(game.getWhite().find(name) == 0 && game.getResult() == "½-½") {
games.push_back(game);
}
}
return games;
}
Games
Games::drawAsBlack(std::string name) {
std::vector<Game> games;
for(auto &game : pgames) {
if(game.getBlack().find(name) == 0 && game.getResult() == "½-½") {
games.push_back(game);
}
}
return games;
}
</code></pre>
<p><strong>main.cpp</strong></p>
<pre><code>#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include "Game.hpp"
#include "Parser.hpp"
#include "Games.hpp"
int main(int argc, const char **argv) {
bool STRtags = false;
std::string line;
//Parser parser;
if(argc > 1) {
// Open argument as file
//parser.parse(std::string(argv[1]));
//games = parser.games();
Games games;
games.openFile(std::string(argv[1]));
games = games.getGamesByType("15|10");
auto months = games.getMonths();
for(auto &month : months) {
std::cout << "Stats for " << month << std::endl;
Games thismonth = games.getGamesByMonth(month);
Games wonbyme = thismonth.getGamesWonBy("madsravn");
Games drawGames = thismonth.getDrawGames();
Games lostbyme = thismonth.getGamesLostBy("madsravn");
std::cout << "Amount of games: " << thismonth.getSize() << std::endl;
std::cout << "Won: " << wonbyme.getSize() << std::endl;
std::cout << "==> As white: " << wonbyme.wonAsWhite().getSize() << std::endl;
std::cout << "==> As black: " << wonbyme.wonAsBlack().getSize() << std::endl;
std::cout << "Lost: " << lostbyme.getSize() << std::endl;
std::cout << "==> As white: " << lostbyme.lostAsWhite().getSize() << std::endl;
std::cout << "==> As black: " << lostbyme.lostAsBlack().getSize() << std::endl;
std::cout << "Draw: " << drawGames.getSize() << std::endl;
std::cout << "==> As white: " << drawGames.drawAsWhite("madsravn").getSize() << std::endl;
std::cout << "==> As black: " << drawGames.drawAsBlack("madsravn").getSize() << std::endl << std::endl;
}
} else {
std::cout << "Takes one argument, the file which needs to be parsed." << std::endl;
}
return 0;
}
</code></pre>
<p><strong>Games.hpp</strong></p>
<pre><code>#ifndef GAMES_HPP_
#define GAMES_HPP_
#include "Game.hpp"
class Games {
public:
Games();
Games(std::vector<Game> games);
void openFile(std::string tfile);
size_t getSize();
Games getGamesWonBy(std::string winner);
Games getGamesLostBy(std::string loser);
std::vector<std::string> getMonths();
Games getGamesByMonth(std::string month);
Games getDrawGames();
Games getGamesByType(std::string type);
Games wonAsBlack();
Games wonAsWhite();
Games lostAsWhite();
Games lostAsBlack();
Games drawAsWhite(std::string name);
Games drawAsBlack(std::string name);
private:
std::vector<Game> pgames;
};
#endif
</code></pre>
|
[] |
[
{
"body": "<p><strong>Games.cpp</strong></p>\n\n<ul>\n<li><p>It's not necessary to have member functions access <code>private</code> data members by their getters. These particular functions already have full access to the class.</p></li>\n<li><p>Too many of your member functions begin with <code>get</code>, yet they don't all perform simple member-accessing. This is a sign that your functions need to be renamed to accurately identify their purpose. Consider this function of yours:</p>\n\n<pre><code>if (game.getDraw() == true) {}\n</code></pre>\n\n<p>Unless <code>draw</code> is a <code>bool</code>, this could be misleading. Make it clear that it's supposed to perform a Boolean operation.</p></li>\n<li><p><code>if (game.getDraw() == true) {}</code> can simply be <code>if (game.getDraw()) {}</code>.</p></li>\n<li><p>I'd recommend making <code>std::vector<Game></code> a <code>typedef</code> (under <code>private</code>).</p></li>\n<li><p>This:</p>\n\n<pre><code>Games::Games(std::vector<Game> games) {\n pgames = games;\n}\n</code></pre>\n\n<p>should be an initializer list instead:</p>\n\n<pre><code>Games::Games(std::vector<Game> games) : pgames(games) {}\n</code></pre></li>\n<li><p><code>getSize()</code> should instead be defined in the class header (also as <code>const</code>):</p>\n\n<pre><code>std::size_t Games::getSize() const {return pgames.size();}\n</code></pre></li>\n<li><p>When a non-native type (such as <code>std::string</code>) parameter will not be modified, have it passed by const-reference:</p>\n\n<pre><code>Games::getGamesWonBy(std::string const& winner) {}\n</code></pre></li>\n<li><p>If these are supposed to be conditionals (kinda hard to tell for sure):</p>\n\n<pre><code>if (game.getWinner().find(winner) == 0) {}\nif (game.getLoser().find(loser) == 0) {}\n</code></pre>\n\n<p>make it clear that they are (<code>false</code> in this case):</p>\n\n<pre><code>if (!game.getWinner().find(winner)) {}\nif (!game.getLoser().find(loser)) {}\n</code></pre></li>\n</ul>\n\n<p><strong>Main.cpp</strong></p>\n\n<ul>\n<li><p>It'd be a good idea to alphabetize your <code>#include <...></code>s for organization.</p></li>\n<li><p>Unless you're okay with flushing the stream with each <code>endl</code>, use <code>\\n</code> in the <code>cout</code>s instead.</p></li>\n<li><p>I'd suggest grouping these lines appropriately based on their roles for readability (especially the outputs). This is important because you need to make sure your driver code is written as intended, as this is what tests your class.</p></li>\n<li><p>It appears that <code>line</code> isn't used anywhere. If it's a leftover, then get rid of it. This is a reason why variables should always declared near the line(s) where they are used.</p></li>\n<li><p>The very last output seems out of place when preceded by that huge block of outputs. You could instead test for a failed condition first. If it does fail, display that message <em>and <code>return EXIT_FAILURE</code></em> (or 1). If it doesn't fail, run the program and then terminate with the <code>return 0</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T01:04:29.370",
"Id": "46243",
"Score": "0",
"body": "Thanks! But I'm a little unsure what you mean about the last comment you made. Why would I make a if(!game.getWinner().find(winner)) ? I just need to check if the winner is the string I pass"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T01:06:51.523",
"Id": "46244",
"Score": "0",
"body": "@Mads: With all that accessing, it's hard to tell exactly what value this is supposed to return. In general, 0 is equal to `false` when dealing with `bool`s. If that's *not* what's being tested here, then I'll correct this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T05:22:30.697",
"Id": "46249",
"Score": "0",
"body": "*If you don't need the default constructor, just leave it out. The compiler will make one for you.* He has defined a non-default constructor as well, and then the compiler will *not* define a default one. So, he does need it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T01:01:37.943",
"Id": "29291",
"ParentId": "29290",
"Score": "4"
}
},
{
"body": "<p>Most of your member functions could (and IMO, should) be rewritten to use standard algorithms, such as:</p>\n\n<pre><code>Games\nGames::getGamesLostBy(std::string loser) {\n std::vector<Game> games;\n for(auto &game : pgames) {\n if(game.getLoser().find(loser) == 0) {\n games.push_back(game);\n }\n }\n return games;\n}\n</code></pre>\n\n<p>...would be better (IMO) as:</p>\n\n<pre><code>Games\nGames::getGamesLostBy(std::string const &loser) { \n std::vector<Game> games;\n\n std::copy_if(pgames.begin(), pgames.end(),\n std::back_inserter(games),\n [&](game const &g) { return g.getLoser().find(loser)==0; });\n return games;\n}\n</code></pre>\n\n<p>Likewise, <code>Games::wonAsWhite()</code> would be better as:</p>\n\n<pre><code>Games\nGames::wonAsWhite() {\n std::vector<Game> games;\n std::copy_if(pgames.begin(), pgames.end(),\n std::back_inserter(games),\n [](Game const &g) { return g.getResult() == \"1-0\";});\n return games;\n}\n</code></pre>\n\n<p>I'd also note that most of <code>Games</code>'s member functions are really pretty much alike -- producing some subset of the games in the <code>Games</code>. Given the number, I think it might be worth considering writing a <code>filtered_iterator</code> (or something similar) that would take a condition like one of the above lambdas, and iterate over the items in the collection that meet the specified condition. Alternatively, you might want to consider using a Boost <a href=\"http://www.boost.org/doc/libs/1_54_0/libs/iterator/doc/filter_iterator.html\" rel=\"nofollow\">filter_iterator</a> that already provides this capability packaged, portable and tested.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T05:40:53.557",
"Id": "29515",
"ParentId": "29290",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T00:28:04.347",
"Id": "29290",
"Score": "4",
"Tags": [
"c++",
"game",
"c++11",
"parsing"
],
"Title": "Reading .pgn files to display statistics about Chess games"
}
|
29290
|
<p>I'm not sure what I'm doing wrong, but I run the code using a Web Vulnerability software and I get a lot of XSS attacks against the code. Is there something I could do better?
<pre><code>// connect to database
include("dbconnect.php");
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$category = $_POST['category'];
$add = $db->prepare("INSERT INTO contacts SET firstName=(?), lastName=(?), email=(?), phone=(?), category=(?)");
$add->bind_param('sssss', $firstName, $lastName, $email, $phone, $category);
$firstName = $db->real_escape_string($firstName);
$lastName = $db->real_escape_string($lastName);
$email = $db->real_escape_string($email);
$phone = $db->real_escape_string($phone);
$category = $db->real_escape_string($category);
$add->execute();
$add->close();
header("Location:http://localhost/address-book/contact.php");
exit;
?>
</code></pre>
<p>Everything works great, but I'm wonder if there's a safer way to go about it.</p>
<p>I wrote it as prepared statements and ran each variable through mysqli_real_escape_string hoping to strip most of the nasty things. But, no lucky.</p>
<p>I'm new to PHP, so this is all a bit alien to me.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T10:48:07.630",
"Id": "46257",
"Score": "0",
"body": "In addition to the answer, it's redundant to escape parameters you bind into a prepared statement."
}
] |
[
{
"body": "<p>XSS attacks affect the whole web, regardless of the stack you're using, you always have to be careful. Based on the redirect url you provided and the queries you execute, I'm assuming you're building an on-line address book. If a client were to fill in the form, saying his name were:</p>\n\n<pre><code><script> alert(document.cookie);</script>\">Gotcha\n</code></pre>\n\n<p>Your code would simply insert that in the database, properly escaped, of course. The escaping is what <code>mysqli_real_escape_string</code> does. It doesn't sanitize, it protects the Database, not the site. I can't, for example, post something like <em><code>\"bobby'; -- DROP TABLE contacts;\"</code></em>, which is a basic example of an injection attack. But storing markup in a DB isn't <em>wrong</em> or <em>dangerous</em> as far as MySQL is concerned, so the data above can be safely inserted, and queried later on. However, when you request a list of contact names, you would get an alert, showing you your cookies. That's annoying, but not <em>that</em> bad. However, <a href=\"http://www.thegeekstuff.com/2012/02/xss-attack-examples/\">Check these examples</a> to get a basic idea of how XSS attacks work, and what they can be used for.<Br/>\nThey're used to bypass login systems, send client data to a third party or even inject/alter your page links to link to another, even more mallicious site:</p>\n\n<pre><code><script>(function()\n{\n var a= document.querySelectorAll('a');\n for(var i=0;i<a.length;a++)\n {\n a[i].setAttribute('href','http://badsite.net');\n }\n}());</script>\n</code></pre>\n\n<p>All your links have now changed to link to another site. Your entire site navigation has been compromised.<br/>\nThe first step to prevent this is to <em>sanitize your data</em>:</p>\n\n<pre><code>$email = $_POST['email'];\nif (!filter_var($email, FILTER_VALIDATE_EMAIL))\n{\n //don't insert, redirect back, with a GENERIC error message\n die('Not all input fields contained the expected data');\n}\n</code></pre>\n\n<p>Why, you might ask, not point out to the client which bit of data failed the checks? Simply because if you were to say <em>\"Please fill in valid emai\"</em>, the attacker knows to <em>not</em> to use that input field, and fill in something like <code>bill.gates@microsoft.com</code>, and try his luck with the other fields.</p>\n\n<p>Another useful thing to do is to avoid actual script tags from being send to the client when using user-supplied data:</p>\n\n<pre><code>echo htmlspecialchars(strip_tags($someUserData));\n//or if some markup is allowed:\necho strip_tags($someUserData, '<p><br>');\n</code></pre>\n\n<p>In case some markup is allowed, though, best go about that like wiki does: using custom markup like <code>[paragraph]text[/paragraph]</code>, to avoid having to parse the supplied DOM and filter-out all attributes that contain what might be JS.</p>\n\n<p><a href=\"https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet\">Here's another site</a> with an array of attack examples, and a how to defend against them.<br/>\n<a href=\"http://html5sec.org/\">Here's a list of XXS weak-spots, introduced by HTML5</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T07:23:21.357",
"Id": "29295",
"ParentId": "29294",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "29295",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T05:05:04.207",
"Id": "29294",
"Score": "2",
"Tags": [
"php",
"mysqli"
],
"Title": "How can I make this code safer against XSS attacks?"
}
|
29294
|
<p>I am fairly new to coding TSQL script and am looking for some second view on my script.
The goal here is to to pull in some data and amongst that data to show a field with a counting the number of working days since the order date only (i.e. minus weekend days and UK bank holidays). The <code>SELECT</code> script below is working as expected in that it shows results and is therefore calling the <code>fn_WorkDays</code> function. What would be helpful is to have a second glance of the function itself as a double check/review. The last part of the function is looking at a date field of a table that contains all of the bank holidays.</p>
<p>I think the script is working okay as I have checked a few going back to January, so I'm looking to get the double check to highlight any unforeseen potential errors or even code improvements.</p>
<pre><code>SELECT
cir.[PW Number] AS PWNum
--Get the correct number of working dayts since the order date by using the fn_WorkDays function
,CONVERT(VARCHAR(10),singleended2.dbo.fn_WorkDays(cir.[Install Date], GETDATE()),103) AS NumberOfDaysSinceOrderDate
,CONVERT(VARCHAR(10), ISNULL(cir.[Install Date],'01/01/1900'),103) AS OrderDate--Get the order dates
,ISNULL(cirRep.CurrentStage, 'Not Set') AS CurrentStage
,cir.[ID] as CircuitID
FROM Quotebase.dbo.Circuits cir
LEFT JOIN Quotebase.dbo.CircuitReports cirRep ON Cir.[PW Number] = CirRep.PWNumber
WHERE Cir.Status='New Circuit Order'
ORDER BY Cir.[PW Number]
</code></pre>
<p>Here is the function script that is called:</p>
<pre><code>ALTER FUNCTION dbo.fn_WorkDays (@StartDate AS DATETIME, @EndDate AS DATETIME)
--Define the output data type.
RETURNS INT
AS
--Calculate the RETURN of the function.
BEGIN
RETURN (
SELECT
(DATEDIFF(dd,@StartDate, @EndDate)+1)--Start with total number of days including weekends +1 Includes the day run
-(DATEDIFF(wk,@StartDate, @EndDate)*2)--Subtact 2 days for each full weekend
-(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' --If StartDate is a Sunday, Subtract 1
THEN 1
ELSE 0
END)
-(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday'--If EndDate is a Saturday, Subtract 1
THEN 1
ELSE 0
END)
--Now check if there are any bank holidays between the start and end and remove that amount
- (SELECT COUNT(ivm.[Date])
FROM [EUROPEVUK386].[InvoiceManagement].[dbo].[tblBankHolidays] ivm
WHERE ivm.[Date] BETWEEN @StartDate AND @EndDate)
--WHERE ivm.[Date] BETWEEN '2006-04-14' AND '2006-05-29')
)
END
GO
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-31T20:52:51.813",
"Id": "53851",
"Score": "0",
"body": "I added two tags I assumed on the SQL-Server tag over sybase. if it is Sybase I will replace SQL-Server with a Sybase Tag, just let me know"
}
] |
[
{
"body": "<p>I did notice in your Function you subtract a day from Saturday if it is an End Date, but not 2 days from the end date if it is Sunday, and not 2 days from the start date if it is Sunday or 1 day from the start date if it is Saturday. </p>\n\n<p>I assume that you want to do these things to make sure you aren't trying to include the weekends especially since you are using <code>Between</code> and that is inclusive, so it would include the start date and the end date</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-31T21:02:07.087",
"Id": "33619",
"ParentId": "29297",
"Score": "2"
}
},
{
"body": "<ol>\n<li><p><code>ISNULL</code>, which you use a few times, is valid T-SQL, but there is an argument for using the more portable <code>COALESCE</code> instead. They're <a href=\"https://stackoverflow.com/questions/7408893/using-isnull-vs-using-coalesce-for-checking-a-specific-condtion\">not straight aliases</a>, though, so consider whether this is appropriate.</p></li>\n<li><p>Comparing the two lines</p>\n\n<pre><code>,CONVERT(VARCHAR(10),singleended2.dbo.fn_WorkDays(cir.[Install Date], GETDATE()),103) AS NumberOfDaysSinceOrderDate \n,CONVERT(VARCHAR(10), ISNULL(cir.[Install Date],'01/01/1900'),103) AS OrderDate--Get the order dates\n</code></pre>\n\n<p>you assume in the second line that <code>cir.[Install Date]</code> might be null, but the first line passes it directly to a function which has no special-casing for that situation. Is this intentional?</p></li>\n<li><p>I think you're overdoing things in</p>\n\n<pre><code>CONVERT(VARCHAR(10), ISNULL(cir.[Install Date],'01/01/1900'),103)\n</code></pre>\n\n<p>You're trying to convert the date to a dd/mm/yyyy string, but if it's <code>NULL</code> you take a string in that format, convert it with whatever the default date format happens to be (although since the day and month are the same you have good odds of getting the right result), and then convert it back. Why not push in the <code>CONVERT</code> and handle the fallback outside?</p></li>\n<li><p>You're making assumptions about locale-related settings inside the function. It's understandable that you hard-code an assumption about which days are the weekends: you're only interested in one culture, so that's a business-level setting. But the localisation of the values returned by <code>DATENAME</code> is a per-connection setting. You might think that your function will always be executed in an English locale, and you might even be right, but it's a small change to replace <code>DATENAME</code> with <code>DATEPART</code>, and it makes the code slightly more robust.</p>\n\n<p>(I've had experience of maintaining a system built for a British organisation but which relied implicitly on using a US locale; since my dev machine has a UK locale, lots of things broke. Don't discount the possibility that in future your code will be maintained by someone from another country who configures their dev machine differently - or even that the production machine might be moved to a server with a different locale).</p></li>\n<li><p>For the benefit of future maintenance programmers, who may not be SQL-Server experts or domain experts on UK bank holidays, it would be nice to add some comments pointing out that <a href=\"http://msdn.microsoft.com/en-us/library/ms181598.aspx\" rel=\"nofollow noreferrer\"><code>DATEDIFF</code> ignores <code>@@DATEFIRST</code> in order to be deterministic</a>, and that <a href=\"https://www.gov.uk/bank-holidays\" rel=\"nofollow noreferrer\">a bank holiday will never be on a weekend</a>.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-01T11:47:51.043",
"Id": "33644",
"ParentId": "29297",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T09:07:51.503",
"Id": "29297",
"Score": "5",
"Tags": [
"sql",
"beginner",
"sql-server",
"datetime",
"t-sql"
],
"Title": "Selecting the number of working days minus weekend days and UK bank holidays"
}
|
29297
|
<p>I am using <code>if</code> statements within my functions to validate form fields and then on the <code>isset</code> event.</p>
<p>I want to be able to create many different functions to validate various fields groups, and it seems that this statement could grow very long:</p>
<pre><code>if (($namecheck === TRUE) && ($emailcheck ===TRUE) && ($messagecheck ===TRUE)) {
</code></pre>
<p>This also causes the alert for each function if no data is entered. I can circumvent this by making statements if one proves false, then stop, but it is only getting messier and messier.</p>
<p>I don't need my code written for me. As such, I am interested in what you suggest, in terms of <code>if</code> statements, using <code>switch</code> or loop instead, or any other ideas.</p>
<p>I am not so much wanting a solution here, as reasons for why some ways are better than others. For the purposes of this discussion, I am not concerned with client side validation. It is a focus on PHP functions only.</p>
<pre><code><?php
include ("contact.html");
function namecheck ($fname, $lname) {
$regexp ="/^[A-Za-z]+$/";
//filter through names
if (preg_match($regexp,$fname,$lname)) {
return TRUE; }
else {
echo'<script type="text/javascript">alert("Enter your names.")</script>';
return FALSE; }}
function emailcheck ($email1, $email2) {
$regexp="/^[a-zA-A-Z0-9_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9.-]+$/";
//validate email address
if (preg_match($regexp,$email1,$email2)) {
return TRUE; }
else {
echo '<script type="text/javascript">alert ("Enter a valid email address.")</script>';
return FALSE; }}
function messagecheck ($message) {
$regex = "/^[a-zA-Z0-9.?!_-]+$/";
//validate message text
if (preg_match($regex,$message)) {
return TRUE;}
else{
echo'<script type="text/javascript">alert("Enter your message.")</script>';
return FALSE; }}
if (isset($_POST['submit'])) {
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$namecheck=namecheck($fname);
$email1=$_POST['email1'];
$email2=$_POST['email2'];
$emailcheck=emailcheck($email1,$email2);
$message = $_POST['message'];
$messagecheck=messagecheck($message);
if (($namecheck === TRUE) && ($emailcheck ===TRUE) && ($emailcheck ===TRUE)) {
$subject="website contact";
mail("myemail", $subject ,$message , "From: $email1");
echo '<script type="text/javascript"> alert("Your form has been submitted.") </script>'; } }
?>
</code></pre>
|
[] |
[
{
"body": "<p>If I understand your problem well, the problem is that you don't want an if clause to become too long and that you have a problem with empty parameters. Your way of checking seems right to me, for the other part I asked myself if you can't just add something like this to the functions namecheck() emailcheck() and messagecheck():</p>\n\n<pre><code> if (strlen($fname) == 0 || strlen($lname) == 0) return false;\n</code></pre>\n\n<p>Furthermore in your code line with the checks you have two times the emailcheck instead of the messagecheck once:</p>\n\n<pre><code> if (($namecheck === TRUE) && ($emailcheck ===TRUE) && ($emailcheck ===TRUE)) {\n</code></pre>\n\n<p>Good luck, hope it helped.</p>\n\n<p>Jef</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T20:57:54.690",
"Id": "29409",
"ParentId": "29299",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T11:49:56.457",
"Id": "29299",
"Score": "1",
"Tags": [
"php",
"algorithm"
],
"Title": "Validating form fields"
}
|
29299
|
<p>I've written the following extension to determine the MIME type of a base64 string. It's worked in my local tests, but can anyone point out issues or alternate methods?</p>
<pre><code>public static AttachmentType GetMimeType(this string value)
{
if(String.IsNullOrEmpty(value))
return new AttachmentType
{
FriendlyName = "Unknown",
MimeType = "application/octet-stream",
Extension = ""
};
var data = value.Substring(0,5);
switch (data.ToUpper())
{
case "IVBOR":
case "/9J/4":
return new AttachmentType
{
FriendlyName = "Photo",
MimeType = "image/png",
Extension = ".png"
};
case "AAAAF":
return new AttachmentType
{
FriendlyName = "Video",
MimeType = "video/mp4",
Extension = ".mp4"
};
case "JVBER":
return new AttachmentType
{
FriendlyName = "Document",
MimeType = "application/pdf",
Extension = ".pdf"
};
default:
return new AttachmentType
{
FriendlyName = "Unknown",
MimeType = string.Empty,
Extension = ""
};
}
}
public class AttachmentType
{
public string MimeType { get; set; }
public string FriendlyName { get; set; }
public string Extension { get; set; }
}
</code></pre>
|
[] |
[
{
"body": "<p>Your attachment types look like static data to me, so I'd personally make <code>AttachmentType</code> an immutable class and define your common bits as <code>static</code> members. I also like making things like this implement an <code>interface</code> for ease of mocking during unit testing. So I have this:</p>\n\n<pre><code>public interface IAttachmentType\n{\n string MimeType\n {\n get;\n }\n\n string FriendlyName\n {\n get;\n }\n\n string Extension\n {\n get;\n }\n}\n\npublic sealed class AttachmentType : IAttachmentType\n{\n private static readonly IAttachmentType unknownMime =\n new AttachmentType(\"application/octet-stream\", \"Unknown\", string.Empty);\n\n private static readonly IAttachmentType photo = new AttachmentType(\"image/png\", \"Photo\", \".png\");\n\n private static readonly IAttachmentType video = new AttachmentType(\"video/mp4\", \"Video\", \".mp4\");\n\n private static readonly IAttachmentType document = new AttachmentType(\"application/pdf\", \"Document\", \".pdf\");\n\n private static readonly IAttachmentType unknown = new AttachmentType(string.Empty, \"Unknown\", string.Empty);\n\n private readonly string mimeType;\n\n private readonly string friendlyName;\n\n private readonly string extension;\n\n // Possibly make this private if you only use the static predefined MIME types.\n public AttachmentType(string mimeType, string friendlyName, string extension)\n {\n this.mimeType = mimeType;\n this.friendlyName = friendlyName;\n this.extension = extension;\n }\n\n public static IAttachmentType UnknownMime\n {\n get\n {\n return unknownMime;\n }\n }\n\n public static IAttachmentType Photo\n {\n get\n {\n return photo;\n }\n }\n\n public static IAttachmentType Video\n {\n get\n {\n return video;\n }\n }\n\n public static IAttachmentType Document\n {\n get\n {\n return document;\n }\n }\n\n public static IAttachmentType Unknown\n {\n get\n {\n return unknown;\n }\n }\n\n public string MimeType\n {\n get\n {\n return this.mimeType;\n }\n }\n\n public string FriendlyName\n {\n get\n {\n return this.friendlyName;\n }\n }\n\n public string Extension\n {\n get\n {\n return this.extension;\n }\n }\n}\n</code></pre>\n\n<p>Then, to avoid a big long <code>switch</code>, I put those into a <code>Dictionary<T,U></code> as such (note the case-insensitive specification, which will remove the <code>ToUpper()</code> later). You can add MIME types with your detection string as needed:</p>\n\n<pre><code> private static readonly IDictionary<string, IAttachmentType> mimeMap =\n new Dictionary<string, IAttachmentType>(StringComparer.OrdinalIgnoreCase)\n {\n { \"IVBOR\", AttachmentType.Photo },\n { \"/9J/4\", AttachmentType.Photo },\n { \"AAAAF\", AttachmentType.Video },\n { \"JVBER\", AttachmentType.Document }\n };\n</code></pre>\n\n<p>Your calling code then simplifies to:</p>\n\n<pre><code> public static IAttachmentType GetMimeType(this string value)\n {\n IAttachmentType result;\n\n return string.IsNullOrEmpty(value)\n ? AttachmentType.UnknownMime\n : (mimeMap.TryGetValue(value.Substring(0, 5), out result) ? result : AttachmentType.Unknown);\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T13:58:36.527",
"Id": "29303",
"ParentId": "29301",
"Score": "4"
}
},
{
"body": "<p>Your switch is wrong: \"<code>/9J/4</code>\" is for JPG images, not PNG (e.g. as shown in <a href=\"https://www.google.com/search?q=base64+jpeg+header+9J%2F4\">these examples</a>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T20:46:23.500",
"Id": "42461",
"ParentId": "29301",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "29303",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T13:15:41.880",
"Id": "29301",
"Score": "8",
"Tags": [
"c#",
"base64"
],
"Title": "Checking MIME Type from a base64 string"
}
|
29301
|
<p>Following is the code to update content via ajax. Please review all aspects of the code.</p>
<pre><code>var ajaxUpdate = {
init: function(){
ajaxUpdate.enableHistory();
},
_this:null,
enableHistory: function(){
History.Adapter.bind(window,'statechange',function() { // Note: We are using statechange instead of popstate
var State = History.getState();
console.log('History: '+State.url)
if(State.data.type == 'maincontainer'){
if(jQuery('#maincontainer').length){
//update content
jQuery('#maincontainer').html(State.data.response);
//select the menu element
jQuery('#main-menu li').removeClass('active');
jQuery('#main-menu li:eq('+State.data.main+')').addClass('active');
}
else{
window.location.href = State.url;
}
}/*
_this.parent().addClass('active');*/
});
},
updateMainContent: function(){
var _this = ajaxUpdate._this;
if ( !History.enabled ) {
return ;
}
jQuery.ajax({
type: 'GET',
url: _this.attr('href'),
beforeSend : function(jqXHR, settings){
jQuery('#maincontainer').addClass('loading');
},
complete: function(jqXHR, textStatus){
jQuery('#maincontainer').removeClass('loading');
},
success: function(response){
var data = {
main : _this.data('main_index'),
type: "maincontainer",
response: response
}
jQuery('#maincontainer').removeClass('loading');
History.pushState(data, _this.data('title'), this.url);
},
error : function(jqXHR, textStatus, errorThrown){
//processERROR();
}
});
return false;
},
mainmenu: function(){
ajaxUpdate._this = jQuery(this);
ajaxUpdate._this.data('main_index', ajaxUpdate._this.parent().index());
return ajaxUpdate.updateMainContent();
},
submenu: function(){
ajaxUpdate._this = jQuery(this);
ajaxUpdate._this.data('main_index', jQuery('#main-menu li.active').index());
return ajaxUpdate.updateMainContent();
},
search: function(){
ajaxUpdate._this = jQuery(this);
ajaxUpdate._this.data('main_index', jQuery('#main-menu li.active').index());
return ajaxUpdate.updateMainContent();
}
};
ajaxUpdate.init();
jQuery('#main-menu a').click(ajaxUpdate.mainmenu);
jQuery('#maincontainer').on('click', '.nav a', ajaxUpdate.submenu);
jQuery('#maincontainer').on('submit', 'form', ajaxUpdate.search);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T18:53:52.120",
"Id": "46271",
"Score": "2",
"body": "What exactly is your question? Does the code work for you? Are you asking us to review it? Are there any specific areas you want the reviews to focus on?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T12:22:45.483",
"Id": "46465",
"Score": "0",
"body": "@svick isn't this a code review site. I just want to get my code reviewed by peers"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T12:47:22.590",
"Id": "46466",
"Score": "2",
"body": "Yeah, but you should state that explicitly, because some people who post here actually want something else."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T15:44:45.840",
"Id": "46474",
"Score": "0",
"body": "Seems clear to me that (s)he wants the code reviewed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T15:49:22.180",
"Id": "46475",
"Score": "0",
"body": "@tomdemuyt: [See my Meta question](http://meta.codereview.stackexchange.com/questions/790/should-a-post-with-no-specific-questions-imply-a-general-review?cb=1)"
}
] |
[
{
"body": "<p>A couple things right off the bat:</p>\n\n<ol>\n<li><p>You use <code>jQuery('#maincontainer')</code> multiple times. You should consider caching that somewhere. Either as part of your object or a separate variable.</p>\n\n<pre><code>// Wherever you use jQuery('#maincontainer'), use ajaxUpdate.mainContainer\najaxUpdate.mainContainer = jQuery('#maincontainer');\n</code></pre></li>\n<li><p>I would suggest passing the <code>this</code> from your event handlers directly to <code>updateMainContent</code> since that is the only method that uses it.</p></li>\n<li><p>Unless you have plans to significantly change the way events are handled between search, submenu, and mainmenu, you can can just have one method that handles those events.</p></li>\n<li><p><code>complete</code> gets called whether it's an error or success. No need to remove the loading class on <code>success</code> and <code>complete</code>.</p></li>\n<li><p>Your <code>beforeSend</code> function is unnecessary since it doesn't actually manipulate any of the data before the AJAX call or cancel the AJAX call. You can move the <code>addClass</code> to before the <code>jQuery.ajax</code>. From the jQuery docs:</p>\n\n<blockquote>\n <p>A pre-request callback function that can be used to modify the <code>jqXHR</code> (in jQuery 1.4.x,\n XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. ...\n Returning <code>false</code> in the <code>beforeSend</code> function will cancel the request. </p>\n</blockquote></li>\n<li><p>You can chain the following lines together (to remove another call to <code>jQuery</code>):</p>\n\n<pre><code>jQuery('#main-menu li').removeClass('active');\njQuery('#main-menu li:eq('+State.data.main+')').addClass('active');\n</code></pre>\n\n<p>Like so:</p>\n\n<pre><code>jQuery('#main-menu li').removeClass('active')\n .filter(':eq('+State.data.main+')').addClass('active');\n</code></pre></li>\n<li><p>Switching your AJAX call to a <code>.get</code> and using the <a href=\"http://api.jquery.com/category/deferred-object/\"><code>promise</code></a> API cleans up the code a little and makes it a bit more concise.</p></li>\n<li><p>In your <code>success</code> response, you don't need to define <code>data</code> since you're just passing it directly to <code>History.pushstate</code>.</p></li>\n</ol>\n\n<p>Not knowing the HTML structure, I think that's the best I can give you. Here's a <a href=\"http://jsfiddle.net/3YvtT/2/\">fiddle</a> with all of these things implemented.</p>\n\n<p>I'm more than happy to answer any questions if you have them. Hopefully this will help you out.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T21:35:01.577",
"Id": "29876",
"ParentId": "29302",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T13:16:30.027",
"Id": "29302",
"Score": "3",
"Tags": [
"javascript",
"html",
"ajax"
],
"Title": "Code to update content via ajax"
}
|
29302
|
<p>Here is the script:</p>
<pre><code>function opening(){
setTimeout(function () {
var opening = $('#stage');
opening.find('h1').fadeIn('slow', function(){
setTimeout(function () {
opening.find('.logo').fadeIn('slow', function(){
setTimeout(function () {
opening.find('p').fadeIn('slow');
opening.find('#btn').fadeIn('slow');
}, 400);
});
}, 800);
});
}, 400);
}
</code></pre>
<p>It's work fine. But I would like to try to simplify it. Is possible?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T10:21:26.770",
"Id": "46459",
"Score": "0",
"body": "Are you interested only in pure JS or also in transcompiling solutions?"
}
] |
[
{
"body": "<pre><code>// Put everything in one function, but break it up internally\nfunction opening() {\n // A tiny, internal helper function\n // I've switched the order of arguments compared to setTimeout\n // because it makes for nicer code (no dangling argument after\n // a function body)\n function createTimeout(delay, func) {\n return function () {\n setTimeout(func, delay);\n };\n }\n\n var step1, step2, step3, // Declare some vars that'll hold functions\n stage = $('#stage'); // and find the #stage element right away\n\n // Create the first step. When called, it'll wait 400ms \n // and then execute the function\n step1 = createTimeout(400, function () {\n stage.find('h1').fadeIn('slow', step2); // call step2, when the fade-in completes\n });\n\n // Same principle as above\n step2 = createTimeout(800, function () {\n stage.find('.logo').fadeIn('slow', step3); // call step3\n });\n\n // and again\n step3 = createTimeout(400, function () {\n stage.find('p').fadeIn('slow');\n stage.find('#btn').fadeIn('slow');\n });\n\n step1(); // execute step 1\n}\n</code></pre>\n\n<p>So calling <code>opening()</code> will</p>\n\n<ul>\n<li>wait 400ms</li>\n<li>make the <code>H1</code> to fade in</li>\n<li>wait 800ms</li>\n<li>make the logo fade in</li>\n<li>wait 400mx</li>\n<li>make the <code>P</code> and <code>#btn</code> elements fade in</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T20:13:28.717",
"Id": "29315",
"ParentId": "29306",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29315",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T14:51:47.360",
"Id": "29306",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Trying to simplify a setTimeout sequence"
}
|
29306
|
<p>I am writing my first programs in Python and want to be sure my code is good and not too C++-like. Consider the problem of finding all common 'associations' for set of 'keys'.</p>
<p>Data format is</p>
<ul>
<li>first line: integer <code>N</code></li>
<li><code>N</code> lines: key: <code>association 1 ... association P_1</code></li>
<li><code>N+2</code>th line: integer <code>K</code></li>
<li><code>K</code> lines: <code>key 1 ... key T_1</code></li>
</ul>
<p>For each line after <code>K</code>, the program should output all common associations for all keys listed.</p>
<p>For example, the correct output for input</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>10
0: even
1: odd
2: even prime
3: odd prime
4: even composite notprime
5: odd prime
6: even composite notprime
7: odd prime
8: even composite notprime
9: odd composite notprime
2
8 4
2 3
</code></pre>
</blockquote>
<p>is</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>composite even notprime
prime
</code></pre>
</blockquote>
<p>My code is</p>
<pre class="lang-python prettyprint-override"><code>f = open('input.txt', 'r') #input file
d = {} #associations
uni = set() #set of all associations
for i in range(int(f.readline())):
t = f.readline().strip().split(': ') #split into list ('key', 'assoc1 ... assoc P_1')
d[t[0]] = s = set(t[1].split(' ')) #d : key -> set('assoc1', ..., 'assoc P_1')
uni |= s #add to uni
for i in range(int(f.readline())):
#read keys as list and intersect uni and list's associations
print reduce(lambda assoc, key: assoc & d[key], set(f.readline().strip().split(' ')), uni.copy())
</code></pre>
<p>How good is my code from the viewpoint of experienced Python programmers?</p>
|
[] |
[
{
"body": "<p>Your code looks pretty good for a newcomer to the language. Some comments:</p>\n\n<ul>\n<li>I don't quite understand why you need <code>uni</code>.</li>\n<li>References to <code>t[0]</code> and <code>t[1]</code>: It's more declarative to unpack tuples/lists and give names to its components -> <code>something, another_thing = t</code></li>\n<li><code>for i in range(int(f.readline()))</code>. I won't say this is bad, but certainly not very declarative. Note that <a href=\"http://docs.python.org/2/library/itertools.html#itertools.islice\" rel=\"nofollow\">itertools.islice</a> can be used to read N lines from a file object -> <code>itertools.islice(f, 10)</code>.</li>\n<li>Python2: Unless you have a compelling reason, use Python 3.</li>\n<li><code>reduce(lambda...</code>. As much as I like functional style, code that uses <code>reduce</code> with long lambdas usually looks cryptic. But I think it's still ok to use <code>reduce</code> with named functions.</li>\n<li><code>int(f.readline())</code>. Personally I like to give names to values when it's not clear what they stand for. Granted, this may increase the LOC slightly, but I think it's worthwhile. In this case, if we write <code>number_of_queries = int(f.readline())</code> and later use the variable, it's easy to see what's going on.</li>\n</ul>\n\n<p>As a first refactor, I'd write:</p>\n\n<pre><code>import itertools\nimport functools\n\nlines = open(\"input.txt\")\n\n# Parse associations\nn_associations = int(lines.readline())\nassociations = {}\nfor line in itertools.islice(lines, n_associations):\n n, associations_string = line.split(\":\")\n associations[n] = set(associations_string.split())\n\n# Parse and run queries\nn_queries = int(lines.readline())\nfor line in itertools.islice(lines, n_queries):\n numbers = line.split()\n common = functools.reduce(set.intersection, (associations[n] for n in numbers))\n print(\" \".join(common))\n</code></pre>\n\n<p>Ok, now let's take it a step further. Firstly, there are no functions at all, no modularization, that's no good. Secondly, I prefer a functional approach and there is some imperative stuff going on there. That's how I would write it in a more functional and declarative style:</p>\n\n<pre><code>def parse_and_execute_queries(path):\n def parse_association(line):\n number, associations_string = line.split(\":\")\n return (number, set(associations_string.split()))\n\n def execute_query(associations, query_string):\n numbers = query_string.split()\n common = functools.reduce(set.intersection, (associations[n] for n in numbers))\n return \" \".join(common)\n\n lines = open(path)\n n_associations = int(lines.readline())\n association_lines = itertools.islice(lines, n_associations)\n associations = dict(parse_association(line) for line in association_lines) \n n_queries = int(lines.readline())\n queries_lines = itertools.islice(lines, n_queries)\n return (execute_query(associations, line) for line in queries_lines)\n\nfor query_result in parse_and_execute_queries(\"input.txt\"):\n print(query_result)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T07:40:06.260",
"Id": "46314",
"Score": "0",
"body": "I needed `uni` because I didn't know `set.intersect`. Thank you for the reply!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T18:52:42.317",
"Id": "29309",
"ParentId": "29307",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29309",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T15:58:03.603",
"Id": "29307",
"Score": "2",
"Tags": [
"python"
],
"Title": "Finding associations for a set of keys"
}
|
29307
|
<p>I really like functional programming in C#, it gives you a lot of flexibility.
I am wondering if it is the right idea to use functions instead of helper methods, and to make the code more readable.</p>
<p>So here is what I want, I have a method that needs to find Saturday and do something with it:</p>
<pre><code>public void SomeMethod()
{
var saturday = DateTime.Today;
while (saturday.DayOfWeek != DayOfWeek.Saturday)
saturday = saturday.AddDays(-1);
//rest of the code
}
</code></pre>
<p>The problem I am having with this code is readability. I have to scan through 3 lines of code to understand that it needs to find Saturday. Plus seeing <code>var saturday = DateTime.Today;</code>, it really bugs my eyes.</p>
<p>Of course I can write a helper method</p>
<pre><code>private DateTime GetSaturday()
{
var saturday = DateTime.Today;
while (saturday.DayOfWeek != DayOfWeek.Saturday)
saturday = saturday.AddDays(-1);
return saturday;
}
</code></pre>
<p>Now I know exactly what the method does but my problem now is that I know that I won't be calling this method anywhere in the class so it kind of pollutes my class.</p>
<p>So here we are at my favorite:</p>
<pre><code>public void SomeMethod()
{
Func<DateTime> GetSaturdayFunc = () =>
{
var date = DateTime.Today;
while (date.DayOfWeek != DayOfWeek.Saturday)
date = date.AddDays(-1);
return date;
};
var saturday = GetSaturdayFunc();
//rest of the code
}
</code></pre>
<p>Although it's a bit more code now my class is not polluted with a lot of utility methods and it is more readable. </p>
<p>What do you think? Is this a good way, are there any better ways?</p>
<p><strong>EDIT</strong></p>
<p>I could also create an extension method which in this case would be appropriate, something like </p>
<pre><code>DateTime.Saturday()
</code></pre>
<p>but that's not what I am referring to in my question. I am asking if it is a good practice to wrap a portion of the code as a function inside that method (since that peace of the code will only be used inside that method and might not apply anywhere else), just for readability purposes.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T21:46:26.767",
"Id": "46293",
"Score": "0",
"body": "Why are the proposed solutions not acceptable? The best practice for this behavior is a utility function or an extension method and you seem to be excluding both of those from the pool of acceptable answers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T21:48:53.150",
"Id": "46294",
"Score": "0",
"body": "If anything, the anonymous method creates more confusion than your original implementation. Especially if you only use the function once."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T21:52:37.353",
"Id": "46296",
"Score": "0",
"body": "Exactly. Anonymous methods are great for things like auto-generated event handlers or LINQ expressions, but using them to hide behavior that you freely admit *shouldn't be part of the class that it's within* seems like an anti-pattern to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T21:55:08.143",
"Id": "46297",
"Score": "0",
"body": "I am not saying those are not acceptable, my question is usage of function instead of utility/helper/other methods in ways of organizing code. I just want to know what other think about it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T22:00:57.877",
"Id": "46298",
"Score": "0",
"body": "And I am not saying that the code does not belong to the class, I am saying that only a single method in that class will be using that code. Something like closures in javascript."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T22:01:27.900",
"Id": "46299",
"Score": "0",
"body": "@DZL: Well, think about it like this: if the code isn't a good fit for the class, and shouldn't be part of the class, why are you embedding it inside of a method of that class? That everyone here thinks extension/utility's the way to go should be pretty solid proof you don't want to use a dynamically generated method here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T22:18:59.843",
"Id": "46301",
"Score": "0",
"body": "Sorry guys, you just didn't give me a good answer to my question, you just said that you would rather use extension methods which is fine. I just want to hear why I shouldn't use func like I do. In javascript I use something like this all the time (closures), why not use it in c#?"
}
] |
[
{
"body": "<p>You could try create a utility function elsewhere in your solution ...</p>\n\n<pre><code>public static class DateUtils\n{\n public static DateTime MostRecent(DayOfWeek weekDay)\n {\n var date = DateTime.Today;\n while (date.DayOfWeek != weekDay)\n date = date.AddDays(-1);\n return date;\n }\n}\n</code></pre>\n\n<p>... and then use it later in your code ...</p>\n\n<pre><code>public void SomeMethod()\n{\n var saturday = DateUtils.MostRecent(DayOfWeek.Saturday);\n // rest of code\n}\n</code></pre>\n\n<p>... which has the benefits of being reusable and in an appropriate object structure.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T20:48:53.837",
"Id": "46285",
"Score": "0",
"body": "The better solution would be to create an extension method and call it like DateTime.Saturday()"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T21:50:25.283",
"Id": "46295",
"Score": "4",
"body": "@DZL: I don't think a `.Saturday()` extension method is a \"better solution\". Hard-coding in a date like that seems arbitrary, especially since it logically follows that you'd have to have `.Sunday()`, `.Monday()`, etc. next. Moreover, `.Saturday()` says nothing about how it's the most-recent Saturday, just that it's *a* Saturday."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T22:07:49.443",
"Id": "46300",
"Score": "0",
"body": "I agree, I was refering to that as a pseudo code, not the real implementation. I was just saying that the extension method for me is a better idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T21:49:45.190",
"Id": "46346",
"Score": "1",
"body": "Being reusable is not an advantage in the OP's case, as he does not intend to call this code from anywhere else."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T20:41:13.830",
"Id": "29320",
"ParentId": "29308",
"Score": "2"
}
},
{
"body": "<p>This is a perfect use case for an extension method. It gives maximum readability to your business code, and makes the method available on any DateTime object. </p>\n\n<pre><code>//Test\nclass Program\n{\n static void Main(string[] args)\n {\n Console.Write(DateTime.Today.MostRecent(DayOfWeek.Saturday));\n Console.Read();\n }\n}\n//Extensions\npublic static class DateTimeExtensions\n{\n public static DateTime MostRecent(this DateTime date, DayOfWeek dayOfWeek)\n {\n var day = date.Date;\n while (day.DayOfWeek != dayOfWeek)\n day = day.AddDays(-1);\n return day;\n\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T21:48:50.950",
"Id": "46345",
"Score": "1",
"body": "As the OP states that he \"won't be calling this method anywhere\", making it an extension method is overkill at best."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T20:46:48.120",
"Id": "29321",
"ParentId": "29308",
"Score": "5"
}
},
{
"body": "<p>I would use an extension method over an utility function.</p>\n\n<pre><code>namespace DateTime.Extensions\n{\n public static class DateTimeExtensions\n {\n public static DateTime Previous(this DateTime now, DayOfWeek day)\n {\n do {\n now = now.AddDays(-1);\n } while (now.DayOfWeek != day)\n\n return now;\n }\n }\n}\n</code></pre>\n\n<p>and its use:</p>\n\n<pre><code>public void SomeMethod()\n{\n var saturday = DateTime.Today.Previous(DayofWeek.Saturday);\n\n //rest of the code\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T20:49:02.613",
"Id": "29322",
"ParentId": "29308",
"Score": "2"
}
},
{
"body": "<p>I actually think I slightly disagree with the other answers in this situation. As you, others have mentioned I see three possible solutions (although there may be others)</p>\n\n<ol>\n<li>Create a local Func()</li>\n<li>Create a method on some sort of utilitly class or on a specific class for dealing with Date manipulation i.e Calendar</li>\n<li>Create a private method to the class (as it won't be used anywhere else anyway)</li>\n<li>Create an extension method</li>\n</ol>\n\n<p>Now from your question you state that you do not intend to use the method anywhere else. Your example tends one to think it would be beneficial in other situations as it is fairly generic. In that situation I would be leaning towards an extension method as others have pointed out.</p>\n\n<p>However I often find myself in the situation where a block of code will be repeated in a function and only the variables passed in will vary dependant on local switches etc In this situation I think it's perfectly reasonable to create a local delegate and use that in the function only.</p>\n\n<p>So, to summarize. <strong>Yes</strong> I think it's acceptable. In your example, probably not, but in situations where the block of code is local only to that method and you know that is the case, then yes. You can always refactor later!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T22:04:40.827",
"Id": "46347",
"Score": "0",
"body": "Yes, that was kind of what I wanted to hear :) I probably choose a bad chunk of code for an example, since it is fairly generic and extension method is a perfect candidate"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T02:18:37.550",
"Id": "46362",
"Score": "0",
"body": "@DZL I don't know if you had a real example but you may have had better feed back if you posted that instead? Otherwise I wonder if programmers might have been a better fit??? Not sure but glad to offer my opinion anyway :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T20:10:08.473",
"Id": "29347",
"ParentId": "29308",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29347",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T18:27:52.663",
"Id": "29308",
"Score": "1",
"Tags": [
"c#",
"functional-programming"
],
"Title": "Using Func<T> instead of helper methods in a class"
}
|
29308
|
<p>The script currently loops through an output line-by-line, picking out elements of interest and adds them to a hash data structure. If a key already exists (in this case the interface name), it appends data to it.</p>
<p>I can work with a data structure, but I am never happy with the approach I take of looping through the data line by line.</p>
<p>Is there a cleaner way of achieving this?</p>
<pre><code>#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
my $output = <<END;
1C:C1:DE:AC:15:C2 192.168.50.16 236263 dhcp-snooping 50 FastEthernet3/0/8
00:24:B5:F7:1A:E3 192.168.58.77 225905 dhcp-snooping 58 FastEthernet3/0/8
00:22:64:A6:E5:C6 192.168.50.61 139103 dhcp-snooping 50 FastEthernet3/0/38
00:1B:25:2E:91:2F 192.168.51.42 222285 dhcp-snooping 51 FastEthernet4/0/15
00:23:7D:4F:18:A5 192.168.51.36 382530 dhcp-snooping 51 FastEthernet4/0/21
C8:F4:06:E0:32:7C 192.168.57.47 258924 dhcp-snooping 57 FastEthernet4/0/21
18:A9:05:1E:5C:B3 192.168.49.21 256946 dhcp-snooping 49 FastEthernet2/0/34
00:22:64:1B:F7:8C 192.168.49.18 192605 dhcp-snooping 49 FastEthernet2/0/21
00:23:7D:50:68:A4 192.168.51.110 381036 dhcp-snooping 51 FastEthernet4/0/26
00:21:E1:FE:E0:94 192.168.57.87 177812 dhcp-snooping 57 FastEthernet2/0/6
00:23:7D:4E:BA:02 192.168.49.80 167839 dhcp-snooping 49 FastEthernet2/0/31
00:23:7D:4F:1A:23 192.168.51.95 293268 dhcp-snooping 51 FastEthernet2/0/36
5C:E2:86:F5:B3:04 192.168.57.48 177809 dhcp-snooping 57 FastEthernet2/0/31
END
my @data = split /\n/, $output;
use Data::Dumper;
my %data_str;
foreach my $line (@data) {
my @output_data = split /\s+/, $line;
# Interface already found, append IP and MAC
if ( exists $data_str{ $output_data[5] }
&& $data_str{ $output_data[5] } eq $data_str{ $output_data[5] } )
{
push $data_str{ $output_data[5] },
{ $output_data[1] => $output_data[0] };
}
# Add IP address and MAC address to hash
else {
$data_str{ $output_data[5] }
= [ { $output_data[1] => $output_data[0] } ];
}
}
say Dumper( \%data_str );
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T13:50:59.077",
"Id": "46273",
"Score": "1",
"body": "The data seems to be one record per line. So why are you unhappy \"looping through the data line by line\"? To put it another way, this seems tailor made for a line-by-line approach."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T13:56:39.970",
"Id": "46274",
"Score": "0",
"body": "Thanks, didn't realise I was actually asking for a review since I thought the code was just plain bad. Colleagues have commented that the code isn't scalable if the input list grows large. Will play around with it myself and checkin with codereview.stackexchange if need be."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T13:58:37.867",
"Id": "46275",
"Score": "3",
"body": "What do you mean by `$data_str{ $output_data[5] } eq $data_str{ $output_data[5] }`? It compares a value to itself, i.e. is always true. In Perl, use autovivification, do not check for existence."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T15:21:09.167",
"Id": "46276",
"Score": "0",
"body": "Your whole inside loop can be `my ($mac, $ip, $if) = (split /\\s+/, $line)[0,1,5]; push $data_str{$if}, {$ip => $mac};` But I don't understand why you not use hash of hashes so last statement will be `$data_str{$if}{$ip} = $mac;`"
}
] |
[
{
"body": "<p>You don't have to write code for testing of key existence because autovivification will do the work for you. So your cycle can be written as simple:</p>\n\n<pre><code>foreach my $line (@data) {\n my ($mac, $ip, $if) = (split /\\s+/, $line)[0,1,5];\n push @{$data_str{$if}}, {$ip => $mac};\n}\n</code></pre>\n\n<p>It is good practice to name your data instead of pollute indexes all over your code. It is much better if they are all in one place. Alternative way is:</p>\n\n<pre><code>my ($mac, $ip, undef, undef, undef, $if) = split /\\s+/, $line;\n</code></pre>\n\n<p>which shows line structure visually.</p>\n\n<p>Another thing is your data structure. Why it has hash value which is array of hashes with IP as one key and mac address. This structure is not good to work with. If I would have to find which MAC belong to given IP I would have to write something like</p>\n\n<pre><code>sub get_mac {\n my ($hash, $if, $ip) = @_;\n for my $x (@{$hash->{$if}}) {\n return $x->{$ip} if exists $x->{$ip};\n }\n return ();\n}\n</code></pre>\n\n<p>which is slow and tedious. Much better is construct two level hash:</p>\n\n<pre><code>foreach my $line (@data) {\n my ($mac, $ip, $if) = (split /\\s+/, $line)[0,1,5];\n $data_str{$if}{$ip} = $mac;\n}\n</code></pre>\n\n<p>Now if I would like to know MAC of given IP</p>\n\n<pre><code>my $mac = $data_str{$if}{$ip};\n</code></pre>\n\n<p>Easy and efficient. I still can get all IPs and MACs</p>\n\n<pre><code>my @ips = keys %{$data_str{$if}};\nmy @macs = values %{$data_str{$if}};\n</code></pre>\n\n<p>I can also make original pairs out of this structure</p>\n\n<pre><code>my @pairs = map {+{$_ => $data_str{$if}{$_}}} keys %{$data_str{$if}};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T23:13:45.773",
"Id": "29325",
"ParentId": "29310",
"Score": "2"
}
},
{
"body": "<p>Use autovivification,</p>\n\n<pre><code>my %data_str;\nforeach my $line (@data) {\n my @output_data = split /\\s+/, $line; \n\n push @{ $data_str{ $output_data[5] } }, {\n $output_data[1] => $output_data[0],\n };\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T15:22:01.740",
"Id": "29592",
"ParentId": "29310",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T13:46:35.467",
"Id": "29310",
"Score": "2",
"Tags": [
"perl"
],
"Title": "Adding elements to a hash from an output"
}
|
29310
|
<p>I've just written an implementation of Conway's Game of Life as an exercise and I'd love to get some feedback on how I can improve this program and hopefully my style in general.</p>
<p>I've tested the code in Python 2.7.3. It requires the <a href="https://github.com/drj11/pypng" rel="nofollow">PyPNG module</a> to render the state of the simulation.</p>
<pre><code>"""Simulate Conway's Game of Life.
The world is finite. Cells at its border always stay dead.
The frames of the simulation are saved as .png files.
"""
from numpy.random import random_integers
from png import from_array
DEAD = 1
ALIVE = 0
def saveAsImage(array, number):
"""Save the array to a .png file.
The files are saved as 1-bit greyscale (black/white).
"""
image = from_array(array, 'L', {'bitdepth': 1})
image.save('image%03i.png' % number)
def simulate(world, simulationLength):
"""Simulate a certain number from steps starting from a given state.
The frames are saved as .png images in the current working directory.
Parameters:
world: The initial state of the world as a two-dimensional numpy
array in which world[y][x] describes the state of the
cell at position x, y
simulationLength: The number of simulated steps,
simulationLength + 1 images are created.
"""
# Retrieve the dimensions of the world
worldHeight = len(world)
worldWidth = len(world[0])
# Make sure there are no living cells on the border.
world[0] = DEAD # top
world[worldHeight - 1] = DEAD # bottom
for y in xrange(1, worldHeight - 2):
world[y][0] = DEAD # left
world[y][worldWidth - 1] = DEAD # right
saveAsImage(world, 0)
for frame in xrange(1, simulationLength + 1):
# Simulate simulationLength frames
nextWorld = world.copy()
for y in xrange(1, worldHeight - 1):
for x in xrange(1, worldWidth - 1):
# Iterate over all cells within the border
neighbors = [world[y - 1][x - 1],
world[y - 1][x],
world[y - 1][x + 1],
world[y][x - 1],
world[y][x + 1],
world[y + 1][x - 1],
world[y + 1][x],
world[y + 1][x + 1]]
livingNeighbors = sum(neighbor == ALIVE
for neighbor in neighbors)
if world[y][x] == ALIVE:
# Living cells with less than 2 or more than three
# living neighbors die
if livingNeighbors not in (2, 3):
nextWorld[y][x] = DEAD
else:
# Dead cells with three living neighbors are reborn
if livingNeighbors == 3:
nextWorld[y][x] = ALIVE
world = nextWorld
saveAsImage(world, frame)
if __name__ == '__main__':
worldWidth = 100
worldHeight = 100
# Populate the world with random living/dead (50% each) cells
world = random_integers(0, 1, (worldHeight, worldWidth))
simulate(world, 50)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T20:37:01.967",
"Id": "46282",
"Score": "0",
"body": "From a quick look, I'd say avoid placing code in the global namespace... place stuff in `main()` function, and use the `__name__ == '__main__'` thing. See http://meta.codereview.stackexchange.com/a/493."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T21:32:02.457",
"Id": "46286",
"Score": "0",
"body": "Thanks, you're right. My line of reasoning was that I didn't intend this snippet to be imported by another module, but of course it's better to put the simulation into a function instead of hard-coding the parameters like I did."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T22:28:25.413",
"Id": "46302",
"Score": "0",
"body": "I've updated my code to reflect your suggestions and already found an error previously covered by namespace ambiguity."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T22:30:47.540",
"Id": "46304",
"Score": "0",
"body": "good to know you fixed something as a result of my excellence :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T11:19:36.400",
"Id": "46322",
"Score": "1",
"body": "Instead of `world[0] = DEAD` don't you need `world[0] = [DEAD] * worldWidth` ? I don't understand how this can work as it stands."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T21:35:08.210",
"Id": "46412",
"Score": "0",
"body": "While this shortcut works just fine, I don't know about the specifics of why this works either, but ndarrays are unknown territory for me. Initializing with either an integer or a list needs further computation, but I don't know which magic method could be responsible."
}
] |
[
{
"body": "<p>The main thing I want to point is that your algorithm is too simple since it uses matrix (list of lists) as a playing field. If it will be 1000*1000 you will process the field in about a second. And it is already slow. But if 10000*10000? 100 seconds per move (100 millions mostly empty cells to process?)</p>\n\n<p>And these nasty borders? They will spoil many game-related problems.</p>\n\n<p>If you are eager to really improve your game (and perhaps your skills), you can try another implementation.</p>\n\n<p>Store only live cells - a set/list/dict of tuples in form (x, y). There would be interesting little task about searching for neighbor cells - you can find several solutions to do it fast (feel free to write if you want a hint).</p>\n\n<p>Then you will have the game on an <strong>endless</strong> field and you will like its speed (and you will be proud for your work, I dare to suppose).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T21:36:24.950",
"Id": "46413",
"Score": "0",
"body": "Thank you for this valuable suggestion! I'll try to tackle this challenge soon!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T17:15:24.467",
"Id": "29346",
"ParentId": "29314",
"Score": "1"
}
},
{
"body": "<p><a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow\">Separate different concerns</a> in your code. The function <code>simulate</code> does two things that should be separated, namely changing the state of the world and calling the function that saves it as an image. As it is, it's impossible to re-use only the state-changing logic. Instead, move the game logic to a function <code>simulate_step</code> (or whatever you want to call it).</p>\n\n<p>Stick to the <a href=\"http://www.python.org/dev/peps/pep-0008/#naming-conventions\" rel=\"nofollow\">PEP8 naming conventions</a>: functions and variables should be written <code>lowercase_with_underscores</code>. Otherwise, you follow the guide very nicely.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T20:09:09.373",
"Id": "29468",
"ParentId": "29314",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29346",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T20:11:13.077",
"Id": "29314",
"Score": "4",
"Tags": [
"python",
"game-of-life"
],
"Title": "General feedback on Conway's Game of Life implementation"
}
|
29314
|
<p>Ok, this might be a very stupid question/idea (I'm still a beginner). Lets say I have a construct like this:</p>
<pre><code>g.setColor(new Color(random.nextInt(5) * speed, 255, speed * 3));
</code></pre>
<p>Now it is very likely that the passed arguments will in some cases be out of the expected range, so the code will throw an exception. To circumvent this case I wrote the following helper class:</p>
<pre><code>public class SafeColor {
static final int INT_MIN = 0;
static final int INT_MAX = 255;
static final float FLOAT_MIN = 0;
static final float FLOAT_MAX = 1;
public static Color safeIntColor(int r, int g, int b) {
if (r < INT_MIN) r = INT_MIN;
if (g < INT_MIN) g = INT_MIN;
if (b < INT_MIN) b = INT_MIN;
if (r > INT_MAX) r = INT_MAX;
if (g > INT_MAX) g = INT_MAX;
if (b > INT_MAX) b = INT_MAX;
return new Color(r, g, b);
}
public static Color safeIntAlphaColor(int r, int g, int b, int a) {
if (r < INT_MIN) r = INT_MIN;
if (g < INT_MIN) g = INT_MIN;
if (b < INT_MIN) b = INT_MIN;
if (a < INT_MIN) a = INT_MIN;
if (r > INT_MAX) r = INT_MAX;
if (g > INT_MAX) g = INT_MAX;
// ... and so on ...
</code></pre>
<p>Now I can do this:</p>
<pre><code>g.setColor(SafeColor.safeIntColor(random.nextInt(5) * speed, 255, speed * 3));
</code></pre>
<p>I guess the question is, does that make any sense? The whole thing looks a bit overdone to me. Is there a better/easier way to accomplish the same thing?</p>
<hr>
<p><strong>Edit:</strong> For anyone interested. I boiled it down to this:</p>
<pre><code>public class SafeColor {
private static final float FLOAT_MAX = 1;
private static final float FLOAT_MIN = 0;
private static final int INT_MAX = 255;
private static final int INT_MIN = 0;
private static float safeFloat(float f) {
return Math.max(Math.min(f, FLOAT_MAX), FLOAT_MIN);
}
private static int safeInt(int i) {
return Math.max(Math.min(i, INT_MAX), INT_MIN);
}
public static Color safeColor(float r, float g, float b, float a) {
return new Color(safeFloat(r), safeFloat(g), safeFloat(b), safeFloat(a));
}
public static Color safeColor(float r, float g, float b) {
return new Color(safeFloat(r), safeFloat(g), safeFloat(b));
}
public static Color safeColor(int r, int g, int b, int a) {
return new Color(safeInt(r), safeInt(g), safeInt(b), safeInt(a));
}
public static Color safeColor(int r, int g, int b) {
return new Color(safeInt(r), safeInt(g), safeInt(b));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T19:36:51.843",
"Id": "46279",
"Score": "1",
"body": "It is a fine thing to do; nice job, in fact! I would not change a thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T19:39:15.117",
"Id": "46280",
"Score": "1",
"body": "Nothing wrong about validation. I'd just use `Math.max()` and `Math.min()` to make the intent more clear."
}
] |
[
{
"body": "<p>There is nothing too bad about this, and it is an acceptable pattern to get rid of extra/boilerplate code (for example <code>IOUtils</code> from Apache Commons has a <code>closeQuietly</code> for streams that takes a way a lot of the nested <code>try-catch-finally</code> madness for closing streams).</p>\n\n<p>However, I would argue that it is better to validate your inputs to make sure that they don't exceed the ranges, or at least change the code that generates your values to ensure that they do not generate invalid values.</p>\n\n<p>For example, you could have a method called <code>generateColor(speed)</code> that returns a sane <code>Color</code> instance.</p>\n\n<p>I would also suggest using <code>Math.max</code> and <code>Math.min</code> in this method instead of using a bunch of <code>if</code>s.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T19:36:51.233",
"Id": "29317",
"ParentId": "29316",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "29317",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T19:33:44.450",
"Id": "29316",
"Score": "3",
"Tags": [
"java"
],
"Title": "Make the awt.Color class constructors except out of range arguments"
}
|
29316
|
<p>I have a script I use to prune packages that have gone stale from my custom Debian repository (i.e. they no longer exists on any of the official repositories):</p>
<pre><code>import apt_pkg
import gzip
import subprocess
CUSTOM_REPO = ("/home/tshepang/.custom_repo/dists/tshepang/main/"
"binary-amd64/Packages.gz")
TEMPLATE = ("/var/lib/apt/lists/http.debian.net_debian_dists_{}_{}_"
"binary-amd64_Packages")
CODENAMES = 'jessie sid experimental'.split()
ARCHIVE_AREAS = "main contrib non-free".split()
def main():
custom_repo = apt_pkg.TagFile(gzip.open(CUSTOM_REPO))
wheezy_packages = list()
for codename in CODENAMES:
for archive_area in ARCHIVE_AREAS:
repo = TEMPLATE.format(codename, archive_area)
repo = apt_pkg.TagFile(gzip.open(repo, "rb"))
wheezy_packages.extend([pkg["Package"] for pkg in repo])
for package in custom_repo:
package_name = package["Package"]
if package_name not in wheezy_packages:
cmd = "apt-cache policy " + package_name
subprocess.call(cmd.split())
choice = raw_input("remove from cache [Y/n]? ")
if not choice or choice.lower().startswith("y"):
cmd = ("reprepro -vv --basedir /home/tshepang/.custom_repo/ "
"remove tshepang " + package_name)
subprocess.call(cmd.split())
if __name__ == "__main__":
main()
</code></pre>
<p>I strongly suspect the code can be better.</p>
<p>As a sidenote, here is sample UI:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>apache2.2-common:
Installed: (none)
Candidate: 2.2.22-13
Version table:
2.2.22-13 0
500 file:/home/tshepang/.custom_repo/ tshepang/main amd64 Packages
remove from cache [Y/n]?
removing 'apache2.2-common' from 'tshepang|main|amd64'...
Exporting indices...
Deleting files no longer referenced...
deleting and forgetting pool/main/a/apache2/apache2.2-common_2.2.22-13_amd64.deb
</code></pre>
</blockquote>
|
[] |
[
{
"body": "<p>Your code looks very good, so I'll just propose some minor (and subjective) improvements:</p>\n\n<ul>\n<li><p>Imports: <a href=\"http://www.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow\">PEP8</a> has some recommendations about grouping imports that sound pretty reasonable.</p></li>\n<li><p><code>(\"s1\" \"s2\")</code>: I don't know what the orthodoxy says, but I prefer an explicit <code>+</code> in between.</p></li>\n<li><p><code>list()</code>: Why not <code>[]</code>?</p></li>\n<li><p><code>wheezy_packages.extend([pkg[\"Package\"] for pkg in repo])</code> -> <code>wheezy_packages.extend(pkg[\"Package\"] for pkg in repo)</code>.</p></li>\n<li><p><code>repo = a</code>, then <code>repo = f(repo)</code>. IMHO this is as common a pattern as is undesirable. Different values <em>deserve</em> different variable names (key point of functional programming).</p></li>\n<li><p>Function too long: I'd split the code in at least two auxiliary functions, one to get <code>wheezy_packages</code> and another to run the commands.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T12:21:38.637",
"Id": "46325",
"Score": "0",
"body": "`list()` was inspired by http://stackoverflow.com/a/2745292"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T12:22:45.080",
"Id": "46326",
"Score": "0",
"body": "Is the explicit `+` in this case common practice?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T12:33:17.917",
"Id": "46327",
"Score": "0",
"body": "Regarding the different values comment, see http://codereview.stackexchange.com/a/1719."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T12:37:48.523",
"Id": "46328",
"Score": "1",
"body": "1) `list()` A.M. is certainly a reference to follow. 2) `+` I prefer to write it, but not really sure what's better/more idiomatic. 3) I strongly disagree with that answer. In that example I'd use `message_pattern` and `pattern`, as I said in the answer, different values, different names. Do you know some Ruby. Those are my ideas about FP (99% can be applied to Python): http://www.slideshare.net/tokland/functional-programming-with-ruby-9975242"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T13:08:35.817",
"Id": "46331",
"Score": "0",
"body": "Am not really familiar with Ruby."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T12:03:11.677",
"Id": "29337",
"ParentId": "29318",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29337",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T20:23:51.600",
"Id": "29318",
"Score": "5",
"Tags": [
"python",
"linux"
],
"Title": "Finding unique/obsolete binary Debian packages"
}
|
29318
|
<p>I have come up with an idea for adding privacy support in JavaScript. I haven't found something similar in the net, so I'm thinking it's probably because the idea is bad, but yet, I want to see some response, just to be sure.</p>
<pre><code>var util = {
s4: function() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
},
guid: function() {
return util.s4() + util.s4() + '-' + util.s4() + '-' + util.s4() + '-' +
util.s4() + '-' + util.s4() + util.s4() + util.s4();
}
};
// template
var Class = (function() {
var privates = {};
var getPrivates = function(obj) {
return privates[ obj.getGUID() ];
};
function Class() {
var guid = util.guid();
privates[guid] = {};
this.getGUID = function() {
return guid;
};
};
return Class;
})();
var MyClass = (function() {
var privates = {};
var getPrivates = function(obj) {
return privates[ obj.getGUID() ];
};
function MyClass(a, b) {
var guid = util.guid();
privates[guid] = {};
this.getGUID = function() {
return guid;
};
var private = getPrivates(this);
private.a = a;
this.b = b;
};
return MyClass;
})();
var obj = new MyClass("private", "public");
console.log(obj.a, obj.b);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T18:16:56.217",
"Id": "46287",
"Score": "0",
"body": "It's a silly example. A class with 2 construct parameters - a and b. a is private, b is public. The last line console.log(obj.a, obj.b); outputs \"undefined\", \"public\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T18:17:30.287",
"Id": "46288",
"Score": "4",
"body": "Interesting idea, but public / private support is generally solved using the [module pattern](http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript). Does your approach offer a significant benefit to that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T18:20:45.397",
"Id": "46289",
"Score": "0",
"body": "This has been done and redone many times, see http://blog.niftysnippets.org/2013/05/private-properties-in-es6-and-es3-and.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T18:21:33.940",
"Id": "46290",
"Score": "0",
"body": "Chris, maybe I'm wrong, but the module pattern doesn't return a constructor, but an object literal?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T18:26:45.293",
"Id": "46291",
"Score": "1",
"body": "The module pattern is the practice of returning functions (generally members of *something*, the titular \"module\") that have scope-access to some variables that are inaccessible to the rest of the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T18:27:02.210",
"Id": "46292",
"Score": "0",
"body": "It is very similar to the Java Script [Module Design Pattern](http://addyosmani.com/resources/essentialjsdesignpatterns/book/). You can read about it here and other similar Design Patterns and variations. As people have pointed out. Hmmm some one even posted the same link lol. I should probably just delete the comment and say ditto."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-06T16:33:05.377",
"Id": "106735",
"Score": "0",
"body": "you shoul look into MooTools class"
}
] |
[
{
"body": "<p>Interesting question,</p>\n\n<p>as mentioned in the comments, privacy support can be (better) achieved with modules, or with IFFE's.</p>\n\n<p>On the whole your design is not sound, <a href=\"http://en.wikipedia.org/wiki/Globally_unique_identifier#Algorithm\" rel=\"nofollow\">your GUID creation code is so weak in generating unique id's</a> that you will have overlapping GUID's and (hard to reproduce) bugs.</p>\n\n<p>Furthermore, the variables are not exactly private if you can iterate over <code>privates</code> and see all the values stored in there..</p>\n\n<p>Finally, I think you might have a pretty good case for a double assignment here, this </p>\n\n<pre><code>var MyClass = (function() {\n var privates = {};\n var getPrivates = function(obj) {\n return privates[ obj.getGUID() ];\n };\n\n function MyClass(a, b) {\n var guid = util.guid();\n privates[guid] = {};\n this.getGUID = function() {\n return guid;\n };\n\n var private = getPrivates(this);\n private.a = a;\n this.b = b;\n };\n\n return MyClass;\n})();\n</code></pre>\n\n<p>could be</p>\n\n<pre><code>var MyClass = (function() {\n var privates = {};\n\n function MyClass(a, b) {\n var private = privates[util.guid()] = {};\n private.a = a;\n this.b = b;\n };\n\n return MyClass;\n})();\n</code></pre>\n\n<p>From a lint/hint perspective you have some semicolon trouble, but nothing too bad.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-06T13:10:23.423",
"Id": "59245",
"ParentId": "29323",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T18:12:34.937",
"Id": "29323",
"Score": "1",
"Tags": [
"javascript",
"object-oriented"
],
"Title": "Privacy approach in JavaScript"
}
|
29323
|
<p>I've followed <a href="http://www.curious-creature.org/2012/12/11/android-recipe-1-image-with-rounded-corners" rel="nofollow">this blog</a> to get images with nice pretty rounded corners in Android.</p>
<p>I've managed to strip out a lot of the superfluous <code>arrayAdapter</code> stuff and make it much more simple.</p>
<p>I've largely tweaked this just until I made it work. Does anyone have any feedback?</p>
<pre><code>class StreamDrawable extends Drawable {
private final float mCornerRadius;
private final RectF mRect = new RectF();
private final BitmapShader mBitmapShader;
private final Paint mPaint;
private final int mMargin;
StreamDrawable(Bitmap bitmap, float cornerRadius, int margin) {
mCornerRadius = cornerRadius;
mBitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setShader(mBitmapShader);
mMargin = margin;
}
@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mRect.set(mMargin, mMargin, bounds.width() - mMargin, bounds.height() - mMargin);
}
@Override
public void draw(Canvas canvas) {
canvas.drawRoundRect(mRect, mCornerRadius, mCornerRadius, mPaint);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
public void setAlpha(int alpha) {
mPaint.setAlpha(alpha);
}
@Override
public void setColorFilter(ColorFilter cf) {
mPaint.setColorFilter(cf);
}
}
public void drawit(){
final int CORNER_RADIUS = 24; // dips
final int MARGIN = 12; // dips
final int mCornerRadius;
final int mMargin;
final float density = this.getResources().getDisplayMetrics().density;
mCornerRadius = (int) (CORNER_RADIUS * density + 0.5f);
mMargin = (int) (MARGIN * density + 0.5f);
ImageView imgvw = (ImageView) findViewById(R.id.imageView2);
Bitmap myBitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.london);
Bitmap resizedBitmap = Bitmap.createScaledBitmap(myBitmap, imgvw.getWidth(), imgvw.getHeight(), false);
StreamDrawable d = new StreamDrawable(resizedBitmap, mCornerRadius, mMargin);
imgvw.setBackground(d);
}
</code></pre>
|
[] |
[
{
"body": "<p>This looks very clean to me. Except perhaps:</p>\n\n<ul>\n<li><code>imgvw</code> - that's <strong>disemvoweling</strong>. nd t's bd. Not to mention it's breaking your <em>camelCasing</em> convention for locals.</li>\n<li><code>drawit</code> - while the name says what the function does, I would avoid <em>DoThatThing</em> names and perhaps go for a more sober <code>render</code> method name, if not just <code>draw</code>.</li>\n</ul>\n\n<p>Lastly, I don't know Java well enough to know if it's convention, but I wouldn't use that <code>m</code> prefix.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T14:20:08.613",
"Id": "58127",
"Score": "0",
"body": "The `m` prefix **is** a convention in Java :) (sometimes used, sometimes not. But there's nothing wrong with using it)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T02:27:30.003",
"Id": "35739",
"ParentId": "29324",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "35739",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T21:40:11.723",
"Id": "29324",
"Score": "2",
"Tags": [
"java",
"optimization",
"android"
],
"Title": "Android image with rounded corners"
}
|
29324
|
<pre><code>require([
'jquery',
'underscore',
'backbone'
], function ($, _, Backbone) {
'use strict';
// TODO: Would like to access through define module, but not sure how..
var player = chrome.extension.getBackgroundPage().YouTubePlayer;
var user = chrome.extension.getBackgroundPage().User;
// If the foreground is opened before the background has had a chance to load, wait for the background.
// This is easier than having every control on the foreground guard against the background not existing.
if (user.get('loaded')) {
loadForeground();
} else {
user.on('change:loaded', function (model, loaded) {
if (loaded) {
loadForeground();
} else {
// Show refreshing message?
}
});
}
function loadForeground() {
if (player.get('ready')) {
// Load foreground when the background indicates it has loaded.
require(['foreground']);
} else {
player.once('change:ready', function () {
// Load foreground when the background indicates it has loaded.
require(['foreground']);
});
}
}
});
</code></pre>
<p>My goal is to call <code>require(['foreground'])</code> once the user object is loaded and the player is ready. This code works fine, but seems really unclear / overly verbose.</p>
<p>Am I missing an easy simplification in trying to express this need?</p>
|
[] |
[
{
"body": "<p><a href=\"http://api.jquery.com/jQuery.Deferred/\" rel=\"nofollow\"><code>jQuery.Deferred</code></a>, or even just <a href=\"http://wiki.commonjs.org/wiki/Promises/A\" rel=\"nofollow\">promises in general</a>, would make your code simpler. In short, a promise can be unfulfilled, fulfilled, or failed. <a href=\"http://api.jquery.com/jQuery.when/\" rel=\"nofollow\"><code>jQuery.when</code></a> lets you compose multiple promises into one promise that's fulfilled when they're all fulfilled or failed as soon as one fails. This means that you can</p>\n\n<ol>\n<li><p>create <code>Deferred</code>s for each event you want to monitor:</p>\n\n<pre><code>var userLoaded = new $.Deferred();\nvar playerReady = new $.Deferred();\n</code></pre></li>\n<li><p>Resolve the promises when whatever event they represent has completed, e.g.:</p>\n\n<pre><code>userLoaded.resolve();\n</code></pre>\n\n<p>If there's an error, you can signal that if you want as well:</p>\n\n<pre><code>userLoaded.reject();\n</code></pre></li>\n<li><p>Compose them together:</p>\n\n<pre><code>$.when(userLoaded, playerReady).then(function() {\n require(['foreground']);\n});\n</code></pre>\n\n<p>If you pass a second argument to <code>then</code>, it will be called if either of the promises are rejected, simplifying error-handling, should you wish to do that.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T05:57:30.397",
"Id": "29330",
"ParentId": "29326",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-02T23:40:56.357",
"Id": "29326",
"Score": "0",
"Tags": [
"javascript",
"backbone.js"
],
"Title": "How to simply express a desire to run a function when two properties are true?"
}
|
29326
|
<p>I've never used a framework before, so I wanted to see if this fairly simple scenario was done correctly or could be improved:</p>
<pre><code>public function actionCreate($id) {
// Is request Ajax
if(Yii::app()->request->getIsAjaxRequest()) {
$userID = Yii::app()->user->id;
try {
$cmd = Yii::app()->db->createCommand();
$cmd->insert('potential_item',array(
'item_id'=> (int) $id,
'user_id' => (int) $userID,
),'id=:id', array(':id'=>$id));
echo 'Item Added';
} catch(CDbException $e){
echo '<strong>Error!</strong> ' . $e->getCode() . '</div>';
}
}
}
</code></pre>
<p>Here's what I wanted to achieve with the code. It's basically just a wish list. It's a pretty basic SQL builder statement that I think is secure.</p>
<p>I have a constraint on the DB so that a user and item ID have to be unique. That's why I used the <code>try catch</code> block, and it's really the only DB issue I see occurring. Would the scenario I have used work okay, or am I missing other exceptions?</p>
<p>I also decided to echo the error code. Would you recommend that I just leave a generic message for the end user?</p>
<p>As I really only expect a constraint error, should I check the error code with an if-statement?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T02:36:52.300",
"Id": "46307",
"Score": "0",
"body": "What language is this? Be sure to add its tag to this post."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T02:38:39.057",
"Id": "46308",
"Score": "0",
"body": "@jamal added to tags"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T12:49:30.043",
"Id": "46884",
"Score": "0",
"body": "Why to you echo your results of the actions? I'm not familiar with your framework, but I guess there is some kind of `views` where you can assign the success state or error messages and all the layout is handled in a template?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T18:56:28.197",
"Id": "47100",
"Score": "0",
"body": "Are you working with db commands in the controller ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T19:21:21.300",
"Id": "47103",
"Score": "0",
"body": "The commands are as noted in the controller yes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T07:39:33.730",
"Id": "62826",
"Score": "1",
"body": "You can use active record (instead of using DAO like you did), then you can setup validation rules along with the message in the model."
}
] |
[
{
"body": "<ol>\n<li><p>The code closes a <code>div</code> tag here:</p>\n\n<blockquote>\n<pre><code>echo '<strong>Error!</strong> ' . $e->getCode() . '</div>'; \n</code></pre>\n</blockquote>\n\n<p>But there isn't any opening <code>div</code> tag inside the function. I guess it's a bug.</p></li>\n<li><p>The name of the function (<code>actionCreate</code>) suggests that it creates an action but it also prints to the output. It's misleading. See also: <a href=\"https://softwareengineering.stackexchange.com/a/164729/36726\">Is it bad practice to output from within a function?</a></p></li>\n<li><blockquote>\n <p>I also decided to echo the error code. Would you recommend that I just leave a generic message for the end user?</p>\n</blockquote>\n\n<p>I don't think that any of your users will be happy when they see that error code. It's probably not useful for them (except they also develop the application). Error messages should give a suggestion about what the user should do. (See: <a href=\"https://ux.stackexchange.com/q/48256/14623\">Should we avoid negative words when writing error messages?</a>, <a href=\"https://ux.stackexchange.com/q/8112/14623\">What will be the Best notifications and error messages?</a>)</p>\n\n<p>If it's not their fault say that. I like <a href=\"https://codereview.stackexchange.com/error\">the way that Stack Overflow handles these errors</a>:</p>\n\n<blockquote>\n <p><strong>Oops! Something Bad Happened!</strong></p>\n \n <p>We apologize for any inconvenience, but an unexpected error occurred while you were browsing our site.</p>\n \n <p>It’s not you, it’s us. This is our fault.</p>\n \n <p>[...]</p>\n</blockquote>\n\n<p>You should also log the errors to a log file. Otherwise you will never know that your users has problems.</p></li>\n<li><blockquote>\n <p>As I really only expect a constraint error, should I check the error code with an if-statement?</p>\n</blockquote>\n\n<p>If that's a normal usage (and not a programming mistake) that you have these errors and your database don't check it I'd check it. Otherwise I wouldn't do that.</p></li>\n<li><blockquote>\n<pre><code>public function actionCreate($id) {\n\n // Is request Ajax\n if(Yii::app()->request->getIsAjaxRequest()) {\n\n $userID = Yii::app()->user->id;\n\n try {\n\n $cmd = Yii::app()->db->createCommand();\n $cmd->insert('potential_item',array(\n $cmd = Yii::app()->db->createCommand();\n $cmd->insert('potential_item',array(\n 'item_id'=> (int) $id,\n 'user_id' => (int) $userID,\n ),'id=:id', array(':id'=>$id));\n...\n</code></pre>\n</blockquote>\n\n<p>Indentation could be better. Currently it doesn't look like that the <code>$userID = Yii::app()->user->id;</code> is inside the <code>if</code> and <code>$cmd = Yii::app()->db->createCommand();</code> (and other statements below that) is inside the <code>try</code> block. Consider this:</p>\n\n<pre><code>public function actionCreate($id) {\n\n // Is request Ajax\n if(Yii::app()->request->getIsAjaxRequest()) {\n $userID = Yii::app()->user->id;\n\n try {\n $cmd = Yii::app()->db->createCommand();\n $cmd->insert('potential_item',array(\n 'item_id'=> (int) $id,\n 'user_id' => (int) $userID,\n ),'id=:id', array(':id'=>$id));\n...\n</code></pre></li>\n<li><p>I'd rename <code>$id</code> to <code>itemId</code> to reflects its purpose.</p></li>\n<li><p>You could create a local variable for <code>Yii::app()</code>.</p></li>\n<li><blockquote>\n<pre><code>// Is request Ajax\nif(Yii::app()->request->getIsAjaxRequest()) {\n</code></pre>\n</blockquote>\n\n<p>The code describes the same, the comment looks redundant for me. (<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p></li>\n<li><p>It's hard to figure out the parameters here:</p>\n\n<blockquote>\n<pre><code>$cmd->insert('potential_item',array(\n'item_id'=> (int) $id,\n'user_id' => (int) $userID,\n),'id=:id', array(':id'=>$id));\n</code></pre>\n</blockquote>\n\n<p>What is the first, what's the second? Where does the second parameter start? What's its purpose? A few explanatory variable would make it readable:</p>\n\n<pre><code>$table = 'potential_item';\n$columns = array(\n 'item_id' => (int) $id,\n 'user_id' => (int) $userID, \n)\n$cmd->insert($table,$columns, 'id=:id', array(':id'=>$id));\n</code></pre>\n\n<p>I would have created such variable for the last two parameters two but I've not found any clue about that in the <a href=\"http://www.yiiframework.com/doc/api/1.1/CDbCommand#insert-detail\" rel=\"nofollow noreferrer\">API documentation</a>.</p>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G19: Use Explanatory Variables</em>; <em>Refactoring: Improving the Design of Existing Code by Martin Fowler</em>, <em>Introduce Explaining Variable</em>)</p></li>\n<li><p>A <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow noreferrer\">guard clause could make the code flatten</a>:</p>\n\n<pre><code>public function actionCreate($id) {\n if(!Yii::app()->request->getIsAjaxRequest()) {\n return;\n }\n $userID = Yii::app()->user->id;\n ...\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-22T10:16:50.747",
"Id": "45075",
"ParentId": "29327",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "45075",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T02:21:21.537",
"Id": "29327",
"Score": "8",
"Tags": [
"php",
"exception-handling"
],
"Title": "Yii exception usage"
}
|
29327
|
<p>I'm writing a function called unzip that turns:</p>
<pre><code>[(1,2);(3,4);(5,6)]
</code></pre>
<p>to</p>
<pre><code>([1;3;5],[2;4;6])
</code></pre>
<p>I've got a working implementation right here:</p>
<pre><code>let unzip (data:(int*int) list) : int list * int list =
match data with
|(x,y)::tl->(x::traverse (tl,true),y::traverse (tl,false))
|[]->([],[])
let rec traverse tree =
match tree with
|((x,y)::tl,dir) -> if dir then x::traverse (tl, dir) else y::traverse (tl,dir)
|([],_) -> [];;
</code></pre>
<p>However I'm not sure if this is the cleanest way to do this. As you can see, my traverse function accepts a boolean to know whether or not to go right or left, specifically because of:</p>
<pre><code>(x::traverse (tl,true),y::traverse (tl,false))
</code></pre>
<p>Now is there even a way to do this so I only have to call one function, AND it knows where to put the data? or is this an alright way of doing it?</p>
<p>PS: I can't use non-core functions. (Modules, etc.)</p>
|
[] |
[
{
"body": "<p>You have the right idea, but you didn't quite know how to get there. You don't need that <code>traverse</code> function to operate on the left or right lists. Just bind them to separate variables through a simple <code>let in</code> expression and you can add the items to each of the lists.</p>\n\n<pre><code>let rec unzip = function\n | (x, y)::t -> let l, r = unzip t in (x::l, y::r)\n | [] -> ([], [])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T07:54:18.707",
"Id": "46315",
"Score": "0",
"body": "Why is its syntax so weird lol. Anyway, thank you very much!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T07:26:55.770",
"Id": "29333",
"ParentId": "29329",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "29333",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T04:45:15.400",
"Id": "29329",
"Score": "2",
"Tags": [
"ocaml"
],
"Title": "Ocaml Functional Programming Tree"
}
|
29329
|
<p>I am trying to implement a vector-like container of my own (just to gain a better understanding of how <code>std::vector</code> works under the hood). I've been using <a href="http://www.cplusplus.com/reference/vector/vector/" rel="nofollow">this</a> as a reference. </p>
<p>Although I've succeeded in implementing most of the interface (only the parts I use the most), I'm still uncertain whether: </p>
<ol>
<li>There are no memory leaks. </li>
<li>All the routines associate with <code>std::vector</code> with respect to performance and space-usage. </li>
</ol>
<p>Please review it to see if it can be improved. Any suggestions related to my commenting style are also welcome!</p>
<pre><code>size_t nearest_power_of_2(size_t n) // Return the nearest( and strictly greater than ) number to "n" which is a power of 2..
{
int count=0;
while(n)
{
n>>=1;
count++;
}
return 1ULL<<count;
}
template<typename T>
class myvector
{
T* vector_pointer; // A pointer pointing to the start of the dynamic array...
size_t vector_size,vector_capacity;
public:
myvector():vector_pointer(NULL),vector_size(0),vector_capacity(0) {} // Default Constructor
myvector(const myvector& other):vector_pointer(NULL),vector_size(0),vector_capacity(0) // Copy Constructor
{
vector_pointer=new T[other.capacity()];
memcpy(vector_pointer,&other[0],sizeof(T)*other.size());
vector_size=other.vector_size;
vector_capacity=other.vector_capacity;
}
~myvector() // Destructor
{
delete[] vector_pointer;
}
myvector& operator =(myvector other) // Assignment operator
{
swap(*this,other);
return *this;
}
void resize(const size_t &newsize) // Change the size of the vector exactly to "newsize"..
{
if(newsize<vector_size)
{
T* temp=new T[newsize];
memcpy(temp,vector_pointer,sizeof(T)*newsize);
delete[] vector_pointer;
vector_pointer=temp;
}
else if(newsize>vector_capacity)
{
reserve(newsize);
}
vector_size=newsize;
}
void reserve(size_t newcapacity) // Change the capacity of the vector to be at least equal to "newcapacity"
{
newcapacity=nearest_power_of_2(newcapacity); // Keep the capacity of the vector as a power of 2 to avoid space wastage..
if(newcapacity>vector_capacity)
{
T* temp=new T[newcapacity];
memcpy(temp,vector_pointer,sizeof(T)*vector_capacity);
delete[] vector_pointer;
vector_pointer=temp;
vector_capacity=newcapacity;
}
}
void push_back(const T &val) // Add a new element of value "val" at the end of the vector..
{
if(vector_capacity<=vector_size)
reserve(vector_capacity);
vector_pointer[vector_size++]=val;
}
void pop_back() // Remove the last element of the vector..
{
if(vector_size)
--vector_size;
} // Doesn't actually deallocate the element block (for performance)..
size_t size() const
{
return vector_size;
}
size_t capacity() const
{
return vector_capacity;
}
T& operator [](const size_t &pos)
{
return vector_pointer[pos];
}
const T& operator [](const size_t &pos) const
{
return vector_pointer[pos];
}
bool empty() const
{
return vector_size==0;
}
T& at(const size_t& pos) // Same as the "[]" operator, but this one checks for out-of-bound exceptions..
{
if(pos>=vector_size)
throw std::out_of_range("");
else
return vector_pointer[pos];
}
const T& at(const size_t& pos) const
{
if(pos>=vector_size)
throw std::out_of_range("");
else
return vector_pointer[pos];
}
void erase(const size_t& pos) // Erase the element at "pos"..
{
for(size_t i=pos; i<vector_size-1; i++)
{
vector_pointer[i]=vector_pointer[i+1]; // Shift all the elements one step left, beginning from "pos+1"
}
--vector_size;
}
void erase(const size_t& pos1,const size_t& pos2) // Erase the elements in range [pos1,pos2)..
{
for(size_t i=pos1; i<vector_size-(pos2-pos1); i++)
{
vector_pointer[i]=vector_pointer[i+pos2-pos1]; // Shift all the elements (pos2-pos1) steps left, beginning from "pos2"
}
vector_size-=pos2-pos1;
}
void insert(const size_t& pos,const T& val) // Insert 1 element of value "val" at "pos"..
{
if(vector_capacity<=vector_size) // Create some space if it doesn't have enough to take another element..
reserve(vector_size);
vector_size++;
for(size_t i=vector_size-1; i>pos; i--) // Shift all the elements one step towards right, beginning from "pos"+1..
{
vector_pointer[i]=vector_pointer[i-1];
}
vector_pointer[pos]=val;
}
void insert(const size_t& pos,const size_t& n,const T& val) // Insert "n" elements of value "val", beginning from "pos"..
{
if(vector_size<n+vector_capacity)
reserve(vector_size+n); // Create space for atleast "n" elements...
vector_size+=n;
for(size_t i=vector_size-1; i>=pos+n; i--) // Shift all the elements "n" step towards right, beginning from "pos"+1..
{
vector_pointer[i]=vector_pointer[i-n];
}
for(size_t i=pos; i<pos+n; i++) // Change all the elements in [pos,pos+n) to "val"..
{
vector_pointer[i]=val;
}
}
void clear()
{
vector_size=0;
} // Again, doesn't actually deallocate (for performance)..
friend void swap(myvector &a,myvector &b) // Copy and Swap Idiom ...
{
using std::swap;
swap(a.vector_size,b.vector_size);
swap(a.vector_capacity,b.vector_capacity);
swap(a.vector_pointer,b.vector_pointer);
}
};
template<typename T>std::ostream& operator <<(std::ostream& out,const myvector<T> &a) // Overloaded output operator to display the contents of a vector..
{
for(size_t i=0; i<a.size(); i++)
{
std::cout<<a[i]<<" ";
}
return out;
}
</code></pre>
<p><strong>EDIT (based on the 2 answers):</strong></p>
<ol>
<li>Modified the <code>nearest_power_of_2()</code> function </li>
<li>Replaced <code>memcpy()</code> with <code>std::copy()</code> </li>
<li>Called the destructor <code>~T()</code> explicitly wherever required </li>
<li>Modified the output operator <code><<</code></li>
</ol>
<p></p>
<pre><code>size_t nearest_power_of_2(const size_t &n) // Return the nearest( and strictly greater than ) number to "n" which is a power of 2..
{
return 1ULL<<(static_cast<size_t>(log2(n))+1);
}
template<typename T>
class myvector
{
T* vector_pointer; // A pointer pointing to the start of the dynamic array...
size_t vector_size,vector_capacity;
public:
myvector():vector_pointer(NULL),vector_size(0),vector_capacity(0) {} // Default Constructor
myvector(const myvector& other):vector_pointer(NULL),vector_size(0),vector_capacity(0) // Copy Constructor
{
vector_pointer=new T[other.capacity()];
std::copy(&other[0],&other[0]+other.size(),vector_pointer);
vector_size=other.vector_size;
vector_capacity=other.vector_capacity;
}
~myvector() // Destructor
{
delete[] vector_pointer;
}
myvector& operator =(myvector other) // Assignment operator
{
swap(*this,other);
return *this;
}
void resize(const size_t &newsize) // Change the size of the vector exactly to "newsize"..
{
if(newsize<vector_size)
{
for(size_t i=newsize; i<vector_size; i++)
{
vector_pointer[i].~T();
}
}
else if(newsize>vector_capacity)
{
reserve(newsize);
}
vector_size=newsize;
}
void reserve(size_t newcapacity) // Change the capacity of the vector to be at least equal to "newcapacity"
{
newcapacity=nearest_power_of_2(newcapacity); // Keep the capacity of the vector as a power of 2 to avoid space wastage..
if(newcapacity>vector_capacity)
{
T* temp=new T[newcapacity];
std::copy(vector_pointer,vector_pointer+vector_capacity,temp);
delete[] vector_pointer;
vector_pointer=temp;
vector_capacity=newcapacity;
}
}
void push_back(const T &val) // Add a new element of value "val" at the end of the vector..
{
if(vector_capacity<=vector_size)
reserve(vector_capacity);
vector_pointer[vector_size++]=val;
}
void pop_back() // Remove the last element of the vector..
{
if(vector_size)
{
vector_pointer[vector_size-1].~T();
--vector_size;
}
}
size_t size() const
{
return vector_size;
}
size_t capacity() const
{
return vector_capacity;
}
T& operator [](const size_t &pos)
{
return vector_pointer[pos];
}
const T& operator [](const size_t &pos) const
{
return vector_pointer[pos];
}
bool empty() const
{
return vector_size==0;
}
T& at(const size_t& pos) // Same as the "[]" operator, but this one checks for out-of-bound exceptions..
{
if(pos>=vector_size)
throw std::out_of_range("");
else
return vector_pointer[pos];
}
const T& at(const size_t& pos) const
{
if(pos>=vector_size)
throw std::out_of_range("");
else
return vector_pointer[pos];
}
void erase(const size_t& pos) // Erase the element at "pos"..
{
vector_pointer[pos].~T();
for(size_t i=pos; i<vector_size-1; i++)
{
vector_pointer[i]=vector_pointer[i+1]; // Shift all the elements one step left, beginning from "pos+1"
}
--vector_size;
}
void erase(const size_t& pos1,const size_t& pos2) // Erase the elements in range [pos1,pos2)..
{
for(size_t i=pos1; i<pos2; i++)
{
vector_pointer[i].~T();
}
for(size_t i=pos1; i<vector_size-(pos2-pos1); i++)
{
vector_pointer[i]=vector_pointer[i+pos2-pos1]; // Shift all the elements (pos2-pos1) steps left, beginning from "pos2"
}
vector_size-=pos2-pos1;
}
void insert(const size_t& pos,const T& val) // Insert 1 element of value "val" at "pos"..
{
if(vector_capacity<=vector_size) // Create some space if it doesn't have enough to take another element..
reserve(vector_size);
vector_size++;
for(size_t i=vector_size-1; i>pos; i--) // Shift all the elements one step towards right, beginning from "pos"+1..
{
vector_pointer[i]=vector_pointer[i-1];
}
vector_pointer[pos]=val;
}
void insert(const size_t& pos,const size_t& n,const T& val) // Insert "n" elements of value "val", beginning from "pos"..
{
if(vector_size<n+vector_capacity)
reserve(vector_size+n); // Create space for atleast "n" elements...
vector_size+=n;
for(size_t i=vector_size-1; i>=pos+n; i--) // Shift all the elements "n" step towards right, beginning from "pos"+1..
{
vector_pointer[i]=vector_pointer[i-n];
}
for(size_t i=pos; i<pos+n; i++) // Change all the elements in [pos,pos+n) to "val"..
{
vector_pointer[i]=val;
}
}
void clear()
{
for(size_t i=0; i<vector_size; i++)
{
vector_pointer[i].~T();
}
vector_size=0;
}
friend void swap(myvector &a,myvector &b) // Copy and Swap Idiom ...
{
using std::swap;
swap(a.vector_size,b.vector_size);
swap(a.vector_capacity,b.vector_capacity);
swap(a.vector_pointer,b.vector_pointer);
}
};
template<typename T>std::ostream& operator <<(std::ostream& out,const myvector<T> &a) // Overloaded output operator to display the contents of a vector..
{
std::copy(&a[0], &a[0]+a.size(), std::ostream_iterator<T>(out, " "));
return out;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T18:48:39.337",
"Id": "46343",
"Score": "2",
"body": "Your update is more dangerous than your original. Because you don't use placement new your use of explicit destructor calls is going to get you in trouble. See me update below."
}
] |
[
{
"body": "<ul>\n<li><p>That's an okay guide for reference, but I'd highly recommend searching for pages that give in-depth information about <code>std::vector</code>s. There's a lot going on under the hood, and one general guide cannot teach you everything.</p></li>\n<li><p>I'm not sure how far you want to go with the STL (minus <code>std::vector</code> of course), but I'd still make use of it. Without it, your code will be too C-like and improper use of raw pointers (also C-like) could attract all sorts of bugs.</p></li>\n<li><p><code>count</code> should also be a <code>size_t</code>.</p></li>\n<li><p>The <code>size_t</code> parameters don't really need to be <code>const</code>, but that's not a big issue.</p></li>\n<li><p><code>std::out_of_range()</code> requires <code><stdexcept></code>.</p></li>\n<li><p>I'd really test the shifting in both <code>erase()</code>es. It's not quite a straightforward algorithm. For one thing, your algorithm will eventually leave a garbage value at the very end if shifting left. Correcting that won't be so easy, which is why this may need to be approached differently.</p></li>\n<li><p><code>std::pop_back()</code> destroys the last element in the vector, yet you're just reducing its size to \"remove\" it. What happens if you increment the size again? Yes, that element will still be there. Vectors are always shrinking and growing, so do just that. Despite the performance hit that you're trying to avoid, this method is not at all like the original. It is supposed to call the destructor for the removed element to make sure it's destroyed for good.</p></li>\n<li><p>Why are you forcing the size to 0 in <code>clear()</code>? Your destruction method should reduce the size itself, thereby giving you an accurate count of the remaining elements (which should be 0). Again, don't take the easy way out in favor of performance. Do what the original is supposed to do.</p></li>\n<li><p>Again, your <code>operator<<</code> is putting the output into <code>std::cout</code> instead of <code>out</code>.</p></li>\n</ul>\n\n<p><strong>Follow-up from comments:</strong></p>\n\n<ul>\n<li><p>Here's a rough idea of how your declarations and definitions should be structured. These can be in separate files (.h for declaration and .cpp for definition), or in this form in one .h file.</p>\n\n<p><em>Class declaration</em></p>\n\n<pre><code>template<typename T>\nclass myvector\n{\n T* vector_pointer;\n // these should go on separate lines\n size_t vector_size;\n size_t vector_capacity;\n\npublic:\n myvector();\n myvector(const myvector&);\n ~myvector();\n myvector& operator=(myvector);\n void resize(size_t);\n void reserve(size_t);\n void push_back(const T&);\n void pop_back();\n T& at(size_t);\n const T& at(size_t);\n void erase(size_t);\n void erase(size_t, size_t);\n void insert(size_t, const T&);\n void insert(size_t, size_t, const T&);\n void clear();\n friend void swap(myvector&, myvector&);\n\n // these are the accessors (moved to the end for organization)\n // they may be implemented within the class declaration\n // because they merely return private data and each have one line\n size_t size() const {return vector_size;}\n size_t capacity() const {return vector_capacity;}\n T& operator[](size_t pos) const {return vector_pointer[pos];}\n const T& operator[](size_t pos) const {return vector_pointer[pos];}\n bool empty() const {return vector_size == 0;}\n};\n</code></pre>\n\n<p><em>Class definition</em></p>\n\n<pre><code> // if a function belongs to the class,\n // it must have the scope operator with the class name\n // (fill in the curly braces with your definitions)\n\n myvector::myvector() : vector_pointer(NULL), vector_size(0), vector_capacity(0) {}\n myvector::myvector(const myvector& other) {}\n myvector::~myvector() {}\n myvector::myvector& operator=(myvector other) {}\n void myvector::resize(size_t newsize) {}\n void myvector::reserve(size_t newcapacity) {}\n void myvector::push_back(const T& val) {}\n void myvector::pop_back() {}\n T& myvector::at(size_t pos) {}\n const T& myvector::at(size_t pos) {}\n void myvector::erase(size_t pos) {}\n void myvector::erase(size_t pos1, size_t pos2) {}\n void myvector::insert(size_t pos, const T& val) {}\n void myvector::insert(size_t pos, size_t n, const T& val) {}\n void myvector::clear() {}\n // swap() is a friend of myvector, so it doesn't get the scope operator\n // friend is also removed from the definition but stays in the declaration\n void swap(myvector& a, myvector& b) {}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T07:25:24.353",
"Id": "46312",
"Score": "1",
"body": "The pop_back() should force the elements destructor to be called. RAII is an important concept and when you pop something you expect it to be destroyed and the destructor called."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T07:26:49.170",
"Id": "46313",
"Score": "0",
"body": "@LokiAstari: Right. I'm already making some changes now. I just didn't want give any false information about it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T10:50:40.087",
"Id": "46321",
"Score": "0",
"body": "`The class declarations and implementations should be noticeably separate, even if they're in one file. I had to scrounge for that };`. Sorry, but I didn't actually get it. How do you differentiate between declarations and implementations? I agree with you on the usage of STL in C++. I use them a lot!! In fact, that was the only reason I was so much curious on how they were implemented! I am not gonna use these implementations in place of the original stuff. I practice that just for the sake of learning ( and fun! )."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T11:41:24.613",
"Id": "46324",
"Score": "2",
"body": "In class: `void resize(const size_t &newsize);` Outside: `void myvector<T>::resize(const size_t& newsize) { /* implementation */ }`. Any book on C++ will show you this. By defining member functions inside the class definition, you are implicitly asking that the compiler inlines them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T16:53:14.820",
"Id": "46337",
"Score": "0",
"body": "Ah. You could've asked me about that before if you were confused. Anyway, Lstor is correct. You could still get an idea online, but I can give you an example in my answer as a start."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T17:27:12.187",
"Id": "46338",
"Score": "0",
"body": "@Jamal No need for that, i got it now! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T17:31:27.480",
"Id": "46339",
"Score": "0",
"body": "@AnmolSinghJaggi: I just happened to finish it already. :-) I'll post it anyway so that it's not a waste. Perhaps a visitor to this question will find it useful."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T07:04:46.570",
"Id": "29332",
"ParentId": "29331",
"Score": "4"
}
},
{
"body": "<p>You can do this with maths rather than a loop:</p>\n\n<pre><code>size_t nearest_power_of_2(size_t n) // Return the nearest( and strictly greater than ) number to \"n\" which is a power of 2..\n</code></pre>\n\n<p>Couple of issues with the copy constructor.</p>\n\n<pre><code>myvector(const myvector& other):vector_pointer(NULL),vector_size(0),vector_capacity(0) // Copy Constructor\n{\n // Don't assign to this object until you\n // know that no exceptions can be thrown.\n // This means all memory allocation and\n // object copying must be completed first.\n vector_pointer=new T[other.capacity()];\n\n // You can use this for POD types.\n // But any non POD types must be copied using their copy constructor.\n memcpy(vector_pointer,&other[0],sizeof(T)*other.size());\n\n\n vector_size=other.vector_size;\n vector_capacity=other.vector_capacity;\n}\n</code></pre>\n\n<p>Similar issues with resize()</p>\n\n<pre><code> // You can use this for POD types.\n // But any non POD types must be copied using their copy constructor.\n memcpy(temp,vector_pointer,sizeof(T)*newsize);\n</code></pre>\n\n<p>Making the size smaller is easier. You don't need to re-allocate. You can just reduce the size value and manually call the destructor on all the objects that don't exist anymore.</p>\n\n<p>Same but slightly different in reserve()</p>\n\n<pre><code> // The trouble with use T as the underlying type.\n // As that this call will call the constructor on all objects\n // upto `capacity`. You don't want that you only want to call\n // the constructor on values upto `newcapacity`\n T* temp=new T[newcapacity];\n\n // You can use this for POD types.\n // But any non POD types must be copied using their copy constructor.\n memcpy(temp,vector_pointer,sizeof(T)*vector_capacity);\n</code></pre>\n\n<p>Your push back is very inefficient:</p>\n\n<pre><code>void push_back(const T &val) // Add a new element of value \"val\" at the end of the vector..\n{\n if(vector_capacity<=vector_size)\n // As noted calls copy constructor\n reserve(vector_capacity);\n\n // Now using the assignment operator.\n // To copy over object that you just fully initialized.\n vector_pointer[vector_size++]=val;\n\n // A better solution is not to construct in the copy constructor.\n // Then here use placement new to create the object in place\n}\n</code></pre>\n\n<p>The pop back needs work</p>\n\n<pre><code>void pop_back() // Remove the last element of the vector..\n{\n if(vector_size)\n --vector_size;\n\n // RAII is an important concept in C++\n // When you pop something out of your vector it should no longer exist.\n // This means you need to call the destructor for the object.\n // Here that means manually calling the destructor.\n\n} // Doesn't actually deallocate the element block (for performance)..\n</code></pre>\n\n<p>More times when destructor needs to be called.</p>\n\n<pre><code>void erase(const size_t& pos) // Erase the element at \"pos\"..\nvoid clear()\n\n// For the elements passed the end of the valid vector (vector_size)\n// You need to call the destructors of these elements as they no longer exist.\n</code></pre>\n\n<p>Fix your output operator:</p>\n\n<pre><code>template<typename T>std::ostream& operator <<(std::ostream& out,const myvector<T> &a) // Overloaded output operator to display the contents of a vector..\n{\n for(size_t i=0; i<a.size(); i++)\n {\n // Should be `out`\n std::cout<<a[i]<<\" \";\n }\n return out;\n}\n</code></pre>\n\n<p>For loops like this use the standard algorithms:\nPersonally I don't see the point. I can achieve the same effect in one line:</p>\n\n<pre><code>std::copy(a.begin(), a.end(), std::ostream_iterator<T>(out, \" \"));\n</code></pre>\n\n<p>Simple Vector:</p>\n\n<pre><code>template<typename T>\nclass LokiVector\n{\n std::size_t size;\n std::size_t capacity;\n std::unique_ptr<char[]> data; // Use char so we don't worry about \n // constructor/destructor issues.\n\n void init(T const& value)\n {\n public:\n LokiVector(std::size_t startSize = 0, T const& defaultValue = T())\n : size(startSize)\n , capacity(std::min(startSize, 16))\n , data(new char[sizeof(T) * capacity])\n {\n T* localData = reinterpret_cast<T*>(data.get());\n for(int loop = 0;loop < size; ++loop)\n {\n new (&localData[loop]) T(defaultValue);\n }\n }\n LokiVector(LokiVector const& rhs)\n : size(rhs.size)\n , capacity(rhs.capacity)\n , data(new char[sizeof(T) * capacity])\n {\n T* localData = reinterpret_cast<T*>(data.get());\n for(int loop = 0;loop < size; ++loop)\n {\n new (&localData[loop]) T(rhs[loop]);\n }\n }\n ~LokiVector()\n {\n T* localData = reinterpret_cast<T*>(data.get());\n for(int loop = 0;loop < size; ++loop)\n {\n // Destroy from tail to front (like arrays do)\n localData[size-1-loop].~T();\n }\n }\n LokiVector& operator=(LokiVector rhs)\n {\n swap(rhs);\n return *this;\n }\n void swap(LokiVector& other) noexcept\n {\n std::swap(size, other.size);\n std::swap(capacity, other.capacity);\n std::swap(data, other.data);\n }\n\n void push_back(T const& value)\n {\n reserve(size+1);\n T* localData = reinterpret_cast<T*>(data.get());\n new (&localData[size]) T(value);\n ++size;\n }\n\n void pop_back()\n {\n if (size > 0)\n {\n --size;\n T* localData = reinterpret_cast<T*>(data.get());\n localData[size].~T();\n }\n }\n\n void reserve(std::size_t min)\n {\n if (min < capacity)\n {\n size_t tmp_capacity = min; // Plus any padding you want to add\n std::unique_ptr<char> tmp_data(new char[sizeof(T) * tmp_capacity);\n T* localData = reinterpret_cast<T*>(data.get());\n T* tmpLocal = reinterpret_cast<T*>(tmp_data.get());\n\n for(int loop = 0;loop < size; ++loop)\n {\n new (&tmpLocal[loop]) T(localData[loop]);\n }\n\n // Update the state of the local object\n std::swap(data, tmp_data);\n std::swap(capacity, tmp_capcity);\n\n // Destroy all the old members\n // Remember these may potentially throw so this is done\n // after the state of the object is completely defined.\n for(int loop = 0;loop < size; ++loop)\n {\n // Destroy from tail to front (like arrays do)\n // Remember that local data still points at the old\n // data even after the swap.\n localData[size-1-loop].~T();\n }\n }\n }\n T& operator[](std::size_t index)\n {\n T* localData = reinterpret_cast<T*>(data.get());\n return localData[index];\n }\n T const& operator[] (std::size_t index) const\n {\n return const_cast<LokiVector&>(*this)[index];\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T10:41:09.410",
"Id": "46320",
"Score": "0",
"body": "`Making the size smaller is easier....manually call the destructor on all the objects that don't exist anymore.` How can we do it??! I asked a [similar question](http://stackoverflow.com/questions/18016295/deleting-elements-of-a-dynamic-array-one-by-one) some time back. Similarly, in `erase()`, how to destruct a single element? ( except for the usual way of reallocating ) . In, `reserve()`, `// The trouble with use T as the ....constructor on values upto newcapacity`.. I don't get it..Is there any other way too?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T11:38:59.837",
"Id": "46323",
"Score": "2",
"body": "The \"similar question\" is about `delete`, which frees memory. @LokiAstari is talking about calling the destructor, which causes the object in question to clean up the resources it owns: `elem->~T();`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T18:36:02.097",
"Id": "46342",
"Score": "1",
"body": "Updated with an example of how I might do it. Needs some cleanup but it should work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T19:24:24.680",
"Id": "57173",
"Score": "0",
"body": "Hi Loki, I was just wondering two things and I am interested in what you think about them. First, shouldn't the `unique_ptr<char` be a `unique_ptr<char[]>` so that the correct version of delete is called? Second, don't you have to destroy all already constructed elements in the constructors when a `T` constructor would throw an exception."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T20:35:05.963",
"Id": "57180",
"Score": "1",
"body": "@bamboon: You are correct on both points. I have fixed the easy one. Calling the destructor I have not done here because that is a lot of work (you can't just do the obvious because pointers and fundamental types don't have destructors)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T07:48:59.563",
"Id": "29334",
"ParentId": "29331",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "29334",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T06:20:29.633",
"Id": "29331",
"Score": "6",
"Tags": [
"c++",
"performance",
"memory-management",
"vectors",
"reinventing-the-wheel"
],
"Title": "Template vector class"
}
|
29331
|
<p>I'm trying to write a message queue implementation
so my threads can exchange data.
To keep things simple, the queue is only responsible for
sending pointers to memory. Only one thread may send messages,
and only one thread may read messages.</p>
<p>The struct <code>mq_t</code> represents a message queue.</p>
<ul>
<li><code>mq_t.messages</code> is a circular buffer of pointers.</li>
<li><code>mq_t.send</code> is the index of the last sent message.</li>
<li><code>mq_t.recv</code> is the index of the next message to be received.</li>
</ul>
<p>I'd like to know some things:</p>
<ol>
<li>Thread Safety: I didn't use a mutex or lock, but I think the code is quite thread-safe. Is this true?</li>
<li>In the code I use things like <code>while (isempty(queue));</code>. Is there a better way to handle such things, like suspending the thread until a memory change occurs?</li>
<li>Cross Platform: does my code rely on some non-cross platform code or undefined behaviour?</li>
<li>Are there other things wrong with my code (except the highly generic function names)?</li>
</ol>
<p></p>
<pre><code>#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#define null ((void*)0)
#define SIZE 2
typedef struct {
int send;
int recv;
void * messages[SIZE];
} mq_t;
inline int isfull(mq_t * queue) {
return (queue->send+1)%SIZE == queue->recv;
}
inline int isempty(mq_t * queue) {
return queue->send == queue->recv;
}
mq_t * create(void) {
mq_t * queue = (mq_t*)malloc(sizeof(mq_t));
queue->send = 0;
queue->recv = 0;
}
void send(mq_t * queue, void * message) {
while (isfull(queue));
int next = (queue->send+1) % SIZE;
queue->messages[next] = message;
queue->send = next;
}
void * recv(mq_t * queue) {
while (isempty(queue));
void * message = queue->messages[queue->send];
queue->recv = (queue->recv+1) % SIZE;
return message;
}
void destroy(mq_t * queue) {
while (!isempty(queue));
free(queue);
}
</code></pre>
<p><strong>Test:</strong></p>
<pre><code>void * sender(void * queue) {
send(queue, "hello, ");
send(queue, "world");
send(queue, "how are you?");
printf("sent data\n");
}
void * recver(void * queue) {
sleep(1);
printf("received '%s'\n", recv(queue));
printf("received '%s'\n", recv(queue));
printf("received '%s'\n", recv(queue));
}
int main() {
mq_t * queue = create();
pthread_t s, r;
pthread_create(&s, null, sender, (void*)queue);
pthread_create(&r, null, recver, (void*)queue);
pthread_join(s, null);
pthread_join(r, null);
return 0;
}
</code></pre>
<p><strong>Output:</strong></p>
<blockquote>
<pre><code>received 'hello, '
received 'world'
received 'how are you?'
sent data
</code></pre>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-27T17:29:23.133",
"Id": "148868",
"Score": "0",
"body": "I don't think POSIX is portable to windows these days. I'm not very windows-savvy so I could easily be mistaken."
}
] |
[
{
"body": "<p>With a size of 2, your 'queue' can hold only one item, so it is not really a queue. If\nyou increase the size to 8 (say) you now really have a queue, but your tests don't\nwork.</p>\n\n<p>You seem to define <code>send</code> and <code>recv</code> as follows:</p>\n\n<ul>\n<li><p><code>send</code> indicates the 'slot' holding the most recently entered data (queue not empty).</p></li>\n<li><p><code>recv</code> indicates the 'slot' <strong>before</strong> the oldest data in the queue (queue not empty).</p></li>\n<li><p>if <code>send == recv</code> the queue is empty. </p></li>\n</ul>\n\n<p>So with both <code>send</code> and <code>recv</code> at zero, when the first data is written it goes to slot 1 and <code>send</code> is incremented to 1; when the 2nd data is written it goes to slot 2 and <code>send</code> is incremented to 2. If you now read from the queue, in <code>recv</code> you use the <code>send</code> counter to extract the data instead of using <code>recv + 1</code>. Hence the queue fails.</p>\n\n<p>A more logical arrangement might be as follows with the counters renamed <code>in</code>\nand <code>out</code> (naming them the same as the access functions is confusing):</p>\n\n<ul>\n<li><p><code>in</code> indicates the next 'slot' to be written by <code>send</code> (queue not empty).</p></li>\n<li><p><code>out</code> indicates the 'slot' containing the next data to be read by <code>recv</code> (queue not empty).</p></li>\n<li><p>if <code>in == out</code> the queue is empty. </p></li>\n</ul>\n\n<p>So with both <code>send</code> and <code>recv</code> at zero, when the first data is sent, it goes into slot 0 (to which <code>in</code> and <code>out</code> already point) and <code>in</code> is incremented to 1. The first read now reads from <code>out</code> at 0 - which is correct.</p>\n\n<hr>\n\n<p>On thread safety, it is very difficult to see/analyse such things. You would be\nbetter to assume that it isn't (it certainly wouldn't be if there were more\nthan 2 threads) and use a mutex. As your wait loops need to be rewritten\n(they just waste CPU cycles needlessly) and you are using Posix threads, use a\nPosix mutex and a \"condition variable\" to synchronise.</p>\n\n<p>Here's an example, but there are many more on the web: <a href=\"http://www.ibm.com/developerworks/library/l-posix3/\" rel=\"nofollow\">http://www.ibm.com/developerworks/library/l-posix3/</a></p>\n\n<hr>\n\n<p>Some minor coding points:</p>\n\n<ul>\n<li><p>Add <code>const</code> to pointer parameters that do not change.</p></li>\n<li><p>Return a value from <code>create</code></p></li>\n<li><p>Don't cast the return from <code>malloc</code>. Casting is necessary in C++ not C\n(where void* can be assigned to any pointer). In C, adding a cast can cause\nproblems if you don't have the header for <code>malloc</code> included, as the compiler\nwill assume that <code>malloc</code> returns an <code>int</code>. If <code>int</code> and <code>pointer</code> have\ndifferent sizes this is a problem.</p></li>\n<li><p><code>null</code> is not really needed. You can use either 0 or NULL.</p></li>\n<li><p>the <code>_t</code> type suffix is apparently reserved by Posix.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T13:43:35.067",
"Id": "29341",
"ParentId": "29338",
"Score": "4"
}
},
{
"body": "<p>This code is surely not MTsafe:</p>\n\n<pre><code>void send(mq_t * queue, void * message) {\n while (isfull(queue));\n int next = (queue->send+1) % SIZE;\n</code></pre>\n\n<p>After <code>while (isfull(queue));</code> and before <code>queue->send = next;</code>, you can enter a bit of threads and writes in common slot before they update <code>queue->send</code> pointer that cause <code>isfull</code> to locked state.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T19:28:03.893",
"Id": "29813",
"ParentId": "29338",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "29341",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T12:10:08.800",
"Id": "29338",
"Score": "6",
"Tags": [
"c",
"thread-safety",
"queue",
"circular-list"
],
"Title": "Thread-safe message queue without mutex in C"
}
|
29338
|
<p>I'm trying to create small PHP framework for my own needs (and likes). However there are questions for which I may need advice of more wise and experienced people before things became too complicated - so I moved it to github from private repo.</p>
<p>Currently I'm curious about organizing imports of modules better. I use the special object, "context" - to hold links to all necessary modules - data access objects, utils etc. I use lazy initialization here, so that when field of this object is required, it is provided by the getter of the same name.</p>
<p>It looks like:</p>
<pre><code>class ProtoContext {
function __get($name) {
$methodName = 'get' . ucfirst($name);
if (!method_exists($this, $methodName)) {
throw new Exception("No property '$name' in Context!");
}
$res = $this->$methodName();
if (is_object($res)) {
$res->ctx = $this;
}
$this->$name = $res;
return $res;
}
protected function getElems() {
return Elems::$elems;
}
protected function getUtil() {
module('sys/Util');
return new Util();
}
}
</code></pre>
<p>main <a href="https://github.com/RodionGork/PhpLayout/blob/master/module/Context.php" rel="nofollow noreferrer">Context</a> class is inherited from this <a href="https://github.com/RodionGork/PhpLayout/blob/master/module/sys/ProtoContext.php" rel="nofollow noreferrer">ProtoContext</a>, though it is not significant now. With the grow of application context may look like this:</p>
<pre><code>module('sys/ProtoContext');
class Context extends ProtoContext {
protected function getAuth() {
module('MyAuth');
return new MyAuth();
}
protected function getUsersDao() {
module('dao/MysqlDao');
return new MysqlDao('users');
}
protected function getRolesDao() {
module('dao/MysqlDao');
return new MysqlDao('roles');
}
/*
* 5-10 more similar methods 'getSomethingDao'
* each including MysqlDao via method 'module'
*/
protected function getLinksCViewDao() {
module('dao/MysqlDao');
return new MysqlDao('linksc_view');
}
}
</code></pre>
<p>There is no problem that <code>module</code> method may be called several times, include is performed once only. However it looks annoying that inclusion of MysqlDao is mentioned so many times. On the other hand if I pull it above the class (like import of ProtoContext) it will be imported even if I need it not. For example when addressing $ctx->auth field (which will call getAuth method).</p>
<p>I wonder, whether here is comfortable workaround which will preserve lazy load and lazy initialization - and at the same time will allow to get rid of extra imports?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T13:21:47.220",
"Id": "46468",
"Score": "0",
"body": "Why would you implement `module` method if we already have lazy loading trough autoloading? It looks to me you're doing something that's been done before (and much better)."
}
] |
[
{
"body": "<p>As N.B. mentioned in their comment - why are you implementing a <code>module</code> method if we already have lazy loading via autoloading? I've even <a href=\"https://github.com/jsanc623/LazyLoader\" rel=\"nofollow\">written a class</a> that you can simply attach and not have to worry about loading your classes. Now, there are better autoloaders out there - like <a href=\"http://symfony.com/doc/current/components/class_loader.html\" rel=\"nofollow\">Symphony's ClassLoader/autoload.php</a>. Anyways, here's your code, with my LazyLoader class handling the loading of methods (untested code). </p>\n\n<p><strong>/LazyLoader.php</strong>\n\n\n<pre><code>/**\n * LazyLoader\n * A fast, strict lazy loader (time ~ 0.0001)\n * \n * Class name must match File name.\n * If class has namespace, must be called via namespace.\n *\n * @author Juan L. Sanchez <juanleonardosanchez.com>\n * @license MIT\n * @version 1.2.0\n * @internal 06.26.2013\n */\n\nNamespace LazyLoader;\n\nclass LazyLoader{\n public static $dirRoot;\n\n public static function autoload($class_name){\n $file = dirname(__FILE__) . \n (strlen(self::$dirRoot) > 0 ? self::$dirRoot : \"\") . \n '/' . array_pop(explode(\"\\\\\", $class_name)) . '.php';\n\n file_exists($file) ? require_once($file) : \"\";\n }\n\n public static function SetBaseDirectory($directory_root){\n self::$dirRoot = substr($directory_root, -1) == \"\\\\\" ? \n substr($directory_root, 0, -1) : \"\";\n }\n\n public static function Register(){\n return spl_autoload_register(__NAMESPACE__ .'\\LazyLoader::autoload');\n }\n}\n\n$LazyLoader = new LazyLoader;\n$LazyLoader->SetBaseDirectory(\"Classes\"); # Optional\n$LazyLoader->Register();\n</code></pre>\n\n<p><strong>/Context.php</strong></p>\n\n<pre><code><?php\nmodule('sys/ProtoContext');\n\nclass Context extends ProtoContext {\n\n protected function getAuth() {\n return new MyAuth();\n }\n\n protected function getUsersDao() {\n return new MysqlDao('users');\n }\n\n protected function getRolesDao() {\n return new MysqlDao('roles');\n }\n\n /*\n * 5-10 more similar methods 'getSomethingDao' \n * each including MysqlDao via method 'module'\n */\n\n protected function getLinksCViewDao() {\n return new MysqlDao('linksc_view');\n }\n\n}\n</code></pre>\n\n<p>The directory structure of the above code would look something like:</p>\n\n<pre><code>/LazyLoader.php\n/Context.php\n/Classes/MyAuth.php\n/Classes/ProtoContext.php\n/Classes/MysqlDao.php\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-29T06:23:57.453",
"Id": "48353",
"Score": "0",
"body": "Thanks for sharing. `is_readable` might be an improvement over `file_exists`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-29T14:07:43.777",
"Id": "48393",
"Score": "1",
"body": "`is_readable` tests whether a file exists and is readable, whereas `file_exists` tests whether a file, well, exists - but doesn't check readability. If the file is not readable, it should fail loudly in the require_once, rather than failing quietly when using `is_readable` and/or `include`. That was my line of thinking. Is there a performance difference between `is_readable` and `file_exists`? That would be surely negated by my use of `require_once` I'd imagine?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T14:12:43.630",
"Id": "29398",
"ParentId": "29340",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "29398",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T13:38:33.163",
"Id": "29340",
"Score": "1",
"Tags": [
"php"
],
"Title": "PHP - avoid many on-demand imports"
}
|
29340
|
<p>I'm just getting to know the whole prototype world, and now I'm trying to do in JS what is normally done in OO languages, namely classes and DAO classes.</p>
<p>I'd be grateful for any comments on whether the code is written in accordance to JS best practices and whatnot. More specifically, I didn't implement getters or setters per se, is my approach still sound?</p>
<pre><code>function Person(obj) {
this.id = obj.id;
this.name = obj.name;
this.surname = obj.surname;
}
Person.prototype.toString = function(){
return "["+this.id+"] name: " + this.name + ", surname: " + this.surname;
};
/*
Field.prototype = {
get value(){
return this._value;
},
set value(val){
this._value = val;
}
};
*/
function PersonDAO(){
this.arrayOfPeople = [];
}
PersonDAO.prototype = {
save:function(personObj){
this.arrayOfPeople.push(personObj);
},
getAll:function(){
return this.arrayOfPeople;
}
};
var John = new Person({
id: 1,
name: "John",
surname: "Smith"
});
var Bob = new Person({
id: 2,
name: "Bob",
surname: "Doe"
});
var pDAO = new PersonDAO();
pDAO.save(John);
pDAO.save(Bob);
console.log(pDAO.getAll()[0].toString());
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T15:40:02.177",
"Id": "46333",
"Score": "0",
"body": "please post the code here, not just link to it. It should persist beyond only until you get the response or until jsbin.com passes away."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T15:46:04.673",
"Id": "46334",
"Score": "0",
"body": "Done, I've copy/paste the code"
}
] |
[
{
"body": "<p>I feel your question is bit abstract, requiring for exactly \"point of view\" :)</p>\n\n<p>You also did not mention which \"normal OO language\" you mean. Supposedly Java. And what javascript kind you use - browser or node.js?</p>\n\n<p>Anyway, I personally agree your code is sound enough, though it looks to me that all this piece (itself) do not require using prototype.</p>\n\n<pre><code>function PersonDao(initParams) {\n this.save = function() {\n }\n}\n</code></pre>\n\n<p>This will still work all right.</p>\n\n<p>My humble opinion is that since JavaScript <strong>is not</strong> normal OO language, you need not pursue all patterns you have in Java for example.</p>\n\n<p>Usually data models do not require to be inherited (though some people have specific view on this issue), only aggregated. Then you need not prototypes for them.</p>\n\n<p>Also note that in most scripting languages DAO is not popular pattern, instead people prefer ActiveRecord here - so that Person will contain methods for save and static method for load (here you may really want address to prototype, perhaps). Though I personally really support DAO-based variant.</p>\n\n<p>Second point, that if you want to move on in java way, you need to have Person properties hidden, not exposed. (I.e. they should be without \"this\", simply vars inside Person) And by the way you obviously can generate getters for them on the fly, since it is scripting language.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T13:07:59.383",
"Id": "46656",
"Score": "0",
"body": "Assigning a function to a property in a constructor means that JS will create a new function object for each instance. That's exactly what prototypes are for. When a cosntructor is called, a prototype is created _anyway_, why let it idle? when an `Object.prototype` method is invoked, JS will first check the `PersonDAO` prototype, which isn't used, so it's just adding dead-weight anyway, why not put it to good use?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T16:48:30.343",
"Id": "29344",
"ParentId": "29343",
"Score": "1"
}
},
{
"body": "<p>Though dynamic, you should not force JavaScript it to use complicated patterns that aren't worth the hassle. In your case, the code you want can be simplified into:</p>\n\n<pre><code>var people = [];\n\npeople.push({\n id: 1,\n name: \"John\",\n surname: \"Smith\"\n});\n\npeople.push({\n id: 2,\n name: \"Bob\",\n surname: \"Doe\"\n});\n</code></pre>\n\n<p>Another thing is that JavaScript has no natural concept of privacy (save closures of course). So when doing some prototypal OOP, <em>almost everything is public</em>. Getters and setters might not hold much purpose.</p>\n\n<p>The key to a big JavaScript app is to never make it big in the first place. Keep components small, simple and easy to debug in case they go wild. Additional baggage will drag you down eventually.</p>\n\n<p>Also, I suggest you don't modify native methods. Though it's common that developers do override some of them, like <code>toString()</code>. But some other code might use it in a way that it expects the native functionality. A general rule in JS is <em>don't modify objects you don't own.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T03:27:42.740",
"Id": "46616",
"Score": "0",
"body": "Just to add - `push()` accepts multiple arguments, so you could rewrite it to only contain one call to `push()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T12:06:19.673",
"Id": "46655",
"Score": "1",
"body": "Pedantic side-notes: JS apps can be as big as you like them to be, it mainly depends on what platform they'll run. Also on the `toString`: the OP merely overrides the `Object.prototype.toString` method, but didn't alter it. He altered the behaviour of _his own_ prototype, and didn't modify any objects he didn't own"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T20:01:33.803",
"Id": "46820",
"Score": "0",
"body": "@EliasVanOotegem - \"The key to a big JavaScript app is to never make it big in the first place.\" = Keep It Simple Stupid! I think Joseph was making the point that you shouldn't add bloat/complexity for the sake of it; not that you can't have big JS apps."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T16:56:21.057",
"Id": "29371",
"ParentId": "29343",
"Score": "3"
}
},
{
"body": "<p>Ok you're definitly headed in the right direction, though there are some things worth mentioning:</p>\n\n<pre><code>function Person(obj)\n{\n this.id = obj.id;\n this.name = obj.name;\n this.surname = obj.surname;\n}\n</code></pre>\n\n<p>You're assuming the user will be kind enough to pass an object to this function, that has three properties readily available. If that's the case, why bother with another constructor? You already have an object, no need to add another prototype to the mix.<br/>You're not even checking for the types of these properties. they could be non-existant (<code>undefined</code>), functions, objects, arrays... anything really, even the argument might be <code>undefined</code>. Consider doing:</p>\n\n<pre><code>function Person(o)\n{\n o = o || {};//default to object literal\n this.id = o.id || 0;//default id\n this.name = (o.name && o.name == (o.name + '') ? o.name : '') + '';//check type, too\n}\n</code></pre>\n\n<p>Ok, you still have the chance someone using this code omits the <code>new</code> keyword when calling the constructor. How do you deal with that? if the function is being called in the global context, <code>this.id</code> will create a global variable, which isn't what you want <em>at all</em>.<br/>\nThere are several ways of dealing with that, starting with the bad way: catching that error and correcting it:</p>\n\n<pre><code>function Person(o)\n{\n if (!this instanceof Person)\n {\n return nuew Person(o);//return new object anyway\n }\n //constructor\n}\n</code></pre>\n\n<p>When a function is called with the <code>new</code> keyword, its call-context will be a new instance of an object, if <code>this</code> is not an instance of <code>Person</code>, it's safe to say the <code>new</code> keyword was omitted. But that's just working around the problem, and leads to BPP (Bad Programming Practice) amongst the users of your code.<br/>\nBetter, but still bad is to silently fail:</p>\n\n<pre><code>if (!this instanceof Person)\n{\n return;//returns undefined\n}\n</code></pre>\n\n<p>This is what some classical OO languages do, too: return <code>void</code>, <code>null</code>, <code>nil</code> or whatever. In JS, not being strongly-typed, this won't result in errors until the variable that was assigned <code>undefined</code> is being used as an object. No telling where this'll happen, so debugging might become troublesome after a while.<br/>\nSo, fail loudly it is:</p>\n\n<pre><code>function Person(o)\n{\n if (!this instanceof Person)\n {\n throw new Error('Person called as function, is a constructor');\n }\n}\n</code></pre>\n\n<p>That looks alright, doesn't it? Of course not! You don't need to perform that type-check every time, if you simply <em>embrace strict-mode</em>:</p>\n\n<pre><code>function Person(o)\n{\n 'use strict';\n o = o || {};\n this.id = o.id || 0;\n}\nPerson({id:123});//error!\nvar p1 = new Person;//OK!\n</code></pre>\n\n<p>That's it. In strict mode, <code>this</code> doesn't default to the global object anymore, but <code>this</code> is <code>null</code>. In JS, and any other language I know of <code>null.id</code> doesn't add up: you can't get a property of a non-object. Great. That's the constructor sorted. Moving on</p>\n\n<pre><code>Person.prototype.toString = function()\n{\n return \"[\"+this.id+\"] name: \" + this.name + \", surname: \" + this.surname;\n};\n</code></pre>\n\n<p>That's OK. You <em>own</em> the <code>Person</code> constructor, so you're free to determine how it's stringified. If ever you come across a situation where this specific <code>toString</code> implementation causes problems, you can easily fix it:</p>\n\n<pre><code>var p1 = new Person;\nmodule.SomFuncThatNeedsDefaultToString(p1);//error because of toString\n//FIX:\np1.toString = {}.toString;//assign this instance the default toString method of an object\nmodule.SomFuncThatNeedsDefaultToString(p1);//works fine!\ndelete p1.toString;//restores the normal Person-behaviour.\n</code></pre>\n\n<p>Next, the <code>PersonDAO</code> constructor and prototype. The object itself merely looks like a wrapper around a single <code>Array</code> instance, so <em>why?</em>, why not use:</p>\n\n<pre><code>var personDAO = [];\npersonDAO.save = personDAO.push;//create an alias if you will\npersonDAO.getAll = function(copy)\n{\n copy = !!copy;//coerce to boolean\n if (copy === true)\n {\n return this.slice(0);//shallow copy\n }\n return this;\n};\npersonDAO.toString = (function(nativeToString)\n{\n return function()\n {\n for (var i=0;i<this.length;i++)\n {\n this[i] = this[i].toString();//stringify Person instances\n }\n return nativeToString.call(this);\n };\n}(personDAO.toString));\n</code></pre>\n\n<p>This allows you to access, the objects you've stored into the array using either their numeric index, or any custom method you've attached to that particular instance of <code>Array</code>. Go nuts, basically. You <em>could</em> create your own constructor, and keep track of all the properties that were assigned too it, and create a magic length property (as a function in drag, really), and assign new properties using a numeric name (<code>var a = {}; a[1] = 'property';</code> is valid in js, numbers can be property-names), but such an object was already created <em>for you</em> either use <code>PersonDAO.prototype = [];</code> (and <code>PersonDAO.prototype.constructor = PersonDAO;</code>, but more on that later) to inherit those goodies, or use an array, with its own methods...<br/>\nAnyway, you're assigning an object literal to the <code>PersonDAO</code>'s prototype. There's nothing wrong with that, but you have to be aware of the fact that <code>PersonDAO</code>'s instances will behave slightly different, because you've overriden the prototype's constructor property. </p>\n\n<pre><code>function PersonDAO()\n{\n this.arrayOfPeople = []; \n}\n\nPersonDAO.prototype = {\n save:function(personObj)\n {\n this.arrayOfPeople.push(personObj);\n },\n getAll:function()\n {\n return this.arrayOfPeople;\n }\n};\nvar dao = new PersonDAO;\nif (dao instanceof PersonDAO)\n{\n console.log('this will never show up!');\n}\nvar secondDao = new dao.constructor;//secondDao will be a regular object\n</code></pre>\n\n<p>I'm assuming you've come across code like this:</p>\n\n<pre><code>function Obj1(){}\nfunction Obj2(){}\nObj2.prototype = new Obj1;\nObj2.prototype.constructor = Obj2;//<==!!\n</code></pre>\n\n<p>By assigning an object literal to the <code>prototype</code>, you're essentially doing the same thing:</p>\n\n<pre><code>Obj2.prototype = new Object();//with a number of properties\n</code></pre>\n\n<p>If you ever get round to setting up a complex prototype chain, you will break that chain, by not restoring the constructor reference to point back to the <em>actual</em> constructor function. As a result, you can't use an instance to call the constructor if that constructor is, for some reason, not in scope:</p>\n\n<pre><code>//if PersonDAO was not declared globally:\nfunction someF(daoInstance)\n{\n var PersonDAO = 'just some var',\n tempDao = new daoInstance.constructor;//doesn't work\n tempDao = new PersonDAO;//error string is not a function.\n}\n</code></pre>\n\n<p>In short, it's no big disaster, but it does brake some (possibly) useful features you normally would have.<br/>\nLastly, and this is perhaps more a personal thing: JS takes a lot of abuse, and allows you to <em>mimic</em> classical OO constructions, but it's at its best when using the prototypal model as intended. Couple that with clever/careful use of closures and you'll soon find your code far more performant and <em>a lot</em> more stable:</p>\n\n<pre><code>var personModule = (function()\n{\n 'use strict';\n var properties = ['id','name','surname'],\n Person = (function(default)\n {\n return function(o)\n {\n o = o || default;\n for (var i=0;i<properties.length;i++)\n {\n this[properties[i]] = o[properties[i]] || default[properties[i]];\n }\n };\n }({id:0,name:'',surname:undefined}));\n Person.prototype.toString = function()\n {\n var i, str = '';\n for (i=0;i<properties.length;i++)\n {\n str += i=== 0 ? '[' + this[properties[i]] + ']' : ' ' + properties[i] + ': ' + this[properties[i]];\n }\n return str;\n };\n return {Person: Person};\n}());\n//usage:\nvar johnDoe = new personMode.Person({id: 0, name: 'John', 'surname': 'Doe'});\n</code></pre>\n\n<p>And do the same thing for the <code>PersonDOA</code>, inside the personModule, and return <code>{Person: Person, PersonDOA: PersonDOA}</code> and you're there. Adding getters and setters is a doddle, too, change the <code>Person</code> constructor, by adding:</p>\n\n<pre><code>this.instanceProperties = properties.slice(0);\n</code></pre>\n\n<p>To give each instance a copy of the properties array. Then add these two methods to the prototype:</p>\n\n<pre><code>Person.prototype.set = function(name, value)\n{\n if (!this.hasOwnProperty(name))\n {\n this.instanceProperties.push(name);\n }\n this[name] = value;\n return this;//chainable\n};\nPerson.prototype.get = function(name)\n{\n if (this.hasOwnProperty(name))\n {\n return this[name];\n }\n for (var i = 0;i<this.instanceProperties.length;i++)\n {\n if (this.instanceProperties[i] === name)\n {\n this.instanceProperties.splice(i,1);//remove element from array\n break;\n }\n }\n};\n</code></pre>\n\n<p>Of course, you'll have to change the <code>toString</code> method, too: instead of looping over <code>properties</code>, you'll have to loop over <code>this.instanceProperties</code>, and check for undefined values.</p>\n\n<p>But all this will possibly give you enough food for thought, so good luck with learning JS, it's a great little language that, but Oh so underrated...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T13:05:06.793",
"Id": "29493",
"ParentId": "29343",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T15:38:19.707",
"Id": "29343",
"Score": "4",
"Tags": [
"javascript"
],
"Title": "JavaScript - prototype, getters, setters, functions"
}
|
29343
|
<p>As this new approach differs from my previous revisions, it shouldn't need references to them.</p>
<p>After receiving much guidance from CR chat, I ended up utilizing these things:</p>
<ul>
<li><code>enum</code>s for the <code>Rank</code> and <code>Suit</code> instead of arrays</li>
<li>a <code>namespace</code> for the <code>enum</code>s and <code>Card</code> class</li>
<li><code>to_string()</code>s for representing the Ranks and Suits as <code>std::string</code>s in <code>operator<<</code></li>
<li>no longer having <code>operator<<</code> as a <code>friend</code></li>
<li>two <code>std::vector</code>s for the <code>Deck</code> class (for retaining the original deck when resetting)</li>
</ul>
<p>I'd like to know if there's still more that can be done, and I have some questions:</p>
<ol>
<li>Is using two vectors an effective way of preserving the deck (as opposed to giving the consuming code the responsibility to return the cards to the deck)?</li>
<li>Should something else be done with the <code>enum</code>s in case the user doesn't know which Suits are in which order (when filling the deck with cards)?</li>
<li>Although <code>enum</code>s are built-in, is <code>const&</code> still good for <code>Card</code>'s constructor?</li>
<li>Is having the user call <code>empty()</code> on the deck good enough so as to avoid complications with exception-handling within the class?</li>
<li>Could the two <code>to_string()</code>s for Rank and Suit be shortened while still resembling a look-up table?</li>
</ol>
<p>Any other feedback is appreciated as well. Beyond these aspects, I desire overall maintainability for adapting to different games (such as adding a Joker). As such, I don't want to hurt the base design with features only associated with a few games.</p>
<p><strong>Card.h</strong></p>
<pre><code>#ifndef CARD_H
#define CARD_H
#include <iostream>
#include <string>
namespace card
{
enum Rank {Ace,Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten,Jack,Queen,King};
enum Suit {Clubs,Diamonds,Hearts,Spades};
class Card
{
private:
Rank m_rank;
Suit m_suit;
std::string to_string(Rank const&) const;
std::string to_string(Suit const&) const;
public:
Card(Rank const&, Suit const&);
std::string to_string() const;
Rank rank() const {return m_rank;}
Suit suit() const {return m_suit;}
};
}
card::Rank& operator++(card::Rank&);
card::Suit& operator++(card::Suit&);
std::ostream& operator<<(std::ostream&, card::Card const&);
#endif
</code></pre>
<p><strong>Card.cpp</strong></p>
<pre><code>#include "Card.h"
#include <stdexcept>
card::Card::Card(Rank const& rank, Suit const& suit)
: m_rank(rank), m_suit(suit) {}
std::string card::Card::to_string(Rank const& rank) const
{
switch (rank)
{
case Ace: return "A";
case Two: return "2";
case Three: return "3";
case Four: return "4";
case Five: return "5";
case Six: return "6";
case Seven: return "7";
case Eight: return "8";
case Nine: return "9";
case Ten: return "T";
case Jack: return "J";
case Queen: return "Q";
case King: return "K";
default: throw std::logic_error("Invalid Rank");
}
}
std::string card::Card::to_string(Suit const& suit) const
{
switch (suit)
{
case Clubs: return "C";
case Diamonds: return "D";
case Hearts: return "H";
case Spades: return "S";
default: throw std::logic_error("Invalid Suit");
}
}
std::string card::Card::to_string() const
{
return ("[" + to_string(m_rank) + to_string(m_suit) + "]");
}
card::Rank& operator++(card::Rank& r)
{
return r = card::Rank(static_cast<int>(r)+1);
}
card::Suit& operator++(card::Suit& s)
{
return s = card::Suit(static_cast<int>(s)+1);
}
std::ostream& operator<<(std::ostream& out, card::Card const& obj)
{
return out << obj.to_string();
}
</code></pre>
<p><strong>Deck.h</strong></p>
<pre><code>#ifndef DECK_H
#define DECK_H
#include <vector>
class Deck
{
private:
std::vector<card::Card> m_original; // retains original cards when resetting deck
std::vector<card::Card> m_playable; // cards are drawn from this one
public:
typedef std::vector<card::Card>::size_type SizeType;
void reset();
void shuffle();
void add(card::Card const&);
card::Card draw();
SizeType size() const {return m_playable.size();}
bool empty() const {return m_playable.empty();}
};
#endif
</code></pre>
<p><strong>Deck.cpp</strong></p>
<pre><code>#include "Card.h"
#include "Deck.h"
#include <algorithm>
void Deck::reset()
{
// is this already exception-safe by itself?
m_playable = m_original;
}
void Deck::shuffle()
{
// my tests tell me that an empty vector will not cause this to fail
std::random_shuffle(m_playable.begin(), m_playable.end());
}
void Deck::add(card::Card const& card)
{
// new cards always added to both vectors
m_original.push_back(card);
m_playable.push_back(card);
}
card::Card Deck::draw()
{
// still not exception-safe, unless not needed if handled in client
card::Card topCard(m_playable.back());
m_playable.pop_back();
return topCard;
}
</code></pre>
|
[] |
[
{
"body": "<h3>General notes</h3>\n\n<ul>\n<li><p>The <code>to_string</code>s for <code>Rank</code> and <code>Suit</code> do not belong in the <code>Card</code> class. Move them out of the class and into the <code>card</code> namespace instead. They can be useful functions for client code as well.</p></li>\n<li><p>I personally dislike the <code>m_</code> prefix. Normally you can just use normal variable names instead. If you must have a naming scheme for member variables, I think <code>foo_</code> is more readable. That way my eyes won't have to discard the <code>m_</code> before getting to the real name.</p></li>\n<li><p>I'd put spaces inside braces and after commas to increase readability:</p>\n\n<pre><code>bool empty() const { return m_playable.empty(); }\nenum Suit { Clubs, Diamonds, Hearts, Spades };\n</code></pre>\n\n<p>Put the <code>enum</code> definitions on multiple lines if you think the line gets too wide.</p></li>\n<li><p>I'd indent the <code>case</code>s in a <code>switch</code> with only single-line cases. Readability trumps consistency:</p>\n\n<pre><code>switch (suit) {\n case Clubs: return \"C\";\n case Diamonds: return \"D\";\n case Hearts: return \"H\";\n case Spades: return \"S\";\n default: throw std::logic_error(\"Invalid Suit\");\n}\n</code></pre></li>\n<li><p>\"<em>My tests tell me that ...</em>\" In C++, where so much is unspecified and undefined, we rely on the standard and/or references, and not on tests. In this case it's easy to be on the safe side:</p>\n\n<pre><code>void Deck::shuffle()\n{\n if (m_playable.empty()) return;\n\n std::random_shuffle(m_playable.begin(), m_playable.end());\n}\n</code></pre></li>\n<li><p>Regarding exception safety for <code>Desk::reset</code>: <code>std::vector::operator=</code> gives the <strong><a href=\"http://en.wikipedia.org/wiki/Exception_safety\" rel=\"nofollow\">basic exception safety guarantee</a></strong>: If the assignment operator throws, the objects will be in a valid state. Since <code>m_playable</code> already has the required capacity, I can't think of a reason why it should ever throw anyway.</p></li>\n<li><p><code>Deck::draw()</code> is exception-safe: <code>std::list::pop_back</code> will never throw. See below.</p></li>\n<li><p>Your <code>Card.h</code> header should include <code><ostream></code> instead of <code><iostream></code>. Since you only need the <code>std::ostream</code> <em>declaration</em>, you could simply include <code><iosfwd></code> and include <code><ostream></code> in <code>Card.cpp</code> instead.</p></li>\n<li><p>Is there a reason why op++ and op<< for <code>Card</code> isn't in the <code>card</code> namespace?</p></li>\n<li><p>You should write unit tests and document your interface.</p></li>\n</ul>\n\n<hr>\n\n<h3>Answers for your questions</h3>\n\n<blockquote>\n <p>Is using two vectors an effective way of preserving the deck (as opposed to giving the consuming code the responsibility to return the cards to the deck)?</p>\n</blockquote>\n\n<p>I think it is. Asking client code to return the cards is too demanding.</p>\n\n<hr>\n\n<blockquote>\n <p>Should something else be done with the <code>enum</code>s in case the user doesn't know which Suits are in which order (when filling the deck with cards)?</p>\n</blockquote>\n\n<p>The client code should be perfectly able to handle this as it is. If it doesn't want to use your increment operator, it can simply define four loops when populating the deck, or even implement its own function to iterate the suits.</p>\n\n<hr>\n\n<blockquote>\n <p>Although <code>enum</code>s are built-in, is <code>const&</code> still good for <code>Card</code>'s constructor?</p>\n</blockquote>\n\n<p>Pass <code>enum</code>s by value.</p>\n\n<hr>\n\n<blockquote>\n <p>Is having the user call <code>empty()</code> on the deck good enough so as to avoid complications with exception-handling within the class?</p>\n</blockquote>\n\n<p>Yes. As it is, <code>Deck::draw()</code> has the <strong>strong exception safety guarantee</strong>: If something goes wrong, it will be rolled back to its original state. In this case you get this for free: <code>std::list::pop_back()</code> has a <strong>nothrow</strong> guarantee. That means that the only operation in <code>draw()</code> that can fail is calling <code>m_playable.back()</code>, and that doesn't modify the container. As long as that call succeeds, the entire function will as well.</p>\n\n<hr>\n\n<blockquote>\n <p>Could the two <code>to_string()</code>s for Rank and Suit be shortened while still resembling a look-up table?</p>\n</blockquote>\n\n<p>I think the way you have done it is fine. You could use a <code>std::map</code>, but that approach has no advantages compared to your approach. If you want to do it anyway, you can do it like this:</p>\n\n<pre><code>std::string to_string(Rank rank)\n{\n static const map<Rank, string> rank_names = { {Ace, \"A\"}, {Two, \"2\"}, {Three, \"3\"} /* ... */ };\n\n return rank_names[rank];\n}\n</code></pre>\n\n<p>Note that this has O(<em>n</em> log <em>n</em>) lookup time, whereas your implementation is likely to be O(1). You could also define an array and use the <code>enum</code> values as indices. That would also be O(1), but there's still no point -- and that approach violates the abstraction.</p>\n\n<hr>\n\n<p>Finally, I have a question for you: How would you implement a joker?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T22:07:25.563",
"Id": "46348",
"Score": "0",
"body": "+1 great stuff yet again. Relieving feedback for the exception-handing. Regarding `std::map`: ignore what I said about it in chat (if you happened to read it). I soon realized that it would be ineffective as a replacement to `switch` (it would be re-created after each call). Unfortunately, I cannot initialize it like you've mentioned due to compiler constraints. Had this not been an issue, I could easily make it `static const` and left a happy camper."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T22:11:45.707",
"Id": "46349",
"Score": "0",
"body": "A *non-rhetorical* question for me? I love the way you think. :-) As it so happens, I *have* been thinking about this. I came up with the following points: 1.) they greatly vary from game-to-game, 2.) they don't have a rank and suit, thus my Card class cannot support one, and 3.) as its role (based on the game) vary, the basic implementation of a joker would be quite limited. The third point propels me to my first solution: give it its own class. Putting it in Card seems like a bad idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T22:12:27.573",
"Id": "46350",
"Score": "0",
"body": "How would you then mix it with `Deck`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T22:13:58.597",
"Id": "46351",
"Score": "0",
"body": "Note that I have updated the answer and added two points. Even if you were able to make a `static const map`, you still shouldn't. The code may be slightly shorter, but it's less effective and about the same in terms of readability."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T22:14:35.187",
"Id": "46352",
"Score": "0",
"body": "Okay, that I haven't quite contemplated, but I'll give it a go: 1.) give Deck another add() specifically for jokers. Looking at its implementation, that looks like the only viable change."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T22:16:26.270",
"Id": "46353",
"Score": "0",
"body": "Ah, right. It would be less-readable. Some of my research has shown that a map *could* be a replacement at times, even though `switch` is built-in. Of course, the latter is still more readable, but also O(1) is most cases."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T22:19:46.360",
"Id": "46354",
"Score": "0",
"body": "Please explain in chat why (or possibly when) you would want to use std::map instead :-)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T21:59:08.677",
"Id": "29351",
"ParentId": "29348",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29351",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T20:11:02.497",
"Id": "29348",
"Score": "4",
"Tags": [
"c++",
"playing-cards"
],
"Title": "Newest approach to deck of cards project"
}
|
29348
|
<p>I need a <code>copy_if_max()</code> function, i.e. copy all the elements in an input range that are equal to the max in that range. The most obvious implementation does two passes over the data:</p>
<pre><code>template<class InputIt, class OutputIt>
OutputIt copy_if_max2(InputIt first, InputIt last, OutputIt dst)
{
using T = typename InputIt::value_type;
auto m = *std::max_element(first, last);
return std::copy_if(first, last, dst, [&](T const& elem) {
return elem >= m; // NOTE: not elem == m, because we use equivalence, not equality
});
}
</code></pre>
<p>This is all nice and dandy (\$O(N)\$ complexity). However, for true input ranges, the two passes over the input data are a no go. </p>
<p>Note also that the maximum of the input range is defined in terms of an <code>operator<</code> that defines an <strong>equivalence</strong> relation, and not necessarily an <strong>equality</strong> relation. The suggested single-pass answer by @Yuushi would therefore not work.</p>
<p>I've come up with what I call a <strong>clearable</strong> <code>back_inserter</code>, that will reset the output range whenever the max is updated. I do that by having an assignment operator that takes a <code>nullptr_t</code> argument (which takes precedence in overload resolution over all other pointers, so even if the actual data would contain a <code>nullptr</code>, this would not match!). Furthermore, there is an implicit conversion to <code>std::size_t</code> so I can detect the underlying output container size. </p>
<pre><code>template<class Container>
class clearable_back_insert_iterator
:
public std::iterator< std::output_iterator_tag, void, void, void, void >
{
private:
Container* c_;
public:
using self_t = clearable_back_insert_iterator;
using value_type = typename Container::value_type;
clearable_back_insert_iterator(Container& c): c_(&c) {}
operator std::size_t() { return c_->size(); }
self_t& operator=(value_type const& v)
{
std::cout << "push_back \n";
c_->push_back(v);
return *this;
}
self_t& operator=(std::nullptr_t)
{
std::cout << "clear \n";
c_->clear();
return *this;
}
self_t& operator*() { return *this; }
self_t& operator++() { return *this; }
self_t& operator++(int) { return *this; }
};
template<class Container>
clearable_back_insert_iterator<Container> clearable_back_inserter(Container& c)
{
return clearable_back_insert_iterator<Container>(c);
}
</code></pre>
<p>This allows me to write a single-pass <code>copy_if_max1()</code> that uses a <code>clearable_back_inserter</code> and a <code>std::transform()</code>:</p>
<pre><code>template<class InputIt, class OutputIt>
OutputIt copy_if_max1(InputIt first, InputIt last, OutputIt dst)
{
using T = typename InputIt::value_type;
auto m = std::numeric_limits<T>::min();
std::transform(first, last, dst, [&](T const& elem) {
if (dst == 0) { // size()
m = elem;
return dst = elem; // push_back()
}
if (m <= elem) {
if (m != elem) {
m = elem;
dst = nullptr; // clear()
}
dst = elem; // push_back()
}
return dst;
});
return dst;
}
</code></pre>
<p><a href="http://coliru.stacked-crooked.com/view?id=ebfec5d2b00e3f27ba9d52fa68aae8e7-b3a39f4e9c268c2df146ea17ecc4d5fd" rel="nofollow"><strong>Live example.</strong></a> I realize that this one-pass version does more copying because it will copy all elements of the input range as long as they match the intermediate maximum, only to be cleared whenever the max is updated. </p>
<p>My <strong>questions</strong>:</p>
<ul>
<li>Which points in this design would you critique?</li>
<li>Do you think clearable back_inserters are a good and reusable concept?</li>
<li>Should I use named members <code>size()</code> and <code>clear()</code> instead of conversion to <code>size_t</code> and assignment from <code>nullptr</code>?</li>
<li>Does Boost have some other alternatives (<code>filter_iterator</code> perhaps?)</li>
<li>Is it better to avoid the complications altogether and use the two-pas version <code>copy_if_max2()</code> (perhaps with a full copy of the input to allow multi-passes)?</li>
</ul>
|
[] |
[
{
"body": "<p>I think you're overcomplicating the solution a bit. Since you're making copies of what is the maximum in the range, all you need is something that keeps a value to store the current max, and another which keeps a count of the number of maximum values that have been found in the input data. For example:</p>\n\n<pre><code>#include <iterator>\n\ntemplate <typename InputIter, typename OutputIter>\nvoid copy_if_max(InputIter begin, InputIter end, OutputIter out_begin)\n{\n std::size_t count = 1;\n typedef typename std::iterator_traits<InputIter>::value_type T;\n\n if(begin == end) return;\n\n T current_max = *begin;\n ++begin;\n\n while(begin != end) {\n if(*begin > current_max) {\n current_max = *begin;\n count = 1;\n } \n else if(*begin == current_max) {\n ++count;\n }\n ++begin;\n }\n\n for(std::size_t i = 0; i < count; ++i) {\n *out_begin++ = current_max;\n }\n}\n</code></pre>\n\n<p>Note that this solution also uses <code>std::iterator_traits<T></code>, which you should be using instead of relying on the <code>InputIterator</code> passed having a nested <code>value_type</code> typedef (which will of course be false if it is passed a <code>T*</code>, for example).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T10:05:00.203",
"Id": "46374",
"Score": "0",
"body": "thanks, this would be a good solution (and therefore +1) if the input range contains non-class types. However, (and I didn't mention this in my original question, sorry!) the maximum over the input range is defined in terms of an equivalence relation `operator<`, e.g. the age of a `Person` class. The `copy` part of the algorithm needs to also copy the other parts of the input range, not just the member that defines the max. Do you have ideas to accomodate this more generalized behavior?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T13:48:42.363",
"Id": "46379",
"Score": "0",
"body": "@TemplateRex Ah, fair enough - that changes it somewhat. Let me have a think about it..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T14:58:49.307",
"Id": "46473",
"Score": "0",
"body": "@TemplateRex I can't really see any problems with your solution, and having thought about it more, I don't think I'm going to come up with anything better. As you've mentioned, if it really is an input iterator, the two pass algorithm will be a no go. I think your design is in general reasonable (although I'm not a fan of implicit conversions)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T08:50:52.627",
"Id": "29365",
"ParentId": "29349",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29365",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T20:23:47.350",
"Id": "29349",
"Score": "3",
"Tags": [
"c++",
"algorithm",
"c++11",
"stl",
"iterator"
],
"Title": "copy_if_max() algorithm"
}
|
29349
|
<p>Currently, in my games, I'm using <code>new</code> and <code>delete</code> to create entities and components. It works fine, but there are slowdowns when creating/deleting many (5000+) entities or components at once.</p>
<p>After <a href="https://stackoverflow.com/questions/17789815/custom-heap-pre-allocation-for-entity-component-system/">asking for advice on StackOverflow</a>, I decided to create my own memory pre-allocator.</p>
<ul>
<li>It allocates a specific amount of memory on the heap when constructed.</li>
<li>It creates objects on "pieces" of the allocated memory by using <code>Preallocator::create<T>()</code></li>
<li>It destroys (calls destructor and reclaims memory "pieces") objects with <code>Preallocator::destroy<T></code></li>
<li>It holds no specific type - it can hold different type of objects at once</li>
<li>It is faster than using <code>new</code> and <code>delete</code>.</li>
</ul>
<p><strong>But is it ready to use in production code?</strong></p>
<p><strong>Could it be even faster?</strong></p>
<hr>
<pre><code>class PreAllocator
{
private:
constexpr static unsigned int bufferSize{1000};
using MemoryUnit = char;
using MemoryPtr = MemoryUnit*;
struct Piece
{
// Piece is a range of memory [begin, end)
MemoryPtr begin, end;
inline Piece(MemoryPtr mStart, MemoryPtr mEnd) : begin{mStart}, end{mEnd} { }
inline size_t getSize() const { return sizeof(MemoryUnit) * (end - begin); }
};
MemoryUnit* buffer{new MemoryUnit[bufferSize]};
vector<Piece> available;
inline void unifyFrom(unsigned int mIndex)
{
auto lastEnd(available[mIndex].end);
auto itr(std::begin(available) + mIndex + 1);
for(; itr != std::end(available); ++itr)
if(itr->begin == lastEnd) lastEnd = itr->end;
else break;
available.erase(std::begin(available) + mIndex, itr);
available.emplace_back(available[mIndex].begin, lastEnd);
}
inline void unifyContiguous()
{
std::sort(std::begin(available), std::end(available), [](const Piece& mA, const Piece& mB){ return mA.begin < mB.begin; });
for(unsigned int i{0}; i < available.size(); ++i) unifyFrom(i);
}
inline std::vector<Piece>::iterator findSuitableMemory(size_t mRequiredSize)
{
// Tries to find a memory piece big enough to hold mRequiredSize
// If it is not found, contiguous memory pieces are unified
// If it is not found again, throws an exception
for(int i{0}; i < 2; ++i)
{
for(auto itr(std::begin(available)); itr != std::end(available); ++itr) if(itr->getSize() >= mRequiredSize) return itr;
unifyContiguous();
}
throw;
}
public:
PreAllocator()
{
// Add the whole buffer to the available memory vector
available.emplace_back(&buffer[0], &buffer[bufferSize]);
}
~PreAllocator() { delete[] buffer; }
template<typename T> inline T* create()
{
// Creates and returns a T* allocated with "placement new" on an available piece of the buffer
// T must be the "real object type" - this method will fail with pointers to bases that store derived instances!
auto requiredSize(sizeof(T));
auto suitable(findSuitableMemory(requiredSize));
MemoryPtr toUse{suitable->begin};
Piece leftover{toUse + requiredSize, suitable->end};
available.erase(suitable);
if(leftover.getSize() > 0) available.push_back(leftover);
return new (toUse) T;
}
template<typename T> inline void destroy(T* mObject)
{
// Destroys a previously allocated object, calling its destructor and reclaiming its memory piece
// T must be the "real object type" - this method will fail with pointers to bases that store derived instances!
mObject->~T();
auto objStart(reinterpret_cast<MemoryPtr>(mObject));
available.emplace_back(objStart, objStart + sizeof(T));
}
};
</code></pre>
<hr>
<p>Test/benchmark:</p>
<pre><code>struct ObjBase { };
struct TestObj : ObjBase { char data[100]; };
struct TestObjBig : ObjBase { char data[500]; };
int main()
{
PreAllocator p;
startBenchmark();
{
for(int k = 0; k < 10000; ++k)
{
vector<TestObj*> objs;
vector<TestObjBig*> objsbig;
for(int n = 0; n < 300; ++n)
{
for(int i = 0; i < 5; ++i) objs.push_back(p.create<TestObj>());
for(int i = 0; i < 5; ++i) p.destroy(objs[i]);
objs.clear();
}
for(int n = 0; n < 100; ++n)
{
for(int i = 0; i < 2; ++i) objsbig.push_back(p.create<TestObjBig>());
for(int i = 0; i < 2; ++i) p.destroy(objsbig[i]);
objsbig.clear();
}
}
}
string b1 = endBenchmark();
startBenchmark();
{
for(int k = 0; k < 10000; ++k)
{
vector<TestObj*> objs;
vector<TestObjBig*> objsbig;
for(int n = 0; n < 300; ++n)
{
for(int i = 0; i < 5; ++i) objs.push_back(new TestObj());
for(int i = 0; i < 5; ++i) delete objs[i];
objs.clear();
}
for(int n = 0; n < 100; ++n)
{
for(int i = 0; i < 2; ++i) objsbig.push_back(new TestObjBig());
for(int i = 0; i < 2; ++i) delete objsbig[i];
objsbig.clear();
}
}
}
string b2 = endBenchmark();
cout << b1 << endl; // prints "193ms"
cout << b2 << endl; // prints "957ms"
return 0;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T22:28:22.950",
"Id": "46355",
"Score": "1",
"body": "Why don't you use [Boost.Pool](http://www.boost.org/doc/libs/1_54_0/libs/pool/doc/html/index.html)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T04:22:22.380",
"Id": "46367",
"Score": "0",
"body": "Not convinced your benchmarks are very useful. They do a very simple situation that does not seem to exercise your code very much."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T09:29:45.837",
"Id": "46371",
"Score": "0",
"body": "@Lstor: I do not want to introduce a Boost dependency in my projects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T09:30:21.590",
"Id": "46372",
"Score": "0",
"body": "@LokiAstari: How can I improve my benchmark? What cases do I have to take into account?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T15:29:15.763",
"Id": "46383",
"Score": "0",
"body": "@VittorioRomeo: Run your `real` code. But put print statements in your constructors and destructors to get an idea of the number of objects being created and destroyed (and an approximate order). Then write a benchmark that imitates a real run of your application."
}
] |
[
{
"body": "<h3>Big Issue:</h3>\n<p>Alignment. You do not consider alignment. You may not need too. But you should definitely comment the code to explain how it can be used.</p>\n<pre><code>p.create<char>();\np.create<int>(); // This will probably crash\n</code></pre>\n<p>Unlike new you don't support objects that don't have a default constructor. Using the C++11 varargs this should be easily doable:</p>\n<pre><code>template<typename T, typename... Args>\nT* PreAllocator::create(Args... args)\n{\n .. STUFF ..\n\n // Not 100% sure the syntax is perfect\n // And I have not tried this. SO experiments and verification are in order\n return new (toUse) T(args...);\n}\n</code></pre>\n<p>I am not convinced your benchmarks are representative of what you are code would do. That looks like an awfully simple test.</p>\n<p>Also the order you do things can be important in benchmarking so putting both tests into the same executable is not a good idea. Build separate executables for each benchmark then run the tests independently. This way you know that both systems start off with a clean environment to test in.</p>\n<p>Rather than use the allocator object directly why not overload the new/delete operators for the classes you want. Then you can turn your allocator on/off as appropriate without searching the code and modifying <code>create => new</code> etc.</p>\n<h3>Code Review</h3>\n<pre><code> // Does not seem like a very big buffer.\n // surprised the general purpose allocator is not working for you.\n constexpr static unsigned int bufferSize{1000};\n</code></pre>\n<p>Avoid the use of <code>inline</code> unless it is needed. And it is not needed here.</p>\n<pre><code> inline void unifyFrom(unsigned int mIndex)\n</code></pre>\n<p>Avoid use of <code>auto</code> for this type of case. Here the types of the variables provided contextual meaning to the reader. Here I found myself thinking lastEnd was an iterator and it took me several reads to actually work out what it was.</p>\n<pre><code> auto lastEnd(available[mIndex].end);\n</code></pre>\n<p>I am fine with <code>auto</code> for iterators. As there creation is obvious and I don't need to know the exact type. Just the fact that it is an iterator.</p>\n<pre><code> auto itr(std::begin(available) + mIndex + 1);\n</code></pre>\n<p>Note: Not all iterators support <code>+</code> as an operator. Prefer to use <code>std::advance()</code></p>\n<p>Why erase all then put at the back? You break up space locality in the data if there are lots of pieces being allocated and deallocated in a random orders.</p>\n<pre><code> available.erase(std::begin(available) + mIndex, itr);\n available.emplace_back(available[mIndex].begin, lastEnd);\n</code></pre>\n<p>I would erase all the items after the current one. Then update the current one with its new size. That way you keep the correct ordering. Thus reducing sorting costs.</p>\n<p>Also the way you have done it will not work correctly with <code>unifyContiguous()</code>. As the element after a squished block now becomes the ith element. The loop will advance to the next element so each <code>Piece</code> after a squished set of blocks is not considered for squishing in the next block set.</p>\n<p>This is not legal:</p>\n<pre><code> throw;\n</code></pre>\n<p>The only time that <code>throw</code> is valid is during an exception handler (and functions called from the exception handler) where there is currently propagating exception (when the exception handler finishes the exception is dead unless re-thrown.</p>\n<p>OK Good.</p>\n<pre><code> PreAllocator()\n ~PreAllocator() { delete[] buffer; }\n</code></pre>\n<p>But you forgot the rule of 3(or 5). So you need to define (or undefine) the copy constructor and assignment operator.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T09:55:00.433",
"Id": "46373",
"Score": "0",
"body": "Thanks for the advice. I'm new to Code Review - should I update the original post with the improved code to get further feedback?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T14:46:25.323",
"Id": "46381",
"Score": "0",
"body": "It depends on the level of changes. If they are substantial, I think it's better to start a new post."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T15:01:27.493",
"Id": "46382",
"Score": "0",
"body": "`PreAllocator::create` should return `T*`, not `void`. I was surprised to see that `throw;` does in fact compile."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T15:36:10.463",
"Id": "46385",
"Score": "0",
"body": "@Lstor: `thorw;` is perfectly valid statement. BUT it can only be used in the context of an exception handler were it means re-throw the currently propagating exception. The trouble doing the static analysis to see if the statement is being used in the correct context is beyond the scope of the compiler (this is not a compiler solvable problem). Remember that an exception handler can call any function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T15:36:54.347",
"Id": "46386",
"Score": "0",
"body": "`throw;` was just a placeholder to make the program crash when there was no more memory. I would never use something like that in production code, sorry if I've been misleading"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T15:38:20.457",
"Id": "46387",
"Score": "1",
"body": "@VittorioRomeo: When I am using it as a placeholder I do `throw 1;` It throws an integer. And they are easy to find with a grep at the end to make sure you have not missed any."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T15:53:16.627",
"Id": "46388",
"Score": "0",
"body": "@LokiAstari Ah, yes, you are absolutely right of course. I looked it up in the grammar as well, which states that anything after `throw` is optional. So the rules are stricter than the grammar in this case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T15:59:11.030",
"Id": "46390",
"Score": "0",
"body": "@Lstor: The semantics of a language add constraints on top of the grammar. There are a lot of places where it is grammar correct but not semantically correct."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T04:08:21.650",
"Id": "29360",
"ParentId": "29350",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "29360",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T21:52:26.913",
"Id": "29350",
"Score": "2",
"Tags": [
"c++",
"performance",
"c++11",
"memory-management",
"heap"
],
"Title": "Heap memory preallocation (intended for games)"
}
|
29350
|
<p>I've hacked together what feels like a mess for an authorize attribute to secure web api methods. The code appears to be functionally correct; passing the unit tests in place. The code has me worried because it will be executing with every call to any web api method and there is a lot going on, including string allocations and database access. I'm sure that a lot of my misgivings are due to premature optimization.</p>
<p>I am looking for a general review of the code; looking for obvious problems, possible performance bottlenecks etc.</p>
<p>The use of this attribute provides for three different scenarios. First, specifying the attribute with no users or roles means that the attribute should simply validate that the supplied user/password authenticate properly. Second, the attribute supports a comma separated list of usernames... so in addition to authenticating the user, it should also verify the user is in the permitted list. Finally, the attribute allows a comma separated list to denote allowed roles... this requires the user to authenticate and to be a member of one of the provided roles. The semantics are such with regard to user or role lists, passing either condition in additional to authenticating successfully should return a true result.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Security;
using WebMatrix.WebData;
using Appsomniacs.Web.Filters;
namespace Appsomniacs.Web.Handlers
{
public class BasicAuthorizeAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var identity = Thread.CurrentPrincipal.Identity;
if (identity == null &&
HttpContext.Current != null)
{
identity = HttpContext.Current.User.Identity;
}
if (identity != null &&
identity.IsAuthenticated)
{
var basicAuth = identity as BasicAuthenticationIdentity;
if (basicAuth != null)
{
if (WebSecurity.Login(basicAuth.Name, basicAuth.Password))
{
if (this.Users.Length > 0)
{
var allowedUsers = this.Users.ToUpperInvariant()
.Split(',');
if (allowedUsers.Contains(basicAuth.Name.ToUpperInvariant()))
{
return true;
}
}
if (this.Roles.Length > 0)
{
var allowedRoles = Roles.Split(',');
var userRoles = System.Web.Security.Roles.GetRolesForUser(basicAuth.Name);
var matches = userRoles.Intersect(allowedRoles).ToArray();
if (matches.Length > 0)
{
return true;
}
}
else
{
return true;
}
}
}
}
return false;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>How about something like this. It's pretty much what you have but all I have done is seperated a couple of the parts into methods</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Web;\nusing System.Web.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Security;\nusing WebMatrix.WebData;\n\nusing Appsomniacs.Web.Filters;\n\nnamespace Appsomniacs.Web.Handlers\n{\n public class BasicAuthorizeAttribute : AuthorizeAttribute\n {\n protected override bool IsAuthorized(HttpActionContext actionContext)\n {\n var identity = Thread.CurrentPrincipal.Identity;\n\n if (identity == null && HttpContext.Current != null)\n {\n identity = HttpContext.Current.User.Identity;\n }\n\n if (identity != null && identity.IsAuthenticated)\n {\n var basicAuth = identity as BasicAuthenticationIdentity;\n\n if (basicAuth != null)\n {\n if (WebSecurity.Login(basicAuth.Name, basicAuth.Password))\n {\n return IsAllowedUser(basicAuth.Name) || IsAutenticatedInRole(basicAuth.Name);\n }\n }\n }\n\n return false;\n }\n\n private bool IsAllowedUser(string name) \n {\n if(this.Users.Length == 0) return false;\n\n var allowedUsers = this.Users.ToUpperInvariant()\n .Split(',');\n\n return allowedUsers.Contains(basicAuth.Name.ToUpperInvariant()); \n }\n\n private bool IsAutenticatedInRole(string name) \n {\n if (this.Roles.Length > 0)\n {\n var userRoles = System.Web.Security.Roles.GetRolesForUser(basicAuth.Name);\n\n var allowedRoles = Roles.Split(',');\n var matches = userRoles.Intersect(allowedRoles).ToArray();\n\n return matches.Length > 0;\n }\n\n return true; \n }\n } \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T03:44:38.283",
"Id": "46363",
"Score": "0",
"body": "That is a much cleaner implementation, I appreciate the review and improvement suggestions. Thank you!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T04:14:14.427",
"Id": "46366",
"Score": "0",
"body": "No problem. One suggestion though. If you leave your question open for a day or so (i.e. not accepted) you are more likely to get some other people offering answers. Just might give you some more ideas or perspectives."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T06:21:20.507",
"Id": "46369",
"Score": "0",
"body": "Fair enough :) I wanted to make sure you got credit for taking the time. I think your refactor is pretty solid and I'm glad I decided to post here instead of rolling with the hacked up version... much clearer. We'll see if anyone has something else to contribute and if not I'll make sure to hit the answer button again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T07:14:51.667",
"Id": "46370",
"Score": "0",
"body": "In the meantime you can almost upvote the answer instead :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T02:10:26.117",
"Id": "29358",
"ParentId": "29353",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "29358",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T22:43:00.587",
"Id": "29353",
"Score": "7",
"Tags": [
"c#",
"asp.net-mvc-4"
],
"Title": "Custom System.Web.Http.AuthorizeAttribute"
}
|
29353
|
<p>I try to implement a (restricted version of) step function in Haskell. A step functions is a function that is constant on a finite number of half intervals, and <code>mempty</code> everywhere else. (equivalently, one can fill those "everywhere else" by half intervals)</p>
<p>This can be modeled as a <code>StepData a b</code>, which stores a list of the half intervals and the associated value for that half interval.
Not all <code>Ord a</code> has a minimum or maximum, I lift it to <code>Bound a</code>, which guaranties it to have a minimum and maximum, this is to make the algorithm clearer. </p>
<p>I implemented <code>eval :: StepData a b -> a -> b</code> to evaluate a step function at a point.</p>
<p>The important part is the ability to make step function a monoid, where <code><></code> is defined as pointwise sum of the function. Currently I implemented <code><></code> for the <code>StepData a b</code>.</p>
<p>P.S. Whenever I want to find a value, I have to run <code>eval f x</code>. Of course I can define <code>g = eval f</code>, but I can't use <code><></code> on the derived function. So I have to pass the data around in order to combine functions, and only call <code>eval</code> when I need to find a value. Are there better ways to handle this?</p>
<pre><code>{-# LANGUAGE NoMonomorphismRestriction #-}
import Data.List
import Data.Monoid
data Bound a = Minimum | Value a | Maximum deriving (Eq, Ord, Show)
data StepData x y = StepData [(Bound x, Bound x, y)]
deriving (Show, Eq, Ord)
instance (Ord x, Monoid y) => Monoid (StepData x y) where
mempty = StepData [(Minimum, Maximum, mempty)]
mappend (StepData a) (StepData b) = StepData (foldl insertInterval b a)
where
insertInterval [] _ = []
insertInterval ((a',b',y'):xs) (a,b,y)
| a >= b' = non [(a',b',y')] ++ insertInterval xs (a,b,y)
| b >= b' = non [(a',a,y'),(a,b',y <> y')] ++ insertInterval xs (b',b,y)
| b < b' = non [(a',a,y'),(a,b, y <> y'),(b,b',y')] ++ xs
where non = filter (\(a,b,_)-> a/=b)
merge (h@(a,_,y):h'@(_,b',y'):xs)
| y == y' = merge ((a,b',y):xs)
| otherwise = h:merge (h':xs)
merge x = x
eval (StepData xs) t = y
where (_,_,y) = head $ dropWhile sol xs
sol (a,b,y)
| a<=Value t && Value t<b = False
| otherwise = True
fromList xs = StepData (map (\(a,b,y)->(Value a, Value b, y)) xs) `mappend` mempty
</code></pre>
|
[] |
[
{
"body": "<p>I might be a little bit late to the party, but better late than never, right?</p>\n<h1>Type signatures</h1>\n<p>Your central functions <code>fromList</code> and <code>eval</code> don't have type signatures. This forces the user to check <code>Value</code> and <code>StepData</code>'s definition. Better add them:</p>\n<pre><code>eval :: Ord a => StepData a\neval = ...\n\nfromList :: (Ord a, Monoid b) => [(a, a, b)]-> StepData a b\nfromList = ...\n</code></pre>\n<h1>Remove dead code</h1>\n<p><code>merge</code> isn't used in your code. It's dead code and not used in your instance at all. Better remove it.</p>\n<h1>Make sure the code compiles</h1>\n<p>That wasn't an issue back in 2013, but nowadays <code>Semigroup</code> is a superclass of <code>Monoid</code>, and you need to implement it too.</p>\n<h1>Don't encode <code>Bool</code> twice</h1>\n<p><code>eval</code>'s <code>sol</code> can be simplified a lot if we just use <code>not</code> around the condition:</p>\n<pre><code>eval (StepData xs) t = y\n where (_,_,y) = head $ dropWhile sol xs\n sol (a,b,_) = not (a <= Value t && Value t < b)\n</code></pre>\n<p>The function also gets easier to understand if we use <code>filter</code> instead, as we don't need to deal with double negation (<code>drop</code> and <code>not</code>):</p>\n<pre><code>eval (StepData xs) t = y\n where (_,_,y) = head $ filter sol xs\n sol (a,b,_) = a <= Value t && Value t < b\n</code></pre>\n<h1>Document requirements of data</h1>\n<p><code>fromList</code> needs a proper sorted list. That's not documented anywhere and neither enforced in its type nor its logic. We might end up with <code>StepData [(Value 3, Value 1, Maybe 3)]</code> or <code>StepData [(Value 3, Value 4, Maybe 3),(Value 1, Value 2, Maybe 3)]</code>, as the list is only <code>map</code>ed.</p>\n<p>Instead, use <code>foldMap</code> and make sure that the values are ordered properly:</p>\n<pre><code>fromList = foldMap go\n where\n go (a, b, y)\n | a < b = StepData [(Value a, Value b, y)]\n | otherwise = StepData [(Value b, Value a, y)]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T20:17:21.303",
"Id": "244850",
"ParentId": "29354",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T23:15:32.767",
"Id": "29354",
"Score": "3",
"Tags": [
"haskell"
],
"Title": "Implement step function in Haskell"
}
|
29354
|
<p>I think many know the problem of working with multiple projects: private projects, company projects, probably even projects for multiple companies.</p>
<p>From day-one, I've always searched for better ways to handle all those projects on the file system level. I think I figured out a nice basic directory structure that works for me and my workflow:</p>
<pre><code>~/code/$company_name/$project_name/[$application_name]
</code></pre>
<p>But, even with auto-completion and a <code>$CODE</code> var that pointed to <code>~/code</code>, I had to type a lot more than I wanted when I had to switch between some projects.</p>
<p>So, for the sake of laziness (I also heard some smart guys call it "efficiency," but nah, I'm just lazy) and to learn a bit more about my shell, I decided to write a function that will do some of the work I'm not willing to do.</p>
<p>These were the functional requirements I defined for that function:</p>
<ul>
<li>quickly <code>cd</code> into a project by given company and project name</li>
<li>possibility to add an optional application name for projects with multiple applications</li>
<li>possibility to pass a flag to create new project directories</li>
</ul>
<p>Since I'm still a junior developer (1-year work experience, no degree, autodidact) and don't have much experience with shell-scripting, I'm pretty sure there is a lot to improve in my solution.</p>
<p>And since I'm always on the search for improvements, I decided to show my code to those of whom might be more experienced in this than me.</p>
<pre><code>function pcd () {
local create=false
local target_dir="$HOME/code"
local argument_count=$#
local root
local app_name
local project_name
# When first param is -c, set create flag to true and remove the param
if [[ $1 == "-c" ]]; then
create=true
(( argument_count=argument_count-1 ))
shift
fi
# the root (private, company1, company2, etc...)
# I really would like to make that optional too, but
# that would require
root=$1
# $PROJECT_ALIASES is a associative array to map some
# project aliases to their actual names, it's set globally
# since it's used in other scripts to and maintained through
# it's own script
project_name=$PROJECT_ALIASES[$2]
# if the passed project string wasn't an alias,
# assume it was the raw project name
if [[ ! -n $project_name ]]; then
project_name=$2
fi
# the app folder (for multi application projects, optional)
app_name=$3
# validate required params
if [[ ! (( -n $root && -n $project_name )) ]]; then
echo "[ERROR] - Please pass at least a root dir and a project name" >&2
return 1
fi
target_dir="$target_dir/$root/$project_name"
if [[ -n $app_name ]]; then
target_dir="$target_dir/$app_name"
fi
# When the create flag is true (-c), create target directory
if [[ $create == true ]]; then
mkdir -p $target_dir
fi
# Finally, cd to the targeted directory
cd $target_dir
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T01:10:14.203",
"Id": "46359",
"Score": "1",
"body": "If you're looking to reduce typing, are you using tab completion? If the company is Acme and the project is FooBar, `cd ~/c<tab>A<tab>F<tab>`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-03T12:12:23.380",
"Id": "238093",
"Score": "1",
"body": "If you're looking for efficiency, and built in functionality, read up on the CDPATH environment variable."
}
] |
[
{
"body": "<h3>Remove unused variables</h3>\n\n<p>The variable <code>argument_count</code> is not used for anything, so you should remove it.</p>\n\n<h3>Simplify shell arithmetics</h3>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code>(( argument_count=argument_count-1 ))\n</code></pre>\n</blockquote>\n\n<p>You could simplify using the postfix operator:</p>\n\n<pre><code>(( argument_count-- ))\n</code></pre>\n\n<h3>Simplify condition</h3>\n\n<p>This condition can be written simpler:</p>\n\n<blockquote>\n<pre><code>if [[ ! (( -n $root && -n $project_name )) ]]; then\n</code></pre>\n</blockquote>\n\n<p>Like this:</p>\n\n<pre><code>if ! [[ -n $root && -n $project_name ]]; then\n</code></pre>\n\n<p>Note that you could also drop both of the <code>-n</code> flags there,\nthe expression will still mean the same:</p>\n\n<pre><code>if ! [[ $root && $project_name ]]; then\n</code></pre>\n\n<p>For the same reason, I suggest to drop all the <code>-n</code> in all conditions.</p>\n\n<h3>Always double-quote path variables</h3>\n\n<p>At some places you did a good job double-quoting path variables:</p>\n\n<blockquote>\n<pre><code> target_dir=\"$target_dir/$root/$project_name\"\n if [[ -n $app_name ]]; then\n target_dir=\"$target_dir/$app_name\"\n fi\n</code></pre>\n</blockquote>\n\n<p>At others you didn't:</p>\n\n<blockquote>\n<pre><code> # When the create flag is true (-c), create target directory\n if [[ $create == true ]]; then\n mkdir -p $target_dir\n fi\n\n # Finally, cd to the targeted directory\n cd $target_dir\n</code></pre>\n</blockquote>\n\n<p>Make it a habit to double-quote path variables always.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-28T10:01:25.647",
"Id": "115257",
"ParentId": "29355",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T00:51:24.453",
"Id": "29355",
"Score": "5",
"Tags": [
"beginner",
"shell",
"zsh"
],
"Title": "A z-shell function to quickly cd into projects"
}
|
29355
|
<p>I'm trying to do a one-way directory sync. Given a list of existing files in a dir, I'd like to make the files in the dir equal a new list of files. There will be subdirs under the dir. Because operating system calls are expensive, I'd rather minimize the number needed.</p>
<p>It's easy to just delete each file in the existing list but not on the new list, but that could leave empty subdirs. I could test for empty subdirs with OS calls, but as noted I'd like to avoid that. Similarly, I'd prefer removing dirs to first removing each file in the dir, then removing the empty dir.</p>
<p>I'm just operating on file names, not checking whether two files with the same name are the same or actually copying or deleting files or directories.</p>
<pre><code>'''
Input:
- list of existing files
- revised list of files
Output:
- lists to be used to transform first list to second list
-- list of files to be added to existing dir
-- list of directories to be pruned
-- list of files to be deleted
'''
import os
import sys
def file_to_list(file):
return [x.strip() for x in open(file, 'r') if not x.startswith('#EXT')]
def one_minus_two(one, two):
return [x for x in one if x not in set(two)]
def reduce_dirs(delete_files, new_list):
new_delete = []
for file in delete_files:
parts = file.split('\\')
sub = ''
for i in range(len(parts)):
sub = os.path.join(sub, parts[i])
if sub == '':
sub = '\\'
count = 0
for song in new_list:
if song.startswith(sub):
count += 1
break
if count == 0:
new_delete.append(sub)
break
return list(set(new_delete))
def reduce_files(remove_dirs, delete_files):
rd = []
rf = []
for dir in remove_dirs:
if dir in delete_files:
rf.append(dir)
else:
rd.append(dir)
return rf, rd
def main():
old_file = sys.argv[1]
new_file = sys.argv[2]
old_list = file_to_list(old_file)
new_list = file_to_list(new_file)
add_files = one_minus_two(new_list, old_list)
print 'add_files', add_files
delete_files = one_minus_two(old_list, new_list)
print '\nraw delete list', delete_files # intermediate result
remove_items = reduce_dirs(delete_files, new_list)
print '\nreduced delete list', remove_items # intermediate result
rf, rd = reduce_files(remove_items, delete_files)
print '\ndelete files', rf
print '\nprune dirs', rd
if __name__ == '__main__':
main()
</code></pre>
<p>Sample list of existing files (old_files):</p>
<blockquote>
<pre><code>\dir\who\tommy\song1
\dir\who\tommy\song2
\dir\who\tommy\song3
\dir\rolling\beggars\song4
\dir\rolling\beggars\song5
\dir\rolling\beggars\song6
\dir\who\next\song7
\dir\who\next\song8
\dir\who\next\song9
\dir\pink\dark\song10
\dir\pink\dark\song11
\dir\pink\dark\song12
\dir\bach\orch\fugue\song13
\dir\bach\orch\fugue\song14
\dir\bach\orch\fugue\song15
</code></pre>
</blockquote>
<p>Sample list of new_files:</p>
<blockquote>
<pre><code>\dir\rolling\beggars\song4
\dir\rolling\beggars\song5
\dir\rolling\beggars\song6
\dir\pink\dark\song10
\dir\pink\dark\song11
\dir\yes\closer\song16
\dir\yes\closer\song17
\dir\yes\closer\song18
\dir\king\court\song2
\dir\king\court\song4
\dir\king\court\song6
</code></pre>
</blockquote>
<p>There are likely cases I'm ignoring with these simple examples.</p>
<p>I have the feeling I'm reinventing the wheel here.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T20:46:28.077",
"Id": "46499",
"Score": "1",
"body": "Some comments: 1) Why are you afraid of leaving empty subdirs? You could just remove all the subdirectories with ``shutil.rmtree(path)``... but I guess that would slow down so still not a viable option. 2) You could replace your ``one_minus_two`` by this: ``set(one) - set(two)``"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T01:48:24.037",
"Id": "29356",
"Score": "4",
"Tags": [
"python",
"algorithm",
"file-system",
"sync"
],
"Title": "Python files sync"
}
|
29356
|
<p>I wrote a program to proxy MDNS requests in a local network to the DNS server. This is useful because in some private networks, host names ending in ".local" are configured in the DNS server. But ".local" is actually reversed for MDNS. Some systems have problems resolving these host names because they only try to resolve names through MDNS while those names are configured in the DNS server.</p>
<p>I started to use Haskell because XMonad. This is my first "practical" program written in Haskell. It would be very helpful if anyone could kindly give me some suggestions to improve my code.</p>
<p>The repository is here: <a href="https://github.com/abaw/mdns2dns" rel="nofollow">https://github.com/abaw/mdns2dns</a></p>
<p>Here's the code for the main program:</p>
<pre><code>{-# LANGUAGE DoAndIfThenElse #-}
import Control.Monad (forever,forM,guard,void)
import Control.Concurrent (forkIO)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Char8 as C
import Data.Binary.Get (getWord32host,runGet)
import Data.Char (isAscii)
import Data.Functor ((<$>))
import Data.Maybe (catMaybes)
import Debug.Trace (traceShow)
import Network.DNS
import Network.Multicast (addMembership)
import Network.Socket hiding (recv,sendTo)
import Network.Socket.ByteString(recv,sendTo)
import System.Environment (getArgs)
import System.Exit (exitFailure)
-- | The port used for MDNS requests/respones
mdnsPort :: PortNumber
mdnsPort = 5353
-- | The multicast IP address used for MDNS responses
mdnsIp :: HostAddress
mdnsIp = runGet getWord32host $ BL.pack [224,0,0,251]
-- | The SockAddr used for MDNS response
mdnsAddr :: SockAddr
mdnsAddr = SockAddrInet mdnsPort mdnsIp
-- | The maximum size of UDP DNS message defined in RFC-1035
maxDNSMsgSize :: Int
maxDNSMsgSize = 512
-- | Convert a String with only ascii characters to Domain
toDomain :: String -> Domain
toDomain = C.pack
-- | Convert strict ByteString to lazy ByteString
bsFromStrict :: B.ByteString -> BL.ByteString
bsFromStrict = BL.pack . B.unpack
-- | Convert lazy ByteString to strict ByteString
bsFromLazy :: BL.ByteString -> B.ByteString
bsFromLazy = B.concat . BL.toChunks
-- | Create a MDNS response
responseMDNS :: DNSFormat -- ^ The original MDNS request
-> [ResourceRecord] -- ^ The answers to response
-> DNSFormat -- ^ The result MDNS response
responseMDNS req answers = DNSFormat h [] answers [] []
where
h = DNSHeader { identifier = identifier (header req)
, flags = (flags $ header req) {qOrR = QR_Response}
, qdCount = 0
, anCount = length answers
, nsCount = 0
, arCount = 0
}
-- | Query DNS for a list of qustions
lookupDNS :: Resolver -- ^ The resolver to lookup with
-> [Question] -- ^ The list of questions to look up
-> IO [ResourceRecord] -- ^ The answers
lookupDNS resolver questions = concat <$> forM questions lookup'
where
lookup' :: Question -> IO [ResourceRecord]
-- returns [] if no results found
lookup' q = maybe [] answer <$> lookupRaw resolver (qname q) (qtype q)
-- | Proxy MDNS queries for domains ending with the given suffixes.
proxyForSuffixes :: [Domain] -> IO ()
proxyForSuffixes suffixes = withSocketsDo $ do
seed <- makeResolvSeed defaultResolvConf
sock <- socket AF_INET Datagram defaultProtocol
-- We should work properly when other MDNS server(e.g. avahi-daemon) is
-- running, so we need to set ReuseAddr socket option.
setSocketOption sock ReuseAddr 1
bind sock serverAddr
mdnsIpStr <- inet_ntoa mdnsIp
addMembership sock mdnsIpStr
forever $ tryReceivingMsg sock seed
where
serverAddr = SockAddrInet mdnsPort 0
tryReceivingMsg sock seed = do
bytes <- recv sock maxDNSMsgSize
case decode (bsFromStrict bytes) of
Left err -> putStrLn $ "received a invalid message:" ++ err
Right msg' -> processMsg sock seed msg'
processMsg sock seed msg = proxyIt
where
proxyIt
| notRequest || null questionToUs = return ()
| otherwise = do
putStrLn $ "will handle:" ++ show questionToUs
void $ forkIO $ withResolver seed $ \resolver -> do
answers <- lookupDNS resolver questionToUs
let rsp = responseMDNS msg answers
void $ sendTo sock (msgToByteString rsp) mdnsAddr
questionToUs = [ q | q <- question msg
, qtype q == A
, any (`C.isSuffixOf` qname q) suffixes]
notRequest = qOrR (flags $ header msg) /= QR_Query
-- encode the response and then convert it to strict ByteString from a
-- lazy one.
msgToByteString = bsFromLazy . encode
main = do
suffixes <- getArgs
if all (all isAscii) suffixes
then proxyForSuffixes $ map (toDomain . fixSuffix) suffixes
else putStrLn "Only supports domain names in ascii!!" >> exitFailure
where
-- names in DNS questions should end in "."
fixSuffix suffix
| last suffix == '.' = suffix
| otherwise = suffix ++ "."
</code></pre>
<p>I was particularly wondering if there is a better way to write:</p>
<pre><code>mdnsIp = runGet getWord32host $ BL.pack [224,0,0,251]
</code></pre>
|
[] |
[
{
"body": "<p>Overall this code reads well. Nice job.</p>\n\n<p>I do not know a better way to write <code>mdnsIp</code>.</p>\n\n<p>I have two concerns:</p>\n\n<ol>\n<li>Logging. A proper daemon should have logging to let people know what is happening.</li>\n<li>Infinite loops. There are several places in the code where the service could just spin for an indeterminate amount of time. The usual solution to this is a timeout of some sort.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-12T19:26:54.287",
"Id": "69640",
"ParentId": "29361",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T04:15:05.580",
"Id": "29361",
"Score": "8",
"Tags": [
"haskell",
"networking",
"socket",
"server",
"proxy"
],
"Title": "A program to proxy MDNS requests to the DNS server"
}
|
29361
|
<p>There are many PHP PDO classes out there, agreed. However I find they do not allow for flexibility. So I created one that helps reduce development time as little as it may be but it does the job (maybe apart from the disconnect part, but it allows to trace whether database is connected via <code>$database->isConnected</code>). Can you please point out any flaws and any possible improvements?</p>
<pre><code><?php
class db
{
public $isConnected;
protected $datab;
public function __construct($username, $password, $host, $dbname, $options=array()){
$this->isConnected = true;
try {
$this->datab = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
$this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
catch(PDOException $e) {
$this->isConnected = false;
throw new Exception($e->getMessage());
}
}
public function Disconnect(){
$this->datab = null;
$this->isConnected = false;
}
public function getRow($query, $params=array()){
try{
$stmt = $this->datab->prepare($query);
$stmt->execute($params);
return $stmt->fetch();
}catch(PDOException $e){
throw new Exception($e->getMessage());
}
}
public function getRows($query, $params=array()){
try{
$stmt = $this->datab->prepare($query);
$stmt->execute($params);
return $stmt->fetchAll();
}catch(PDOException $e){
throw new Exception($e->getMessage());
}
}
public function insertRow($query, $params){
try{
$stmt = $this->datab->prepare($query);
$stmt->execute($params);
}catch(PDOException $e){
throw new Exception($e->getMessage());
}
}
public function updateRow($query, $params){
return $this->insertRow($query, $params);
}
public function deleteRow($query, $params){
return $this->insertRow($query, $params);
}
}
//USAGE
/*
Connecting to DataBase
$database = new db("root", "", "localhost", "database", array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
Getting row
$getrow = $database->getRow("SELECT email, username FROM users WHERE username =?", array("yusaf"));
Getting multiple rows
$getrows = $database->getRows("SELECT id, username FROM users");
inserting a row
$insertrow = $database ->insertRow("INSERT INTO users (username, email) VALUES (?, ?)", array("yusaf", "yusaf@email.com"));
updating existing row
$updaterow = $database->updateRow("UPDATE users SET username = ?, email = ? WHERE id = ?", array("yusafk", "yusafk@email.com", "1"));
delete a row
$deleterow = $database->deleteRow("DELETE FROM users WHERE id = ?", array("1"));
disconnecting from database
$database->Disconnect();
checking if database is connected
if($database->isConnected){
echo "you are connected to the database";
}else{
echo "you are not connected to the database";
}
*/
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T08:00:55.103",
"Id": "46454",
"Score": "7",
"body": "You are actually making it worse! At this moment you throow away one of the most powerfull features of PDO: prepared statements. You can execute prepared statements multiple times with different variables. But your function doesnt allow this. Extending/wrapping a class should add functionality, not remove it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T11:40:20.167",
"Id": "46464",
"Score": "0",
"body": "@Pinoniq: every query this class performs uses a prepared statement, AFAIKT"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T13:18:00.387",
"Id": "46467",
"Score": "2",
"body": "Wrapping PDO into something \"better\" is impossible. PDO is as good as it gets. What you did is made it worse. Why would anyone learn your class methods for inserting/deleting/updating if they already know SQL? I'd never use $obj->insertRow() or any of similar. I'd use a class that implements ActiveRecord pattern which completely obliviates the existence of insert/delete/update commands. Don't take it the wrong way, but do check ActiveRecord and Object Relational Mapper."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T07:45:36.093",
"Id": "46511",
"Score": "0",
"body": "@EliasVanOotegem reading your comment tells me one thing. You don't grasp the real power of prepared statements. Prepared statements can be resued over and over again. But this PDO wrapper doesn't cache the statementHandler thus throwing away a very powerfull tool PDO gives us."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T08:26:55.117",
"Id": "46516",
"Score": "1",
"body": "@EliasVanOotegem true about the db providing those stmt's but what use is your code if it doesnt allow us to access them. I was simply pointing out that saying (he uses prepared statemends because of the ->prepare() function is for me the same as 'he is writing OO because of the keyword class'. Apologies if I offended you... I'm not the morning type ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T11:01:06.193",
"Id": "46526",
"Score": "0",
"body": "WOAH guys I don't have plans of using this (well not until Elias Van Ootegem said it's useless :P ), but when originally creating this I was not trying to re-invent the wheel and I was learning OOP and I made a class incorporating databases but then i fount it useful as i don't have to prepare-execute-fetch every time I want to write a query (YES I'm lazy)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-21T21:39:36.663",
"Id": "260544",
"Score": "1",
"body": "I'm reading this question now and crying with laughter."
}
] |
[
{
"body": "<p>Personally, I must say that close to all PDO derived/based classes I've seen so far suffer from the same problem: They are, essentially, completely pointless.<Br/>\nLet me be clear: <code>PDO</code> offers a clear, easy to maintain and neat interface on its own, wrapping it in a custom class to better suit the needs of a particular project is essentially taking a decent OO tool, and altering it so that you <em>can't</em> reuse it as easily in other projects. If you were to write a wrapper around MySQLi, I could understand the reasoning, but PDO? No, I'm really struggeling to understand the logic behind that <strong>unless</strong>:</p>\n<p>You were to write a table mapper class to go with it, that establishes a connection between the tables you query, and the data models into which you store the data. Not unlike how <code>Zend\\Db</code> works.<br/>\nMySQL is, as you well know, not as flexible as PHP is in terms of data-types. If you are going to write a DB abstraction layer, common sense dictates that layer reflects that: it should use casts, constants, filters <em>as well as prepared statements</em> to reflect that.<br/>\nMost mature code out there also offerst an API that doesn't require you to write your own queries:</p>\n<pre><code>$query = $db->select('table')\n ->fields(array('user', 'role', 'last_active')\n ->where('hash = ?', $pwdHash);\n</code></pre>\n<p>These abstraction layers often (if not always) offer another benefit, they build the queries for you, based on <em>what DB you're connection to</em>. If you're using <code>mysql</code>, they'll build a MySQL query, if you happen to switch to PostgreSQL, they'll churn out pg queries, without the need to rewrite thousands of queries. If you want to persist and write your own abstraction layer, make sure you offer something similar, too. If you don't, you're back to square one: embarking on a labour intensive, pointless adventure that <em>won't</em> be worth it.</p>\n<p>An alternative approach is to <em>extend</em> the PDO class. Again, this has been done before and is, in theory, perfectly OK. Although, again this might be personal, it does violate one principle which is upheld by many devs I know: Don't extend, or attempt to change an object <em>you don't own</em>. PDO is a core object,so it's pretty clear you don't own it.<br/>\nSuppose you were to write something like:</p>\n<pre><code>class MyDO extends PDO\n{\n public function createProcedure(array $arguments, $body)\n {\n //create SP on MySQL server, and return\n }\n}\n</code></pre>\n<p>And lets assume that, after some serious debugging, and testing, you actually got this working. Great! But then what if, some time in the future, <code>PDO</code> got its own <code>createProcedure</code> method? it'll probably outperform yours, and might be more powerful. That, in itself isn't a problem, but suppose it's signature were different, too:</p>\n<pre><code>public function createProcedure (stdClass $arguments)\n{\n}\n</code></pre>\n<p>That would mean you <em>either</em> have to ditch your method, and refactor your entire code-base to sing to the tune of <code>PDO</code>'s latest and greatest hit, or you'd have to alter your method to:</p>\n<pre><code>public function createProcedure(array $arguments, $body)\n{\n $arguments = (object) $arguments;//create stdClass\n //parse $body and:\n $arguments->declare = $body[0];\n $arguments->loops = (object) array('loop1' => $body[1], 'loop2' => $body[2]);\n $arguments->body = (object) array(\n 'main' => $body[3],\n 'loop1_body' => $body[4],\n 'loop2_body' => $body[5]\n );\n return parent::createProcedure($arguments);\n}\n</code></pre>\n<p>That would mean that, for all code you wrote, you're actually having to call 2 methods, turning your once so clever <code>createProcedure</code> method into dead weight. So what, you might say? Well, don't think you're out of the woods just yet, because <em><strong>This alternative method above is illegal</strong></em>, it can't be written, it can't work, it shouldn't work, it's just all shades of wrong, here's why:</p>\n<p>The Liskov principle states that a child (the class extending <code>PDO</code>) may not alter the signature of inherited methods if those alterations constitute a breach of contract, meaning the expected types (type-hints) may not be stricter than or different to the types defined in the parent (ie: <code>array</code> vs <code>stdClass</code> is not allowed). Additional arguments are allowed, provided they're <em>optional</em>.<br>\nIf the <code>PDO</code> method itself takes but a single argument of the type <code>stdClass</code>, then your child class may only add optional arguments, and should either drop the type-hint, or uphold it (ie: hint at <code>stdClass</code>, which would break all existing code), or don't hint at all (which is as error-prone as it gets).</p>\n<p>What's more, after a couple of months, people might use third party code (frameworks), that rely on the <code>createProcedure</code> method, and pass it an instance of <code>stdClass</code>. You'll have to change your method again, to the vague, and error prone signature:</p>\n<pre><code>public function createProcedure($arrOrObject, $body = null)\n{\n if ($arrOrObject instanceof stdClass)\n {\n return parent::createProcedure($arrOrObject);\n }\n if ($body === null)\n {\n //What now??\n }\n //parse body\n}\n</code></pre>\n<p>If <code>$body</code> is null, and <code>$arrOrObject</code> is an array, the user might have structured the <code>$arrOrObject</code> array in the same way as <code>PDO</code> would like to see the object structured, in which case <code>json_decode(json_encode($arrOrObject));</code> would do the trick (not casting, because a cast doesn't cast recursive), but it's just as likely that the code calling your method contains a bug. What to do? convert to an object, and <code>try-catch</code>, with the extra overhead that might cause?</p>\n<p>This leads me to the last, and for now biggest omission:<br/>\nWhen using a wrapper object, it's generally a good idea to implement a (slow) magic <code>__call</code> method, that checks if a method call was meant for the wrapper object, or if it was meant for the wrapped object.<br/>\nUsing your object, I might want to set another attribute on the PDO extension, but since you failed to implement the <code>setAttribute</code> method, I can't change the charset, nor can I change how <code>PDO</code> deals with <code>NULL</code> values. Which can only be considered to be a glaring omission. Especially since you expect the user to pass bare PDO constants to the constructor. Basically, the least you <em>should</em> do is add:</p>\n<pre><code>public function __call($method, array $arguments )\n{\n return call_user_func_array($this->datab, $arguments);\n}\n</code></pre>\n<p>This way, you semi-expose the actual wrapped object to the user, in the sense that, methods you haven't implemented can still be used. New methods that might be implemented in the future will automatically be accessible, too.<br/>\nWhat's more, you'll be able to validate/check the arguments and log which methods are used by the users, so that you could fine-tune your class to better reflect the way it is being used.</p>\n<h2>Recap:</h2>\n<ul>\n<li>Building an abstraction class on a user-friendly raw-API like <code>PDO</code> is, IMHO, like a broken pencil: Pointless</li>\n<li>Extending PDO means you don't have to create <em>pass-through</em> methods that call the wrapped API (like creating a <code>prepare</code> method), but it does mean there is a chance you'll have to refactor your code whenever PDO changes</li>\n<li>If you still feel like using a wrapper object, either consider wrapping it around something less well known, but in some respects better (<code>mysqli_*</code> is what I'm hinting at), but <em>implement the magic <code>__call</code> and, if required <code>__callStatic</code> methods.</em></li>\n<li>Again, if you're going to procede: work on an entire abstraction layer, that allows for users to map tables to data models, and take it from there. Ensure that those data-models can be used easily to build HTML forms, for example in order for those forms to be linked to the DB in the blink of an eye, bot don't forget about sanitizing your data, of course.</li>\n</ul>\n<h2>On the code itself:</h2>\n<p>There is one thing you <em>have</em> to fix about your code, above all else, and that's your constructor:<br/>\nI might choose to construct an object like so:</p>\n<pre><code>$database = new db("user", "pwd", "host", "mydb",\n array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ));\n</code></pre>\n<p>Setting the default fetch-mode to fetch objects, and the new instance of <code>PDO</code> will be passed the correct attribute array. Sadly, right after constructing that PDO object, you're deciding that the default fetch-mode should've been <code>PDO::FETCH_ASSOC</code>, because 2 lines further down:</p>\n<pre><code>$this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);\n</code></pre>\n<p>I'd hate to use that code. Also, this just doesn't add up:</p>\n<pre><code>try\n{ \n $this->datab = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); \n $this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); \n $this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);\n} \ncatch(PDOException $e)\n{ \n $this->isConnected = false;\n throw new Exception($e->getMessage());\n}\n</code></pre>\n<p>Try-catch-throw? Why? The connection failed, the <code>PDOException</code> tells me why, that's what I want to know, why catch that exception, and throw a new, more general one? What if I passed <code>PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT</code> to the constructor, and the connection failed? You're probably better of replacing it with this:</p>\n<pre><code>$this->datab = new PDO($connString, array(\n PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,\n PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,\n PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'//careful with this one, though\n));\nforeach($options as $attr => $value)\n{\n $this->datab->setAttribute($attr, $value);\n}\n</code></pre>\n<p>And <em>let the exception go</em>. If the connection to the DB fails, the script can't do what it's supposed to do anyway. The <code>PDOExceptions</code> are usefull in a scenario where you're using transactions. If 999 queries succeeded, but the 1000th query failed, rather than inserting partial data, catching the exception, and rolling back the transaction is what you do, but catching an exception to rethrow it again is just silly.</p>\n<p>But, again, I'm not going to stop you from doing what you want, perhaps you can prove me wrong and actually make something great. But in order to do that, you must know what's out there already:</p>\n<ul>\n<li>As always start with the theory, wiki's a great place to start\n<ol>\n<li>the <a href=\"http://en.wikipedia.org/wiki/Object-relational_mapping\" rel=\"noreferrer\">ORM wiki</a></li>\n<li>The <a href=\"http://en.wikipedia.org/wiki/Active_record_pattern\" rel=\"noreferrer\">ActiveRecord Pattern wiki</a></li>\n</ol>\n</li>\n<li><a href=\"http://www.doctrine-project.org/\" rel=\"noreferrer\">doctrine</a>\n<ol>\n<li>And all of its <a href=\"http://www.doctrine-project.org/projects.html\" rel=\"noreferrer\">projects</a></li>\n<li>Not in the least, its <a href=\"http://www.doctrine-project.org/projects/orm.html\" rel=\"noreferrer\">ORM</a></li>\n</ol>\n</li>\n<li><a href=\"http://propelorm.org/\" rel=\"noreferrer\">Propel</a>, haven't used it, but N.B. recommended it</li>\n<li><a href=\"http://www.phpactiverecord.org/\" rel=\"noreferrer\">PHPActiveRecord</a></li>\n<li><a href=\"http://framework.zend.com/manual/2.0/en/modules/zend.db.adapter.html\" rel=\"noreferrer\">Zend\\Db\\Adapter</a> and all of the components in the <code>Zend\\Db</code> namespace</li>\n<li>Even the old <a href=\"http://framework.zend.com/manual/1.12/en/zend.db.html\" rel=\"noreferrer\">Zend_Db</a> has something going for it, still</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T06:49:24.857",
"Id": "46509",
"Score": "8",
"body": "@YusafKhaliq: I understand your thinking behind catching the error if a malformed query-string were passed as an argument, but you shouldn't do that. If you catch that exception and _attempt_ to fix the error, that malformed query won't get fixed, and every time that piece of code gets executed, you'll slow the system down. If a query is malformed, it's a bug: don't work around it, fix it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T11:28:19.383",
"Id": "29394",
"ParentId": "29362",
"Score": "69"
}
},
{
"body": "<p>Kind of an old post, but I had to add something where I saw this line</p>\n<pre><code>$this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); \n$this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);\n</code></pre>\n<p>Which seems to me like you had hard-coding the settings, right after this line:</p>\n<pre><code>$this->datab = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); \n</code></pre>\n<p>Which means, whatever (relating to <code>ATTR_ERRMODE</code>, <code>ATTR_DEFAULT_FETCH_MODE</code>) the user sets as <code>$options</code> in the constructor will be overriding by the <code>setAttribute</code> method. Which in my opinion seems pointless. I would suggest changing the constructor to something like:</p>\n<pre><code>...\n\nprivate $defaultPdoAttr = [\n \\PDO::ATTR_EMULATE_PREPARES => FALSE,\n \\PDO::ATTR_ERRMODE => \\PDO::ERRMODE_EXCEPTION,\n \\PDO::ATTR_DEFAULT_FETCH_MODE => \\PDO::FETCH_ASSOC\n];\n \npublic function __construct($dsn, $username, $password, array $driverOptions = [])\n{\n if (!$driverOptions) {\n $driverOptions = $this->defaultPdoAttr;\n } \n \n $this->datab = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $driverOptions );\n\n...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-10T15:56:14.910",
"Id": "190706",
"Score": "0",
"body": "I'm not saying you did it on purpose, but you've basically repeated what I've said in my answer (first thing I discuss under _\"On the code itself\"_). PS: I wouldn't merely reassign `$driverOptions` if it was empty, I'd iterate over my defaults, and add the keys that aren't set in `$driverOptions` (merging the arrays), similar to what I suggest in the last code snippet in my answer ;)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2015-08-03T10:05:02.420",
"Id": "98873",
"ParentId": "29362",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "29394",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T06:04:32.813",
"Id": "29362",
"Score": "54",
"Tags": [
"php",
"object-oriented",
"mysql",
"pdo"
],
"Title": "Class for reducing development time"
}
|
29362
|
<p>Some background: I work mostly in Python (specifically numpy), doing Bioinformatics type work. I am interested in moving towards Haskell. Initially, I hope it will be possible to replace some of the simple exploratory scripting I've been doing with Haskell. The following is not something that would actually be particularly useful, but I thought it might be a good starting point for my first program in Haskell!</p>
<p>The following code takes two files: </p>
<ol>
<li>Describes regions of a chromosome that have been
categorized as similar. Line 1 shows the start basepair of the
region, line 2 the end basepair, and so on. A shortened example: <a href="http://pastebin.com/RMd13Kv3" rel="nofollow">http://pastebin.com/RMd13Kv3</a></li>
<li>Shows an interaction matrix between "bins" of the chromosome. A row has chrmName startBp endBp, followed by the row of the interaction matrix. This is not necessarily in order. Example: <a href="http://pastebin.com/Q5CaVHAu" rel="nofollow">http://pastebin.com/Q5CaVHAu</a></li>
</ol>
<p>The code is attempting to work out the fraction of the whole chromosome spanned by the regions.</p>
<pre><code>import System.IO
import System.Environment(getArgs)
import Data.Either
import Data.List
joinLinePairs :: [a] -> ([a], [a])
joinLinePairs x = partitionEithers $ zipWith ($) (cycle [Left, Right]) x
zipLinesPairs :: ([a], [a]) -> [(a, a)]
zipLinesPairs (a, b) = zip a b
pairDifference :: (String, String) -> Int
pairDifference (a, b) = (read b) - (read a)
domainArea :: [String] -> Int
domainArea inpLines = sum (map pairDifference $ zipLinesPairs $ joinLinePairs inpLines)
processRawMat :: [String] -> [[Int]]
processRawMat x = map (processMatRow . words) x
processMatRow :: [String] -> [Int]
processMatRow (x:y:z:_) = [read y, read z]
maxMinBin :: [[Int]] -> (Int, Int)
maxMinBin lst = (minimum vals, maximum vals)
where vals = concat lst
coverageFrac :: (Integral a, Fractional b) => (a, a) -> a -> b
coverageFrac (mn, mx) domArea = (fromIntegral domArea) / ((fromIntegral mx) - (fromIntegral mn))
main :: IO ()
main = do
args <- getArgs
rawDomains <- readFile (args !! 0)
let coveredArea = domainArea $ lines rawDomains
print $ coveredArea
rawMatrix <- readFile (args !! 1)
let rawMatLines = lines rawMatrix
let listolists = processRawMat rawMatLines
print $ coverageFrac (maxMinBin listolists) coveredArea
</code></pre>
<p>One thing I noticed is that this code is very slow when running on real data (in reality the second file can run to tens of thousands of lines, and hundreds of mb). As most of the things I would be doing involve dealing with very large text files (these would be considered small, by comparison), this worries me a bit!</p>
<p>I would appreciate any feedback anyone could offer me. Thanks!</p>
|
[] |
[
{
"body": "<p>Try using the functions from then <a href=\"http://hackage.haskell.org/packages/archive/bytestring/0.9.2.1/doc/html/Data-ByteString-Lazy-Char8.html\" rel=\"nofollow\">ByteString</a> package instead of System.IO and String as they are much more efficient. Also, consider using lazy IO (using heGetContents from the link I sent) to read the huge input file as it will not load it all at once in memory while you parse it making it more efficient.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-03T10:31:23.570",
"Id": "48825",
"Score": "0",
"body": "oneway's code is already using lazy IO through the [`readFile` function](http://hackage.haskell.org/packages/archive/base/latest/doc/html/System-IO.html#v:readFile)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T10:18:27.430",
"Id": "29366",
"ParentId": "29363",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T07:59:13.603",
"Id": "29363",
"Score": "3",
"Tags": [
"haskell"
],
"Title": "Calculating chromosome coverage of a set of regions"
}
|
29363
|
<p>I am capturing a window of my own choice, and taking a screenshot of it constantly in a loop. Latency and speed is everything.</p>
<p>It's very capable, but I hope it can be improved.</p>
<pre><code>var proc = Process.GetProcessesByName(prcname)[0];
IntPtr hwnd = proc.MainWindowHandle;
RECT rc;
NativeMethods.GetWindowRect(hwnd, out rc);
Bitmap bmp = new Bitmap(rc.Width, rc.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
Graphics gfxBmp = Graphics.FromImage(bmp);
IntPtr hdcBitmap = gfxBmp.GetHdc();
NativeMethods.PrintWindow(hwnd, hdcBitmap, 0);
gfxBmp.ReleaseHdc(hdcBitmap);
gfxBmp.Dispose();
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
return new MemoryStream(Lz4.CompressBytes(ms.GetBuffer()));
</code></pre>
<p>I will set a name <code>prcname</code> which will be the name of a process, for example, Internet Explorer. It will then hook on to that and save it as a bitmap and then .bmp (or other).</p>
<p>I then return the memory stream , and then I can do what I want with it (lz4 is used here to compress, which is very fast and lossless so it works pretty well).</p>
<p>Here are the <code>Import</code>s used:</p>
<pre><code>[DllImport("user32.dll")]
internal static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")]
internal static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, int nFlags);
</code></pre>
<p>Then there is the <code>RECT</code> class, which is enormous, and I did not write it. I took it and reused this code for my own purposes, but <code>RECT</code> has been untouched, as I don't feel safe messing around with it.</p>
<p>Now, is there a way to improve the speed? Preferably I would like to improve the latency, meaning the frame it lags behind.</p>
<p>I am willing to try something else if user32 is not enough for this, so I'm open for suggestions and examples on that.</p>
<p>Can this code be improved?</p>
<pre><code>NetSerializer.Serializer.Serialize(tcpcap.GetStream(), PrintWindow(process));
PrintWindow(process).Dispose();
panel1.BackgroundImage = Image.FromStream(new Lz4DecompressionStream((MemoryStream)NetSerializer.Serializer.Deserialize(tt1.GetStream())));
</code></pre>
|
[] |
[
{
"body": "<p>Well, yes, you're holding on to a bunch of <code>IDisposable</code> objects which should be dealt with by employing the <code>using</code> statement:</p>\n\n<pre><code>IntPtr hwnd;\n\nusing (var proc = Process.GetProcessesByName(prcname)[0])\n{\n hwnd = proc.MainWindowHandle;\n}\n\nRECT rc;\nNativeMethods.GetWindowRect(hwnd, out rc);\nusing (Bitmap bmp = new Bitmap(rc.Width, rc.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb))\n{\n using (Graphics gfxBmp = Graphics.FromImage(bmp))\n {\n IntPtr hdcBitmap = gfxBmp.GetHdc();\n try\n {\n NativeMethods.PrintWindow(hwnd, hdcBitmap, 0);\n }\n finally\n {\n gfxBmp.ReleaseHdc(hdcBitmap);\n }\n }\n\n using (MemoryStream ms = new MemoryStream())\n {\n bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);\n return new MemoryStream(Lz4.CompressBytes(ms.GetBuffer()));\n }\n}\n</code></pre>\n\n<p>Plus, the <code>MemoryStream</code> you return should be <code>Dispose()</code>'d be the calling code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T19:49:39.317",
"Id": "46404",
"Score": "0",
"body": "Not quite familiar what´s going on there. Why will \"Using\" be faster then just using variables around the place? (New to this). And how can i dispose the last memory stream in the calling code? Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T19:56:50.567",
"Id": "46405",
"Score": "0",
"body": "I updated the code to show where i use it, tell me if it´s correct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T20:28:51.200",
"Id": "46407",
"Score": "2",
"body": "@Zerowalker My understanding is by using the using statements you are guaranteed even on failure (within the code block) that the Dispose method will be called thus releasing resources."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T20:43:58.187",
"Id": "46409",
"Score": "0",
"body": "Ah well that sounds good. I am a bit lacking when it comes to properly use and dispose. But i don´t get how i am supposed to dispose the Memory Stream i am using, as disposing it like i put above, didn´t do anything but slow it down."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T00:22:00.607",
"Id": "46430",
"Score": "0",
"body": "@Zerowalker well, to be fair, I never claimed it would be faster :) You asked if the code could be improved and here's the improvement. However, using the `using` deterministic disposal pattern, you're probably relieving memory pressure."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T18:56:29.780",
"Id": "29375",
"ParentId": "29364",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "29375",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T08:25:34.470",
"Id": "29364",
"Score": "6",
"Tags": [
"c#",
"image",
"serialization"
],
"Title": "Capturing and taking a screenshot of a window in a loop"
}
|
29364
|
<p>Please criticize the classes <code>GameJudgeImpl</code> and <code>GameInfo</code> so that I could make them clearer.</p>
<pre><code>public interface GameJudge {
public GameInfo gameInfo();
}
public enum GameResult {
UNKNOWN, DRAW, PLAYER_WINS, OPPONENT_WINS
}
public enum Cell {
EMPTY, PLAYER, OPPONENT
}
</code></pre>
<p><strong>↓</strong></p>
<pre><code>public class GameInfo {
private final GameResult gameResult;
private final List<Matrix.Position> cellsOnFire;
public static GameInfo unknownResult() {
return new GameInfo(GameResult.UNKNOWN, new ArrayList<Matrix.Position>());
}
public static GameInfo drawResult() {
return new GameInfo(GameResult.DRAW, new ArrayList<Matrix.Position>());
}
public GameInfo(GameResult gameResult, List<Matrix.Position> cellsOnFire) {
this.gameResult = gameResult;
this.cellsOnFire = cellsOnFire;
}
public GameResult gameResult() {
return gameResult;
}
public List<Matrix.Position> cellsOnFire() {
return cellsOnFire;
}
public boolean resultIsKnown() {
return gameResult != GameResult.UNKNOWN;
}
}
</code></pre>
<p><strong>↓</strong></p>
<pre><code>public class GameJudgeImpl implements GameJudge {
private final Matrix<Cell> gameBoard;
private final int gameBoardDimension;
public GameJudgeImpl(Matrix<Cell> gameBoard) {
this.gameBoard = gameBoard;
this.gameBoardDimension = gameBoard.rows;
}
@Override
public GameInfo gameInfo() {
GameInfo gameInfo = checkAllRowsColumns();
if (gameInfo.resultIsKnown()) {
return gameInfo;
}
gameInfo = checkDiagonals();
if (gameInfo.resultIsKnown()) {
return gameInfo;
}
if (gameBoard.contains(Cell.EMPTY)) {
return GameInfo.unknownResult();
}
return GameInfo.drawResult();
}
private GameInfo checkAllRowsColumns() {
for (int i = 0; i < gameBoardDimension; ++i) {
GameInfo gameInfo = checkRowColumn(i);
if (gameInfo.resultIsKnown()) {
return gameInfo;
}
}
return GameInfo.unknownResult();
}
private GameInfo checkRowColumn(int index) {
GameInfo rowGameInfo = checkRow(index);
if (rowGameInfo.resultIsKnown()) {
return rowGameInfo;
} else {
return checkColumn(index);
}
}
private GameInfo checkRow(int row) {
return gameInfoByCellsPositions(cellsPositionsOnRow(row));
}
private List<Matrix.Position> cellsPositionsOnRow(int row) {
List<Matrix.Position> cells = new ArrayList<Matrix.Position>(gameBoardDimension);
for (int column = 0; column < gameBoardDimension; ++column) {
cells.add(new Matrix.Position(row, column));
}
return cells;
}
private GameInfo gameInfoByCellsPositions(List<Matrix.Position> cellsPositions) {
Matrix.Position firstCellOnLinePosition = cellsPositions.get(0);
Cell firstCellOnLine = gameBoard.get(firstCellOnLinePosition);
if (firstCellOnLine == Cell.EMPTY) {
return GameInfo.unknownResult();
}
for (int i = 1; i < gameBoardDimension; ++i) {
Matrix.Position currentPosition = cellsPositions.get(i);
Cell currentCell = gameBoard.get(currentPosition);
if (firstCellOnLine != currentCell) {
return GameInfo.unknownResult();
}
}
return new GameInfo(cellToResult(firstCellOnLine), cellsPositions);
}
private GameResult cellToResult(Cell cell) {
if (cell == Cell.PLAYER) {
return GameResult.PLAYER_WINS;
} else if (cell == Cell.OPPONENT) {
return GameResult.OPPONENT_WINS;
}
throw new IllegalArgumentException("Input cell must be not empty!");
}
private GameInfo checkColumn(int column) {
return gameInfoByCellsPositions(cellsPositionsOnColumn(column));
}
private List<Matrix.Position> cellsPositionsOnColumn(int column) {
List<Matrix.Position> cells = new ArrayList<Matrix.Position>(gameBoardDimension);
for (int row = 0; row < gameBoardDimension; ++row) {
cells.add(new Matrix.Position(row, column));
}
return cells;
}
private GameInfo checkDiagonals() {
GameInfo leftUpperDiagonalGameInfo = checkLeftUpperDiagonal();
if (leftUpperDiagonalGameInfo.resultIsKnown()) {
return leftUpperDiagonalGameInfo;
} else {
return checkRightUpperDiagonal();
}
}
private GameInfo checkLeftUpperDiagonal() {
return gameInfoByCellsPositions(cellsPositionsOnLeftUpperDiagonal());
}
private List<Matrix.Position> cellsPositionsOnLeftUpperDiagonal() {
List<Matrix.Position> positions = new ArrayList<Matrix.Position>(gameBoardDimension);
for (int i = 0; i < gameBoardDimension; ++i) {
positions.add(new Matrix.Position(i, i));
}
return positions;
}
private GameInfo checkRightUpperDiagonal() {
return gameInfoByCellsPositions(cellsPositionsOnRightUpperDiagonal());
}
private List<Matrix.Position> cellsPositionsOnRightUpperDiagonal() {
List<Matrix.Position> positions = new ArrayList<Matrix.Position>(gameBoardDimension);
for (int i = 0; i < gameBoardDimension; ++i) {
positions.add(new Matrix.Position(i, gameBoardDimension - i - 1));
}
return positions;
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>Interface, GameJudge, doesn't seem to make sense.</p>\n\n<ul>\n<li><p>the method gameInfo(), doesn't have an action verb so it's hard to determine what exactly it is doing. getGameInfo() perhaps?</p></li>\n<li><p>An interface is a contract. So if another class were to implement this interface, would the return type, GameInfo, and the method gameInfo() make sense? i.e. for chess. If not, perhaps you'd want to rename your interface to something more specific to tic-tac-toe.</p></li>\n</ul></li>\n<li><p>The Enum, GameResult, looks pretty good but needs some tweaking.</p>\n\n<ul>\n<li><p>Since this is the result of the game, suggest that it only have 3 states: Player wins, Opponent wins, and Draw.</p></li>\n<li><p>The value of <strong>Unknown</strong> leads me to believe that you will be using it to check the game's state. If that is the case, rename the class to <strong>GameState</strong></p></li>\n</ul></li>\n<li><p>The Enum, Cell, is fine. It will contain the state of the Cell.</p></li>\n</ol>\n\n<hr>\n\n<p>A few things jump out of me are:</p>\n\n<h3> The use of static methods</h3>\n\n<ul>\n<li><p>In general, static methods make your code harder to test. See (<a href=\"http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/\">Mikso Hevery</a>). Since you always want to have tests with your code, try to avoid static methods until you have a better grasp of when to use them and when not to. This will help you with your OO design skills.</p></li>\n<li><p>In this case, you're are using it to return a new instance (factory pattern) of GameInfo. The problem is that the static methods are in the same class you are returning. You would be better off creating a separate class that owns the responsibility of creating GameInfo objects.</p></li>\n<li><p>I would argue that for any single game, you should only have a single GameInfo object. So you probably don't even need that factory method since you can create a new object during the start of the game and then return the same one when the game is finished.</p></li>\n</ul>\n\n<h3> A large number of private variables</h3>\n\n<ul>\n<li>When you see a single public method and a large number of private methods, it could be an indication of that class having too much responsibility. Investigate your private methods and see if you can find common patterns/usage. If so, you can move those methods to the new class so that it can handle the responsibility.</li>\n</ul>\n\n<p>For example, you have a lot of methods that start with 'check'. Could you make a class called, <strong>BoardChecker</strong>?</p>\n\n<p>Keep repeating the process and breakdown your class into other classes when applicable.</p>\n\n<h3>Too many return statements</h3>\n\n<p>A large number of return statements can be confusing (and hard to debug if the method is large). Try to only have one or two return statements.</p>\n\n<p>See method, <strong>gameInfo()</strong></p>\n\n<h3>Naming Convention</h3>\n\n<p>What is <strong>Matrix.Position</strong> anyway? This seems very strange to me. Please ollow Java naming conventions for your class names.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T01:39:09.530",
"Id": "46434",
"Score": "1",
"body": "Position is inner class of Matrix class. Code: https://github.com/Leonideveloper/TicTacToe/blob/master/TicTacToe/src/main/java/com/gmail/leonidandand/tictactoe/utils/Matrix.java"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T16:12:18.980",
"Id": "46476",
"Score": "1",
"body": "No problem, happy to help. I would suggest that since you are using github, keep iterating on the same problem with new branches! You'll find that as you learn more, your design will change :) Keep up the good work!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T18:59:22.583",
"Id": "29376",
"ParentId": "29367",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "29376",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T11:49:52.637",
"Id": "29367",
"Score": "2",
"Tags": [
"java",
"object-oriented",
"tic-tac-toe"
],
"Title": "Extremely Object Oriented Tic-Tac-Toe in Java"
}
|
29367
|
<p>The PHP Mess Detector of my IDE warns about a Cyclomatic Complexity of 14 (threshold is 10). To me this code doesn't seem to hard to follow. Would you refactor it in some way to lower the metric?</p>
<ol>
<li>Exit if <code>$payload</code> isn't an array or has a number of elements not equal to 1</li>
<li>If <code>$payload</code> is <code>array</code> or <code>ArrayAccess</code> build a proper checker/setter</li>
<li>If <code>$payload</code> is <code>stdClass</code> do the same as 2</li>
<li>Use control options and checker/setter to actually set the value inside <code>$payload</code></li>
</ol>
<p>The method:</p>
<pre><code>public function onBeforeEncrypt(CryptDecryptEvent $event)
{
// Get the actual parameters of the call
$payload = $event->getPayload();
// Avoid errors when __soapCall is invoked directly with custom arguments
if (!is_array($payload) || 1 !== count($payload)) {
return;
}
// Reference to the payload (by reference just in case it's an array)
$payload = &$payload[0];
// Shortcuts to control options
$paramName = $this->options['name'];
$paramValue = $this->options['value'];
$allowOverride = $this->options['allowOverride'];
$nullLikeNotSet = $this->options['threatNullLikeNotSet'];
// Dynamically build checker and setter based on the type
$checker = $setter = null;
// Payload is array or ArrayAccess implementation inside main array
if (is_array($payload) || $payload instanceof \ArrayAccess) {
$checker = function ($k) use ($payload, $nullLikeNotSet) {
return isset($payload[$k]) || (null === $payload[$k] && $nullLikeNotSet);
};
$setter = function ($k, $v) use (&$payload) { $payload[$k] = $v; };
}
// Payload is stdClass inside the main array
if ($payload instanceof \stdClass) {
$checker = function ($p) use ($payload, $nullLikeNotSet) {
return isset($payload->$p) || (null === $payload->$p && $nullLikeNotSet);
};
$setter = function ($p, $v) use ($payload) { $payload->$p = $v; };
}
// Set the value if we can override or parameter is abset
if ($checker && $setter && ($allowOverride || !$checker($paramName)) {
$setter($paramName, $paramValue);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You could easily extract the 4 functions you have within if statements by having</p>\n\n<pre><code>arrayChecker()\narraySetter()\nclassChecker()\narraySetter()\n</code></pre>\n\n<p>And then have something like </p>\n\n<pre><code>//Exit immediately if override is not allowed ( why wait ? )\n//Personally, that would be the first line for me\nif(!$allowOverride)\n return;\n\n// Payload is array or ArrayAccess implementation inside main array\nif (is_array($payload) || $payload instanceof \\ArrayAccess) {\n if(!$arrayChecker($paramName)) {\n $arraySetter($paramName, $paramValue);\n }\n}\n\n// Payload is stdClass inside the main array\nif ($payload instanceof \\stdClass) {\n if(!$classChecker($paramName)) {\n $classSetter($paramName, $paramValue);\n }\n} \n</code></pre>\n\n<p>One more thing, you re-use the payload variable. For me, what you get from ->getPayload() is a payload of an array with something in the first position. ( crate plus the goods ). To then re-use the variable to point just to the goods seems wrong to me.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T14:06:50.163",
"Id": "29397",
"ParentId": "29368",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T15:42:25.143",
"Id": "29368",
"Score": "1",
"Tags": [
"php",
"php5"
],
"Title": "Lowering the cyclomatic complexity of this method, suggestions?"
}
|
29368
|
<p>I am building a PHP framework and would like to get some feedback on a few different section of the project so far. I consider myself still a neophyte in PHP so I would like to ask if I'm going about completing this different task in an efficient and or correct way.</p>
<p>This section is of the Template parser. I wish to create a parser that will take html files with only tags [@tag] and <strong>no php</strong> and have it parse the file replacing the tags with supplied data and return it if it need to be used in the parsing of another template.</p>
<p>From research and a personal idea I thought it would be best to try and divide the parsing mechanics and the injecting of dynamic data/info. So I created two classes the Page class and Template class. The template class over sees the parsing of the html files and the page over sees that tag replacement.</p>
<p>Template Class (instantiates the page class)<br>
<strong>template.object.php</strong></p>
<pre><code>class Template{
private $appath;
private $page;
protected $settings;
private $issettings;
public $tags = array();
public $store = array();
public $template = array();
//Set path for templat use
public $path;
/**
* Set app_path, include page class
* Create Page instance
*/
public function __construct(){
$this->appath = APP_PATH;
require_once(dirname(__FILE__).'/'.'page.object.php');
$this->page = new Page();
}
/**
* Set the path to template file
* values are added to an array
* @param Int $tempkey - Key value to be used to identify value
* @return Int $tempkey used
*/
public function SetTemplateFile($tempkey,$file){
if(isset($this->settings)){
$template = $this->appath.'/styles/'.$this->settings.'/templates/'.$file.'.template.html';
if(file_exists($template)){
$this->template[$tempkey] = $template;
return $tempkey;
}else{
trigger_error('Temple file not found',E_USER_ERROR);
}
}
}
/**
* Retrieves set template files
* Note: Retrieved from an array Key identifier needed
* @param String or Int $key - Index key used to
* @return Int $tempkey used
*/
public function GetTemplateFile($key){
if(array_key_exists($key,$this->template)){
return $this->template[$key];
}else{
trigger_error('Template File key not found',E_USER_ERROR);
}
}
/**
* Manually set temple block tags content
* Note: Manually add content to a section of the template
* @param String $tags - the template tag to place $value
* @param String $value - content to replace $tag
* @return String of the tag selected
*/
public function SetTags($tags,$value){
$this->tags[$tags] = $value;
return $tags;
}
/**
* Set a group of tags with using an array
* Note: meant to use a multidimensional array
* @param Array $array - multidimensional array with the tag as the key and value as the tag value
* @return Null
*/
public function SetGroupTags($array){
if(is_array($array)){
foreach ($array as $subarray) {
foreach ($subarray as $key => $value) {
$this->tags[$key] = $value;
}
}
}else{
trigger_error('Paramete for not an array '.gettype($array).' type given',E_USER_ERROR);
}
}
/**
* Set a group of tags with using an array
* Note: Meant to work with a multidimensional array
* Stores the data in member variable $store
* @param Array $array - multidimensional array with the tag as the key and value as the tag value
* @return Null
*/
public function SetBlock($tempkey,$array){
if(file_exists($this->template[$tempkey])) {
foreach ($array as $subarray) {
$output = file_get_contents($this->template[$tempkey]);
foreach ($subarray as $key => $value) {
$tagToReplace = "[@$key]";
$output = str_replace($tagToReplace, $value, $output);
}
$this->store[] = $output;
}
}else{
trigger_error('Unable to set template block',E_USER_ERROR);
}
}
/**
* Phrases values stored in member variable $store
* @param Null
* @return String phrased template block
*/
public function RunBlock(){
foreach ($this->store as $value) {
$output .=$value."\n";
}
//Temp FIX
unset($this->store);
return $output;
}
/**
* Set page template tags with meta, script, and style tags value
* @param Null
* @return Null
*/
public function AddHeadFiles(){
$this->tags['meta'] = $this->page->GetMeta();
$this->tags['script'] = $this->page->GetJS();
$this->tags['styles'] = $this->page->GetCSS();
}
/**
* Set page template tags with meta, script, and style tags value
* @param Null
* @return Null
*/
public function Output($key){
if (file_exists($this->template[$key])) {
//Add JavaScripts, StyleSheets and Meta tags info using (PageCon method)
$this->AddHeadFiles();
$output = file_get_contents($this->template[$key]);
foreach ($this->tags as $key => $value) {
$tagToReplace = "[@$key]";
$output = str_replace($tagToReplace, $value, $output);
}
return $output;
}else{
trigger_error('Unable to phrase template block',E_USER_ERROR);
return false;
}
}
/**
* Set the styles directory to use
* Note: Settings is used to reference the directory to use
* when working this a template files
*
* @param String $data - Name of directory of template files
* @return Null
*/
public function SetSettings($data){
if($this->IsSetting($data)){
$this->settings = $data;
//Add the [@path] tag with
//To supply a direct path for the css and js files
$this->tags['path'] = 'styles/'.$data;
//Send setting to PageCon
$this->page->GetTempSet($data);
}else{
trigger_error('Invalid parameter of: ('.$data.')',E_USER_ERROR);
}
}
/**
* Check to see if a directory with the name of the setting valus
*
* @param String $data - setting valus being used
* @return true or Null
*
* If error is caught for the DirIterator throws and exception
*/
public function IsSetting($data){
$this->issettings = $this->appath.'/styles/'.$data;
try{
$dir = new DirectoryIterator($this->issettings);
if($dir->isDir()){
return true;
}
}catch(Exception $e){
echo '<strong>Template Error: in Class Template{} Line '.$e->getLine().'</strong><br />';
}
}
public function __destruct(){
//Empty
}
}
</code></pre>
<p>Page Class<br>
<strong>page.object.php</strong> </p>
<pre><code>class Page{
//Header tags
public $title;
public $meta = array();
public $styles = array();
public $scripts = array();
private $settings;
//Body tage
public $menu = array();
public $bodyTags = array();
public $addBodyTags;
public function __construct(){
//Empty
}
/**
* Set the metatags to be added to the page
* @param Array $array - an array of the meta tags and information
* @return Null
*/
public function SetMeta($array){
foreach ($array as $value) {
foreach ($value as $key => $value) {
$output .= ''.$key.'="'.$value.'" ';
}
$this->meta[] = "<meta $output />";
unset($output);
}
}
/**
* Retrieve the metatag information set
* @param Null
* @return string of metatag information
*/
public function GetMeta(){
foreach ($this->meta as $metatag) {
$output .= $metatag."\n";
}
return $output;
}
/**
* Set template setting for Template class
* @param String $settings - template file to use when generating page
* @return Null
*/
public function GetTempSet($settings){
$this->settings = $settings;
}
/**
* An array of JavaScript files
* @param Array $array - js files to add
* @return Null
*/
public function AddJS($array){
$arg = explode(',',$array);
for ($i = 0; $i < count($arg); $i++){
if(strpos($arg[$i],'.js')){
$this->scripts[] = '<script src="styles/'.$this->settings.'/js/'.$arg[$i].'" type="text/javascript"></script>';
}else{
$this->scripts[] = '<script src="styles/'.$this->settings.'/js/'.$arg[$i].'.js" type="text/javascript"></script>';
}
}
}
/**
* Retrieve a list of the added JavaScript files to include into the page
* @param Null
* @return String list of js files
*/
public function GetJS(){
foreach ($this->scripts as $script) {
$output .= $script."\n";
}
return $output;
}
/**
* An array of CSS files
* @param Array $array - css files to add
* @return Null
*/
public function AddCSS($array){
$arg = explode(',',$array);
for ($i = 0; $i < count($arg); $i++){
if(strpos($arg[$i],'.css')){
$this->styles[] = '<link rel="stylesheet" href="styles/'.$this->settings.'/css/'.$arg[$i].'"/>';
}else{
$this->styles[] = '<link rel="stylesheet" href="styles/'.$this->settings.'/css/'.$arg[$i].'.css"/>';
}
}
}
/**
* Retrieve a list of the added CSS files to include into the page
* @param Null
* @return String list of css files
*/
public function GetCSS(){
foreach ($this->styles as $style) {
$output .= $style."\n";
}
return $output;
}
public function __destruct(){
//Empty
}
}
</code></pre>
<p>Here is an example of them being used to generate a html list using ulist.template.html and lilist.template.html </p>
<p>HTML files being used in esample<br>
<strong>ulist.template.html</strong> </p>
<pre><code><ul>
[@list]
</ul>
</code></pre>
<p><strong>lilist.template.html</strong></p>
<pre><code><li><a href="[@link]">[@text]</a></li>
</code></pre>
<p><strong>PHP code EX</strong></p>
<pre><code>//Sample array of data
$array = array(
array('link' => 'http://website1.com','text' => 'Website One'),
array('link' => 'http://website2.net','text' => 'Website Two'),
array('link' => 'http://website3.org','text' => 'Website Three')
);
$template = new Template;
//Set style to use for template
$template->SetSettings('demo');
//Set ulist.template.html as a temp file
//to be used
$ultag = $template->SetTemplateFile('ulist','ulist');
//Set lilist.template.html as a temp file
//to be used
$litag = $template->SetTemplateFile('lilist','lilist');
//Data to be inputed into the temp file
//data used from $array
$template->SetBlock($litag,$array);
//Parse the lilist.template.html file
//with $array data and return parsed temp file
$generatedlilist = $template->RunBlock();
//Add the parsed lilist into ulist.template file
$template->SetTags('list',$generatedlilist);
//Echo generated html list
echo $template->Output($ultag);
</code></pre>
<p>It then outputs the html</p>
<pre><code><ul>
<li><a href="http://website1.com">Website One</a></li>
<li><a href="http://website2.net">Website Two</a></li>
<li><a href="http://website3.org">Website Three</a></li>
</ul>
</code></pre>
<p>There a few steps to parsing a template file I'm not sure if that is a bad thing. I find that it makes building a little easier.</p>
<p>Is this a good way to build this type of function/feature? I am open to any tip, tricks, suggestions, and advice.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T20:19:52.063",
"Id": "46406",
"Score": "0",
"body": "Why reinvent the wheel? Googling \"PHP template engine\" yields smarty, twig, and rain.tpl. Unless this is strictly a learning exercise, I'd use an existing engine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T23:21:03.363",
"Id": "46421",
"Score": "0",
"body": "I'm building this for learning exercise and having a little framework when working on projects wouldn't hurt. Do you think this could be coded better?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T23:21:28.360",
"Id": "46422",
"Score": "0",
"body": "What if the `link` value contains `[@text]`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T23:41:07.703",
"Id": "46425",
"Score": "0",
"body": "I did not think of that then `<a href=\"Website One\">Website One</a>` Are you suggestion I make sure tags can not be used as values to be inputted into the template in the parsing process?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T00:57:19.293",
"Id": "46433",
"Score": "0",
"body": "@andrewnite: Instead of using HTML as input, use XML. Instead of hard-coding tags deep inside PHP, use XSLT to transform XML input into HTML documents."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T03:14:12.223",
"Id": "46437",
"Score": "0",
"body": "@DaveJarvis Thanks for the suggestion. Are you mentioning the `$array`? I used it for a example. It's meant to use info from a db."
}
] |
[
{
"body": "<p>I would separate the components as follows:</p>\n\n<ul>\n<li>Database Layer (PL/SQL)</li>\n<li>View Layer (XSLT)</li>\n<li>Controller Layer (PHP)</li>\n</ul>\n\n<h1>Database Layer</h1>\n\n<p>Abstract out the database so that you can make generic calls to a database. For example:</p>\n\n<pre><code> /**\n * Call a database function and return the results. If there are\n * multiple columns to return, then the value for $params must contain\n * a comma; otherwise, without a comma, the value for $params is used\n * as the return column name. For example:\n *\n *- SELECT $params FROM $proc( ?, ? ); -- with comma\n *- SELECT $proc( ?, ? ) AS $params; -- without comma\n *- SELECT $proc( ?, ? ); -- empty\n *\n * @param $proc Name of the function or stored procedure to call.\n * @param $params Name of parameters to use as return columns.\n */\n public function call( $proc, $params = \"\" ) {\n $args = array();\n $count = 0;\n $placeholders = \"\";\n\n // Key is zero-based (e.g., $proc = 0, $params = 1).\n foreach( func_get_args() as $key => $parameter ) {\n // Skip the $proc and $params arguments to this method.\n if( $key < 2 ) continue;\n\n $count++;\n $placeholders = empty( $placeholders ) ? \"?\" : \"$placeholders,?\";\n array_push( $args, $parameter );\n }\n\n $sql = \"\";\n\n if( empty( $params ) ) {\n // If there are no parameters, then just make a call.\n $sql = \"SELECT schema.$proc( $placeholders )\";\n }\n else if( strpos( $params, \",\" ) !== false ) {\n // If there is a comma, select the column names.\n $sql = \"SELECT $params FROM schema.$proc( $placeholders )\";\n }\n else {\n // Otherwise, select the result into the given column name.\n $sql = \"SELECT schema.$proc( $placeholders ) AS $params\";\n }\n\n $db = $this->getDataStore();\n $statement = $db->prepare( $sql );\n\n for( $i = 1; $i <= $count; $i++ ) {\n //$this->log( \"Bind \" . $i . \" to \" . $args[$i - 1] );\n $statement->bindParam( $i, $args[$i - 1] );\n }\n\n try {\n $result = null;\n\n if( $statement->execute() === true ) {\n $result = $statement->fetchAll( PDO::FETCH_ASSOC );\n $this->decodeArray( $result );\n }\n else {\n // \\todo Send an e-mail.\n $info = $statement->errorInfo();\n $this->log( \"SQL failed: $sql\" );\n $this->log( \"Error: \". $info[2] );\n }\n }\n catch( PDOException $ex ) {\n // \\todo Send an e-mail.\n $this->log( $ex->getMessage() );\n }\n\n return $result;\n }\n</code></pre>\n\n<p>Be sure to replace <code>schema.</code> with your own schema name, or pass it in. This allows you to write:</p>\n\n<pre><code>$db->call( \"stored_function\", ... );\n</code></pre>\n\n<p>Where <code>...</code> represent the parameters and name of the return value. For the most part, the database functions should return an XML document.</p>\n\n<p>The XML document is the contract between the database and the controller. This not only separates concerns, but it means that you can swap databases and implementation languages independently. If your project needs PostgreSQL over MySQL, so be it: no PHP code needs to change. If your project needs to use Go instead of PHP, so be it: no database code needs to change.</p>\n\n<h1>View Layer</h1>\n\n<p>Write a wrapper around PHP's XSLT processor. This can then be used to transform the XML document into any data format you require. This includes XHTML, CSV, or even LaTeX (to generate high-quality PDFs). Such a class might resemble:</p>\n\n<pre><code>Use XSLTProcessor;\nUse DOMDocument;\n\n/**\n * Transforms XML data (into HTML, LaTeX, and XML).\n */\nclass Xslt {\n /** The XML DOM to transform (mandatory). */\n private $xmlDom;\n\n /** The stylesheet DOM to use for the transformation (mandatory). */\n private $xslDom;\n\n /** The XSLT Engine to use for transforming XML documents. */\n private $xslt;\n\n /**\n * Instantiates a new XSLTProcessor class.\n *\n * \\todo Enforce XML and XSL data as arguments and make corresponding\n * set methods private?\n */\n public function __construct() {\n $this->xslt = new XSLTProcessor();\n }\n\n /**\n * Performs the XSL transformation and then returns the results. The\n * XML document must have been set using the setXml method.\n *\n * @see setXml\n * @return The results from transformToXML on the DOM using the\n * internal XSLTProcessor instance.\n */\n public function transform() {\n $this->getXsltEngine()->importStyleSheet( $this->getXslDom() );\n return $this->getXsltEngine()->transformToXML( $this->getXmlDom() );\n }\n\n /**\n * Sets the XML DOM based on the given data. This calls the toXmlDom\n * method.\n *\n * @param $xmlData An XML document as a string.\n * @see toXmlDom\n * @see setXmlDom\n */\n public function setXml( $xmlData ) {\n $this->setXmlDom( $this->toXmlDom( $xmlData ) );\n }\n\n /**\n * Sets the XML DOM based on the given data. The data must have\n *\n * @param $xmlDom A DOM object.\n * @see setXml\n */\n public function setXmlDom( $xmlDom ) {\n $this->xmlDom = $xmlDom;\n }\n\n /**\n * Converts the given XML data into a DOM object. This does not update\n * the internal DOM object.\n *\n * @param $data An XML document as a string to convert to a DOM.\n */\n public function toXmlDom( $data ) {\n $dom = $this->createDom();\n $dom->formatOutput = $this->getFormatOutput();\n $dom->preserveWhiteSpace = $this->getPreserveWhiteSpace();\n $dom->loadXML( $data );\n\n return $dom;\n }\n\n /**\n * Sets the XSL DOM.\n */\n public function setStylesheet( $stylesheet ) {\n $xsl = $this->createDom();\n $xsl->load( $stylesheet );\n\n $this->xslDom = $xsl;\n }\n\n /**\n * Passes a parameter to the XSLT engine, in the default namespace.\n */\n public function setParameter( $k, $v ) {\n $this->getXsltEngine()->setParameter( \"\", $k, $v );\n }\n\n /**\n * Returns the XML DOM to use for transformation.\n */\n private function getXmlDom() {\n return $this->xmlDom;\n }\n\n /**\n * Returns the XSL DOM to use for transformation.\n */\n private function getXslDom() {\n return $this->xslDom;\n }\n\n /**\n * Returns false to indicate that the XML output should not be formatted\n * in a human-readable way (i.e., indented).\n */\n private function getFormatOutput() {\n return false;\n }\n\n /**\n * Returns false to indicate that white space should not be preserved in\n * the final document.\n */\n private function getPreserveWhiteSpace() {\n return false;\n }\n\n /**\n * Returns the XSLT engine to use for transformations.\n */\n private function getXsltEngine() {\n return $this->xslt;\n }\n\n /**\n * Helper method to create a DOM object (used for XML and XSL DOMs).\n */\n private function createDom() {\n global $DEFAULT_CHARACTER_ENCODING;\n return new DOMDocument( \"1.0\", $DEFAULT_CHARACTER_ENCODING );\n }\n}\n</code></pre>\n\n<p>You would have to write an <a href=\"http://en.wikipedia.org/wiki/XSLT#XSLT_examples\" rel=\"nofollow\">XSLT stylesheet</a> to transform the XML document into your desired output.</p>\n\n<p>The advantage here is that the lines for <code><link ... /></code> need be written only once. You can completely do away with any element duplication in your source code by using XSLT.</p>\n\n<p>A big disadvantage is that XSLT is not simple.</p>\n\n<h1>Controller Layer</h1>\n\n<p>Use PHP to parse the requests from the user, determine what type of output you want (XHTML vs. CSV vs. LaTeX), set any necessary parameters, then call the XSLT engine to transform the XML document retrieved from the database into your final output. In code, this might resemble:</p>\n\n<pre><code>// Get the requested command by the user.\n$command = $_POST[ \"command\" ];\n\n// Determine the appropriate method call.\n$method = $this->lookup( $command );\n\n// Execute the user's command.\n$this->{$method}();\n\n// Render the result.\n$this->render();\n</code></pre>\n\n<p>You might, for example, map a command such as \"update.username\" to an <code>updateUserName</code> method:</p>\n\n<pre><code>private function updateUserName() {\n $id = $this->getId();\n $userName = $_POST[ \"username\" ];\n\n $result = $this->call( \"set_username\", $userName, \"x\" );\n\n $this->setXml( $result[0][\"x\"] );\n}\n\nprivate function render() {\n $xslt = new Xslt();\n echo $xslt->transform();\n}\n</code></pre>\n\n<p>Now you can:</p>\n\n<ul>\n<li>Control the look of the application from XSL files.</li>\n<li>Vary the database and the implementation language independently.</li>\n<li>Avoid proliferating CRUD operations throughout the PHP code base.</li>\n<li>Limit the amount of duplicated code throughout the entire application.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T03:55:42.223",
"Id": "29383",
"ParentId": "29369",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29383",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T16:44:20.843",
"Id": "29369",
"Score": "1",
"Tags": [
"php",
"optimization",
"design-patterns"
],
"Title": "PHP framework building: Template parsing"
}
|
29369
|
<p>After 4+ months since I started learning web design I created my very first website. It's far from perfect but I learned a lot since then. I would appreciate it if someone would be so kind to review my work and suggest fixes to make it more functional and run more smoothly.</p>
<p>Please, don't pay attention to background photos as I use them just to be able to test how everything works. Rather, pay attention on how the text, images and other elements behave on different screen sizes.</p>
<p>I tried to add some media queries too, but I'm not satisfied how everything behaves when I shrink my screen (especially the navbar).</p>
<p><a href="http://jsfiddle.net/vEEEv/" rel="nofollow">jsFiddle</a></p>
<p><strong>HTML:</strong></p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<title>My Web Design Studio</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.min.js'></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel='stylesheet' type='text/css' href='http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css'/>
<script type='text/javascript' src='smoothscrolling.js'></script>
<link type="text/css" rel="stylesheet" href="stylesheet.css"/>
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
</head>
<body>
<header>
<a href="#" id="#logo"><img class="topleftlogo" src="images/Mangosteen.png"/></a>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#portfolio">Portfolio</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</header>
<section id="home" class="photobg">
<div class="inner">
<div class="copy">
<h1 class="logoimage"></h1>
</div>
</div>
</section>
<section id="about" class="content">
<div class="inner">
<div class="copy">
<h1>Who I Am</h1>
<p class="aboutparagraph">Hello! Lorem ipsum dolor sit amet, <span class="lightblue">consectetuer adipiscing elit,</span> sed diam nonummy nibh euismod tincidunt ut <span class="mangosteenred">laoreet dolore magna</span> aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.<br></br>Duis autem vel eum iriure dolor in hendrerit in <span class="green">vulputate</span>.</p>
<p class="aboutparagraph">Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem.Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius.</p>
</div>
</div>
</section>
<section id="services" class="photobg">
<div class="inner">
<div class="copy">
<h1>What I Do</h1>
<p class="aboutparagraph">Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, <span class="yellow">quam nunc putamus parum claram,</span> anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.</p>
<p class="aboutparagraph">Duis autem <span class="yellow">vel eum iriure</span> lorem ipsum <span class="yellow">dolor in hendrerit <span class="yellow">lorem ipsum </span>yut putamus parum</span> in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p>
<div class="skills">
<img src="images/html5.png"></img>
<img src="images/css3.png"></img>
<img src="images/javascript.png"></img>
<img src="images/jquery.png"></img>
<img src="images/php.png"></img>
</div>
</div>
</div>
</section>
<section id="portfolio" class="content portfolio">
<div class="inner">
<div class="copy">
<div class="container">
<div class="box">
<h1>What I have designed so far...</h1>
<div class="myprojects">
<div class="projectshot">
<a href="http://www.yahoo.com" target="_blank">
<img alt="Tour Eiffel" src="http://www.blirk.net/wallpapers/800x600/eiffel-tower-wallpaper-6.jpg">
</a>
</div>
<div class="projectshot">
<a href="http://www.google.com" target="_blank">
<img alt="OJ" src="http://www.wallpaperpimper.com/wallpaper/Food/Drink/Orange-Juice-2-TYHC9143B7-800x600.jpg">
</a>
</div>
<div class="projectshot">
<a href="http://www.yahoo.com" target="_blank">
<img alt="Maldives" src="http://imgs.mi9.com/uploads/holiday/1194/maldives-wallpapers_800x600_17618.jpg">
</a>
</div>
<div class="projectshot">
<a href="http://www.google.com" target="_blank">
<img alt="Ice Block" src="http://wfiles.brothersoft.com/a/amazing-ice-block_178821-800x600.jpg">
</a>
</div>
<div class="projectshot">
<a href="http://www.yahoo.com" target="_blank">
<img alt="Ko Phi Phi" src="http://www.allystrip.com/photos/desktops/desktop800x600_Thailand%20-%20IMG_2274.jpg">
</a>
</div>
<div class="projectshot">
<a href="http://www.google.com" target="_blank">
<img alt="Serious Wheels" src="http://www.seriouswheels.com/pics-2006/2006-Faralli-and-Mazzanti-Antas-V8-Top-800x600.jpg">
</a>
</div>
<div class="projectshot">
<a href="http://www.yahoo.com" target="_blank">
<img alt="Sushi" src="http://www.wallpaperpimper.com/wallpaper/Food/Seafood/Sasami-Sushi-2-BYS187A20O-800x600.jpg">
</a>
</div>
<div class="projectshot">
<a href="http://www.google.com" target="_blank">
<img alt="Tea" src="http://www.wallpaperpimper.com/wallpaper/Food/Drink/Ice-Tea-4-51RE8V877Y-800x600.jpg">
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="contact" class="newsection">
<div class="copy">
<h1>Where You Can Find Me</h1>
<p>My Web Design Studio &#8226; A: Lorem Ipsum 1234, New York, NY, USA</p>
<p>T: +1 983 294 787 &#8226; E: contact@mywebstudio.com</p>
<div class="mapholder"><a href="https://maps.google.com/maps?q=New+York,+NY,+United+States&hl=en&sll=37.0625,-95.677068&sspn=35.684144,86.572266&oq=New+Yo&hnear=New+York&t=m&z=10" target="_blank"><img class="map" src="images/Map.png"/></a></div>
<p>Thank you for visiting my website!</p>
</div>
<div id="footer"><p>&copy; 2013 My Web Design Studio. All rights reserved.</p></div>
</section>
<link href='http://fonts.googleapis.com/css?family=Roboto+Slab:400,700' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Noto+Sans' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Fauna+One' rel='stylesheet' type='text/css'>
</body>
</html>
</code></pre>
<p><strong>CSS:</strong></p>
<pre class="lang-css prettyprint-override"><code>html, body{
margin:0px;
padding:0px;
height: 100%;
}
section {
height: 100%;
}
header{
z-index: 1;
position:fixed;
width:100%;
background:rgba(0,0,0,0.1);
min-width: 900px; /* This prevents the entire header(logo and nav buttons) from dropping underneath one another when the width of the page is smaller than the nav width.*/
}
header ul{
float:right;
padding:0px;
margin:0px;
}
header ul li{
display: inline;
float:left;
}
header ul li a:hover{
color:yellow;
}
header a{
color:white;
background:rgba(0,0,0,0.1);
display:inline-block;
padding:0px 30px;
height:60px;
line-height:60px;
text-align:center;
font-family: 'Roboto Slab', serif;
text-decoration:none;
text-transform:uppercase;
letter-spacing:2px;
font-weight:700;
@include breakpoint(mobile) { width: 100%; }
@include breakpoint(tablet) { width: 50%; }
@include breakpoint(desktop) { width: 25%; }
@include breakpoint(widescreen) {}
}
#home{
background:url(images/sailing.JPG);
background-size:cover;
background-position:center center;
background-attachment:fixed;
}
#services{
background: url(images/nyc1.jpg);
background-size:cover;
background-position:center center;
background-attachment:fixed;
}
.skills{
width: 100%;
margin: 0 auto;
}
.photobg, .content{
text-align:center;
position:relative;
width: 100%;
}
.inner{
height: 100%;
text-align: center;
&:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em; /* Adjusts for spacing */
}
}
.photobg .inner{
background: rgba(0,0,0,0.4) url(images/pattern.png);
}
.copy{
@include pad-rwd;
display: inline-block;
vertical-align: middle;
max-width: 85%;
height:100%;
}
.photobg h1, .photobg p{
color:#fff;
}
.content h1, .content p{
color:#333;
}
h1{
margin-top:70px;
font-family: 'Roboto Slab', serif;
font-weight:400;
font-size:32px;
}
p{
font-family: 'Roboto Slab', serif;
font-size:14px;
}
/*PORTFOLIO*/
.portfolio{
background: url(images/bgnet.png) repeat;
}
.box{
text-align: center;
width: 80%;
margin: 0 auto;
}
.myprojects {
margin-top: 70px;
margin-bottom: 30px;
}
.projectshot {
position: relative;
margin: 0 10px 10px 0;
display: inline-block;
}
.projectshot img {
width: 200px;
height: 150px;
border-radius:5px;
box-shadow: 0 9px 13px rgba(0,0,0,.14);
}
.projectshot a:before {
position: absolute;
border-radius: 5px;
background: url(images/whiteplus.png) center center no-repeat rgba(51,51,51,0.6);
width: 200px;
height: 150px;
content: '';
top: 0;
left: 0;
opacity: 0;
transition: opacity .5s;
}
.projectshot a:hover:before {
opacity: 1;
}
/*END OF PORTFOLIO*/
.newsection{
background: rgb(0, 55, 92);
height:100%;
width:100%;
position:relative;
background-attachment:fixed;
border-top: 5px solid #f5a700;
text-align:center;
color:#fff;
}
.copy .aboutparagraph{
font-family: 'Fauna One', serif;
font-size: 28px;
}
/*SPAN COLORS*/
.lightblue{
color: rgb(19, 139, 204);
}
.mangosteenred{
color: rgb(222, 24, 39);
}
.green{
color: rgb(139, 161, 55);
}
.yellow{
color: yellow;
}
/* END OF SPAN COLORS*/
#about{
background: url(images/bgnet.png) repeat;
}
.logoimage{
background: url("images/mylogo.png") no-repeat scroll center center;
width: 500px;
height: 140px;
background-size: contain;
position:absolute;
top: 50%;
left: 50%;
margin-top: -70px; /* Half the height */
margin-left: -250px; /* Half the width */
}
.topleftlogo{
width: 40px;
height: 40px;
margin-top: 10px;
}
/* CONTACT SECTION*/
p{
font-family: 'Roboto Slab', serif;
font-size:18px;
}
#footer{
position: absolute;
bottom: 0;
width: 100%;
margin: auto;
}
#footer p{
text-align: center;
}
.map{
height: 300px;
width: 300px;
}
/*MEDIA QUERIES*/
@media screen and (max-width : 480px) {
header{
width: 100%;
text-align:center;
}
header ul {
font-size: 70%;
width: 100%;
}
header ul li{
width: 480px;
}
header a{
display:block;
padding:0px 0px;
height:30px;
width: 100%;
line-height:30px;
}
header a:hover{
background-color: rgba(255, 136, 0, 0.5);
width: 100%;
}
header ul li a:hover{
color:white;
}
.logoimage{
background: url("images/mylogo.png") no-repeat scroll center center;
width: 300px;
height: 84px;
background-size: contain;
position:absolute;
top: 50%;
left: 50%;
margin-top: -42px; /* Half the height */
margin-left: -150px; /* Half the width */
}
.topleftlogo{
display: none;
}
h1{
margin-top:190px;
font-family: 'Roboto Slab', serif;
font-weight:400;
font-size:24px;
}
.copy .aboutparagraph{
font-family: 'Fauna One', serif;
font-size: 14px;
}
.box{
text-align: center;
width: 100%;
margin: 0 auto;
}
.myprojects {
margin-top: 20px;
margin-bottom: 20px;
}
.projectshot img {
width: 100px;
height: 75px;
border-radius:3px;
box-shadow: 0 9px 13px rgba(0,0,0,.14);
}
.projectshot a:before {
position: absolute;
border-radius: 3px;
background: url(images/whiteplus.png) center center no-repeat rgba(51,51,51,0.6);
width: 100px;
height: 75px;
content: '';
top: 0;
left: 0;
opacity: 0;
transition: opacity .5s;
}
p {
font-size: 12px;
}
.map{
height: 150px;
width: 150px;
}
}
@media screen and (min-width: 481px) and (max-width : 768px) {
header{
width: 100%;
text-align:center;
}
header ul {
font-size: 90%;
width: 100%;
}
header ul li{
width: 768px;
}
header a{
display: block;
padding:0px 0px;
height:30px;
width: 100%;
line-height:30px;
}
header a:hover{
background-color: rgba(255, 136, 0, 0.5);
width: 100%;
}
header ul li a:hover{
color:white;
}
.logoimage{
background: url("images/mylogo.png") no-repeat scroll center center;
width: 300px;
height: 84px;
background-size: contain;
position:absolute;
top: 50%;
left: 50%;
margin-top: -42px; /* Half the height */
margin-left: -150px; /* Half the width */
}
.topleftlogo{
display: none;
}
h1{
margin-top:190px;
font-family: 'Roboto Slab', serif;
font-weight:400;
font-size:28px;
}
.copy .aboutparagraph{
font-family: 'Fauna One', serif;
font-size: 18px;
}
.box{
text-align: center;
width: 100%;
margin: 0 auto;
}
.myprojects {
margin-top: 20px;
margin-bottom: 20px;
}
.projectshot img {
width: 133px;
height: 100px;
border-radius:3px;
box-shadow: 0 9px 13px rgba(0,0,0,.14);
}
.projectshot a:before {
position: absolute;
border-radius: 3px;
background: url(images/whiteplus.png) center center no-repeat rgba(51,51,51,0.6);
width: 133px;
height: 100px;
content: '';
top: 0;
left: 0;
opacity: 0;
transition: opacity .5s;
}
p {
font-size: 12px;
}
.map{
height: 200px;
width: 200px;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T17:57:01.143",
"Id": "46392",
"Score": "1",
"body": "As per the FAQ, you must embed the code you want reviewed. Email delivery will not work because all these posts are to benefit *everyone*."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T17:59:05.567",
"Id": "46393",
"Score": "0",
"body": "I understand that but how can I post my images here or on jsfiddle? Everything is on my hard disc. Not on a server. I have html, css, javascript and images folder with some patterns, backgrounds and images."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T18:03:09.480",
"Id": "46394",
"Score": "0",
"body": "You'll just have to find a way to include it in this post, otherwise I'm afraid it may not work here. I could probably flag a moderator and see if anything else could be done."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T18:06:44.697",
"Id": "46395",
"Score": "0",
"body": "That's why I thought emailing my work in ZIP is the easier way. Without images it would be hard to review my work and get a real picture how everything behaves and what flaws and mistakes are needed to be corrected. Thanks anyway!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T18:46:13.753",
"Id": "46398",
"Score": "3",
"body": "Actually, a good developer should be able to look at the code and figure out what is going on. This site is for reviewing code looking for formatting, best practices, anti-patterns, etc.. We are less concerned about critiquing the output, or final product."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T18:53:49.580",
"Id": "46399",
"Score": "0",
"body": "Thanks for your reply. I added JSFiddle above. Hope somebody can review my code now, although, some images, patterns and backgrounds are missing. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T18:57:06.217",
"Id": "46400",
"Score": "0",
"body": "@C.Felipe The code in that link could still be embedded, which will make it on-topic. The link itself will not suffice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T19:02:44.977",
"Id": "46401",
"Score": "2",
"body": "I added the code above."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T19:16:22.490",
"Id": "46486",
"Score": "0",
"body": "There are quite a few sample image sites out there for creating quick demos that will serve an image in just about any size you can think of. I've personally used http://placekitten.com and http://placehold.it"
}
] |
[
{
"body": "<p><strong>Regarding your HTML:</strong></p>\n\n<p>You could/should add a <code>meta</code> element (as the first element in the <code>head</code>) specifying the character encoding of the document. If it’s UTF-8, it could look like:</p>\n\n<pre><code><meta charset=\"utf-8\" />\n</code></pre>\n\n<p>Your logo image misses an <code>alt</code> attribute.</p>\n\n<p>You could use <code>nav</code> as container for the navigation <code>ul</code> in the <code>header</code>.</p>\n\n<p>The <code>img</code> markup (your skills) should be <code><img src=\"images/html5.png\" /></code> instead of <code><img src=\"images/html5.png\"></img></code>. + <code>alt</code> attribute.</p>\n\n<p>You have three <code>link</code> elements at the end of your <code>body</code>. This is not allowed (they need to be in the <code>head</code>, if they are not used for e.g. Microdata).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T09:14:59.343",
"Id": "46705",
"Score": "0",
"body": "Thanks for your review and suggestions. I appreciate it very much! Why is it important to add alt attribute to my logo image? Also, some people add link elements at the end of the body so I don't really see the difference as they are working fine even when they are at the bottom. Why is it not allowed? Thank you again for your response and help!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T10:12:55.873",
"Id": "46707",
"Score": "0",
"body": "@C.Felipe: `alt` attribute is useful for people and bots that can’t access the image, for example visually impaired users, text browser users, users that have deactivated graphics or that have loading problems, search engines, …."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T10:17:36.097",
"Id": "46708",
"Score": "0",
"body": "@C.Felipe: What works is not necessarily correct. Problems can occur, can occur only with some browser, or only in some time in the future, etc. That’s why there are standards. You should follow them (unless you have strong reasons). See how the [`link` element](http://www.w3.org/TR/html5/document-metadata.html#the-link-element) is defined and where it is allowed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T17:27:30.027",
"Id": "59597",
"Score": "0",
"body": "If with links in the bottom you wanted defer the loading maybe you can do this with `javascript` instead. But it will not be a designer question anymore."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T21:24:18.623",
"Id": "29414",
"ParentId": "29373",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "29414",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T17:46:33.747",
"Id": "29373",
"Score": "4",
"Tags": [
"html",
"css"
],
"Title": "Web design studio site"
}
|
29373
|
<pre><code>def dfs(graph, node):
"""Run DFS through the graph from the starting
node and return the nodes in order of finishing time.
"""
stack = [[node, True]]
while True in [x[1] for x in stack]:
i = 0
for x in xrange(len(stack)):
if stack[x][1] == True:
i = x
break
stack[i][1] = False
stack = [[x, True] for x in graph[stack[i][0]] \
if (([x, True] not in stack) and ([x, False] not in stack))] + stack
return [x[0] for x in stack]
</code></pre>
<p><strong>Input:</strong> Graph as adjacency list Eg: {1:[2, 3], 2:[1], 3:[]}<br>
Node is an integer value from where depth first search begins Eg: 1<br>
<strong>Output:</strong> The list of nodes in order of their finishing times.<br>
Eg: [3, 2, 1] </p>
<p>For large graphs, the above code is taking too long to execute. Is there a better way to do this?<br>
<strong>Edit:</strong> I could do better time by implementing the following code. Is it possible to do even better? </p>
<pre><code>def dfs(graph, node):
"""Run DFS through the graph from the starting
node and return the nodes in order of finishing time.
"""
seen = defaultdict(bool)
stack = [node]
while True:
flag = True
for x in stack:
if not seen[x]:
stack = [a for a in graph[x] if not seen[a]] + stack
seen[x] = True
flag = False
break
if flag:
break
return stack
</code></pre>
<p><strong>Edit:</strong> I've changed seen and stack variables to sets. But I'm not getting the required performance boost. What am I doing wrong? </p>
<pre><code>def dfs(graph, node):
"""Run DFS through the graph from the starting
node and return the nodes in order of finishing time.
"""
seen = set()
stack = {node}
while True:
flag = True
for x in stack:
if x not in seen:
stack = stack.union(set(graph[x]))
seen = seen.union({x})
flag = False
break
if flag:
break
return list(stack)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T12:17:59.620",
"Id": "46536",
"Score": "0",
"body": "This does not do depth-first search, it does breadth-first search. Which do you want? I'll write an answer later today when I have time. Btw: The third function doesn't work because sets aren't ordered (unless all you want to do is to find all nodes that are reachable from the starting node)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T06:18:07.243",
"Id": "46643",
"Score": "0",
"body": "Winston has already answered it better than I could, so nevermind."
}
] |
[
{
"body": "<p>Some hints.</p>\n\n<p>Set type can be used for seen variable.</p>\n\n<p>That stack = [...] + stack is a monster, both + operation and list comprehension.</p>\n\n<p>Is it possible to use set there (what type graph[x] is?). Maybe, its more efficient to have stack in a list of lists form?</p>\n\n<p><strong>UPDATE</strong>: loop over the whole stack again and again can be another point of optimization.</p>\n\n<p><strong>UPDATE2</strong>: in case you have not solved the problem, one possible way is to eliminate the inefficient filtering of the stack against seen values. This can be achieved by having a set of not yet visited nodes and using set operations to get the next level from the current level. This is why I've advised to keep levels in the stack (list of sets - as particular order inside a level is not important, is it?). Operating on relatively small number of nodes in the latest level is more efficient than looping over the whole stack. Actually, already seen nodes can also be subtracted from \"next level\", so if the speed is ok, set of unvisited nodes can be redundant.</p>\n\n<p><strong>UPDATE3</strong>:</p>\n\n<p>I think, the following produces result, which is stated in the docstring. Finishing time is a time when the node has no more children to process and is popped from the stack. Reverse order can also be easily achieved by changing .append(x) to insert(0, x). </p>\n\n<pre><code>def dfs(graph, node):\n \"\"\"Run DFS through the graph from the starting\n node and return the nodes in order of finishing time.\n \"\"\"\n seen = {node}\n stack = [node]\n result = []\n while stack:\n x = stack[-1]\n nxt = set(graph.get(x, [])) - seen\n if nxt:\n stack.extend(list(nxt))\n seen |= nxt\n else:\n result.append(x)\n stack.pop()\n return result\n</code></pre>\n\n<p>Remark: the algorithm does not preserve the order of children. Minor modification may be needed to preserve the order of graph.get(x, []), in if nxt:</p>\n\n<pre><code>stack.extend(nx for nx in graph[x] if nx in nxt)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T10:52:30.693",
"Id": "46524",
"Score": "0",
"body": "I tried using sets, I've edited the question description to include the edited code. The running time is not very different from my second attempt. Can you tell me where I'm going wrong?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T12:20:14.160",
"Id": "46537",
"Score": "0",
"body": "@Roman The type of `graph[x]` is a list: (quoting vaishaks) \"Input: Graph as adjacency list Eg: `{1:[2, 3], 2:[1], 3:[]}`\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T15:19:43.897",
"Id": "46565",
"Score": "0",
"body": "Those can be easily converted to sets, of course. (if the order of traversal is not important)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T07:23:11.647",
"Id": "46739",
"Score": "0",
"body": "@Roman Update3 is achieving exactly what I needed and it's running in good time. Thanks a lot Roman!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T19:30:45.320",
"Id": "29408",
"ParentId": "29374",
"Score": "2"
}
},
{
"body": "<pre><code>def dfs(graph, node):\n</code></pre>\n\n<p>This isn't a depth first search</p>\n\n<pre><code> \"\"\"Run DFS through the graph from the starting \n node and return the nodes in order of finishing time.\n \"\"\"\n seen = set()\n stack = {node}\n</code></pre>\n\n<p>You aren't using this as a stack, don't call it that</p>\n\n<pre><code> while True:\n flag = True\n</code></pre>\n\n<p>avoid flag variables, they confound code. Also that's a very undescriptive name.</p>\n\n<pre><code> for x in stack:\n if x not in seen:\n</code></pre>\n\n<p>Seen these are sets, you should be probably use: <code>for x in stack - seen:</code> which should be more efficient</p>\n\n<pre><code> stack = stack.union(set(graph[x]))\n</code></pre>\n\n<p>Using this approach will make things rather slow, you just keep making stack bigger and bigger.</p>\n\n<pre><code> seen = seen.union({x})\n</code></pre>\n\n<p>Use seen.add to add things to the set. Using union like this will be much slower</p>\n\n<pre><code> flag = False\n break\n if flag:\n break\n return list(stack)\n</code></pre>\n\n<p>The set gives you no guarantees as to the order of the elements. I'm guessing that's now what you wanted. As it stands,this will end up giving you all the elements in your graph in a random order.</p>\n\n<p>My approach</p>\n\n<pre><code>def breadth_first_search(graph, start):\n seen = set()\n current = {start}\n history = []\n\n while current:\n history.extend(current) # record when we found all these elements\n seen.update(current) # add them to the list of elements we've already seen\n neighbours = set() # generate a set of all elements that we can reach from these ones\n for node in current:\n neighbours.update(graph[node])\n current = neighbours - seen # the next round of elements is this one, except those we've already seen\n\n\n return history\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T14:09:06.797",
"Id": "46658",
"Score": "0",
"body": "That is a brilliant answer Winston. I learnt a lot from that. But my application requires me to return the nodes in order of finishing times the way dfs would finish. I agree my iterative code looks a lot like bfs. And your code works perfectly well if I needed the nodes to be returned in order of finishing times the way bfs would. But the code I wrote gives me the right answer for small graphs. It's not at all random(because of using sets) as one would expect it to be. I find that very weird now that I know sets are un-ordered. Can you please tell me how you would do it for dfs?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T17:13:39.557",
"Id": "46675",
"Score": "0",
"body": "@vaishaks, your code working for small graphs is greatly mysterious. Any chance you can get me the data you ran it against?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T18:20:11.253",
"Id": "46682",
"Score": "0",
"body": "Sorry the output of the set code makes no sense actually. My bad. I've now reverted to function 2. The one with the defaultdict. \n**Graph:** {1: [3], 2: [1], 3: [2], 4: [3, 5, 6], 6: [8], 7: [6], 8: [7]} \n**Start:** 8, \n**Your approach Output:** [8, 7, 6] **Required output:** [6, 7, 8]. **Start:** 4, **Your approach Output:** [4, 3, 5, 6, 8, 2, 1, 7], **Required output:** [7, 8, 1, 2, 3, 5, 6, 4]"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T20:36:29.917",
"Id": "46688",
"Score": "0",
"body": "@vaishaks, ok. why do you need this in dfs order?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T07:18:24.000",
"Id": "46703",
"Score": "0",
"body": "@vaishaks: You're right that it's not bfs (I was mistaken earlier), but it's not dfs either. (This may or may not be what you want.) E.g., in your last example, dfs would start at 4, go to one of the successors of 4, (let's say 3). Then dfs would take one of the children of 3, and so on. The other successor of 4 would only be traversed later. Also, is it important that the output be in \"reversed\" order (starting point at the end)?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T16:19:46.090",
"Id": "29460",
"ParentId": "29374",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "29408",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T18:18:34.683",
"Id": "29374",
"Score": "4",
"Tags": [
"python",
"optimization",
"algorithm",
"performance",
"graph"
],
"Title": "Can someone help me optimize my DFS implementation in Python?"
}
|
29374
|
<p>I'm new to Haskell and I've made a very short <a href="https://en.wikipedia.org/wiki/KenKen" rel="nofollow">KenKen</a> solver. Any input is welcome.</p>
<pre><code>import Data.List
import Control.Monad
set :: [Int] -> Bool
set x = x == nub x
mats :: Int -> [[[Int]]]
mats x = filter (all set . transpose) . replicateM x $ permutations [1 .. x]
doIt :: Int -> [([(Int, Int)], [Int] -> Int, Int)] -> [[Int]]
doIt n blocks = join . take 1 . foldl' (flip filter) (mats n) $ map bfun blocks
revSort :: Ord a => [a] -> [a]
revSort = sortBy $ flip compare
quotient :: [Int] -> Int
quotient = foldl1 div . revSort
sub :: [Int] -> Int
sub = foldl1 (-) . revSort
bfun :: ([(Int, Int)], [Int] -> Int, Int) -> [[Int]] -> Bool
bfun (locs, opp, res) mat = res == opp (map (\ (x, y) -> mat !! x !! y) locs)
sampleBlocs :: [([(Int, Int)], [Int] -> Int, Int)]
sampleBlocs = [([(0, 0), (1, 0)], quotient, 2),
([(0, 1), (1, 1)], sub, 1),
([(0, 2)], sum, 1),
([(2, 0), (2, 1)], sub, 2),
([(1, 2), (2, 2)], product, 6)]
sampleBlocs2 :: [([(Int, Int)], [Int] -> Int, Int)]
sampleBlocs2 = [([(0, 0), (0, 1)], sub, 2),
([(1, 0)], sum, 4),
([(2, 0), (2, 1)], quotient, 2),
([(3, 0), (3, 1)], sub, 1),
([(0, 2), (1, 1), (1, 2)], product, 8),
([(2, 2), (3, 2), (3, 3)], sum, 8),
([(0, 3), (1, 3), (2, 3)], sum, 6)]
-- doIt 3 sampleBlocs == [[2,3,1],[1,2,3],[3,1,2]]
-- doIt 4 sampleBlocs2 == [[1,3,4,2],[4,1,2,3],[2,4,3,1],[3,2,1,4]]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-24T10:41:27.560",
"Id": "365162",
"Score": "1",
"body": "It's been almost four years since you've asked this question. Maybe you want to review your own code?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T20:48:17.003",
"Id": "29378",
"Score": "4",
"Tags": [
"beginner",
"haskell",
"sudoku"
],
"Title": "A short KenKen solver"
}
|
29378
|
<p>I made a site where you can add movies into the database. You can use up to 3 different hosts.</p>
<p>Everything works well, but it is very long. I would love to shorten it!</p>
<p>Code to enter the 3 hosts + the links to the host:</p>
<pre><code><TABLE>
<TR><TD width=120>Hoster*:</TD>
<TD>
<SELECT class="interfaceforms" name="hoster"><OPTION value="">Please select</OPTION>
<?PHP
foreach($hoster_list AS $aKey => $aValue) {
echo'<option value="'.$aKey.'">'.$aValue.'</option>';
}
?>
</SELECT>
</TD>
</TR>
<TR>
<TD>&nbsp;
<BR><a href="#" onClick="document.getElementById('addhoster2').style.display='';return false;">>Add hoster<</a>
</TD>
<TD>
Part 1: <INPUT class="interfaceforms" type="text" name="part1"> link or embed code<BR>
Part 2: <INPUT class="interfaceforms" type="text" name="part2"><BR>
</TD>
</TR>
</TABLE>
<TABLE id="addhoster2" style="display:none;">
<TR>
<TD width=120>Hoster*:</TD>
<TD>
<SELECT class="interfaceforms" name="hoster2"><OPTION value="">Please select</OPTION>
<?PHP
foreach($hoster_list AS $aKey => $aValue) {
echo'<option value="'.$aKey.'">'.$aValue.'</option>';
}
?>
</SELECT>
</TD>
</TR>
<TR>
<TD>&nbsp;
<BR><a href="#" onClick="document.getElementById('addhoster3').style.display='';return false;">>Add hoster<</a>
</TD>
<TD>
Part 1: <INPUT class="interfaceforms" type="text" name="part21"> link or embed code<BR>
Part 2: <INPUT class="interfaceforms" type="text" name="part22"><BR>
</TD>
</TR>
</TABLE>
<TABLE id="addhoster3" style="display:none;">
<TR>
<TD width=120>Hoster*:</TD>
<TD>
<SELECT class="interfaceforms" name="hoster3"><OPTION value="">Please select</OPTION>
<?PHP
foreach($hoster_list AS $aKey => $aValue) {
echo'<option value="'.$aKey.'">'.$aValue.'</option>';
}
?>
</SELECT>
</TD>
</TR>
<TR>
<TD>&nbsp;
<BR><a href="#" onClick="document.getElementById('addhoster4').style.display='';return false;">>Add hoster<</a>
</TD>
<TD>
Part 1: <INPUT class="interfaceforms" type="text" name="part31"> link or embed code<BR>
Part 2: <INPUT class="interfaceforms" type="text" name="part32"><BR>
</TD>
</TR>
</TABLE>
</code></pre>
<p>Now here is the function to add the input into the database:</p>
<pre><code> if(!empty($_POST['title']) && !empty($_POST['language']) && !empty($_POST['hoster']) && !empty($_POST['part1']) && !empty($_POST['fsk']) && !empty($_POST['description']) && checkimdbID($_POST['imdbID']) ){
$movie = $imdb->find_by_id($imdbID);
$inTitle = mysql_real_escape_string($_POST['title']);
$inName = TitleToDbEncode($movie->title);
$inDescription = mysql_real_escape_string($_POST['description']);
$part_1 = mysql_real_escape_string($_POST['part1']);
$part_2 = mysql_real_escape_string($_POST['part2']);
$actors = myEncode4($movie->actors);
$director = myEncode4($movie->director);
$sqlCmd="INSERT INTO topmovies.movies
(imdb_id,username,title,name,language,hoster,part_1,part_2,picturequality,soundquality,genre,cover,description,duration,fsk,countryyear,director,actors,status,cinema,rating)
VALUES
('".$imdbID."','".$_SESSION['user_username']."','".$inTitle."','".$inName."','".$_POST['language']."','".$_POST['hoster']."','".$part_1."','".$part_2."','".$_POST['picturequality']."','".$_POST['soundquality']."','".$movie->genre."','".$bildDatei."','".$inDescription."','".$movie->runtime."','".$_POST['fsk']."','".$movie->year."','".$director."','".$actors."','queued','".$_POST['cinema']."','".$movie->rating."')";
$sqlQry = mysql_query($sqlCmd,$sqlHp) or die(mysql_error());
if($sqlQry) {
echo'Film erfolgreich hinzugef&uumlgt.';
echo'<meta http-equiv="refresh" content="1; URL=index.php"> ';
}else { echo'Es ist ein fehler aufgetaucht. Bitte alle felder richtig ausf&uumlllen.'; }
}else { echo'Es ist ein fehler aufgetaucht. Bitte alle felder richtig ausf&uumlllen.'; }
if(!empty($_POST['title']) && !empty($_POST['language']) && !empty($_POST['hoster2']) && !empty($_POST['part21']) && !empty($_POST['fsk']) && !empty($_POST['description']) && checkimdbID($_POST['imdbID']) ){
$inTitle = mysql_real_escape_string($_POST['title']);
$inName = TitleToDbEncode($movie->title);
$inDescription = mysql_real_escape_string($_POST['description']);
$part_1 = mysql_real_escape_string($_POST['part21']);
$part_2 = mysql_real_escape_string($_POST['part22']);
$actors = myEncode4($movie->actors);
$director = myEncode4($movie->director);
$sqlCmd="INSERT INTO topmovies.movies
(imdb_id,username,title,name,language,hoster,part_1,part_2,picturequality,soundquality,genre,cover,description,duration,fsk,countryyear,director,actors,status,cinema,rating)
VALUES
('".$imdbID."','".$_SESSION['user_username']."','".$inTitle."','".$inName."','".$_POST['language']."','".$_POST['hoster2']."','".$part_1."','".$part_2."','".$_POST['picturequality']."','".$_POST['soundquality']."','".$movie->genre."','".$bildDatei."','".$inDescription."','".$movie->runtime."','".$_POST['fsk']."','".$movie->year."','".$director."','".$actors."','queued','".$_POST['cinema']."','".$movie->rating."')";
$sqlQry = mysql_query($sqlCmd,$sqlHp) or die(mysql_error());
}
if(!empty($_POST['title']) && !empty($_POST['language']) && !empty($_POST['hoster3']) && !empty($_POST['part31']) && !empty($_POST['fsk']) && !empty($_POST['description']) && checkimdbID($_POST['imdbID']) ){
$inTitle = mysql_real_escape_string($_POST['title']);
$inName = TitleToDbEncode($movie->title);
$inDescription = mysql_real_escape_string($_POST['description']);
$part_1 = mysql_real_escape_string($_POST['part31']);
$part_2 = mysql_real_escape_string($_POST['part32']);
$actors = myEncode4($movie->actors);
$director = myEncode4($movie->director);
$sqlCmd="INSERT INTO topmovies.movies
(imdb_id,username,title,name,language,hoster,part_1,part_2,picturequality,soundquality,genre,cover,description,duration,fsk,countryyear,director,actors,status,cinema,rating)
VALUES
('".$imdbID."','".$_SESSION['user_username']."','".$inTitle."','".$inName."','".$_POST['language']."','".$_POST['hoster3']."','".$part_1."','".$part_2."','".$_POST['picturequality']."','".$_POST['soundquality']."','".$movie->genre."','".$bildDatei."','".$inDescription."','".$movie->runtime."','".$_POST['fsk']."','".$movie->year."','".$director."','".$actors."','queued','".$_POST['cinema']."','".$movie->rating."')";
$sqlQry = mysql_query($sqlCmd,$sqlHp) or die(mysql_error());
}
</code></pre>
<p>I want to shorten the function if possible. I think I could do something like this:</p>
<pre><code><SELECT class="interfaceforms" name="hoster[1]"><OPTION value="">Please select</OPTION>
Part 1: <INPUT class="interfaceforms" type="text" name="part[1][0]"><BR>
Part 2: <INPUT class="interfaceforms" type="text" name="part[1][1]"><BR>
</code></pre>
<p>Host 2 would be:</p>
<pre><code><SELECT class="interfaceforms" name="hoster[2]"><OPTION value="">Please select</OPTION>
Part 1: <INPUT class="interfaceforms" type="text" name="part[2][0]"><BR>
Part 2: <INPUT class="interfaceforms" type="text" name="part[2][1]"><BR>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T21:20:30.777",
"Id": "46410",
"Score": "3",
"body": "Using prepared statements for your SQL would save you having to do all the manual escaping."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T21:28:07.750",
"Id": "46411",
"Score": "0",
"body": "Yea I know but the problem is I dont know how nor I know what I have to search at google to learn how I do this :/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T07:12:27.267",
"Id": "46450",
"Score": "1",
"body": "You don't have to google anything, just go to [any of the `mysql_*` function docs](http://www.php.net/mysql_connect), and _read_ the warning in the red box at the top. it contains all the links you need"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T07:53:18.523",
"Id": "46452",
"Score": "0",
"body": "A very good tut on PDO can be found at: http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/"
}
] |
[
{
"body": "<p>I fixed it up a little bit. The problem now, is that he keeps doing 3 queries even if I have only selected 1 or 2 hosts.</p>\n\n<pre><code><TABLE> \n <TR>\n <TD width=120>Hoster*:</TD>\n <TD>\n <SELECT class=\"interfaceforms\" name=\"addmovie[0][hoster]\">\n <OPTION value=\"\">Please select</OPTION>\n <?PHP\n foreach($hoster_list AS $aKey => $aValue) {\n echo'<option value=\"'.$aKey.'\">'.$aValue.'</option>';\n }\n ?>\n </SELECT>\n </TD>\n </TR>\n <TR>\n <TD>&nbsp;\n <BR><a href=\"#\" onClick=\"document.getElementById('addhoster2').style.display='';return false;\">>Add hoster<</a>\n </TD>\n <TD>\n Part 1: <INPUT class=\"interfaceforms\" type=\"text\" name=\"addmovie[0][part]\"> link or embed code<BR>\n Part 2: <INPUT class=\"interfaceforms\" type=\"text\" name=\"addmovie[0][part2]\"><BR>\n </TD>\n </TR>\n</TABLE>\n<TABLE id=\"addhoster2\" style=\"display:none;\"> \n <TR>\n <TD width=120>Hoster*:</TD>\n <TD>\n <SELECT class=\"interfaceforms\" name=\"addmovie[1][hoster]\">\n <OPTION value=\"\">Please select</OPTION>\n <?PHP\n foreach($hoster_list AS $aKey => $aValue) {\n echo'<option value=\"'.$aKey.'\">'.$aValue.'</option>';\n }\n ?>\n </SELECT>\n </TD>\n </TR>\n <TR>\n <TD>&nbsp;\n <BR><a href=\"#\" onClick=\"document.getElementById('addhoster3').style.display='';return false;\">>Add hoster<</a>\n </TD>\n <TD>\n Part 1: <INPUT class=\"interfaceforms\" type=\"text\" name=\"addmovie[1][part]\"> link or embed code<BR>\n Part 2: <INPUT class=\"interfaceforms\" type=\"text\" name=\"addmovie[1][part2]\"><BR>\n </TD>\n </TR>\n</TABLE>\n<TABLE id=\"addhoster3\" style=\"display:none;\"> \n <TR>\n <TD width=120>Hoster*:</TD>\n <TD>\n <SELECT class=\"interfaceforms\" name=\"addmovie[2][hoster]\">\n <OPTION value=\"\">Please select</OPTION>\n <?PHP\n foreach($hoster_list AS $aKey => $aValue) {\n echo'<option value=\"'.$aKey.'\">'.$aValue.'</option>';\n }\n ?>\n </SELECT>\n </TD>\n </TR>\n <TR>\n <TD>&nbsp;\n <BR><a href=\"#\" onClick=\"document.getElementById('addhoster4').style.display='';return false;\">>Add hoster<</a>\n </TD>\n <TD>\n Part 1: <INPUT class=\"interfaceforms\" type=\"text\" name=\"addmovie[2][part]\"> link or embed code<BR>\n Part 2: <INPUT class=\"interfaceforms\" type=\"text\" name=\"addmovie[2][part2]\"><BR>\n </TD>\n </TR>\n</TABLE>\n</code></pre>\n\n<p>Code:</p>\n\n<pre><code>$result = $_POST[\"addmovie\"];\n\nif (count($result > 0))\n $new = array();\n\nforeach ($result as $key)\n{\n $new[] = \"('\" . $key[\"hoster\"] . \"', '\" . $key[\"part\"] . \"', '\" . $key[\"part2\"] . \"')\";\n}\n\nif (count($new) > 0)\n{\n $query = mysql_query(\"INSERT INTO topmovies.movies2 (hoster, part_1, part_2) VALUES \" . implode(', ', $new));\n if ($query)\n {\n echo 'SUCCESS';\n print_r($new);\n echo '<BR>';\n }\n else\n {\n echo 'FAILED';\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T09:23:49.173",
"Id": "29388",
"ParentId": "29379",
"Score": "0"
}
},
{
"body": "<p>Here is one way of shortening your HTML. A lot of it is identifying the areas that repeat themselves, and then looping it around the size of your host array, for future proofing if you increase the amount of hosts the tables produced will naturally increase with it.</p>\n\n<p>The below code though will change your expected post results of <code>$_POST['part1']</code> to <code>$_POST['part11']</code>.</p>\n\n<pre><code><?php\n//Setup a bogus array of hosts\n$hoster_list[] = \"host1\";\n$hoster_list[] = \"host2\";\n$hoster_list[] = \"host3\";\n\n$i=1;\nwhile($i<=sizeof($hoster_list)) {\n //If we are the 1st host then produce a visible table else produce the incremented table\n echo ($i == 1) ? \"<TABLE>\" : \"<TABLE id='addhoster\".$i.\"' style='display:none;'>\";\n\n //For each loop increment the same html\n echo \" \n <TR><TD width=120>Hoster*:</TD>\n <TD>\n <SELECT class='interfaceforms' name='hoster\".$i.\"'><OPTION value=''>Please select</OPTION>\n \";\n //Perform option dump\n foreach($hoster_list AS $aKey => $aValue) {\n echo'<option value=\"'.$aKey.'\">'.$aValue.'</option>';\n }\n echo \"\n </SELECT>\n </TD>\n </TR>\n <TR>\n <TD>\n <BR><a href='#' onClick='document.getElementById('addhoster\".$i.\"').style.display='';return false;'>>Add hoster<</a>\n </TD>\n <TD>\n Part 1: <INPUT class='interfaceforms' type='text' name='part\".$i.\"1'> link or embed code<BR>\n Part 2: <INPUT class='interfaceforms' type='text' name='part\".$i.\"2'><BR>\n </TD>\n </TR>\n </TABLE>\n \";\n\n $i++;\n}\n?> \n</code></pre>\n\n<p><a href=\"http://codepad.org/1j91VQqn\" rel=\"nofollow\">Working example</a> of this part.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T10:04:48.733",
"Id": "29389",
"ParentId": "29379",
"Score": "2"
}
},
{
"body": "<p>Use a loop to shorten your html:</p>\n\n<pre><code><?php for ($i = 0; $i <= 2; ++$i): ?>\n <TABLE id=\"addhoster<?php echo $i + 1; ?>\" <?php if ($i > 0) echo 'style=\"display: none\"'; ?>> \n <TR><TD width=120>Hoster*:</TD>\n <TD>\n <SELECT class=\"interfaceforms\" name=\"addmovie[<?php echo $i; ?>][hoster]\"><OPTION value=\"\">Please select</OPTION>\n <?PHP\n foreach($hoster_list AS $aKey => $aValue) {\n echo'<option value=\"'.$aKey.'\">'.$aValue.'</option>';\n }\n ?>\n </SELECT>\n </TD>\n </TR>\n <TR>\n <TD>&nbsp;\n <BR><a href=\"#\" onClick=\"document.getElementById('addhoster<?php echo $i + 2; ?>').style.display='';return false;\">>Add hoster<</a>\n </TD>\n <TD>\n Part 1: <INPUT class=\"interfaceforms\" type=\"text\" name=\"addmovie[<?php echo $i; ?>][part]\"> link or embed code<BR>\n Part 2: <INPUT class=\"interfaceforms\" type=\"text\" name=\"addmovie[<?php echo $i; ?>][part2]\"><BR>\n </TD>\n </TR>\n </TABLE>\n<?php endfor; ?>\n</code></pre>\n\n<p>Then stop empty hosts inserting by checking if <code>addMovie[key][hoster]</code> is set:</p>\n\n<pre><code>$result = $_POST[\"addmovie\"];\n\nif (!empty($result))\n{\n $new = array();\n\n foreach ($result as $key)\n {\n if ($key['hoster'] != '')\n {\n $new[] = \"('\" . $key[\"hoster\"] . \"', '\" . $key[\"part\"] . \"', '\" . $key[\"part2\"] . \"')\";\n }\n }\n\n $query = mysql_query(\"INSERT INTO topmovies.movies2 (hoster, part_1, part_2) VALUES \" . implode(', ', $new));\n\n if ($query)\n {\n echo 'SUCCESS';\n print_r($new);\n echo '<BR>';\n }\n else\n {\n echo 'FAILED';\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T10:09:46.230",
"Id": "29390",
"ParentId": "29379",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29390",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T21:18:57.397",
"Id": "29379",
"Score": "1",
"Tags": [
"php"
],
"Title": "Adding movies into a database"
}
|
29379
|
<p>I currently have a container that has two features it allows adding objects to it and at the same time an independent thread continuously consumes items from it. It is a FIFO type deque. Which receives object at an extremely high rate. Following is the code for the container</p>
<pre><code>std::deque<Some_object*> my_container;
void Container::Add_item(Some_object* obj)
{
try
{
{//Begin Lock
boost::lock_guard<boost::mutex> lock(mutex_lk);
my_container.push_back(obj);
}
condition_consumer_silo.notify_one();
}
catch (std::exception& e)
{
__debugbreak();
}
}
//This method continuously consumes object in FIFO order
void Container::Consume_Object()
{
while(true)
{
Some_object* obj;
{//Lock
try
{
boost::unique_lock<boost::mutex> lock(mutex_lk);
while(my_container.empty()) { condition_consumer_silo.wait(lock); }//Block if empty - for spurious wakeup
if(!my_container.empty())
{
obj = my_container.front();
my_container.pop_front();
}
}
catch (std::exception& e)
{
__debugbreak();
}
}//Unlock
try
{
Consume_obj(obj);
} catch (std::exception& e)
{
__debugbreak();
}
}//end while
}
</code></pre>
<p>Could this container be improved ? Is there a library out there that would do a better job.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T03:35:02.913",
"Id": "46438",
"Score": "0",
"body": "hi, got your comment message, hope you get a good answer cheers"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T14:51:34.197",
"Id": "46472",
"Score": "0",
"body": "In case you don't get an answer: I'm not quite sure, but I think there is something in \"C++ Concurrency in Action\" by Anthony Williams that could help you."
}
] |
[
{
"body": "<h3>Ownership symantics:</h3>\n<pre><code>void Container::Add_item(Some_object* obj)\n</code></pre>\n<p>Who owns <code>obj</code>?\nThis is a C-Style interface. Don't do it.</p>\n<p>It would be better to pass in as unique_ptr. This shows transfer of ownership. Also with good compiler optimization is no more expensive than a normal pointer. This also results in slight modification in your code to make sure it handles ownership correctly.</p>\n<p>Note: I would still use: <code>std::deque<Some_object*> my_container;</code></p>\n<h3>Lockless queues</h3>\n<p>Lock are very expensive (relatively to queue management). There is a concept of thread safe lock-less queues.</p>\n<p>If you have a very high frequency modification to the queue then that is something I would look into. see <a href=\"https://stackoverflow.com/questions/1724630/how-do-i-build-a-lockless-queue\">How do I build a lockless queue?</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T07:21:11.683",
"Id": "29425",
"ParentId": "29382",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T03:28:20.120",
"Id": "29382",
"Score": "6",
"Tags": [
"c++",
"design-patterns"
],
"Title": "Deque Container with an instant consumer for high speed object dumping"
}
|
29382
|
<p>I am working on going through "Head First Design Patterns" and I am trying to properly convert the Java code into C#. Here is what I have. Can you tell me if this is a good implementation/conversion so far?</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Duck
{
public abstract class Duck
{
public FlyBehavior flyBehavior;
public QuackBehavior quackBehavior;
public Duck(){
}
public abstract void display();
public void performFly()
{
flyBehavior.fly();
}
public void performQuack()
{
quackBehavior.quack();
}
public void swim()
{
Console.WriteLine("All ducks float, even decoys!");
}
}
public interface FlyBehavior
{
void fly();
}
public class FlyWithWings : FlyBehavior
{
public void fly()
{
Console.WriteLine("I'm flying!");
}
}
public class FlyNoWay : FlyBehavior
{
public void fly()
{
Console.WriteLine("I can't fly!");
}
}
public interface QuackBehavior
{
void quack();
}
public class Quack : QuackBehavior
{
public void quack()
{
Console.WriteLine("Quack");
}
}
public class MuteQuack : QuackBehavior
{
public void quack()
{
Console.WriteLine("<< Silence >>");
}
}
public class Squeak : QuackBehavior
{
public void quack()
{
Console.WriteLine("Squeak");
}
}
public class MallardDuck : Duck
{
public MallardDuck()
{
quackBehavior = new Quack();
flyBehavior = new FlyWithWings();
}
public override void display()
{
Console.WriteLine("I'm a real Mallard duck");
}
}
public class MiniDuckSimulator
{
public static void Main(string[] args)
{
Duck mallard = new MallardDuck();
mallard.performQuack();
mallard.performFly();
Console.ReadLine();
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Oddly enough, in the Microsoft C# world, <code>PascalCasing</code> (as opposed to <code>camelCasing</code>) doesn't just apply to classes, but also to public fields, public methods, and public properties.</p>\n\n<p>So maybe you might want to rename <code>Duck.flyBehavior</code> to <code>Duck.FlyBehavior</code>, <code>Duck.quackBehavior</code> to <code>Duck.QuackBehavior</code>, etc.</p>\n\n<p>While you're at it, since those are public fields, you might also want to switch those to C# properties, instead, in case you ever needed the added functionality of sanitizing input.</p>\n\n<p><strong>before</strong></p>\n\n<p><code>\npublic FlyBehavior FlyBahavior\n</code></p>\n\n<p><strong>after*</strong></p>\n\n<p><code>\npublic FlyBehavior FlyBehavior { get; set; }\n</code></p>\n\n<p>Although, I still write C# the old school way, but if things haven't changed, I think interfaces still are prefixed with a capital <code>I</code>. So your <code>FlyBehavior</code> interface will be named <code>IFlyBehavior</code>. Same thing for <code>QuackBehavior</code>; it will become <code>IQuackBehavior</code>.</p>\n\n<p>Another pedantic remark: although I have a hunch that you already know this, but classes should be in their own file*. I'm just saying, in case my hunch was wrong, and you didn't know.</p>\n\n<p>* Disclaimer: I'm not exactly sure why separating classes into files is considered important. And I am in no way saying that it isn't important, just that if you want to know why, I'm afraid I can only give you my own intuition as to why I <em>think</em> it's important to separate classes into their own file.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T08:11:52.040",
"Id": "46456",
"Score": "0",
"body": "\"Disclaimer: I'm not exactly sure why separating classes into files is considered important.\" Pretty certain it's purely organisational - it's easier to find `public abstract class Duck` when the file is called `Duck.cs` rather than if everything is in `MyProgram.cs`, or separated into `Stuff1.cs`, `Stuff2.cs` etc - easier to find the file *and* easier to find the location in the file where the class starts (the beginning). Edit: I think in Java each class *has to* be a separate file due to the way the compiler works (it expects `Duck.java` to contain `Duck`). Might be wrong on that though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T08:13:59.813",
"Id": "46457",
"Score": "0",
"body": "Although I personally employ an amount of flexibility in C# - if I've got small, related classes, I'll often dump them into the same file because they'll still be easy to find - in this case, I'd stick `FlyBehaivour` and its implementations in the same file because they're so small and tightly related."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T08:06:17.303",
"Id": "29387",
"ParentId": "29384",
"Score": "3"
}
},
{
"body": "<p><code>public</code> fields are a bit of a no-no since that violates encapsulation. So I've changed the fields to <code>private readonly</code> and inject those dependencies via the constructor. Speaking of constructor, I made it <code>protected</code> as a <code>public</code> constructor on an <code>abstract</code> class doesn't make much sense. Also, make note of C# naming conventions which PascalCase's methods and that <code>interface</code>s should start with \"<code>I</code>\":</p>\n\n<pre><code>using System;\n\nnamespace Duck\n{\n public abstract class Duck\n {\n private readonly IFlyBehavior flyBehavior;\n private readonly IQuackBehavior quackBehavior;\n protected Duck(IFlyBehavior flyBehavior, IQuackBehavior quackBehavior)\n {\n this.flyBehavior = flyBehavior;\n this.quackBehavior = quackBehavior;\n }\n\n public abstract void Display();\n\n public void PerformFly()\n {\n this.flyBehavior.Fly();\n }\n\n public void PerformQuack()\n {\n this.quackBehavior.Quack();\n }\n\n public void Swim()\n {\n Console.WriteLine(\"All ducks float, even decoys!\");\n }\n }\n\n public interface IFlyBehavior\n {\n void Fly();\n }\n\n public class FlyWithWings : IFlyBehavior\n {\n public void Fly()\n {\n Console.WriteLine(\"I'm flying!\");\n }\n }\n\n public class FlyNoWay : IFlyBehavior\n {\n public void Fly()\n {\n Console.WriteLine(\"I can't fly!\");\n }\n }\n\n public interface IQuackBehavior\n {\n void Quack();\n }\n\n public class Quack : IQuackBehavior\n {\n public void Quack()\n {\n Console.WriteLine(\"Quack\");\n }\n }\n\n public class MuteQuack : IQuackBehavior\n {\n public void Quack()\n {\n Console.WriteLine(\"<< Silence >>\");\n }\n }\n\n public class Squeak : IQuackBehavior\n {\n public void Quack()\n {\n Console.WriteLine(\"Squeak\");\n }\n }\n\n public class MallardDuck : Duck\n {\n public MallardDuck() : base(new FlyWithWings(), new Quack())\n {\n }\n\n public override void Display()\n {\n Console.WriteLine(\"I'm a real Mallard duck\");\n }\n }\n\n public class MiniDuckSimulator\n {\n public static void Main(string[] args)\n {\n Duck mallard = new MallardDuck();\n mallard.PerformQuack();\n mallard.PerformFly();\n Console.ReadLine();\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T16:21:38.130",
"Id": "46477",
"Score": "0",
"body": "Thanks guys! I am going to look over both your answers, but I really appreciate that you took the time to explain in such depth. I am working hard to learn these design patterns and input like this is going to just speed up the process."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T16:29:58.010",
"Id": "46478",
"Score": "1",
"body": "Yes, I am aware that if this was a production application each class would be its own file, but since this is just to learn a strategy pattern in C# I have kept them all in the same file. The changes made by Jesse are perfect and make the code cleaner and safer, so thanks for that. I am studying it will get back to you guys if I have any questions. Thanks a million!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T13:06:39.743",
"Id": "29396",
"ParentId": "29384",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "29396",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T04:06:33.453",
"Id": "29384",
"Score": "5",
"Tags": [
"c#",
"design-patterns"
],
"Title": "Strategy Pattern"
}
|
29384
|
<p>Common Lisp has a "special operator" called <a href="http://www.lispworks.com/documentation/HyperSpec/Body/s_multip.htm" rel="nofollow"><code>multiple-value-call</code></a>, which does something similar to Scheme's <code>call-with-values</code> but with a nicer syntax, and allowing multiple producers (<a href="http://trac.sacrideo.us/wg/ticket/87" rel="nofollow">unlike <code>call-with-values</code></a>). So I thought I'd try to implement <code>multiple-value-call</code> in Scheme, using <code>call-with-values</code> (dressed up here as <a href="http://srfi.schemers.org/srfi-8/srfi-8.html" rel="nofollow"><code>receive</code></a>) behind the scenes:</p>
<pre><code>(define-syntax multiple-value-collect
(syntax-rules ()
((multiple-value-collect) '())
((multiple-value-collect expr next ...)
(receive vals expr
(cons vals (multiple-value-collect next ...))))))
(define-syntax multiple-value-call
(syntax-rules ()
((multiple-value-call func expr ...)
(apply func (concatenate! (multiple-value-collect expr ...))))))
</code></pre>
<p>Is there a better (more idiomatic, performant, etc.) way to implement this? (<code>concatenate!</code> is from <a href="http://srfi.schemers.org/srfi-1/srfi-1.html" rel="nofollow">SRFI 1</a>, and <code>receive</code> is from <a href="http://srfi.schemers.org/srfi-8/srfi-8.html" rel="nofollow">SRFI 8</a>.)</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T04:45:05.803",
"Id": "29385",
"Score": "2",
"Tags": [
"scheme",
"macros"
],
"Title": "`multiple-value-call` in Scheme"
}
|
29385
|
<p>Here's the start of some code for a clock that can display time in 24 and 12 hours.</p>
<p>What could be added to it? How could I can apply notions such as OOP, model and Enums here?</p>
<pre><code>public Clock {
private int time = 0;
public int get24hrTime(){
return time;
}
public int set24hrTime( int newTime ){
this.time = newTime;
}
public int get12hrTime(){
if( time - 12 < 0 ){
return time;
} else {
return time - 12;
}
}
public String get12hrPostfix(){
if( hours - 12 < 0 ){
return "AM";
} else {
return "PM";
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T10:38:03.117",
"Id": "46460",
"Score": "1",
"body": "\"Do not fix something that works\", what is the issue with this code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T10:41:27.500",
"Id": "46462",
"Score": "1",
"body": "There is no functional issue with this code. It will get the green flag in TDD. But I am bothered by the design aspect. I just want to see how other programmers could design this more elegantly with comments on their reasoning."
}
] |
[
{
"body": "<p>Why do you check the time with <code>(hours - 12 < 0)</code>. This involves two operations, one subtraction and one compare. You could simply use <code>(hours < 12)</code>.</p>\n\n<p>Also you rely that in the method <code>set24hrTime(int newTime)</code> the time is never > 23 for your code to work. Why don't you check this?</p>\n\n<p>Also what about the value <code>0</code> for your hours? This must be displayed as <code>12 AM</code>. At the moment you return <code>0</code> in this case where it must be <code>12</code>.</p>\n\n<p>Also for the value <code>12</code> of the hours you return <code>0</code> as value for the <code>12hrTime</code> which is wrong.</p>\n\n<p>To sum up I would suggest the following code:</p>\n\n<pre><code>public Clock {\n private int time = 0;\n public int get24hrTime() {\n return time;\n }\n public int set24hrTime(int newTime) {\n if (newTime > 23 || newTime < 0) {\n throw new IllegalArgumentException();\n }\n this.time = newTime;\n }\n public int get12hrTime(){\n if (time == 0) {\n return 12; // Special case 0\n } else if (time <= 12) {\n return time;\n } else {\n return time - 12;\n }\n }\n public String get12hrPostfix() {\n if (time < 12) {\n return \"AM\";\n } else {\n return \"PM\";\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-01T20:00:37.090",
"Id": "291732",
"Score": "0",
"body": "Where does the \"throw new IlllegalArguemntExeption()\" come from and what does it do?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-01T21:48:50.790",
"Id": "291741",
"Score": "0",
"body": "The IllegalArgumentException is a RuntimeException of Java. You can throw this exception if you detect an illegal argument (e.g. a negative hour or an hour above 23)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T11:06:56.700",
"Id": "29393",
"ParentId": "29392",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "29393",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T10:32:34.357",
"Id": "29392",
"Score": "3",
"Tags": [
"java",
"datetime"
],
"Title": "Programming a simple clock"
}
|
29392
|
<p>I wrote this as a way to deliver static portion of the app. I'm wondering if there is a better way to write this, as I am new to Express.</p>
<p>The goal is to let a single-page app to handle routing as needed. There is an API layer of this app that is defined under the /api/ route namespace.</p>
<p>I wanted to note that all assets are served from /app folder and are not public. I can adjust that, but as of now, that's the folder structure. /app is a compilation destination. root folder contains server.js where the below code resides and contains app/ and src/ folders, as well as server/ folder that contains API related stuff.</p>
<pre><code>var express = require('express');
var http = require('http');
var path = require('path');
var app = express();
require('./express/api')(app);
app.get("/css/*",function(req,res){
res.sendfile('app'+req.path);
});
app.get("/js/*",function(req,res){
res.sendfile('app'+req.path);
});
app.get("/img/*",function(req,res){
res.sendfile('app'+req.path);
});
app.get("/pages/*",function(req,res){
res.sendfile('app'+req.path);
});
app.get('*',function(req,res){
res.sendfile('app/index.html');
});
app.listen(3000);
console.log('Listening on port 3000');
</code></pre>
|
[] |
[
{
"body": "<p>There is a better way.</p>\n\n<p>If you wish to serve static files with express - it comes bundled with <code>static</code> middleware. To use it, you simply add this line <strong>before</strong> your routes:</p>\n\n<pre><code>app.use(express.static(__dirname + '/public'));\n</code></pre>\n\n<p>This may require slight adjustment to your paths but it replaces all those manual routes and is more efficient (caching, expiration etc).</p>\n\n<p><a href=\"http://expressjs.com/api.html#app.use\" rel=\"nofollow\">Check out this example</a>.</p>\n\n<p>I would, however, suggest that you use something like <code>nginx</code> for your static assets since it's typically more robust and it'll free resources from your node server.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T15:59:18.860",
"Id": "47540",
"Score": "0",
"body": "thanks @diversario, this would require me to adjust my build process, is there a way to set the public directory to something else. I will look at it my self, just maybe you know."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T19:15:08.107",
"Id": "47551",
"Score": "1",
"body": "You can set the directory to anything you like, just make sure it contains only public assets."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T19:58:00.217",
"Id": "47603",
"Score": "0",
"body": "This works great, so i just had to add this before any routes, and then just leave wild card to serve index.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T14:18:10.983",
"Id": "77346",
"Score": "1",
"body": "If the index.html is within your public directory it will be serve as well. You don't need a specific route for it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T19:51:29.513",
"Id": "415838",
"Score": "0",
"body": "Note that the **middleware** must come **before** the **wildcard** definition in order to work."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T01:13:55.563",
"Id": "29902",
"ParentId": "29401",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "29902",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T16:24:49.443",
"Id": "29401",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"express.js"
],
"Title": "Serving static assets through wildcard rule"
}
|
29401
|
<p>I have a manager class (included below) and sub data types that are included inside it. All of the different stored types are more or less the same with some wrapper functions calling the exact same named function below to the sub object. This feels dirty and I can't help but think there's a better way to do this. Suggestions?</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using Inspire.Shared.Models.Enums;
using Lidgren.Network;
namespace GameServer.Editor.ContentLocking
{
/// <summary>
/// The content lock manager helps provide delegation
/// </summary>
public class ContentLockManager
{
// This is a mapping of all the different content lock stores available
Dictionary<ContentType, ContentLockStore> _contentLockStores = new Dictionary<ContentType, ContentLockStore>();
public ContentLockManager()
{
// Generate the ContentMap dynamically, assinging everyone a backing
foreach (var contentType in GetValues<ContentType>())
_contentLockStores.Add(contentType, new ContentLockStore());
}
/// <summary>
/// Invalidates and purges all locks for a given connection.
/// This is typically called when a connection has disconnected from the node.
/// </summary>
/// <param name="connection"></param>
public void PurgeLocks(NetConnection connection)
{
foreach (var contentLockStore in _contentLockStores.Values)
{
contentLockStore.ReleaseLocks(connection);
}
}
public List<int> GetLockedContent(ContentType contentType)
{
var contentStore = _contentLockStores[contentType];
return contentStore.GetLockedContentIDs();
}
public bool HasLock(NetConnection connection, int ID, ContentType contentType)
{
var contentStore = _contentLockStores[contentType];
return contentStore.HasLock(connection, ID);
}
public bool AnyoneHasLock(NetConnection connection, int ID, ContentType contentType)
{
var contentStore = _contentLockStores[contentType];
return contentStore.AnyoneHasLock(connection, ID);
}
public bool TryAcquireLock(NetConnection connection, int ID, ContentType contentType)
{
var contentStore = _contentLockStores[contentType];
return contentStore.TryAcquireLock(connection, ID);
}
public bool TryReleaseLock(NetConnection connection, int ID, ContentType contentType)
{
var contentStore = _contentLockStores[contentType];
return contentStore.ReleaseLock(connection, ID);
}
private static IEnumerable<T> GetValues<T>()
{
return Enum.GetValues(typeof(T)).Cast<T>();
}
}
}
</code></pre>
<p>And then I have a mapping inside like so:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Lidgren.Network;
namespace GameServer.Editor.ContentLocking
{
/// <summary>
/// A collection of keys internally of content that has been locked
/// </summary>
public class ContentLockStore
{
// Current locks on a particular piece of content
private Dictionary<int, NetConnection> _contentLocks = new Dictionary<int, NetConnection>();
public bool TryAcquireLock(NetConnection connection, int ID)
{
// Trying to aqquire a lock for something you already have or you're not authorized to obtain
if (_contentLocks.ContainsKey(ID))
return false;
// Noone has taken it - go ahead and grab this
_contentLocks.Add(ID, connection);
return true;
}
/// <summary>
/// Release sall locks with an associated contention
/// </summary>
/// <param name="connection"></param>
public void ReleaseLocks(NetConnection connection)
{
var keys = _contentLocks.Where(cLock => cLock.Value == connection).ToList();
keys.ForEach(x => ReleaseLock(x.Value, x.Key));
}
public bool ReleaseLock(NetConnection connection, int ID)
{
// If they don't have a lock, they can't release it
if (!HasLock(connection, ID))
return false;
// Release the lock
_contentLocks.Remove(ID);
return true;
}
/// <summary>
/// Returns a list of all the locked content IDs for a particular store
/// </summary>
/// <returns></returns>
public List<int> GetLockedContentIDs()
{
return _contentLocks.Keys.ToList();
}
/// <summary>
/// Determines whether a particular connection has a lock on a piece of content
/// </summary>
/// <param name="connection"></param>
/// <param name="ID"></param>
/// <returns></returns>
public bool HasLock(NetConnection connection, int ID)
{
// If the key dosen't even exist, don't bother
if (!_contentLocks.ContainsKey(ID))
return false;
return _contentLocks[ID] == connection;
}
public bool AnyoneHasLock(NetConnection connection, int ID)
{
return _contentLocks.ContainsKey(ID);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T19:06:04.297",
"Id": "46485",
"Score": "0",
"body": "I'm not entirely sure I understand the relationship between the two classes. What does the constructor for `ContentLockManager` do? Are IDs always `int`? What other mappings do you have other than `ContentLockStore`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T19:29:21.830",
"Id": "46487",
"Score": "0",
"body": "@Bobson The lock manager is creating a backing store for every ContentType and adding it to the dictionary. IDs are always ints - as defined. It's just a pure backing store. I need a ContentType locking store each ContentType. Basically, when a piece of content is opened I want it \"locked\" to that connection. This is done per content piece (by ID) and per content type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T19:37:44.083",
"Id": "46488",
"Score": "0",
"body": "So, `Manager` -> list of all things that can be locked, and `Store` -> individual item's locks? And you have multiple `Store` classes, for each type of `item`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T19:39:24.107",
"Id": "46489",
"Score": "0",
"body": "@Bobson That is correct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T19:48:15.673",
"Id": "46490",
"Score": "0",
"body": "I think I'm getting it. Last question: Is there *any* change in the code between the various `Store` classes? I don't see anything in there which actually uses `ContentType`. Or is the question simply about having near-duplicate code in the `Manager` and `Store` classes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T19:51:25.537",
"Id": "46491",
"Score": "0",
"body": "@Bobson Nope, it's purely just a storage bin as you can see. The ContentType on the higher level was strictly a way to get the right lock. There is no code changes - they all define the exact same operations and always will. They manage locks and nothing more. \n\nThe question is basically just that - they're both storing nearly the exact same function(s). I wonder - is there no better to do this rather than wrapping a bunch of API calls?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T19:59:11.097",
"Id": "46493",
"Score": "0",
"body": "Well, you should only have one `ContentLockStore` class, with one instance per `ContentType`, but the only alternative way to have the functions would be to provide a `ContentManagerStore.GetConnection(ContentType type)` function and use that to access the locking functions on the `ContentLockStore` directly. I'm not sure if that counts as better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T20:00:31.533",
"Id": "46494",
"Score": "0",
"body": "@Bobson Not really - thanks for trying, though. Maybe the code duplication isn't so bad. :)"
}
] |
[
{
"body": "<p>As per the comments and Your actual problem, it seems that You are unknowingly and partly using a <a href=\"http://www.dofactory.com/Patterns/PatternProxy.aspx\" rel=\"nofollow noreferrer\">Proxy Pattern</a>. </p>\n\n<p>So as a slight modification You should be having an interface extracted from ContentLockStore and then inherited in both of Your ContentLockManager and ContentLockStore classes, in Your case since the Manager class is having a third parameter as well, it is impossible to do even this, and <strong>hence partly</strong> implemented Proxy pattern.</p>\n\n<p>I wonder whether Indexers can come to Your rescue, try reading <a href=\"http://msdn.microsoft.com/en-us/library/vstudio/6x16t2tx.aspx\" rel=\"nofollow noreferrer\">them</a>.</p>\n\n<p>Besides Your main question, consider using <a href=\"https://softwareengineering.stackexchange.com/questions/177649/what-is-constructor-injection\">Constructor Injection</a> in Your code, Your Manager class's constructor should not be having that loop, a factory should should be creating a dictionary and then passing it in the constructor. Doing that will promote testability.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-01T15:12:17.207",
"Id": "30618",
"ParentId": "29403",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T17:46:07.530",
"Id": "29403",
"Score": "3",
"Tags": [
"c#"
],
"Title": "How can I avoid seemingly unneccessary wrappers like this?"
}
|
29403
|
<p>For Coursera's Algorithms course, I have written Kosaraju's algorithms which calculates strongly-connected components in a directed graph using depth first search. The code itself is correct but apparently not very efficient, because it took me almost 24 hours to get the answer for the file <a href="http://spark-public.s3.amazonaws.com/algo1/programming_prob/SCC.txt" rel="nofollow">SCC.txt</a> which contains about 800.000 edges. Most of the other students could get the answer in well under a minute, so there is definitely something wrong with my code.</p>
<blockquote>
<p>The file contains the edges of a directed graph. Vertices are labeled
as positive integers from 1 to 875714. Every row indicates an edge,
the vertex label in first column is the tail and the vertex label in
second column is the head (recall the graph is directed, and the edges
are directed from the first column vertex to the second column
vertex). So for example, the 11th row looks liks : “2 47646″. This
just means that the vertex with label 2 has an outgoing edge to the
vertex with label 47646</p>
<p>Your task is to code up the algorithm from the video lectures for
computing strongly connected components (SCCs), and to run this
algorithm on the given graph.</p>
<p>Output Format: You should output the sizes of the 5 largest SCCs in
the given graph, in decreasing order of sizes, separated by commas
(avoid any spaces). So if your algorithm computes the sizes of the
five largest SCCs to be 500, 400, 300, 200 and 100, then your answer
should be “500,400,300,200,100″. If your algorithm finds less than 5
SCCs, then write 0 for the remaining terms. Thus, if your algorithm
computes only 3 SCCs whose sizes are 400, 300, and 100, then your
answer should be “400,300,100,0,0″.</p>
</blockquote>
<p>Could someone take a look? Any critique or advice is welcome.</p>
<pre><code>import csv
import sys
import threading
threading.stack_size(67108864)
sys.setrecursionlimit(2**20)
def read_graph(filename):
g, g_rev = {}, {}
edge_list = []
for line in open(filename):
edge = [int(num.strip()) for num in line.split()]
edge_list.append(edge)
g.setdefault(edge[0], []).append(edge[1])
for ii in range(0,len(edge_list)):
edge_list[ii][0],edge_list[ii][1]=edge_list[ii][1],edge_list[ii][0]
g_rev.setdefault(edge_list[ii][0],[]).append(edge_list[ii][1])
return g, g_rev
def DFS(graph,node1):
global s, s_explored, leader, finishing_time, leader
s_explored.append(node1)
leader[node1]=s
if node1 in graph.keys():
for node2 in graph[node1]:
if node2 not in s_explored:
DFS(graph,node2)
finishing_time.append(node1)
def DFS_loop(graph, transverse_list):
global s,s_explored,finishing_time,leader
leader = {}
s_explored, finishing_time = [], []
s = 0
for node1 in transverse_list[::-1]:
if node1 not in s_explored:
s = node1
DFS(graph, node1)
return finishing_time, leader
def main():
filename = sys.argv[1]
g, g_rev = read_graph(filename)
#Define the global variables
leader = {}
s_explored, finishing_time = [], []
s = 0
#define the inputs and outputs of first DFS-loop
#f_t is a list with the finishing times of the nodes according to the first DFS
#this list of finishing times will be used in the second loop
#lead is a dictionary with the leaders; {[9]:8} for example means that the leader
#of node 9 is node 8.
#the leader-dict coming from the first loop is not used, but the leader-dict coming
#from the second loop is used to calculate which nodes have the same leader and
#therefore are part of the same SCC.
grev_nodes = [key for key in g_rev.keys()]
f_t, lead = [], {}
f_t, lead = DFS_loop(g_rev, grev_nodes)
#define the inputs and outputs of second DFS-loop
f_t2, lead2 = [],{}
f_t2, lead2 = DFS_loop(g, f_t)
#print out result
SCC = {}
for ii in range(0,len(lead2.values())):
SCC.setdefault(lead2.values()[ii],[]).append(ii)
SCC_lengths = []
for key in SCC.keys():
SCC_lengths.append(len(SCC[key]))
SCC_lengths.sort(reverse=True)
if len(SCC_lengths)<5:
for ii in range(5-len(SCC_lengths)):
SCC_lengths.append(0)
print SCC_lengths
if __name__ == '__main__':
thread = threading.Thread(target=main)
thread.start()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T18:34:46.270",
"Id": "46484",
"Score": "0",
"body": "You missed placing the links in the paragraphs after the code. BTW you can use Ctrl + L to place links on text. There are other shortcuts that you can see at the topwhen you use edit button. It is cleaner that way instead of pure markup and easier to edit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T21:06:33.577",
"Id": "46502",
"Score": "0",
"body": "I cannot tell you why it is slow, but I can tell you that the code is hard to read. What is g, the difference between g_rev and edge_list. I would start by using meaninful variables for everything before finding out what slows this down."
}
] |
[
{
"body": "<p>Generally, with Kasuraju's algorithm (and other graph search algorithms), the biggest bottleneck is reading in the edges and then holding these in memory. If I understand this correctly, you have about 800,000 VERTEXES, which will lead to a few million edges. Holding both <code>G</code> and <code>G_rev</code> in memory at the same time will be a big call. You could consider writing a helper function to read in the graph (either <code>G</code> or <code>G_rev</code>). As an example:</p>\n\n<pre><code>def read_graph(input_file, reverse=False):\n\n G = defaultdict(list)\n\n for line in open(input_file):\n i, j = line.split()\n\n # initialise each node:\n # G = { node : [False, [outgoing arcs], ...}\n # where False indicates whether visited or not\n G[int(i)] = [False] if not G[int(i)] else G[int(i)]\n G[int(j)] = [False] if not G[int(j)] else G[int(j)]\n\n # read in the directed edges\n # read in straight for second DFS, read in reversed for first DFS\n if not reverse:\n G[int(i)].append(int(j))\n else:\n G[int(j)].append(int(i))\n\n return G\n</code></pre>\n\n<p>After your first DFS loop (using <code>G_rev</code>) you could flush <code>G_rev</code> from memory and then call <code>read_graph()</code> again to read in the forward directed graph.</p>\n\n<p>I haven't had a good look through the rest of the code, but I will do later today. As a first thought, you are keeping a list of explored nodes - again I think this is using more memory than you really need and could be replaced with a flag in the dictionary (see the boolean True / False flag in the dictionary above).</p>\n\n<p>-- DFS function\nThis looks like it may be one of your biggest bottlenecks. Recursion is not particularly well supported in Python - this is a problem for an algorithm that runs this deep! You might have to consider an iterative approach to calculating the \"magic ordering\" in the first DFS loop. Perhaps something like:</p>\n\n<pre><code>def magic_order():\n\n global stack # Last In, First Out data stucture\n global ranks # the finishing times for each node\n global G\n\n keys = sorted(G.keys(), reverse=True)\n for node in keys:\n if not G[node][0]:\n stack.append(node)\n\n while stack:\n leader = stack[-1]\n try:\n G[leader][0] = True\n outgoing = []\n try:\n outgoing = [j for j in G[leader][1:] if not G[j][0]]\n except IndexError:\n pass\n if outgoing:\n stack.extend(outgoing)\n else:\n ranks.append(leader)\n stack.pop()\n except KeyError:\n ranks.append(leader)\n</code></pre>\n\n<p>Hopefully this will help put you on the right track. The original graph will need to be re-sorted to match the finishing times calculated, and a second DFS call coded to calculate the SCCs (which should be less memory intensive than these first two steps). Good luck!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T21:06:03.533",
"Id": "29411",
"ParentId": "29404",
"Score": "1"
}
},
{
"body": "<p>my fellow Algo classmate.</p>\n\n<p>You need be careful picking the right data structure for your variables. Considering the large size of the input file and the purpose of variables, I would generally avoid using <code>list</code>, lookups in <code>list</code> is order of <code>O(n)</code> while <code>O(1)</code> in <code>dict</code> and <code>set</code>. </p>\n\n<p>That being said, a <code>set</code> is perfect for your <code>s_explored</code>, and you can make <code>finishing_time</code> a <code>dict</code>. I bet these alone would make a big difference. And you can follow the same principle to refactor your code. Overall, I don't see a problem in your implementation of the algorithm, so the performance is all about handling the data. </p>\n\n<p>I think tomdemuyt made a good point about readability, which is important especially when you want your code reviewed.</p>\n\n<p>BTW, <a href=\"http://teacode.wordpress.com/2013/07/27/algo-week-4-graph-search-and-kosaraju-ssc-finder/\" rel=\"nofollow\">here</a> is my personal implementation of the algorithm, you may want to take a look.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T21:24:00.640",
"Id": "29413",
"ParentId": "29404",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "29411",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T18:18:09.637",
"Id": "29404",
"Score": "1",
"Tags": [
"python",
"performance",
"algorithm"
],
"Title": "Calculating strongly-connected components in a directed graph using DFS"
}
|
29404
|
<p>My page has been loading a bit slower than I want it to. </p>
<p>The website is <a href="http://www.digitechlab.com/" rel="nofollow">www.digitechlab.com</a></p>
<p>I segregated so many files because they were pretty big and I wanted to be able to work on just one section of that page at a time without running the risk of breaking the entire page. This way I could work on, say, the header on its own. </p>
<p>Here is what I have</p>
<pre><code><!DOCTYPE html>
<!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
<title>DigiTech Dental Lab - Dental Lab Services- Digital Dental Restorations</title>
<meta name="keywords" content="dental lab, dentist laboratory, dental restorations, digital dental, dental implants, dental bridges, implant system, implant abutments, Bruxzir, IPS.emax, Prismatik, cad/cam technology" />
<meta name="description" content="DigiTech dental lab offers CAD/CAM technology and digital dentistry to provide quality dental restorations, crowns and bridges at a competitive price." />
<meta name="google-site-verification" content="" /> <!-- not shown -->
<meta name="y_key" content="" /> <!-- not shown -->
<meta name="msvalidate.01" content="" /> <!-- not shown -->
<!--#include file="/_includes/template/head-styles-scripts.html" -->
<link rel="stylesheet" href="/css/header.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="/css/font-museo500.css" type="text/css" charset="utf-8" />
</head>
<body class="bgWht container-bg">
<!--#include file="/_includes/template/header.html" -->
<div id="homePageHeader">
<div id="headerTagline">
<h1>CAD/CAM Digital Dental Restorations</h1>
</div>
<div class="responsiveHeaderContainer blkBorder">
<div id="headerLogo">
<img src="/img/home/bruxzir-bridge.png" />
</div>
<div id="headerModelImageContainer"><div id="headerModelImage"></div></div>
<div id="headerCopy">
<p>At DigiTech Dental Restorations, we take great pride in offering you quality products at a competitive price. Our dedicated team uses state-of-the-art CAD/CAM processes and equipment to fabricate each restoration, ensuring each crown or bridge is created with an unsurpassed degree of precision. The DigiTech staff is specially trained in monolithic BruxZir material, and our experience is evident in every BruxZir case you prescribe. From crowns &amp; bridges to Inclusive<sup>&reg;</sup> Implant Abutments, DigiTech is committed to both dentist and patient satisfaction.</p>
</div>
<div id="headerCTA">
<div>
<a href="tel:888-336-1301">
<div>
Schedule a pickup<br>
888-336-1301
</div>
</a>
</div>
</div>
</div> <!-- end of responsiveContainer -->
</div> <!-- end of homePageHeader -->
<!--#include file="/_includes/template/home-page/home-page-nav.html" -->
<!--#include file="/_includes/template/home-page/home-page-videos.html" -->
<!--#include file="/_includes/template/footer.html" -->
<!--#include file="/_includes/template/scripts.html" -->
<script>
$(document).foundation();
</script>
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T19:22:34.037",
"Id": "46599",
"Score": "2",
"body": "Looks fine to me from a code review perspective, the font choice is not so good. It looks ugly on my machine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T20:53:11.693",
"Id": "46606",
"Score": "0",
"body": "@tomdemuyt , I am guessing Google Chrome on PC, and you are referring to the page titles? I only added the ttf of Myriad, as that is all the designers gave me. or are you referring to the font that is sitewide? I used 'sintony' from Google fonts, are you not a fan of it? Thanks for pointing that out, I am open to suggestions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T21:48:45.357",
"Id": "46609",
"Score": "1",
"body": "Yeah, Sintony is bad."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-31T20:24:07.073",
"Id": "53849",
"Score": "0",
"body": "When you change `bgWht` to be a different colour than white, the class becomes misleading. Never put colour names into CSS classes: describe the content instead. The point of CSS is to provide the ability to change how the page looks without changing the page content. If you have to change the HTML and the CSS to change how it looks, fundamentally a mistake has been made. See also: http://www.csszengarden.com/"
}
] |
[
{
"body": "<p>your structure looks good.</p>\n\n<p>I am sure you have a reason for nesting so many <code><div></code>s </p>\n\n<p>you know that you can add classes to Tags as well, and you don't have to add them to only <code><div></code> tags you can add them to other tags.</p>\n\n<p>it just looks like you are surrounding some tags with Div tags because you think you can only style them that way.</p>\n\n<p>like this</p>\n\n<pre><code><div id=\"headerTagline\">\n <h1>CAD/CAM Digital Dental Restorations</h1>\n</div>\n</code></pre>\n\n<p>you can change to this</p>\n\n<pre><code><h1 id=\"headerTagline\"> CAD/CAM Digital Dental Restorations </h1>\n</code></pre>\n\n<p>or</p>\n\n<pre><code><h1 class=\"headerTagline\">CAD/CAM Digital Dental Restorations</h1>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-31T20:21:22.010",
"Id": "33618",
"ParentId": "29405",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "33618",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T18:51:05.123",
"Id": "29405",
"Score": "1",
"Tags": [
"html"
],
"Title": "Is this home page well organized and what can I do to improve performance here?"
}
|
29405
|
<ol>
<li>What do you consider the readability of this program?</li>
<li>Do you think it's easy to understand what the variables and functions do just by reading their names?</li>
<li>Would you prefer more, less, or this amount of comments?</li>
<li>Do the comments make it easier or harder for you to understand the program?</li>
<li>Do you like a program to have comments (in general)?</li>
</ol>
<p></p>
<pre><code># This program generates prime numbers
# Introduces user
def welcome():
print("""
Welcome to the prime number generator!
This program genarates all prime numbers starting from zero
to an upper limit. You´ll decide the upper limit.
Have fun :)
""")
# User inputs a natural number that will be the upper limit for checking primenumbers
def limit(question):
while True:
try:
limit = int(input(question))
except:
limit = ""
if limit:
return limit
break
# Checks if the number is a prime number. If it is, the number will be returned. If it is not, then None will be returned
def is_it_prime(current_number, prime_number):
y = 0
while True:
ratio = current_number / prime_number[y]
y += 1
if ratio == int(ratio):
break
if y == len(prime_number):
return current_number
# Adds prime number to list
def ad_prime(prime_number, it_is_prime):
a = len(prime_number)
prime_temp = (a+1)*[None]
for i in range(a):
prime_temp[i] = prime_number[i]
if i+1 == a:
prime_temp[i+1] = it_is_prime
return prime_temp
# Main program
upper_limit_question = "Type the upper limit and press enter. It has to be a natural number expressed in digits: "
lower_limit = 2
prime_number = [2]
welcome()
upper_limit = limit(upper_limit_question)
while lower_limit < upper_limit:
lower_limit +=1
it_is_prime = is_it_prime(lower_limit, prime_number)
if it_is_prime != None:
prime_number = ad_prime(prime_number, it_is_prime)
print("\n" +str(prime_number), "\n\nThanks for generating prime numbers :)")
</code></pre>
|
[] |
[
{
"body": "<p>It is easy to get a general understanding of what your code does. You did a good job separating the code into functions. It could be made more readable in a few ways though, mostly by doing things in a simpler way. For example, your <code>add_prime</code> function (which appends a number to the end of a list) could be written in one line (I'll get to how later).</p>\n\n<p>I recommend reading the <a href=\"http://docs.python.org/3/tutorial/\" rel=\"nofollow\">Python tutorial</a>. By the time you get to chapter 4, you'll notice a lot of thing you would have done differently. :)</p>\n\n<p>The variable names are good and make it easy to follow what you're doing, but the are a couple of names that are a bit confusing. In particular, <code>prime_number</code> should be <code>prime_numbers</code> or simply <code>primes</code> because it is a list of numbers. Also, <code>limit</code> isn't very descriptive at all. The difference between the <code>limit</code> function and the <code>upper_limit</code> variable is that one gets the value from the user, and the other stores it. <code>limit</code> should be <code>get_limit</code> or <code>get_limit_from_user</code>.</p>\n\n<p>I like the way you comment. The amount of comments is good and they improve readability. Keep commenting like that. I have one note, though: When you're writing a comment that describes what a whole function or a whole program does, use a <strong>docstring</strong>. This makes it clearer to other programmers what you commenting about, and makes it possible to access the comment in the code.</p>\n\n<p>Here is what an improved version of the code could look like (comments starting with <code>##</code> are part of this review and don't belong to the program):</p>\n\n<pre><code>\"\"\"Generate prime numbers.\"\"\" ## This is a docstring.\n\n\nWELCOME_TEXT = \"\"\"Welcome to the prime number generator!\n\nThis program generates all prime numbers starting from zero to an upper limit.\nYou'll decide the upper limit.\n\nHave fun :)\n\"\"\"\n\nLIMIT_PROMPT = (\"Type the upper limit and press enter. It has to be a natural \"\n \"number expressed in digits: \")\n</code></pre>\n\n<p><code>ALL_CAPS_NAMES</code> are a convention meaning a value should be treated as constant. In general, you should set constant values at the start of your program. In this case, this also has the advantage that the <code>WELCOME_TEXT</code> won't be indented.</p>\n\n<p>The two strings in <code>LIMIT_PROMPT</code> will automatically be concatenated. This way, you can write a one-line string in two lines of code.</p>\n\n<pre><code>def welcome():\n \"\"\"Introduce user.\"\"\" ## Also a docstring. If your function definition starts \n print(WELCOME_TEXT) ## with a string, the string will be made a docstring.\n\n\ndef get_limit():\n \"\"\"Let user input a an upper limit for checking prime numbers.\n\n The input must be a natural number.\"\"\"\n\n while True:\n try:\n return int(input(LIMIT_PROMPT))\n except ValueError:\n pass\n</code></pre>\n\n<p>I made a few changes to the <code>get_limit</code> function. You should always catch only specific exceptions (<code>ValueError</code> in this case.) Also, I think it's better not to mix strings and numbers in one variable. </p>\n\n<pre><code>def is_prime(current_number, prime_numbers):\n \"\"\"Check whether the number is a prime number.\n\n prime_numbers must contain all prime numbers lower than current_number.\"\"\"\n\n for prime in prime_numbers:\n if current_number % prime == 0: ## (current_number % prime) is the remainder\n return False ## when current_number is divided by prime.\n return True\n</code></pre>\n\n<p>You can loop over a list can be done easier this way. Making <code>is_prime</code> return a boolean will make things easier for you in the main part of the program.</p>\n\n<pre><code>def main():\n welcome()\n upper_limit = get_limit()\n prime_numbers = []\n for number in range(2, upper_limit+1):\n if is_prime(number, prime_numbers):\n prime_numbers.append(number) ## This adds number to the end of prime_numbers,\n ## so you don't need add_prime anymore.\n print(\"\\n\", prime_numbers, \"\\n\\nThanks for generating prime numbers :)\")\n\nmain()\n</code></pre>\n\n<p>I put the main part of the program into a <code>main</code> function (this is a useful convention). Again, you can simplify the loop, this time using the <code>range</code> function. For simple loops, there is usually a way of using a very readable <code>for</code> loop instead of a <code>while</code> loop. I also changed the name <code>lower_limit</code> to <code>number</code>, which fits better in my opinion.</p>\n\n<p>If you have any questions, feel free to ask them. Welcome to codereview. :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T14:07:15.777",
"Id": "46546",
"Score": "0",
"body": "If you catch only ValueErrors, you will immediatly when notice a different exception is thrown. Let's say you type `return int(input(LIMITPROMPT))` (note the missing underscore in `LIMIT_PROMPT`). This will throw a `NameError`. With a bare `except:`, this error will be silently ignored and the program will be caught in an infinite loop. With `except ValueError:`, however, you will notice the typo because you will get an error message."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T14:22:10.560",
"Id": "46554",
"Score": "0",
"body": "I deleted the comment that flornquake answered. Posting it again: When the `ValueError` statement is removed the program seems to be working fine. Why is the `ValueError` statement good?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T14:26:06.887",
"Id": "46556",
"Score": "0",
"body": "Is it not an infinite loop anaway (in this case)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T14:31:58.050",
"Id": "46559",
"Score": "0",
"body": "Well, yes, but what I meant is that if you have a bare `except:` and a typo as in `return int(input(LIMITPROMPT))`, your program won't ask you for input anymore. Instead, it will get stuck in an infinite loop you can't break out of, unless you interrupt the program."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T14:40:40.517",
"Id": "46560",
"Score": "0",
"body": "If the code stays the same except that `ValueError` is removed. It still asks for input. And when running it shows the same reults."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T15:09:59.193",
"Id": "46564",
"Score": "0",
"body": "True, as long as no other exceptions are thrown. But if you make a mistake and the code throws an unexpected exception (e.g. when you make a typo), the `except` will catch the exception. This is not what you want because it will hide the underlying problem instead of printing a useful error message."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T23:28:52.057",
"Id": "29419",
"ParentId": "29412",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29419",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T21:19:41.783",
"Id": "29412",
"Score": "4",
"Tags": [
"python",
"primes",
"python-3.x"
],
"Title": "User-input prime number generator"
}
|
29412
|
<p>First of all, I won't include the spin game there, cause it's very simple.</p>
<p>I went a bit deeper into object oriented since the last time, I learned array lists, using them with objects, maphashes, and more.</p>
<p>They are pretty useful I must say!</p>
<p>Let's begin:</p>
<p><strong>Mains.java</strong>:</p>
<pre><code>public class Mains {
public static void main (String[] args) {
//Start the game
startGame();
}
private static void startGame() {
//Declares
GameHandler handler = new GameHandler();
Scanner console = new Scanner(System.in);
boolean game = true;
String input = "";
//Print program welcome text
handler.printStart();
//While in game...
while (game) {
//Getting input ready for new commands from the player
input = console.nextLine();
//Checking if input was set.
if (input != null) {
//Selecting the game you want to play.
handler.selectGame(input);
//If game was selected.. then.. let's start playing.
while (handler.inGame) {
//Use will say something.
input = console.nextLine();
//If it was "exit", it will go back and select another game.
if (input.equals("exit")) {
handler.exitGame();
} else {
//Play again.
handler.continueGame(input);
}
}
}
}
}
}
</code></pre>
<p><strong>GameHandler.java</strong>:</p>
<pre><code>public class GameHandler {
private String[] games = {"Spin", "Tof"};
private Spin spin = new Spin();
private Tof tof = new Tof();
private boolean spinGame = false;
public static boolean tofGame = false;
public boolean inGame = false;
public int myPoints = 0;
/**
* Method printStart
*
* Will welcome the player to the program.
*/
public void printStart() {
this.print(0, "Welcome to the program!");
this.print(0, "Please select a game: " + this.availableGames());
}
/**
* Method available games
*
* This will print all the games that are located in the games array in one row.
**/
private String availableGames() {
String names = "";
for (int i = 0; i < games.length; i++) {
names = (names + games[i]);
if (i < games.length -1) {
names = (names + ", ");
}
}
return names;
}
/**
* Method selectGame
*
* This will select the given game.
* @param command The entered command.
**/
public void selectGame(String command) {
if (this.inArray(command))
{
if (command.equalsIgnoreCase("spin")) {
this.startGame("spin");
} else if (command.equalsIgnoreCase("tof")) {
this.startGame("tof");
}
} else {
this.print(0, "Could not find game!");
}
}
/**
* Method inArray
*
* This will check if the entered game name is exisiting in the games array.
* If yes, will return a boolean true, else false.
*
* @param value The entered game name.
* @return boolean true/false.
**/
private boolean inArray(String value) {
boolean exists = false;
for (String s : games) {
if (value.equalsIgnoreCase(s)) {
exists = true;
}
}
return exists;
}
/**
* Method startGame
*
* Will start the game, and print instructions.
* will set the game boolean to true.
**/
private void startGame(String game) {
switch (game) {
case "spin":
this.print(0, "Welcome to spin game!");
this.print(0, "Please click on any key to spin!");
spinGame = true;
break;
case "tof":
this.print(0, "Welcome to the ToF game!");
this.print(0, "Please answer the questions.");
System.out.println("");
System.out.println("===============");
System.out.println("QUESTION");
System.out.println("===============");
System.out.println("");
this.generateQuestion();
tofGame = true;
break;
}
inGame = true;
}
private void generateQuestion() {
System.out.println(tof.selectQuestion());
}
/**
* Method continueGame
*
* Will continue the game, either spin again, or print new question or even answer.
* @param command The entered command.
**/
public void continueGame(String command) {
while (inGame) {
if (spinGame) {
this.spinWheel();
// Break out of the loop.
break;
}
if (tofGame) {
this.checkAnswer(command);
break;
}
}
}
public void checkAnswer(String command) {
if (tof.checkQuestion(command)) {
tof.myPoints++;
System.out.println("<------------->");
System.out.println("Nice job!");
System.out.println("You received 1 point, you now have " + tof.myPoints + " Points");
System.out.println("<------------->");
System.out.println("");
System.out.println("===============");
System.out.println("NEXT QUESTION");
System.out.println("===============");
System.out.println("");
this.generateQuestion();
}
else {
System.out.println("");
System.out.println("Your answer was incorrect.");
System.out.println("");
System.out.println("===============");
System.out.println("NEXT QUESTION");
System.out.println("===============");
System.out.println("");
this.generateQuestion();
}
}
/**
* Method exitGame
*
* Exit the game..
**/
public void exitGame() {
System.out.println("");
System.out.println("");
spinGame = false;
tofGame = false;
inGame = false;
this.printStart();
tof.selectQuestion();
}
/**
* Method spinWheel
*
* This will spin the wheel.
**/
private void spinWheel() {
this.print(0, spin.spinWheel());
}
/**
* Method print
*
* Prints text using System.out
* @param type printing type (Println/print).
* @param message The message
**/
private void print(int type, String message) {
switch (type) {
case 0:
System.out.println(message);
break;
case 1:
System.out.print(message);
break;
}
}
}
</code></pre>
<p><strong>Tof.java:</strong></p>
<pre><code>public class Tof {
private Random r = new Random();
private ArrayList<QnA> questionArray = new ArrayList<QnA>();
public int question;
public int myPoints = 0;
public Tof() {
questionArray.add(new QnA("Is daniel big? ", "true"));
questionArray.add(new QnA("Does Daniel sucking at linux?", "false"));
questionArray.add(new QnA("Daniel is pink? ", "true"));
questionArray.add(new QnA("Daniel is funny? ", "false"));
}
public String selectQuestion() {
if (questionArray.size() > 0) {
int index = r.nextInt(questionArray.size());
this.question = index;
return questionArray.get(index).getQuestion();
}
else {
this.noQuestions();
return "Please type exit and re-enter the game.";
}
}
public boolean checkQuestion(String answer) {
boolean returning = false;
if (questionArray.get(this.question).getAnswer().equalsIgnoreCase(answer)) {
returning = true;
}
questionArray.remove(this.question);
return returning;
}
private void noQuestions() {
if (GameHandler.tofGame) {
System.out.println("");
System.out.println("Oh boy! It looks like you've ran out of questions.");
System.out.println("blabla");
System.out.println("");
System.out.println("You could gain total of " + this.myPoints + " Points.");
this.myPoints = 0;
}
GameHandler.tofGame = false;
}
}
</code></pre>
<p>and last one, QnA class:</p>
<pre><code>public class QnA {
private String question = "";
private String answer = "";
public QnA(String q, String a) {
this.question = q;
this.answer = a;
}
public String getQuestion() {
return question;
}
public String getAnswer() {
return answer;
}
}
</code></pre>
<p>I want to focus on my Object-oriented structures, how I handle the code, etc.
Please tell me what's wrong and useless code there (Besides the plant printlns hehe).</p>
<p>Thanks!</p>
|
[] |
[
{
"body": "<p>If you are focussing on OO it would be good to put your games in a separate class. For OO perspective you should check which are the different entities in your application and represent them in a class, defining that each entity can do and the relations to other entity. </p>\n\n<p>You might want to to have a parent game class which defines standard behaviour of a game such as starting, stopping, requested game name, loading your game dependencies, ... and an extention / implementation of that general game class to a specific game.</p>\n\n<p>Make your handler / controller use the generic game interface as it only needs to access the standard behaviour of a game and not it's specific implementation. Like that create a loose coupling between your controller & your games, making it easier to extend the game with more games later on. You can also inject all your different games into the handler making it easier to unit test the functionality of the handler (with a mock set of games). </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T15:51:20.723",
"Id": "29459",
"ParentId": "29415",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T21:24:20.440",
"Id": "29415",
"Score": "1",
"Tags": [
"java",
"object-oriented",
"game"
],
"Title": "Game selection menu"
}
|
29415
|
<p>I've been writing a program to perform a kind of pattern-matching in XML and text files. </p>
<p>When my program reaches this section of the code, the CPU usage gets very high and the performance slows down to a point where the program seems to be frozen. It actually isn't, but depending on the input (number of text files and their content), it may take several hours to complete the task.</p>
<p>I'm looking for a more efficient way to rewrite this section of the code:</p>
<pre><code>List<string> CandidatesRet = new List<string>();
for (int indexCi = 0; indexCi < Ci.Count - 1; indexCi++)
{
// generate all sub itemset with length-1
string[] allItems = Ci[indexCi].Split(new char[] { ' ' });
for (int i = 0; i < allItems.Length; i++)
{
string tempStr = "";
for (int j = 0; j < allItems.Length; j++)
if (i != j)
tempStr += allItems[j] + " ";
tempStr = tempStr.Trim();
subItemset.Add(tempStr);
}
// THE PROBLEM BEGINS HERE
foreach (string subitem in subItemset)
{
int iFirtS;
for (int indexCommon = indexCi + 1; indexCommon < Ci.Count; indexCommon++)
if ((iFirtS = Ci[indexCommon].IndexOf(subitem)) >= 0)
{
string[] listTempCi = Ci[indexCommon].Split(new char[] { ' ' });
foreach (string itemCi in listTempCi)
if (!subitem.Contains(itemCi))
commonItem.Add(itemCi);
}
allCommonItems.Add(commonItem);
}
// generate condidate from common item
foreach (string item in oldItemsetCi)
{
bool flagCi = true;
foreach (List<string> listCommItem in allCommonItems)
if (!listCommItem.Contains(item))
{
flagCi = false;
break;
}
if (flagCi)
CandidatesRet.Add((Ci[indexCi] + " " + item).Trim());
}
</code></pre>
<p>There are many nested loops and I know this is the problem. What do you think should be improved?</p>
|
[] |
[
{
"body": "<p>This should help a little bit:</p>\n\n<pre><code> List<string> CandidatesRet = new List<string>();\n\n var splitChars = new[] { ' ' };\n\n for (var indexCi = 0; indexCi < Ci.Count - 1; indexCi++)\n {\n // generate all sub itemset with length-1\n var allItems = Ci[indexCi].Split(splitChars);\n\n subItemset\n .AddRange(allItems.Select((s, i) => allItems.Where((t, j) => i != j)\n .Aggregate(string.Empty, (current, t) => current + (t + \" \")))\n .Select(tempStr => tempStr.Trim()));\n\n // THE PROBLEM BEGINS HERE \n foreach (var subitem in subItemset)\n {\n for (var indexCommon = indexCi + 1; indexCommon < Ci.Count; indexCommon++)\n {\n if (Ci[indexCommon].IndexOf(subitem, StringComparison.Ordinal) < 0)\n {\n continue;\n }\n\n var listTempCi = Ci[indexCommon].Split(splitChars);\n\n commonItem.AddRange(listTempCi.Where(itemCi => !subitem.Contains(itemCi)));\n }\n\n allCommonItems.Add(commonItem);\n }\n\n // generate condidate from common item\n CandidatesRet.AddRange(oldItemsetCi\n .Select(item => new { item, flagCi = allCommonItems.All(listCommItem => listCommItem.Contains(item)) })\n .Where(t => t.flagCi)\n .Select(t => (Ci[indexCi] + \" \" + t.item).Trim()));\n }\n }\n</code></pre>\n\n<p>However, the big problem is the still the double loop, which will grow as a power-of-two rather than linearly with your data size.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T02:26:54.983",
"Id": "29420",
"ParentId": "29418",
"Score": "2"
}
},
{
"body": "<p>Use a StringBuilder instead of string concatenation. You will be surprised at how slow string concatenation is in bulk.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T04:02:40.333",
"Id": "29543",
"ParentId": "29418",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29420",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T22:58:09.860",
"Id": "29418",
"Score": "3",
"Tags": [
"c#",
"performance"
],
"Title": "Program slows down significantly based on input"
}
|
29418
|
<p>I have written a simple command line program in Python 3 that accepts a function (in the mathematical sense) from a user and then does various "calculus things" to it. I did it for my own purposes while taking a math class, so I was more concerned with getting it to output the right number than with security.</p>
<p>I was just hoping to get some feedback as to whether this program is readable, understandable, and if there are any serious issues with it.</p>
<p>Here is the file that defines my data structures, which is what I'm mostly concerned with at the moment (<code>datums.py</code>):</p>
<pre><code>from fractions import Fraction
from copy import copy
from collections import namedtuple
class Point(namedtuple("Point", ["x", "y"])):
"""
Represents a point in two dimensional space.
Probably in R^2, but you can store anything you want.
"""
def __str__(self):
return "({x}, {y})".format(x=self.x, y=self.y)
class Function(object):
"""
A Function in the mathematical sense. Basically it's just a lambda in the background
with some fancy formatting thrown in.
"""
def __init__(self, args, expr, name="f"):
"""
Create the "function" object.
args: A comma (and potentially whitespace) separated list of variable names
expr: A mathematical expression in terms of the variables given in args.
Any valid python expression is valid, and any function in the math module
is available.
name: A friendly name can be given to this function, but it only affects the
formatting when it's printed out and not any of its actual behavior
"""
self.name = name
self._args = [i.strip() for i in args.split(",")];
self._expr = expr;
self._func = eval("lambda {v}: {x}".format(v=args, x=expr), _mathdict())
def __str__(self):
args = ", ".join(self._args)
return "{name}({v}) = {e}".format(name=self.name,
v=args,
e=self._expr)
def __call__(self, *args, **kwargs):
return self._func(*args, **kwargs)
class Graph(object):
"""
A "graph"... Precalculates a set of points in two dimensional space
over a given interval and with a given distance from each other,
and stores their locations to speed up certain other processes.
"""
def __init__(self, func, low, high, steps, include_end=False):
"""
Initialize a graph.
Calculates func(x) at a set of different points,
each at a distance of ((high - low) / steps) from its neighbors,
starting at {low} and ending at {high} (inclusive).
func: a Function() object.
low: the starting x coordinate of the graph.
high: the ending x coordinate of the graph. This point will be computed.
steps: The number of points to be computed, excluding the endpoint.
include_end: A boolean representing whether you want an iterator over this
object to include the end. The last point will be computed and
stored regardless.
"""
self.func = func
self.interval = (low, high)
self.n = steps
self.include_end = include_end
self.delta = Fraction((high - low) / steps).limit_denominator()
xs = tuple(float(low + i * self.delta) for i in range(steps + 1))
ys = tuple(func(x) for x in xs)
self.points = tuple(Point(x, y) for x, y in zip(xs, ys))
def __getitem__(self, sl):
return self.points[sl]
def __len__(self):
return self.n + (1 if self.include_end else 0)
def __iter__(self):
return iter(self.points[:len(self)])
def __min__(self):
return min(self, key=lambda p: p[-1])
def __max__(self):
return max(self, key=lambda p: p[-1])
def __str__(self):
interval = "[{a}, {b}{close}".format(a=self.interval[0],
b=self.interval[1],
close="]" if self.include_end else ")")
mesg = "interval={inter}, n={n}, delta={d}"
return mesg.format(func=self.func,
inter=interval,
n=self.n,
d=self.delta)
def with_include_end(self, include_end):
"""
Copy this object to a new graph, with all of the same points and the same
function, but with include_end set as given.
"""
new = copy(self)
new.include_end = include_end
return new
def _mathdict():
"""
Imports math, then pulls out all of its Functions that aren't private
into a dict for use in eval-ing a lambda.
"""
import math
return {f: getattr(math, f) for f in dir(math) if not f.startswith("_")}
</code></pre>
<p>Notice in the Function's <code>__init__()</code> method, it takes the argument list and the expression, then eval's a lambda. I know that running eval() on unsanitized user input is an enormous no-no. (<code>eval("[i for i in open('/dev/zero')]")</code> for instance). But in this case, the user is me only so "user data" can be considered safe. If I ever go big-time with this, then I'll look in to sanitizing it but for now, in this case, that's not an issue of concern</p>
<p>The original version of this program's Function just stored <code>expr</code> and then <code>eval</code>'d it in <code>__call__</code>, but that was orders of magnitude slower than this way (and in this case, it's not premature optimization, since if I'm doing Simpson's method with n=9000000, it can take some time).</p>
<p>Is there a better way to have arbitrary expressions created and evaluated at runtime than I'm doing? It feels a little odd to do it this way.</p>
<p>Here's the driver file (<code>__main__.py</code>):</p>
<pre><code>from sys import argv
import integrals
import diffapprox
_commands = {"integrate": integrals,
"diffapprox": diffapprox}
def show_help():
print("Need a command. One of:")
for name, pkg in _commands.items():
print("{name}: {desc}".format(name=name, desc=pkg.desc))
def main():
try:
command = argv[1]
job = _commands[command]
except:
show_help()
return
job.main(*argv[2:])
if __name__ == "__main__":
main()
</code></pre>
<p>Here's an example use file (<code>integrals.py</code>):</p>
<pre><code>from datums import Function, Graph, Point
desc = "Perform approximate numerical integration"
def left_rectangles(graph):
g = graph.with_include_end(False)
return g.delta * sum(p.y for p in g)
def right_rectangles(graph):
g = graph.with_include_end(True)
pts = g[1:]
return g.delta * sum(p.y for p in pts)
def midpoint_rule(graph):
g = graph.with_include_end(False)
f = graph.func
halfdelta = graph.delta / 2
midpoints = [p.x + halfdelta for p in g]
return g.delta * sum(f(x) for x in midpoints)
def trapezoid_rule(graph):
g = graph.with_include_end(True)
s = g[0].y + g[-1].y + 2 * sum(p.y for p in g[1:-1])
return s * g.delta / 2
def simpsons_rule(graph):
g = graph.with_include_end(True)
s = g[0].y + g[-1].y
s += 4 * sum(p.y for p in g[1:-1:2])
s += 2 * sum(p.y for p in g[2:-1:2])
return s * g.delta / 3
def parseargs(a, e, l, h, n):
"""
Return a tuple of arguments.
a = arguments to the function
e = expression of the function
l = lowpoint
h = highpoint
n = n
"""
return (a,
e,
float(l),
float(h),
int(n),)
__all__ = [left_rectangles,
right_rectangles,
midpoint_rule,
trapezoid_rule,
simpsons_rule]
def show_help():
print("Usage:")
print()
print("integrate {vars} {expression} {low} {high} {n}")
print()
print("Integrates f({vars}) from {low} to {high} with the given integer n.")
def main(*args):
try:
args, expr, low, hi, n = parseargs(*args)
except:
show_help()
return
function = Function(args, expr)
graph = Graph(function, low, hi, n)
# methods will be mapped to their names, formatted for the user's viewing pleasure
methods = {method.__name__.replace("_", " ").title(): method for method in __all__}
longest = max(len(name) for name in methods.keys())
print(function)
print(graph)
print()
for name, method in methods.items():
print("{name:<{len}}: {approx:.10n}".format(name=name, len=longest, approx=float(method(graph))))
</code></pre>
<p>There is more to this program but that's the gist of it. Is this okay? Terrible?
Any feedback would be appreciated.</p>
<p>Sample input:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>python MathJunk x "x ** 2" 0 1 10
f(x) = x ** 2
interval=[0.0, 1.0), n=10, delta=1/10
Right Rectangles: 0.385
Midpoint Rule : 0.3325
Left Rectangles : 0.285
Simpsons Rule : 0.3333333333
Trapezoid Rule : 0.335
</code></pre>
</blockquote>
|
[] |
[
{
"body": "<p>Looks well organized, understandable, and suited for the domain. You might want to take care with naming to improve readability. For example, name the class Function to be MathFunction to prevent confusion of purpose. Also single-letter variable names should normally be avoided, particularly lower-case \"L\", except for obvious increment counters.</p>\n\n<p>For more on Python naming style see the <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP guides</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T02:25:05.357",
"Id": "29475",
"ParentId": "29421",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29475",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T05:18:44.263",
"Id": "29421",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"mathematics",
"console"
],
"Title": "Command line calculus program"
}
|
29421
|
<p>Can this be shortened, optimised or made more pythonic ?</p>
<pre><code>a = [1,9,'foo',5,7]
b = ['bar',4,8,6]
c = []
min_len = min(len(a),len(b))
for i in range(min_len):
c.extend([a.pop(0), b.pop(0)])
c.extend(a)
c.extend(b)
print c
</code></pre>
<p>output: [1, 'bar', 9, 4, 'foo', 8, 5, 6, 7]</p>
|
[] |
[
{
"body": "<p>There are a few possibilities...</p>\n\n<pre><code>from itertools import chain, izip_longest\ndef alternate(a, b):\n for i in range(max(len(a), len(b))):\n if i < len(a):\n yield a[i]\n if i < len(b):\n yield b[i]\n\ndef alternate2(list_a, list_b):\n unfound = {}\n for a, b in izip_longest(list_a, list_b, fill=unfound):\n if a is not unfound:\n yield a\n if b is not unfound:\n yield b\n\na = [1,9,'foo',5,7] \nb = ['bar',4,8,6] \nprint list(alternate(a, b))\nprint list(alternate2(a, b))\nprint list(chain.from_iterable(zip(a, b))) + a[len(b):] + b[len(a):]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T09:32:11.120",
"Id": "46520",
"Score": "0",
"body": "not sure about those `A`/`B` for local variables."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T08:05:23.260",
"Id": "29426",
"ParentId": "29423",
"Score": "1"
}
},
{
"body": "<p>I'd write:</p>\n\n<pre><code>import itertools\n\ndef alternate(xs, ys):\n head = itertools.chain.from_iterable(zip(xs, ys))\n return itertools.chain(head, xs[len(ys):], ys[len(xs):])\n\nprint(list(alternate([1, 2, 3, 4, 5], [\"a\", \"b\", \"c\"]))) \n# [1, 'a', 2, 'b', 3, 'c', 4, 5]\n</code></pre>\n\n<p>Another solution without <code>itertools</code> and using the (long-awaited) <a href=\"http://www.python.org/dev/peps/pep-0380/\" rel=\"nofollow\">yield from</a> construction added in <a href=\"http://docs.python.org/3/whatsnew/3.3.html\" rel=\"nofollow\">Python 3.3</a>:</p>\n\n<pre><code>def alternate(xs, ys):\n yield from (z for zs in zip(xs, ys) for z in zs)\n yield from (xs[len(ys):] if len(xs) > len(ys) else ys[len(xs):])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T08:45:22.417",
"Id": "29428",
"ParentId": "29423",
"Score": "1"
}
},
{
"body": "<p>I would avoid doing <code>x.pop(0)</code> because <a href=\"http://docs.python.org/2/tutorial/datastructures.html#using-lists-as-queues\" rel=\"nofollow\">it is slow</a> (unlike <code>x.pop()</code>, by the way). Instead, I would write (in Python 2):</p>\n\n<pre><code>import itertools\n\ndef alternate(a, b):\n \"\"\"Yield alternatingly from two lists, then yield the remainder of the longer list.\"\"\"\n for A, B in itertools.izip(a, b):\n yield A\n yield B\n for X in a[len(b):] or b[len(a):]:\n yield X\n\nprint list(alternate([1, 2, 3, 4, 5], [\"a\", \"b\", \"c\"]))\n</code></pre>\n\n<p>In Python 3, <code>itertools.izip</code> becomes <code>zip</code> and, as tokland has noted, we can use <a href=\"http://www.python.org/dev/peps/pep-0380/\" rel=\"nofollow\"><code>yield from</code></a> in Python 3.3:</p>\n\n<pre><code>def alternate(a, b):\n \"\"\"Yield alternatingly from two lists, then yield the remainder of the longer list.\"\"\"\n for A, B in zip(a, b):\n yield A\n yield B\n yield from a[len(b):] or b[len(a):]\n\nprint(list(alternate([1, 2, 3, 4, 5], [\"a\", \"b\", \"c\"])))\n</code></pre>\n\n<p>The following will work with any kind of iterables:</p>\n\n<pre><code>def alternate(a, b):\n \"\"\"Yield alternatingly from two iterables, then yield the remainder of the longer one.\"\"\"\n x, y = iter(a), iter(b)\n while True:\n try:\n yield next(x)\n except StopIteration:\n yield from y\n return\n x, y = y, x\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T09:57:57.327",
"Id": "29431",
"ParentId": "29423",
"Score": "1"
}
},
{
"body": "<p>If the lists cannot contain <code>None</code> as a valid item that you want copied to <code>c</code>, you can use this:</p>\n\n<pre><code>from itertools import izip_longest\n\nc = [item for items in izip_longest(a, b) for item in items if item is not None]\n</code></pre>\n\n<p>It is shorter/concise*, doesn't modify the original lists and probably performs a bit better.</p>\n\n<p>*Yet it doesn't look so elegant, but it's a common pattern in Python, which is most important.</p>\n\n<p>As a bonus, it scales to more lists easily.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T10:38:52.187",
"Id": "29433",
"ParentId": "29423",
"Score": "1"
}
},
{
"body": "<p>Without <code>pop</code>, <code>yield</code> or <code>itertools</code></p>\n\n<pre><code>c = []\nfor i,x in enumerate(zip(a,b)): \n c.extend(x)\ni += 1\nc.extend(a[i:])\nc.extend(b[i:])\n</code></pre>\n\n<p>In older versions the loop could be written as a comprehension, but in newer ones <code>i</code> is not accessible outside the loop. But:</p>\n\n<pre><code>c = [y for x in zip(a,b) for y in x]\ni = len(c)//2 # or i = min(len(a),len(b))\nc.extend(a[i:])\nc.extend(b[i:])\n</code></pre>\n\n<p>At its core, this is a question of how to flatten <code>zip(a,b)</code>. <a href=\"https://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python\">https://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python</a>\nmakes the case that <code>itertools.chain</code> is somewhat faster than the comprehension, though not drastically so.</p>\n\n<pre><code>c = chain.from_iterable(zip(a,b)) # or\nc = chain(*zip(a,b))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T16:54:52.837",
"Id": "46673",
"Score": "0",
"body": "Why would one avoid `yield` (a language construct) or `itertools` (batteries included, what Python is famous for)?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T16:02:07.397",
"Id": "29500",
"ParentId": "29423",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T06:09:56.533",
"Id": "29423",
"Score": "5",
"Tags": [
"python"
],
"Title": "New list from the elements of two lists popping sequentially"
}
|
29423
|
<p>I am trying to capture screenshots as fast as possible from when it's displayed, meaning that I want the latency to be minimal.</p>
<p>Currently, I am using user32.dll to capture a window. So, if I have a game, I capture that window along with borders and everything. It's very fast, but I wonder if hooking into the API (DirectX) and getting the buffer will be faster than this (I don't know how to do that, though).</p>
<p>Here's how I'm doing it:</p>
<pre><code> [DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetWindowRect(IntPtr hWnd, out Rect lpRect);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, int nFlags);
private static MemoryStream PrintWindow(string prcname)
{
IntPtr hwnd;
using (var proc = Process.GetProcessesByName(prcname)[0])
{
hwnd = proc.MainWindowHandle;
}
Rect rc;
NativeMethods.GetWindowRect(hwnd, out rc);
using (Bitmap bmp = new Bitmap(rc.Width, rc.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
{
using (Graphics gfxBmp = Graphics.FromImage(bmp))
{
IntPtr hdcBitmap = gfxBmp.GetHdc();
try
{
NativeMethods.PrintWindow(hwnd, hdcBitmap, 0);
}
finally
{
gfxBmp.ReleaseHdc(hdcBitmap);
}
}
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms;
}
}
</code></pre>
<p>I give it a process name and it will hook to that certain window. And as I've said, it's not slow; it's fast. But I think it may be slower than what can be achieved, especially since the actual render of the game is often different from the screen (for example, 30FPS on the game, and it's 60HZ on the screen, meaning 50% of the images will be duplicates).</p>
<p>Any ideas about this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T12:29:30.470",
"Id": "61637",
"Score": "1",
"body": "For inspiration, I would have a look at how [OBS does it](https://github.com/jp9000/OBS/tree/master/GraphicsCapture/GraphicsCaptureHook). One important aspect to remember is that not all games do use DirectX - you may want to create an additional class to capture OpenGL, too."
}
] |
[
{
"body": "<blockquote>\n<p><em>It's very fast, but I wonder if hooking into the API (DirectX) and getting the buffer will be faster than this (I don't know how to do that, though).</em></p>\n</blockquote>\n<p>I don't know either.</p>\n<p>What you have here, probably hasn't been reviewed yet, because there's essentially nothing blatantly wrong with it.</p>\n<hr />\n<h3>What you've done well</h3>\n<p>Pretty much everything, as far as I can tell:</p>\n<ul>\n<li><p>Every <code>IDisposable</code> is wrapped in a <code>using</code> block and thus, whether it blows up or not, things get disposed correctly.</p>\n</li>\n<li><p><code>try...finally</code> is the best thing you could do here; if there's an exception, it will bubble up, and the <code>finally</code> block will run in all cases, ensuring the resources cleanly get released.</p>\n</li>\n<li><p>You're working everything in a <code>MemoryStream</code>, which is the only logical thing to do (hitting the file system would be utter nonsense).</p>\n</li>\n</ul>\n<h3>Question marks</h3>\n<ul>\n<li><p><em>Returning</em> the <code>MemoryStream</code> means <em>closing</em> and <em>disposing</em> the stream isn't the responsibility of the method that created it - that's a potential issue. I would try to <code>Freeze()</code> the bitmap and return a <code>Bitmap</code> object instead, although there might be a performance penalty in doing that.</p>\n</li>\n<li><p>If the method is called in a tight loop, does the result of <code>NativeMethods.GetWindowRect(hwnd, out rc);</code> change at all between calls? Perhaps the method could take a <code>Rect</code> as a parameter?</p>\n</li>\n<li><p>It being <code>static</code> scares me a little, but it's <code>private</code> and you're not showing the class it's a member of... You'll want the method wrapped in an object that you can create and pass around, not just a global/static "helper" method that's part of some undefined <em>ambient context</em>.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T14:47:20.480",
"Id": "42961",
"ParentId": "29424",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T06:22:06.173",
"Id": "29424",
"Score": "13",
"Tags": [
"c#",
"performance",
"windows"
],
"Title": "Capture with User32.dll or hook?"
}
|
29424
|
<p>I am using some string which contains an html. As follows</p>
<pre><code>var pagerHtml = '<span>No.Of Records</span><select class="rmselect" id="records" ><option value="10">10</option><option value="20">20</option><option value="40">40</option><option value="80">80</option><option value="100">100</option></select>';
</code></pre>
<p>Another is with " and escape sequence \" for " in the html as follows</p>
<pre><code>var pagerHtml = "<span>No.Of Records</span><select class=\"rmselect\" id=\"records\" ><option value=\"10\">10</option><option value=\"20\">20</option><option value=\"40\">40</option><option value=\"80\">80</option><option value=\"100\">100</option></select>";
</code></pre>
<p>And I am writing this html to a div using jquery</p>
<p>Which one gives the better performance while parsing?</p>
<p>Is there any performance difference on parsing escape sequence?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T08:46:35.237",
"Id": "46518",
"Score": "2",
"body": "You should check out [jsPerf](http://jsperf.com/). IMO, this isn't really a performance concern. I'd rather worry about maintaining this code, since HTML in JS isn't really good."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T09:49:02.213",
"Id": "46521",
"Score": "1",
"body": "Are you aware that the only difference would be when the Javascript code is parsed? When the code runs those are identical strings, so parsing them into HTML elements will give exactly the same performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T09:51:11.770",
"Id": "46522",
"Score": "0",
"body": "@JosephtheDreamer and Guffa - thank you for the suggestions"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T07:33:46.090",
"Id": "46704",
"Score": "1",
"body": "@Nithesh: Never forget that premature optimization is the root of all evil. This sort of micro-optimization really is of little use, especially with languages like JS. The JS engines change so rapidly, and the implementations can differ so much, that, when you've updated your code to work as fast as possible on V8, the engine might have changed, and your optimizations turn out to be slower on the latest version..."
}
] |
[
{
"body": "<p>According to <a href=\"http://jsperf.com/parsing-escape\" rel=\"nofollow\">this jsperf test</a>, there is no consistent difference between parsing a string literal with and without escape sequences.</p>\n\n<p>There are differences depending on what browser you use, but they are quite small, and Chrome even seems to parse strings with escape sequences faster than strings without.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T10:05:37.590",
"Id": "29432",
"ParentId": "29427",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29432",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T08:44:05.613",
"Id": "29427",
"Score": "0",
"Tags": [
"javascript",
"jquery",
"performance",
"parsing"
],
"Title": "Javascript parsing performance"
}
|
29427
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.