body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
A tree-like data structure used to hold an associative array, also called a Prefix Tree.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T09:18:17.137",
"Id": "41634",
"Score": "0",
"Tags": null,
"Title": null
}
|
41634
|
<p>My main DLL is a .Net one that has an async running method and fires an event when it's done:</p>
<pre><code>public class LicenceVerifier
{
private readonly ILicence _licence;
private readonly int _programkey;
public delegate void LicencedCheckedEventHandler(object sender, LicenceVerifierResultArgs args);
public event LicencedCheckedEventHandler LicencedChecked;
public LicenceVerifier(int programKey)
{
_programkey = programKey;
_licence = GetLicensing();
}
public void IsValidLicenceAsync()
{
new Task(() =>
{
LicenceVerifierResult valid = LicenceVerifierResult.NotAvailable;
if (_licence != null)
valid = _licence.IsValid(_programkey);
LicencedChecked(this, new LicenceVerifierResultArgs(valid));
}).Start();
}
.....
}
</code></pre>
<p>Now I have a C++ API for our C++ and VB6 applications. I'm registering here to the .Net <code>LicensedCheckedEventHandler</code> to get a callback to the C++ API.</p>
<p>In the C++ API callback method, I post a message to a created window to get out of the worker thread back to the UI thread and then call back to the C++/VB6 applications.</p>
<pre><code>#include "stdafx.h"
#include <windows.h>
#include "PublicHeader\Licensing.h"
using namespace System;
using namespace XxxX::Licensing;
using namespace std;
#define WM_LICENSING_RESULT (WM_APP + 1001)
LRESULT CALLBACK RedirectWndProc (HWND, UINT, WPARAM, LPARAM);
long lCallbackAddress;
void(*callBackFunction)(int);
enum CallbackType {
UNKNOWN,
C,
VB
};
public ref class LicenceVerifierCallback
{
public:
HWND m_hWnd;
CallbackType m_Type;
//Callback from .NET dll
void handler(System::Object^ sender, LicenceVerifierResultArgs^ e)
{
PostMessage(m_hWnd, WM_LICENSING_RESULT, convertResult(e->Result), (CallbackType)m_Type);
};
int convertResult(LicenceVerifierResult verifierResult)
{
if(verifierResult == LicenceVerifierResult::Available)
return 0;
return 1;
};
};
void RegisterRedirectWnd(wchar_t szClassName[])
{
WNDCLASSEX wc;
wc.lpszClassName = (LPCWSTR)szClassName;
wc.lpfnWndProc = RedirectWndProc;
wc.cbSize = sizeof (WNDCLASSEX);
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
RegisterClassEx (&wc);
}
LRESULT CALLBACK RedirectWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if(message == WM_LICENSING_RESULT)
{
if((CallbackType)lParam == VB)
{
typedef void ( *FUNCPTR) (int iResult);
FUNCPTR vbCallBackFunction;
vbCallBackFunction = (FUNCPTR)lCallbackAddress;
vbCallBackFunction(wParam);
}
if((CallbackType)lParam == C)
callBackFunction(wParam);
}
return DefWindowProc (hwnd, message, wParam, lParam);
}
//Create a window to be able to receive messages
HWND CreateMessageRetriever()
{
RegisterRedirectWnd(L"Licensing");
return CreateWindow(L"Licensing", NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0);
};
void IsLicenseValid(int iPrgKey, CallbackType type)
{
HWND hwnd = CreateMessageRetriever();
LicenceVerifierCallback^ callback = gcnew LicenceVerifierCallback();
callback->m_hWnd = hwnd;
callback->m_Type = type;
//The .Net object that processes the actual licensing check async
LicenceVerifier^ licenceVerifier = gcnew LicenceVerifier(iPrgKey);
licenceVerifier->LicencedChecked += gcnew LicenceVerifier::LicencedCheckedEventHandler(callback, &LicenceVerifierCallback::handler);
licenceVerifier->IsValidLicenceAsync();
}
// Entry point: Call from vb6 application
void __stdcall CheckLicenseAsyncVb(int iPrgKey, int cbAddress)
{
lCallbackAddress = cbAddress;
IsLicenseValid(iPrgKey, VB);
}
// Entry point: Call from c++ application
void __stdcall Licensing::CheckLicenseAsyncC(int iPrgKey, void(*callbackFunc)(int))
{
callBackFunction = callbackFunc;
IsLicenseValid(iPrgKey, C);
};
//Notifies the backend that the application got closed and the licence can be releases
void __stdcall Licensing::NotifyApplicationClosed(int iPrgKey)
{
LicenceVerifier^ licenceVerifier = gcnew LicenceVerifier(iPrgKey);
licenceVerifier->ApplicationClosed();
};
</code></pre>
<p>I'm not that familiar with C++ and wonder if the code looks okay and if the way it's done is okay as well. I have to mention that using COM was not an option. Any further suggestions and corrections are highly welcome and appreciated.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T10:06:05.433",
"Id": "41637",
"Score": "4",
"Tags": [
"c++",
"asynchronous",
"windows",
"callback"
],
"Title": "Aysnc call back to UI Thread"
}
|
41637
|
<p>I would like to heat some feedback on this. I'm coming from a Java background and this is my first program in Scala. I solved <a href="http://en.wikipedia.org/wiki/Range_Minimum_Query" rel="nofollow">Range Minimum Query</a> problem.</p>
<pre><code>object Solution {
def main(args: Array[String]){
val readInfo = readLine.split(" ");
val numberofElements = Integer.parseInt(readInfo(0))
val numberOfQuery = Integer.parseInt(readInfo(1))
val storeElemets: Array[Int] =readLine.split(" ").map(_.toInt);
val j =0;
for(j<-0 until numberOfQuery){
val z = readLine.split(" ")
val from = Integer.parseInt(z(0))
val to = Integer.parseInt(z(1))+1
val i=from
val getNumber = (from until to).map{i => storeElemets(i)}
println(getNumber.min);
}
}
}
</code></pre>
<p>I would like to know, What are the best practices and is there any better way to implement this solution ?</p>
|
[] |
[
{
"body": "<p>For starters,\n your spacing is rather inconsistent: <code>val j =0</code> <code>val i=from</code>,\n typos abound: <code>storeEleme<b>n</b>ts</code>, <code>number<b>O</b>fElements</code> <code>numberOfQuer<b>ies</b></code>,\n and you terminate some statements with <code>;</code>.</p>\n\n<p>Be aware that a lambda <code>foo => bar(foo)</code> is similar to the declaration <code>def anonymous(foo) = bar(foo)</code>. That is, the parameter name <code>foo</code> is already declared by being a parameter – your <code>val i = from</code> is a absolutely unnecessary. Similarly, <code>val j = 0</code> is not needed because <code>j <- ...</code> in the <code>for</code>-comprehension already amounts to a declaration.</p>\n\n<p>In Scala, curly braces <code>{}</code> and parens <code>()</code> are rather similar. Use curlies only when using a multi-statement lambda.</p>\n\n<p>In one place, you do <code>_.toInt</code>, in another you <code>Integer.parseInt(_)</code>. I'd rather use the first solution, as it is shorter.</p>\n\n<p>If we clean up these minor problems (and remove some unnecessary variables), we end up with this code:</p>\n\n\n\n<pre class=\"lang-scala prettyprint-override\"><code>object Solution { \n def main(args: Array[String]) {\n val readInfo = readLine.split(\" \")\n val numberOfElements = readInfo(0).toInt\n val numberOfQueries = readInfo(1).toInt\n val storeElements = readLine.split(\" \").map(_.toInt)\n for (i <- 0 until numberOfQueries) {\n val z = readLine.split(\" \")\n val from = z(0).toInt\n val to = z(1).toInt + 1\n val getNumber = (from until to).map(i => storeElements(i))\n println(getNumber.min)\n }\n }\n}\n</code></pre>\n\n<p>A number of things appears suspect, for example the name <code>z</code> which should better be <code>range</code>, and the <code>+1</code> for the upper bound of the range. The <code>a until b</code> method excludes the upper bound <code>[a, b)</code>. However, there is also a <code>a to b</code> function, which produces an inclusive range <code>[a, b]</code>.</p>\n\n<p>The <code>getNumber</code> variable has a rather weird name, and I wouldn't even assign this value to a name. The minimum is more interesting than the slice.</p>\n\n<p>What <code>(z(0).toInt to z(1).toInt).map(i => storeElements(i))</code> calculates is a <em>slice</em> of elements in the array. There is the builtin method <code>slice</code> for this use case (which takes the inclusive lower and exclusive upper bound as arguments).</p>\n\n<p>We now have the code:</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>object Solution { \n def main(args: Array[String]) {\n val problemSize = readLine.split(\" \")\n val elements = problemSize(0).toInt\n val queries = problemSize(1).toInt\n val input = readLine.split(\" \").map(_.toInt)\n for (i <- 0 until queries) {\n val range = readLine.split(\" \")\n val minimum = input.slice(range(0).toInt, range(1).toInt + 1).min\n println(minimum)\n }\n }\n}\n</code></pre>\n\n<p>But is this a <em>Range Minimum Query</em>? No, it just returns the minimal element in that slice. We are not interested in the minimal value, but rather in the <em>position</em> of the minimal value.</p>\n\n<p>Because this is just a code review, I won't explain an algorithm for performing the RMQ, but the external links in the Wikipedia article you linked to contain a few algorithms.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T12:17:03.480",
"Id": "41644",
"ParentId": "41640",
"Score": "2"
}
},
{
"body": "<p>If you really would like to get the index instead of the value I would utilise zipWithIndex, which maps the list into a Tuple2 where left is the original value and right its index.</p>\n\n<p>Like so:</p>\n\n<pre><code>val result = List(0, 5, 2, 5, 4, 3, 1, 6, 3).zipWithIndex.slice(3, 8).minBy(_._1)._2\nprintln(result)\n</code></pre>\n\n<p>Of course accessing tuples by _._1 and _._2 isn't very pretty or readable, but we can convert tuple into case class</p>\n\n<pre><code>case class ValueAndIndex(value: Int, index: Int)\nval result = List(0, 5, 2, 5, 4, 3, 1, 6, 3).zipWithIndex.map {\n case (value, index) => ValueAndIndex(value, index)\n}.slice(3, 8).minBy(_.value).index\nprintln(result)\n</code></pre>\n\n<p>or even</p>\n\n<pre><code>case class ValueAndIndex(value: Int, index: Int)\nval result = List(0, 5, 2, 5, 4, 3, 1, 6, 3).zipWithIndex\n .map(ValueAndIndex.apply _ tupled).slice(3, 8).minBy(_.value).index\nprintln(result)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T19:39:39.467",
"Id": "41682",
"ParentId": "41640",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T10:48:14.767",
"Id": "41640",
"Score": "3",
"Tags": [
"optimization",
"performance",
"scala"
],
"Title": "Range Minimum Query Implementation in Scala"
}
|
41640
|
<p>Something that bothers me a lot when coding is best practice. I am completely self taught and I find it difficult to know whether I am doing things in the 'right way'.</p>
<p>Let's say I have a Gridview on a page which displays data from the following list:</p>
<pre><code>(from foo in someContext.foobars select foo).ToList
</code></pre>
<p>Regardless or how simple or complex the query is, can I just bind the Gridview in the page code behind file as below (in Page.Load or wherever else I want it to run):</p>
<pre><code>gvSomeGridview.DataSource = (from foo in someContext.foobars select foo).ToList();
gvSomeGridview.DataBind();
</code></pre>
<p>Or, should I have a class elsewhere that performs the query and returns a list and then bind the Gridview like:</p>
<pre><code>gvSomeGridview.Datasource = helperClass.GetGridviewData
gvSomeGridview.DataBind()
</code></pre>
<p>Perhaps go one further and also pass the GridView to the helper class as such:</p>
<pre><code>helperClass.BindGridView(gvSomeGridview)
</code></pre>
<p>If I am going to require this list elsewhere in my application or bind a different Gridview with the same data then clearly a class is the way forward, however if I do not, is it fine to just bind the GridView using the query in the code behind as per the first example, or is it recommended to keep all such operations in separate classes regardless? </p>
|
[] |
[
{
"body": "<p>First, you should separate the UI logic (with terms like GridView, databinding etc.) from the business and/or data logic (with terms like queries, DbContext etc.). So your second approach with a helper class is the more correct approach. In general this kind of helper classes are called the <a href=\"http://msdn.microsoft.com/en-us/library/ff649690.aspx\" rel=\"nofollow\">Repository pattern</a>.</p>\n\n<p>You should not pass the UI controls like GridView to your business and/or data logic layer.</p>\n\n<p>About where to put <code>GridView.DataBind()</code> - there are few approaches each useful in certain cases:</p>\n\n<ol>\n<li>Set the <code>.DataSource</code> and call <code>.DataBind()</code> in your <code>Page_Init()</code> method - this way the controls created will not all go in the ViewState. This is not always possible but should be used whenever possible.</li>\n<li>Set the <code>.DataSource</code> and call <code>.DataBind()</code> in <code>GridView_PreRender()</code> event - this event is only called when <code>GridView.Visible == true</code> so if you show/hide the grid, you will not end up going for the data if it is not displayed.</li>\n</ol>\n\n<p>Also always experiment if setting <code>EnableViewState=false</code> works for you - since by default <code>GridView</code> will always store everything in the ViewState. If this does not work, you should only call <code>.DataBind()</code> when the data is initially retrieved or the view changed (such as <code>Page.IsPostBack == false</code> or when clicking a search button etc.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T12:18:58.630",
"Id": "41645",
"ParentId": "41643",
"Score": "4"
}
},
{
"body": "<p>Well, </p>\n\n<p>The GridView is an implementation, \nDown the line if you decide to swap the GridView for a listview or something it should have no bearing on the data.</p>\n\n<p>Exactly how to go about sharing the information is subjective. there is no <em>right</em> way.</p>\n\n<p>My personal preference is a super contracted approach via interfaces.\ne.g:</p>\n\n<pre><code>public interface FooView\n{\n IEnumberable<Foobar> Foobars { set; }\n\n FooPresenter Presenter { set; }\n\n void ShowView();\n}\n\n\npublic interface FooPresenter\n{\n void DisplayFoos();\n void StartApplication();\n\n}\n</code></pre>\n\n<p>Now i imagine the above doesn't really give much detail but it outlines the vaguest contract between whatever visual representation you choose and the source of the data. In this manner if either change the other is perfectly fine. </p>\n\n<p>As for an example implementation of the above:</p>\n\n<pre><code> public class GridFooView : FooView\n {\n public FooPresenter Presenter { private get; set; }\n\n\n public IEnumerable<Foobar> Foobars\n {\n get{ return _foobars; }\n set\n {\n _foobars = value;\n UpdateFoobarGrid(); //Do binding here\n } \n }\n\n\n void Button_ShowFoo_Clicked(object sender,Eventargs e)\n {\n Presenter.DisplayFoos();\n }\n\n\n private IEnumerable<Foobar> _foobars;\n }\n\n\n\npublic class FooPresenterImpl : FooPresenter\n{\n\n FooView _view;\n\n public FooPresenterImpl(FooView view)\n {\n if(view == null) throw new NullArgumentException(\"view\")\n _view = view;\n _view.Presenter = this;\n }\n\n\n void DisplayFoos()\n {\n //generate your data then pass it to the view who updates himself.\n // the example i have here includes another abstraction of a datamodel.\n _view.Foobars = someDataModel.GetFoos();\n }\n\n void StartApplication()\n {\n //Do prerequisites\n _view.ShowView(); \n }\n\n\n}\n</code></pre>\n\n<p>Now finally in your program run file you simple instantiate the Presenter of choice, with the view of choice and run <code>startApplication()</code>.</p>\n\n<pre><code>FooPresenter presenter = new FooPresenterImpl(new GridFooView());\npresenter.StartApplication();\n</code></pre>\n\n<p>So now if you decide to completely change how Foo's are delivered to the UI, replace the presenter but all views still work, want to make a different representation of the same data? make a new view object, finally your presenter could also contain a datamodel which could be swapped out between storage methods, different database's or config files or we service or whatever. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T15:51:35.003",
"Id": "41658",
"ParentId": "41643",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "41645",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T12:02:47.690",
"Id": "41643",
"Score": "2",
"Tags": [
"c#",
"asp.net"
],
"Title": "Where to databind a GridView?"
}
|
41643
|
<p>I needed a script to import repositories from other Bitbucket accounts to my own Bitbucket account. I have some 250 repositories in my account and I wanted them to move under Team (which is same as Organization in Github). Though Bitbucket has APIs, I couldn't find any API to import, and instead they provide a HTML form on their site. When I couldn't get my pure <a href="https://stackoverflow.com/questions/21749403/python-script-using-robobrowser-to-submit-a-form-on-bitbucket-to-import-repo">Python script</a> to automate and fill the form, I decided to go with Selenium IDE. The following Python script generates Selenium IDE script, which I later run on the IDE.</p>
<p>This is how this script works:</p>
<ol>
<li>It takes a REST call to Bitbucket, to find all the repositories</li>
<li>The Bitbucket provides a paginated response, the response includes repo URL which is just enough</li>
<li>I make a series of calls to get all repository URLs</li>
<li>Once I have all the URLs, I fill in the Selenium script template and write it back to a file </li>
</ol>
<p>This script also can be used to import repositories from Github/or any other version control server by importing the <code>generate_sel_script</code> function.</p>
<pre><code>import json
import requests
from requests.auth import HTTPBasicAuth
from templates import sel_script_template
from templates import command_template
from settings import *
def generate_bb_repo_urls():
def make_rest_call(url):
auth = HTTPBasicAuth(SRC_AC_USERNAME, SRC_AC_PASSWORD)
return requests.get(url=url, auth=auth).json()
seed_url = 'https://bitbucket.org/api/2.0/repositories/' + SRC_AC_USERNAME
response = make_rest_call(seed_url)
bb_repo_urls = []
while('next' in response.keys()):
for repo in response['values']:
bb_repo_urls.append(repo['links']['html']['href'])
response = make_rest_call(response['next'])
return bb_repo_urls
def generate_sel_script(src_repo_urls):
commands = "".join(map(lambda url: command_template.substitute({
'bb_username': SRC_AC_USERNAME,
'bb_password': SRC_AC_PASSWORD,
'repo_url': url,
'owner_value': IMPORTER_ID
}), src_repo_urls))
with open('selenium-script.txt', 'w') as sel_file:
sel_file.write(sel_script_template.substitute({
'bb_username': IMPORTER_BB_USERNAME,
'bb_password': IMPORTER_BB_PASSWORD,
'commands': commands
}))
if __name__ == '__main__':
generate_sel_script(generate_bb_repo_urls())
</code></pre>
<p>settings.py:</p>
<pre><code>SRC_AC_USERNAME = 'bitbucket'
SRC_AC_PASSWORD = 'ohlongjohnson'
IMPORTER_BB_USERNAME = 'bitbucket'
IMPORTER_BB_PASSWORD = 'ohlongjohnson'
IMPORTER_ID = '007007'
</code></pre>
<p>templates.py:</p>
<pre class="lang-xml prettyprint-override"><code>from string import Template
sel_script_template = Template("""<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="https://bitbucket.org/account/signin/?next=/repo/import" />
<title>New Test</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">New Test</td></tr>
</thead><tbody>
<tr>
<td>open</td>
<td>/account/signin/?next=/repo/import</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=id_username</td>
<td>$bb_username</td>
</tr>
<tr>
<td>type</td>
<td>id=id_password</td>
<td>$bb_password</td>
</tr>
<tr>
<td>clickAndWait</td>
<td>name=submit</td>
<td></td>
</tr>
<tr>
<td>pause</td>
<td>100</td>
<td></td>
</tr>
$commands
</tbody></table>
</body>
</html>
""")
command_template = Template("""<tr>
<td>pause</td>
<td>1000</td>
<td></td>
</tr>
<tr>
<td>open</td>
<td>https://bitbucket.org/repo/import</td>
<td></td>
</tr>
<tr>
<td>pause</td>
<td>100</td>
<td></td>
</tr>
<tr>
<td>open</td>
<td>https://bitbucket.org/repo/import</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=id_url</td>
<td>$repo_url</td>
</tr>
<tr>
<td>click</td>
<td>id=id_auth</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=id_username</td>
<td>$bb_username</td>
</tr>
<tr>
<td>type</td>
<td>id=id_password</td>
<td>$bb_password</td>
</tr>
<tr>
<td>select</td>
<td>id=id_owner</td>
<td>value=$owner_value</td>
</tr>
<tr>
<td>clickAndWait</td>
<td>xpath=(//button[@type='submit'])[2]</td>
<td></td>
</tr>""")
</code></pre>
<p>What I am looking for:</p>
<ul>
<li>Any general code improvements/comments</li>
<li>How do I avoid <code>from settings import *</code>? (or is it okay for <code>import *</code> in this case) I have two options, <code>import settings</code> or five <code>import</code> statements for each variable.</li>
<li>Is it possible to avoid this line <code>bb_repo_urls = []</code>, but create a empty list later and append directly in while loop?</li>
<li>Any way to improve this line : <code>"".join(map(lambda url...</code></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T19:02:54.963",
"Id": "71674",
"Score": "1",
"body": "One suggestion: perhaps consider using the [`keyring`](https://pypi.python.org/pypi/keyring) module rather than storing Bitbucket credentials in `settings.py`."
}
] |
[
{
"body": "<p>Its actually very simple, there is no need to write complex scripts. </p>\n\n<p>What I did was, complete one import process using BitBuckets HTML form, and record the post request that form makes using chrome. The chrome will give you the request in cURL form. Then use a simple nodejs script to run the same cURL command by just replacing the repo URL and the repo name.</p>\n\n<pre><code>var shell = require('shelljs');\n\nvar arr = {\n \"https://laxxxxxxtee.git\": \"pyyyyye\",\n \"https://lxxxxxxxxlace.git\": \"shyyyyyce\",\n \"https://latttttttwa.git\": \"syyyyya\",\n \"https://laxxxxxxxappy-ionic.git\": \"snayyyyic\",\n \"https://laxxxxxxxxxxxxnter-ui.git\": \"viyyyyyyr-ui\",\n \"https://laxxxxxxxxxnter.git\": \"vyyyyyer\",\n \"https://laxxxxxxxxtend.git\": \"viyyyyy\"\n};\n\nfor (var url in arr) {\n var name = arr[url];\n name = encodeURIComponent(name);\n url = encodeURIComponent(url);\n var command = \"curl 'https://bitbucket.org/repo/import?owner=txxxxh' -H 'Pragma: no-cache' -H 'Origin: https://bitbucket.org' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: en-US,en;q=0.8,en-GB;q=0.6,ml;q=0.4' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36' -H 'Content-Type: application/x-www-form-urlencoded' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' -H 'Cache-Control: no-cache' -H 'Referer: https://bitbucket.org/repo/import?owner=txxxxxh' -H 'Cookie: optimizelyEndUserId=oexxxxxxxxxx643798; __ar_v4=3coookies-form' -H 'Connection: keep-alive' -H 'DNT: 1' --data 'source_scm=git&source=source-git&goog_project_name=&goog_scm=svn&sourceforge_project_name=&sourceforge_mount_point=&sourceforge_scm=svn&codeplex_project_name=&codeplex_scm=svn&url=\" + url + \".git&auth=on&username=nyyyyyys&password=Gvvvvv&owner=36vvvv2&name=\" + name + \"&description=&is_private=on&forking=no_forks&no_forks=True&no_public_forks=True&has_wiki=on&language=php&csrfmiddlewaretoken=MErrrrrrrrrOZ91r&scm=git' --compressed\";\n\n shell.exec(command, function(code, output) {\n console.log('Exit code:', code);\n console.log('Program output:', output);\n });\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T02:37:48.393",
"Id": "454978",
"Score": "0",
"body": "Thanks! Minimal `curl` with basic auth: `curl 'https://bitbucket.org/repo/import' -H 'Content-Type: application/x-www-form-urlencoded' --data 'source_scm=git&source=source-git&sourceforge_scm=hg&codeplex_scm=hg&forking=no_public_forks&no_forks=False&no_public_forks=True&scm=git&url=<URL-encoded GitHub repo URL>&is_private=on&username=<GitHub username>&password=<GitHub password>&owner=<BitBucket user ID>&name=<BitBucket repo name>' -H 'Authorization: <basic auth>'` BitBucket user ID: \"owner\" field on import form, or \"id\" field on \"bb-bootstrap\" HTML meta tag on any page"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-03T17:51:40.980",
"Id": "71557",
"ParentId": "41647",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T12:45:09.853",
"Id": "41647",
"Score": "2",
"Tags": [
"python"
],
"Title": "Script to import repositories to Bitbucket"
}
|
41647
|
<p>In my db MySQL, I have a table <code>ranks</code> with many fields, one for each page I want limit access for the user in the menu application with PHP control:</p>
<pre><code> <?php if ($row_ranks['padric'] == '1' ) {
echo ('<li><a href="padroncini_ric.php">Ricerca</a></li>');
}
else {
echo ('<li><a href="#" class="disabled">Ricerca</a></li>');
}
?>
</code></pre>
<p>In the admin panel, I have a page for seting the privileges to single page with relative checkbox.</p>
<p>The checkbox as a name equal at field name in table like this example:</p>
<pre><code><div>
<input type="checkbox" name="padric" value="1"
<?php if ($row_user_ranks['padric'] == 1) { echo "checked"; } ?>
>Ricerca
</div>
</code></pre>
<p>For set the privileges I make this PHP code:</p>
<pre><code> mysql_select_db($database_geomo, $geomo);
$query_RSfields = sprintf("SHOW COLUMNS FROM ranks WHERE Field NOT IN ('ID', 'userID', 'gruppo')");
$RSfields = mysql_query($query_RSfields, $geomo) or die(mysql_error());
$row_RSfields = mysql_fetch_assoc($RSfields);
$totalRows_RSfields = mysql_num_rows($RSfields);
do {
$field = $row_RSfields['Field'] ;
if (!isset($_POST[$field])) { // set value = 0 for checkbox not checked
$_POST[$field] = '0' ;
}
$updateSQL = sprintf("UPDATE ranks SET $field='".$_POST[$field]."' WHERE userID='".$_POST['ID']."'"); // set privileges for user
mysql_select_db($database_geomo, $geomo);
$Result1 = mysql_query($updateSQL, $geomo) or die(mysql_error());
} while ($row_RSfields = mysql_fetch_assoc($RSfields));
</code></pre>
<p>I've made this code in this way because if the checkbox is not checked, it shouldn't return a value and should generate an error "unknown column" for the update SQL.</p>
<p>So, there is another more simply way for doing this job?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T14:32:06.317",
"Id": "71630",
"Score": "2",
"body": "The very first thing you can do is stop using `mysql_query`. It has been deprecated for a while now, and only dinosaurs, \"24 hours\" noobs, and w3schools dropouts still use it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T11:10:22.783",
"Id": "71756",
"Score": "0",
"body": "@cHao after your suggestion i've made a code review with MySqli connection."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T11:13:58.750",
"Id": "71758",
"Score": "0",
"body": "Your code is vulnerable to SQL-Injection."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T11:18:49.747",
"Id": "71759",
"Score": "0",
"body": "@Bobby This web application work on internal server not connected to internet. My employes are not able to make same SQL-Injection but if you have same suggestion for fix that i'm appreciated that :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T11:50:17.573",
"Id": "71763",
"Score": "0",
"body": "@Bobby after your suggestion i've add a escape string."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T12:20:20.120",
"Id": "71765",
"Score": "2",
"body": "@geomo: Let me tell you one thing: If it can be broken, it will be broken."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T14:29:03.590",
"Id": "71787",
"Score": "0",
"body": "@Bobby I think you can write an answer about prepared queries perhaps?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T15:26:39.013",
"Id": "71791",
"Score": "1",
"body": "@SimonAndréForsberg: Yeah, I'll draft something together...now where was that gif, just to make sure..."
}
] |
[
{
"body": "<h1><a href=\"https://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php\">DO NOT USE THE mysql_* FUNCTIONS!</a></h1>\n<p>They are DEPRECATED.</p>\n<hr />\n<pre><code><?php if ($row_ranks['padric'] == '1' ) {\n echo ('<li><a href="padroncini_ric.php">Ricerca</a></li>');\n } \n else {\n echo ('<li><a href="#" class="disabled">Ricerca</a></li>');\n } \n?>\n</code></pre>\n<p>Your indentation style is a mess, decide what indentation style to use and if to use tabs or spaces (and if yes how many) and then stick to it:</p>\n<pre><code><?php\n if ($row_ranks['padric'] == '1' ) {\n echo '<li><a href="padroncini_ric.php">Ricerca</a></li>';\n } else {\n echo '<li><a href="#" class="disabled">Ricerca</a></li>';\n } \n?>\n</code></pre>\n<p>Normally there's also no space between the line and the closing semicolon.</p>\n<p>Additionally the <code>echo</code> function does not need any parentheses.</p>\n<hr />\n<pre><code>if ($row_ranks['padric'] == '1' )\n</code></pre>\n<p>If your code is in your native language, please always convert it to English before posting it here for review. It makes things easier for us.</p>\n<p>Now what you use here is called a <a href=\"http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Unnamed_numerical_constants\" rel=\"nofollow noreferrer\">magic string or magic number</a>, it's a fixed value that has <em>some</em> meaning but does not provide any explanation what's-o-ever what that meaning is or why it is that way. Use named constants instead.</p>\n<pre><code>const SOME_CONDITION = "1"; // Change the name to something meaningful.\n\nif ($row['padric'] == SOME_CONDITION) {\n</code></pre>\n<p>Also do you now the difference between the <a href=\"http://www.php.net/manual/en/language.operators.comparison.php\" rel=\"nofollow noreferrer\">equality and identity operator</a>? The equality operator <code>==</code> will perform casting as needed which can yield interesting effects, the identity operator <code>===</code> on the other hand will also compare the types.</p>\n<p>Some examples:</p>\n<pre><code>0 == 0 --> true\n0 == "0" --> true\n0 == "" --> true\n0 == NULL --> true\n\n0 === 0 --> true\n0 === "0" --> false\n0 === "" --> false\n0 === NULL --> false\n</code></pre>\n<p>So always sue <code>===</code> unless you have a compelling reason not to.</p>\n<hr />\n<pre><code>$_POST[$field] = '0' ;\n</code></pre>\n<p>First of all, <a href=\"http://en.wikipedia.org/wiki/Global_variable\" rel=\"nofollow noreferrer\">global variables are bad</a>. And after that, <em>writing into <a href=\"http://www.php.net/manual/en/language.variables.superglobals.php\" rel=\"nofollow noreferrer\">the Super-Globals</a></em> is a bad idea for many reasons. Nobody expects that super globals are modified in any way and that can lead to funny errors which you'll be looking for for days.</p>\n<p>Extract the values from the super globals and work with that variable.</p>\n<hr />\n<pre><code>$updateSQL = sprintf("UPDATE ranks SET $field='".$_POST[$field]."' WHERE userID='".$_POST['ID']."'"); // set privileges for user\n</code></pre>\n<p>One word (okay, it's two): <a href=\"http://en.wikipedia.org/wiki/Sql_injection\" rel=\"nofollow noreferrer\">SQL Injection</a>. There is no, absolutely no (and I mean no) excuse to allow SQL injection. Imagine somebody would manipulate the POST request to contain the value <code>'; DROP TABLE ranks; --</code> which will yield the query:</p>\n<pre><code>UPDATE ranks SET field='field' WHERE userID=''; DROP TABLE ranks; --'\n</code></pre>\n<p>...any questions?</p>\n<p>Why are you using sprintf here?</p>\n<hr />\n<pre><code>$row_RSfields = mysql_fetch_assoc($RSfields);\ndo {\n // code \n} while ($row_RSfields = mysql_fetch_assoc($RSfields));\n</code></pre>\n<p>Traditionally it's a <code>while</code> loop:</p>\n<pre><code>$result = getResult();\nwhile ($row = fetchRow($result)) {\n\n}\n</code></pre>\n<hr />\n<p>Now let's get to the core problem: You are using the <code>mysql_*</code> functions. You should either use <a href=\"http://ch2.php.net/mysqli\" rel=\"nofollow noreferrer\"><code>mysqli_*</code></a> or <a href=\"http://www.php.net/manual/en/book.pdo.php\" rel=\"nofollow noreferrer\">PDO</a>.</p>\n<p>Personally I prefer PDO over <code>mysqli_*</code> because it has an object oriented interface and support multi-statements. So here's an example on how to use PDO:</p>\n<pre><code>/**\n * \n * @var PDO\n */\n$pdo = new PDO($dsn, $user, $password, $options);\n$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // See footnote!\n\n/**\n *\n * @var PDOStatement\n */\n$statement = $pdo->prepare("SELECT field FROM table WHERE id = :id;");\n$statement->bindValue(":id", $id, PDO::PARAM_INT);\n\n$statement->execute();\n\nwhile ($row = $statement->fetch()) {\n echo $row['field'];\n}\n\n$statement->closeCursor();\n</code></pre>\n<p><a href=\"https://stackoverflow.com/questions/10113562/pdo-mysql-use-pdoattr-emulate-prepares-or-not\">Question on Stack Overflow about when to turn off emulated prepares</a>.</p>\n<hr />\n<p>Are you aware of the difference between strings?</p>\n<pre><code>'A simple string'\n"A string with automatic $variable expansion"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T16:24:07.050",
"Id": "71797",
"Score": "0",
"body": "One word (okay, it's two): code review (with mysqli).\nAbout SQL Injection : no way for doing that in this case because there aren't input field but only checkbox checked or not and the value are 1 or 0. More : all page have php require_once for function.php with `get_magic_quotes_gpc()` for \"cleaning\" the value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T16:39:42.507",
"Id": "71799",
"Score": "1",
"body": "@geomo Just because **you** aren't able to inject some SQL doesn't mean that **someone else** can't!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T17:18:27.437",
"Id": "71801",
"Score": "1",
"body": "@geomo: Everything that comes from the other side of the connection, no matter if it comes from `GET`, `POST` or a cookie is **never** to be trusted. **Everything** that comes from the outside can be forged."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T17:37:50.747",
"Id": "71807",
"Score": "0",
"body": "@Bobby You are a great coder.. tnx for all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T15:06:30.923",
"Id": "72092",
"Score": "0",
"body": "@Bobby I read in to another answer this : \"The PDO internally builds the query string, calling mysql_real_escape_string() (the C API function) on each bound string value.\"\nNow, if mysql_* function are deprecated, the PDO call mysqli_* function instead ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T15:24:21.700",
"Id": "72093",
"Score": "0",
"body": "@geomo: Where did you get that idea? [It uses native prepared queries directly from the MySQL driver](http://at2.php.net/manual/en/ref.pdo-mysql.php). I can't locate the PDO MySQL Driver source right now, but [the PDO source does not look like it does any string concatenation at all](https://github.com/php/php-src/blob/master/ext/pdo/pdo.c) (well, it does pretty few things, to be honest)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T15:30:49.050",
"Id": "72095",
"Score": "0",
"body": "@geomo: [Turns out I'm just blind](https://github.com/php/php-src/blob/master/ext/pdo_mysql/mysql_statement.c), and that driver is calling the native (MySQL) methods for binding parameters as far as I can see."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T15:37:18.683",
"Id": "72097",
"Score": "0",
"body": "@geomo: If you mean [this answer](http://stackoverflow.com/a/12202218/180239), I'll take that to the PHP chat/IRC when I'm home (and I don't forget). I think it's just badly worded and he means that it uses low-level C equivalents of these functions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T16:09:14.610",
"Id": "72112",
"Score": "0",
"body": "@Bobby I made a code review with PDO method but don't change the value inside a table ranks.. what i'm wrong ? Tnx for all :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T16:22:39.687",
"Id": "72115",
"Score": "0",
"body": "@Bobby i found the error in code : row_fields <> row_field and now it's work but set all fields = 0 in the table :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T20:24:28.600",
"Id": "72175",
"Score": "0",
"body": "@geomo: I took the liberty to roll all that back. Please don't \"endlessly\" extend a question. Questions should be answerable and not drag on and on and on. Also see [the guide lines for follow-up questions](http://meta.codereview.stackexchange.com/questions/1065/how-to-post-a-follow-up-question)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T22:47:51.203",
"Id": "72192",
"Score": "0",
"body": "@geomo: Regarding the confusion about `mysql_real_escape_string`, [it's not about the PHP function, but about the MySQL API function](http://chat.stackoverflow.com/transcript/message/14767322#14767322)."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T16:03:16.793",
"Id": "41740",
"ParentId": "41648",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "41740",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T12:52:30.503",
"Id": "41648",
"Score": "4",
"Tags": [
"php",
"mysql"
],
"Title": "How can I improve this PHP MySQL rank query?"
}
|
41648
|
<p>I split my implementation of this sequence alignment algorithm in three methods. Where NeedlemanWunsch-method makes use of the ScoringFunction and the Traceback methods. Further I decided to go with two matices. One matrix is for the scoring, the second contains data to make the traceback easier.</p>
<pre><code>public static int ScoreFunction(char a,char b,int matchScore,int mismatchScore)
{
if (a == b)
{
return matchScore;
}
else
{
return mismatchScore;
}
}
public static string[] NeedlemanWunsch(string sequenceA, string sequenceB, int gapPenalty, int matchScore, int mismatchScore)
{
#region Initialize
int[,] matrix = new int[sequenceA.Length + 1, sequenceB.Length + 1];
char[,] tracebackMatrix = new char[sequenceA.Length + 1, sequenceB.Length + 1];
matrix[0, 0] = 0;
for (int i = 1; i < sequenceA.Length + 1;i++)
{
matrix[i,0] = matrix[i-1,0] + gapPenalty;
tracebackMatrix[i,0] = 'L';
}
for (int i = 1; i < sequenceB.Length + 1; i++)
{
matrix[0, i] = matrix[0 , i - 1] + gapPenalty;
tracebackMatrix[0,i] = 'U';
}
#endregion
#region Scoring
for (int i = 1; i < sequenceA.Length + 1;i++)
{
for (int j = 1; j < sequenceB.Length + 1;j++)
{
int diagonal = matrix[i - 1, j - 1] + ScoreFunction(sequenceA[i-1],sequenceB[j-1],matchScore,mismatchScore);
int links = matrix[i - 1, j] + gapPenalty;
int oben = matrix[i, j - 1] + gapPenalty;
matrix[i, j] = Math.Max(oben,Math.Max(links, diagonal));
if(matrix[i,j] == diagonal)
{
tracebackMatrix[i, j] = 'D';
}
else if (matrix[i, j] == links)
{
tracebackMatrix[i, j] = 'L';
}
else if (matrix[i, j] == oben)
{
tracebackMatrix[i, j] = 'U';
}
}
}
#endregion
#region Traceback
return TraceBack(tracebackMatrix,sequenceA,sequenceB);
#endregion
}
public static string[] TraceBack(char[,] tracebackMatrix,string sequenzA, string sequenzB)
{
int i = tracebackMatrix.GetLength(0) - 1;
int j = tracebackMatrix.GetLength(1) - 1;
string alignedSeqA = "";
string alignedSeqB = "";
while(i != 0 && j != 0)
{
switch (tracebackMatrix[i, j])
{
case 'D':
alignedSeqA += sequenzA[i - 1];
alignedSeqB += sequenzB[j - 1];
i--;
j--;
break;
case 'U':
alignedSeqA += "-";
alignedSeqB += sequenzB[j - 1];
j--;
break;
case 'L':
alignedSeqA += sequenzA[i - 1];
alignedSeqB += "-";
i--;
break;
}
}
string[] alignments = new string[2];
alignedSeqA = new string(alignedSeqA.Reverse().ToArray());
alignedSeqB = new string(alignedSeqB.Reverse().ToArray());
alignments[0] = alignedSeqA;
alignments[1] = alignedSeqB;
return alignments;
}
</code></pre>
<p>I am especially concerned about the traceback method and whether it is a good idea to use two matrices.</p>
|
[] |
[
{
"body": "<p>First of all, your method \"TraceBack\" does not return anything (what should it return, both strings?). You can also simplify your first method to use this instead:</p>\n\n<pre><code>public static int ScoreFunction(char a, char b, int matchScore, int mismatchScore)\n{\n return a == b ? matchScore : mismatchScore;\n}\n</code></pre>\n\n<p>Rest does not look bad to me, however, I am not that familiar with the algorithm...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T12:12:52.593",
"Id": "71764",
"Score": "0",
"body": "I somehow missed to copy/paste the return statement into the function. So edit is done."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T15:58:18.763",
"Id": "41660",
"ParentId": "41652",
"Score": "3"
}
},
{
"body": "<p>Some general notes:</p>\n\n<ul>\n<li><p>The TraceBack method does string concatenation in a tight loop. This is a big f***ing nono. Use a <a href=\"http://msdn.microsoft.com/en-us/library/system.text.stringbuilder%28v=vs.110%29.aspx\" rel=\"nofollow\">StringBuilder</a> instead, and you will notice a considerable speedup. You have to understand that .net Strings are <strong>immutable</strong>. This means that a statement like <code>strA += strB</code> does not <em>update</em> <code>strA</code>, it creates a third string and updates the reference to <code>strA</code>. This means concatenation in a tight loop is <em>very</em> expansive. </p></li>\n<li><p>If you do not have a compelling reason to use 2d Arrays (<code>var bla = new int[5,5]</code>), use jagged arrays (<code>var bla = new int[5][5]</code>). Most of the time, the .net JIT compiler can drop the bounds checks for jagged arrays, but not for 2D arrays.</p></li>\n<li><p>It may be worthwhile to convert tracebackMatrix from chars (16 bits) to bytes (8 bits) </p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T15:15:55.707",
"Id": "71788",
"Score": "0",
"body": "All three points make sense to me. But I don't really understand how the StringBuilder would change the method. That wouldn't make the while-loop unnecessary, would it? Or should I just replace the concatenation \"\" += \"\" by a call to a StringBuilder method?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T11:25:05.023",
"Id": "71887",
"Score": "2",
"body": "I've edited the description but yes, you would replace ``strA += strB`` with ``strBuilderA.Append(strB)`` and at the end you would add a single statement like ``result = strBuilderA.ToString()``"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T13:28:55.687",
"Id": "41731",
"ParentId": "41652",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "41731",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T13:32:49.110",
"Id": "41652",
"Score": "4",
"Tags": [
"c#",
"algorithm",
"bioinformatics"
],
"Title": "How to improve this Needleman-Wunsch implementation in C#?"
}
|
41652
|
<p>I am trying to implement <a href="http://www.drdobbs.com/database/the-squarelist-data-structure/184405336">squarelist</a> by using iteration that points to the head element. I've create this iterator class to make my iterator id directional. I just want to see if I implemented it correctly.</p>
<pre><code>class iterator : public std::iterator<std::bidirectional_iterator_tag , Object , int>
{
public:
iterator(Node* p=nullptr) : _node(p){}
~iterator(){}
Node* getNode(){return _node;}
Object operator * () { return _node->data; }
iterator & operator ++()
{
_node = _node->next;
return *this;
}
iterator operator ++(int)
{
iterator retVal = *this;
++this;
return retVal;
}
bool operator < (iterator const& rhs) const
{
return _node < rhs._node;
}
bool operator != (iterator const& rhs) const
{
return _node != rhs._node;
}
bool operator == (iterator const& rhs) const
{
return _node == rhs._node;
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T10:42:19.703",
"Id": "72046",
"Score": "0",
"body": "Its hard to tell without more information. How do you define the `end` marker. Are member guaranteed to be laid out in contiguous memory (unlikely but possible)? Show us how you construct members of your square list and how you build the begin and end iterator for the list."
}
] |
[
{
"body": "<p>You almost got the <code>bool operator < (iterator const& rhs) const</code> (same for other operators overloading) right.</p>\n\n<p>The idea is to make the left operand behave semantically equals to the right operand.</p>\n\n<p>You went one step forward with this idea by defining the argument type as <code>const&</code>. Then, if I create a class that inherits from your class, the following would work:</p>\n\n<pre><code>iterator i;\nderived j;\ni < i;\nj < i;\nj < j;\ni < j;\n</code></pre>\n\n<p>The problem lies on objects implicitly convertible to iterator. They cannot be used as a left-argument for the expression. You loses the symmetry property.</p>\n\n<p>Define as non-member functions and everything is gonna be alright. Declare it as friend if needed.</p>\n\n<p>I learnt about its importance following <a href=\"https://groups.google.com/a/isocpp.org/d/msg/concepts/IAHQkYcbCDc/XhQGRiy7yywJ\" rel=\"noreferrer\">discussions on one of the C++ working groups</a>. It's a good practice to follow smarter people.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T03:18:31.830",
"Id": "71989",
"Score": "0",
"body": "PS: I didn't look on the linked url nor the rest of the code. I'll be happy enough with an upvote (don't need the full bounty)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T10:43:09.033",
"Id": "72047",
"Score": "0",
"body": "-1: Yes the symmetry thing is important in mathematical operations. But here you are asking for trouble by auto converting a node into an iterator (can you think of a situation where you want a node to auto convert into an iterator (I can't)) or a situation where an iterator converts to another type of iterator (as the only type of iterators you can compare belong to the same container). You should rather keep the `operator<` as a member and make the constructor explicit to stop auto conversion. The less auto conversion the better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:08:35.057",
"Id": "72117",
"Score": "0",
"body": "@LokiAstari: \"make the constructor explicit to stop auto conversion\" won't forbid auto conversion. Look for conversion operators. Also, I didn't encouraged the use of implicit conversion. And lastly, your approach does nothing but break simmetry, because the implicit conversion will still work for right operand. Can you think a reason why would you want to declare the operators inside the class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:14:16.043",
"Id": "72119",
"Score": "0",
"body": "Adding an conversion operation is not auto conversition. This is a situation where you have sat down and thought about an automated method to convert and then explicitly provided one. So yes explicit does prevent auto conversion. But it does not prevent conversion that you have manually programmed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:15:02.843",
"Id": "72120",
"Score": "0",
"body": "Why do I want symmetry between two different unrelated types. Can you think of a single reason where that would do anything useful (apart from hide bugs). You can not compare iterators from different containers (that is meaningless). So the types are never going to be different when doing a comparison. All you are doing here is creating symmetry when 1) none is required. 2) hiding bugs when auto conversion kicks in."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:28:18.010",
"Id": "72124",
"Score": "0",
"body": "Basically your comments here. Take an issue that is important `symmetry` but introduce it into a situation where it is not relevant and causes issues. Yet you have not identified any of the real problems in the code. This answer is so bad it should really be deleted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:50:12.043",
"Id": "72134",
"Score": "0",
"body": "\"Adding an conversion operation is not auto conversition.\". Well, I don't know what is auto conversion. I know what is implicit conversion and explicit conversion. When you add a conversion function, you'll instruct the compiler to perform implicit conversion in certain situations. \"So yes explicit does prevent auto conversion\". `explicit` won't prevent me from implement an object implicitly convertible to your class/object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:52:34.587",
"Id": "72135",
"Score": "0",
"body": "\"Can you think of a single reason where that would do anything useful (apart from hide bugs)\". Stop the FUD. Implement operators as non-member functions will **not** hide bugs. \"You can not compare iterators from different containers (that is meaningless)\". It is **not** about iterators from different containers. You fail to understand what is going on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:53:03.530",
"Id": "72136",
"Score": "0",
"body": "No it won't. But that's a completely different issue. If I want to write a conversion function I will have thought about it carefully first. Because converion operators are dangerious. But again completely outside the scope of your suggestions. Which introduces unneeded symmetry (because it has no practical use) and introduces bugs because people think the comparison did something useful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:54:52.947",
"Id": "72137",
"Score": "0",
"body": "It hides bugs. Because you can now do comparisons on things that are in no way related. This hiding it from you. If thats not an easy way to hide a bug I don;t know what is. Your the one that is introducing irrelevant concepts to hide the fact your ideas a re silly and you applying technique just because you just learnt them without understanding why you should use them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:55:27.880",
"Id": "72138",
"Score": "0",
"body": "\"Take an issue that is important symmetry but introduce it into a situation where it is not relevant and causes issues\". Implicit conversion may have side effects. You need to carefully think about its consequences. But I'm not encouraging implicit conversions. I'm encouraging operators implemented as non-member functions. Can you cite one example where operators declared as member functions is better?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:56:15.420",
"Id": "72139",
"Score": "0",
"body": "I think you are failing to understand what the OP is doing here. He has an iterator. You want it to work without introducing irrelevant concepts that are not applicable to this situation. The OP would actually want to find real issues with his iterator that you seem to have completely missed just to spout what you read in a book and don;t understand when to apply."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:57:22.513",
"Id": "72140",
"Score": "0",
"body": "\"Which introduces unneeded symmetry (because it has no practical use) and introduces bugs because people think the comparison did something useful\". What bug? Can you enlighten me?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:58:32.193",
"Id": "72141",
"Score": "0",
"body": "`What bug? Can you enlighten me?` Easy you can now compare two iterators of different types with `operator<` when is that ever going to produce a valid answer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:58:55.053",
"Id": "72142",
"Score": "0",
"body": "\"It hides bugs\". Two can play this game: It doesn't hide bugs. Now, can you show us a snippet?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T18:00:25.153",
"Id": "72144",
"Score": "0",
"body": "\"Your the one that is introducing irrelevant concepts to hide the fact your ideas a re silly and you applying technique just because you just learnt them without understanding why you should use them\". This is the only relevant text you wrote in the whole thread."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T18:00:40.283",
"Id": "72145",
"Score": "0",
"body": "`Now, can you show us a snippet` I point you at your code above with `i` and `j`. When are these values going to be valid. Such that the comparison actual provides a correct value. The answer never. Yet now they will compile but previously at least half of them will have generated a compiler error."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T18:00:56.360",
"Id": "72146",
"Score": "0",
"body": "\"Easy you can now compare two iterators of different types\". No, you cannot."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T18:02:26.290",
"Id": "72147",
"Score": "0",
"body": "Are `i` and `j` not different types. Are you not comparing them with `operator<` is this ever going to provide anything useful? When we are talking about iterators."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T18:04:59.050",
"Id": "72148",
"Score": "0",
"body": "\"I point you at your code above with `i` and `j`. When are these values going to be valid. Such that the comparison actual provides a correct value\". They are valid. They are an instance-of base, which is the only needed thing by the implementation of the operators. \"Are i and j not different types\". They are instances of the same type, the `base`/`iterator` type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T18:07:30.013",
"Id": "72150",
"Score": "0",
"body": "So you have a class that gives out different types for the different methods that return iterators. You are now beraking all the conventions of container. A container is supposed to define its iterator type as a member type `typename XXX iterator;`. So there is only one type of iterator per container (not counting const versions). There is no ability to have base/iterator whatever that means. More misdirection without any substance behind it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T18:07:42.457",
"Id": "72151",
"Score": "1",
"body": "If you'd like to continue this conversation, please take it to chat. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T18:09:54.977",
"Id": "72152",
"Score": "0",
"body": "@Jamal: I think I am finished. vinipsmaker obviously has nothing of importance to say."
}
],
"meta_data": {
"CommentCount": "23",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T03:17:42.763",
"Id": "41847",
"ParentId": "41655",
"Score": "5"
}
},
{
"body": "<p>A couple of real issues (rather than the imaginary ones previously pointed out):</p>\n<p>Your code does not fully implement the requirements of iterator.</p>\n<ul>\n<li>You have not implemented the <code>operator-></code> as required by the iterator concept.</li>\n<li><code>operator*</code> should return by reference.<br />\nThis is because <code>*x = t</code> is a requirement of iterator and without the reference this will not work as expected (or at all depending).</li>\n</ul>\n<p>Without the container code its hard to tell if you can use the same iterator for both const and non-const iterator types. So sometimes its useful to provide const overloads of the above (but that will depend on usage).</p>\n<p>see: <a href=\"http://www.sgi.com/tech/stl/trivial.html\" rel=\"noreferrer\">http://www.sgi.com/tech/stl/trivial.html</a></p>\n<p>You classify your iterator as</p>\n<pre><code>std::bidirectional_iterator_tag\n</code></pre>\n<p>This is an indication that you can go backwards and forwards with the iterator. In fact the concept means that your iterator must also support <code>operator--</code> are well as <code>operator++</code>.</p>\n<p>See: <a href=\"http://www.sgi.com/tech/stl/BidirectionalIterator.html\" rel=\"noreferrer\">http://www.sgi.com/tech/stl/BidirectionalIterator.html</a></p>\n<p>The link you provide indicates that a square list is circular. So moving forward all the time you may never reach the end. But without understanding (or seeing your implementation) it is hard to tell if the current implementation will work.</p>\n<pre><code> iterator & operator ++()\n {\n _node = _node->next; // Will this ever reach a NULL\n // Or do you have a special version of\n // iterator that marks the end.\n //\n // Note: end is one past the last element\n // Which makes this doubly hard to\n // implement with a circular list.\n // But can be done if you use a sentinel.\n //\n // The default constructor suggests that the\n // end is marked by a NULL but hard to be sure.\n return *this; \n }\n</code></pre>\n<p>No point in defining destructor the default version will work perfectly. (As a side note: since it is not virtual there can be no derived types with alternative behaviors so making things symmetric is doubly useless).</p>\n<pre><code> ~iterator(){}\n</code></pre>\n<p>This is perfectly fine.</p>\n<pre><code> iterator retVal = *this;\n</code></pre>\n<p>But just as a personal preference I prefer:</p>\n<pre><code> iterator retVal(*this);\n</code></pre>\n<p>As mentioned above (but without the container code it is hard to tell). Well this test work for the <code>end</code> iterator.</p>\n<pre><code> bool operator != (iterator const& rhs) const\n {\n return _node != rhs._node;\n }\n bool operator == (iterator const& rhs) const \n {\n return _node == rhs._node;\n }\n</code></pre>\n<p>There is no requirement for bidirectional iterators to have a less than comparison. Unless you really want to store iterators in a sorted container I would leave this out.</p>\n<p>Note: A random access iterator does have a requirement for a less than operator. But it has a precondition that it can only compare iterators that are reachable from each other.</p>\n<p>see: <a href=\"http://www.sgi.com/tech/stl/RandomAccessIterator.html\" rel=\"noreferrer\">http://www.sgi.com/tech/stl/RandomAccessIterator.html</a></p>\n<pre><code> bool operator < (iterator const& rhs) const\n { \n return _node < rhs._node; \n }\n</code></pre>\n<p>The second thing to consider is the sort ordering correct?</p>\n<ol>\n<li>You are defining the less than operator in term of pointer arithmetic. Unless the object are allocated by the same allocators from a known block this is actually undefined behavior. For pointer comparison to be valid they need to be in the same allocated block.</li>\n<li>Is this a good ordering? Youre ordering is based on their address (not the position in the container). So things may be in a jumbled up state in relation to everything else. This may be perfectly fine but something you should keep in mind.</li>\n</ol>\n<h2>WHY The following answers is a complete waste of time and WRONG</h2>\n<p>So please stop voting for it.</p>\n<blockquote>\n<p>I learnt about its importance following discussions on one of the C++ working groups. It's a good practice to follow smarter people.</p>\n</blockquote>\n<p>Yes but you have to also understand when to apply these principles. Some ideas contradict other ideas if you just use them bluntly. You need to understand each idea but also when to apply it.</p>\n<p>The concept of <code>operator symmetry</code> is an important concept when used in the correct situation (no argument there). The problem is that iterators are not the correct situation and it plays no part.</p>\n<p>But we have two competing concepts at play here. One: is symmetry is good. Two: auto conversion of types by the compiler is bad.</p>\n<p>You have to balance the two concepts. In terms of iterators auto converting iterators is a <strong>very bad</strong> idea. You want to make the user of the iterator be explicit about any conversions (as the STL designers did (see below)). As a result the symmetry concept can not be used (as it requires auto conversion).</p>\n<h3>Why it makes no sense for auto conversion</h3>\n<pre><code> Container x;\n AltCont y;\n\n // You can not compare iterators\n // From different containers.\n if (x.begin() < y.end()) {\n // At best this is undefined\n // At worst this is undefined behavior.\n }\n\n // There is no logic to that situation.\n // SO because you should not compare iterators from different\n // containers the type of the iterator when being tested will\n // ***ALWAYS*** be the same type.\n\n // The type of the iterator is always `Container::iterator`\n // Its a required property of a container.\n Container::iterator begin = x.begin();\n Container::iterator end = x.end(); \n</code></pre>\n<p>Q: A but you can create other types of iterator from your iterator.<br />\nA: Yes. But this new type is not comparable to the old type.</p>\n<pre><code>typedef std::reverse_iterator<Container::iterator> reverse_iterator;\nreverse_iterator rbegin(end);\nreverse_iterator rend(begin);\n</code></pre>\n<p>The types are still not comparable.</p>\n<pre><code> if (begin < rbegin) { // Compile time error\n } // For a good reason\n // there is no logical reason for the ranges\n // to be equivalent. \n</code></pre>\n<p>You will also note it does not work the other way around.</p>\n<pre><code> if (rbegin < begin) {\n }\n</code></pre>\n<p>Why you ask is this second case a big deal. Well there is no constructor on Cont::iterator to create an object of type <code>std::reverse_iterator<Cont::iterator></code>. So in the first test above there was no way to convert rbegin into the correct type.</p>\n<p>BUT there is a constructor on <code>std::reverse_iterator<Cont::iterator></code> that takes an object of <code>Cont::iterator</code> so in the second condition we could be in a situation where <code>begin</code> is auto converted into <code>std::reverse_iterator<Cont::iterator></code> and the expression would compile. But luckily for us the designers of the STL decided that was a <strong>bad idea</strong> and made the constructor <code>explicit</code> to prevent auto conversion and thus prevent the code from compiling.</p>\n<h3>OK so why is in Dangerous</h3>\n<p>Its also hides errors.\nThe above code will generally generate a compiler error (so you spot it and correct it quickly). But lets dig in and build the code as suggested by @vinipsmaker.</p>\n<p>For this to work there either has to be a conversion from one iterator to the other or as he suggests a base class and a derived type.</p>\n<pre><code> class IterBase\n { /* Define iterator */ }\n\n class IterDerivedForCont1: public IterBase\n { /* Define iterator */ }\n\n class IterDerivedForCont2: public IterBase\n { /* Define iterator */ }\n\n class Cont1 {\n typedef IterDerivedForCont1 iterator;\n /* Other Stuff */\n }\n\n class Cont2 {\n typedef IterDerivedForCont2 iterator;\n /* Other Stuff */\n }\n\n bool operator<(IterBase const& l, IterBase const& r)\n { return TEST(l,r);}\n\n Cont1 a;\n Cont2 b;\n\n if (a.begin() < b.end()) {\n // You want this to compile?\n // Not really. But it will\n }\n\n // So in this case you are hiding errors from the user.\n // That could have been easily spotted by the compiler.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T18:49:13.413",
"Id": "41904",
"ParentId": "41655",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "41904",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T14:57:09.793",
"Id": "41655",
"Score": "8",
"Tags": [
"c++",
"c++11",
"iterator"
],
"Title": "Iterator class using a square list"
}
|
41655
|
<p>I have this code to edit certain cells in my Excel file using Apache POI, but it is really slow. How can I improved the performance?</p>
<p>Ideally I would like to edit 20000 rows in less than one minute. At the moment it does ~100/min. Any suggestions would be great.</p>
<pre><code>public static void main(String[] args) throws IOException, InvalidFormatException{
InputStream inp = new FileInputStream("test.xls");
FileOutputStream fileOut = new FileOutputStream("edited-test.xls");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
for(int i=2;i <20002;i++){
Row row = sheet.getRow(i);
Cell cell4 = row.getCell(4);
cell4.setCellValue(i);
Cell cell6 = row.getCell(6);
cell6.setCellValue("aa"+i);
Cell cell8 = row.getCell(8);
cell8.setCellValue("2");
wb.write(fileOut);
System.out.println(i);
}
fileOut.close();
System.out.println("Done!");
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T15:35:44.270",
"Id": "71635",
"Score": "3",
"body": "Keep in mind that `System.out.println(i)` could slow your application. If you don't need it, I would suggest you to remove it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T15:39:06.977",
"Id": "71637",
"Score": "0",
"body": "@Marc-Andre good to know, i had it there so i could see how quickly each row was processed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T15:41:37.870",
"Id": "71639",
"Score": "0",
"body": "It's not always decisive, but it could help. Try to execute the code by removing it and try with it to see if it does indeed make a difference."
}
] |
[
{
"body": "<p>First thing you should do is only write the file out once, not 20,000 times ;-)</p>\n\n<p>Move the <code>wb.write(fileOut);</code> to be outside the loop.....</p>\n\n<p>Additionally, there may be some improvement by reversing the loop:</p>\n\n<pre><code>for(int i=2;i <20002;i++){\n</code></pre>\n\n<p>can become:</p>\n\n<pre><code>for(int i=20001;i >= 2;i--){\n</code></pre>\n\n<p>This may make some memory management in the API faster.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T10:39:22.070",
"Id": "71884",
"Score": "0",
"body": "How would reversing the loop help?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T14:39:41.383",
"Id": "71910",
"Score": "0",
"body": "because often data structures are incrementally extended, and starting from the largest member and working backwards **may** mean that only one large allocation is done, instead of multiple smaller ones as the data set grows."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T15:25:09.960",
"Id": "41657",
"ParentId": "41656",
"Score": "8"
}
},
{
"body": "<p>Replace:</p>\n\n<pre><code>cell6.setCellValue(\"aa\"+i);\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>cell6.setCellValue(aa.append(i).toString());\naa.setLength(2); // cut the StringBuilder to just \"aa\", keeping it's original capacity\n</code></pre>\n\n<p>and the write the following two lines before the for:</p>\n\n<pre><code>StringBuilder aa = new StringBuilder(7); // length of \"aa\" plus 5 digits for max value of the loop index\naa.append(\"aa\");\n</code></pre>\n\n<p>-- Edited to add capacity optimization and use setLength() per comments.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T19:01:09.713",
"Id": "71673",
"Score": "0",
"body": "I am not 100 % but this probably what already happening when the code is compiled."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T19:15:49.517",
"Id": "71676",
"Score": "0",
"body": "Agree with @Marc-Andre - but, an interesting observation, and worth noting that moving the `new StringBuilder()` outside the loop, and then reusing it with a `aa.setLength(0);` may have a small benefit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T19:24:13.050",
"Id": "71677",
"Score": "0",
"body": "@rolfl As I said, I'm not that good in optimization, but maybe using `setLength()` would not help that much http://stackoverflow.com/a/5193094/2115680 ."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T23:26:24.367",
"Id": "71729",
"Score": "0",
"body": "I guess this string could be constructed with a array of chars[7], and then updating just the digit(s) that changed in the loop, but unfortunately I don't have time right now to build the full example. Sorry :P"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T18:22:38.690",
"Id": "41675",
"ParentId": "41656",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "41657",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T15:17:52.990",
"Id": "41656",
"Score": "6",
"Tags": [
"java",
"performance",
"excel"
],
"Title": "Fast edit of Excel file"
}
|
41656
|
<p>A question was asked <a href="https://stackoverflow.com/questions/19733364/is-it-possible-to-use-reflection-with-linq-to-entity/19733636">here</a> about reflection and LINQ to entity. I'm trying to modify the code that was presented to fit my needs.</p>
<p>Here's what I am trying to accomplish: I'm writing back-end support for a web site that will be able to run reports on data we have. I want to write this as generically as possible so that the UI has the latitude to query however it wants without having to change the back end.</p>
<p>Leaning heavily on the above-mentioned link, and also using <a href="http://www.albahari.com/nutshell/linqkit.aspx" rel="nofollow noreferrer">LinqKit</a> I've cobbled together something that appears to work, but it's kinda' ugly and I was hoping there was a way to slim it down a bit.</p>
<p>First, I want to be able to pass arbitrarily complex and/or statements to the search. This part I'm perfectly satisfied with, but I'm including it as a reference to the next part:</p>
<pre><code>public class QueryGroup
{
public readonly List<Tuple<string, CompareTypes, string>> conditions;
public List<QueryGroup> qGroups;
public Operators Operator { get; private set; }
public QueryGroup(Operators op)
{
Operator = op;
conditions = new List<Tuple<string, CompareTypes, string>>();
}
}
public enum CompareTypes
{
Equals, GreaterThan, LessThan
}
public enum Operators
{
And, Or
};
</code></pre>
<p>The most important part to notice here is</p>
<pre><code>public readonly List<Tuple<string, CompareTypes, string>> conditions;
</code></pre>
<p>This list of conditions is a way for us to say that some key (first string) relates in a specified way (<code>CompareType</code>s like <code>==</code>, <code><</code>, <code>></code>, etc.) to a given value (second string). So for an object <code>Foo</code>, if Foo had a member <code>Bar</code> and we wanted to compare the value of <code>Foo.Bar</code>, then the first string would be "Bar" (note that we will already know we are searching for properties inside of Foo). If we wanted to say that the value of "Bar" should be equal to, say, 5, then the <code>CompareType</code> would be <code>CompareTypes.Equals</code> and the last string would be "5".</p>
<p>OK, on to the ugly part...</p>
<p>Continuing on the Foo/Bar example from above, let's say I had a function like this:</p>
<pre><code>public List<Foo> GetFoosBy(QueryGroup qGroup)
{
var pred = parseQueryGroup<Foo>(qGroup);
return _context.Foos.AsExpandable().Where(pred).ToList();
}
</code></pre>
<p>Again, this isn't so bad until we get into <code>parseQueryGroup</code>. Here's what that looks like (brace yourself):</p>
<pre><code>private static Expression<Func<T, bool>> parseQueryGroup<T>(QueryGroup q)
{
var retVal = q.Operator == Operators.And ? PredicateBuilder.True<T>() : PredicateBuilder.False<T>();
if (q.qGroups != null && q.qGroups.Count > 0)
{
//must call .Expand on the subqueries:
//https://stackoverflow.com/questions/2947820/c-sharp-predicatebuilder-entities-the-parameter-f-was-not-bound-in-the-specif
foreach (QueryGroup subGroup in q.qGroups)
retVal = q.Operator == Operators.And ? retVal.And(parseQueryGroup<T>(subGroup).Expand()) : retVal.Or(parseQueryGroup<T>(subGroup).Expand());
}
foreach (Tuple<string, CompareTypes, string> condition in q.conditions)
{
Tuple<string, CompareTypes, string> cond = condition;
Expression<Func<T, string, bool>> expression = (ex, value) => value.Trim() == cond.Item3;
MemberExpression newSelector = Expression.Property(expression.Parameters[0], cond.Item1);
Expression<Func<T, bool>> lambda;
if (newSelector.Type == typeof(string))
{
switch (condition.Item2)
{
case CompareTypes.Equals:
expression = (ex, value) => value == cond.Item3;
break;
case CompareTypes.GreaterThan:
expression = (ex, value) => string.Compare(value, cond.Item3) > 0;
break;
case CompareTypes.LessThan:
expression = (ex, value) => string.Compare(value, cond.Item3) < 0;
break;
default:
throw new Exception("Unrecognized compare type");
}
newSelector = Expression.Property(expression.Parameters[0], cond.Item1); //do we need this?
Expression body = expression.Body.Replace(expression.Parameters[1], newSelector);
lambda = Expression.Lambda<Func<T, bool>>(body, expression.Parameters[0]);
}
else if (newSelector.Type == typeof(byte) || newSelector.Type == typeof(short) || newSelector.Type == typeof(int) || newSelector.Type == typeof(long))
{
long iCondItem3 = Convert.ToInt64(cond.Item3);
Expression<Func<T, int, bool>> expression2;
switch (condition.Item2)
{
case CompareTypes.Equals:
expression2 = (ex, value) => value == iCondItem3;
break;
case CompareTypes.GreaterThan:
expression2 = (ex, value) => value > iCondItem3;
break;
case CompareTypes.LessThan:
expression2 = (ex, value) => value < iCondItem3;
break;
default:
throw new Exception("Unrecognized compare type");
}
newSelector = Expression.Property(expression2.Parameters[0], cond.Item1);
var body = expression2.Body.Replace(expression2.Parameters[1], newSelector);
lambda = Expression.Lambda<Func<T, bool>>(body, expression2.Parameters[0]);
}
else if (newSelector.Type == typeof(float) || newSelector.Type == typeof(double) || newSelector.Type == typeof(decimal))
{
decimal fCondItem3 = Convert.ToDecimal(cond.Item3);
Expression<Func<T, decimal, bool>> expression2;
switch (condition.Item2)
{
case CompareTypes.Equals:
expression2 = (ex, value) => value == fCondItem3;
break;
case CompareTypes.GreaterThan:
expression2 = (ex, value) => value > fCondItem3;
break;
case CompareTypes.LessThan:
expression2 = (ex, value) => value < fCondItem3;
break;
default:
throw new Exception("Unrecognized compare type");
}
newSelector = Expression.Property(expression2.Parameters[0], cond.Item1);
var body = expression2.Body.Replace(expression2.Parameters[1], newSelector);
lambda = Expression.Lambda<Func<T, bool>>(body, expression2.Parameters[0]);
}
else if (newSelector.Type == typeof(bool))
{
bool bCondItem3 = Convert.ToBoolean(cond.Item3);
Expression<Func<T, bool, bool>> expression2 = (ex, value) => value == bCondItem3;
newSelector = Expression.Property(expression2.Parameters[0], cond.Item1);
var body = expression2.Body.Replace(expression2.Parameters[1], newSelector);
lambda = Expression.Lambda<Func<T, bool>>(body, expression2.Parameters[0]);
}
else if (newSelector.Type == typeof(DateTime))
{
DateTime dCondItem3 = DateTime.Parse(cond.Item3);
DateTime dCondItem3_NextDay = dCondItem3.Date.AddDays(1);
Expression<Func<T, DateTime, bool>> expression2;
switch (condition.Item2)
{
case CompareTypes.Equals:
expression2 = (ex, value) => (value > dCondItem3.Date && value < dCondItem3_NextDay); //For == on DateTime, we only care about the date
break;
case CompareTypes.GreaterThan:
expression2 = (ex, value) => value > dCondItem3;
break;
case CompareTypes.LessThan:
expression2 = (ex, value) => value < dCondItem3;
break;
default:
throw new Exception("Unrecognized compare type");
}
newSelector = Expression.Property(expression2.Parameters[0], cond.Item1);
var body = expression2.Body.Replace(expression2.Parameters[1], newSelector);
lambda = Expression.Lambda<Func<T, bool>>(body, expression2.Parameters[0]);
}
else
throw new ArgumentException("Need to code for type " + newSelector.Type);
retVal = q.Operator == Operators.And ? retVal.And(lambda) : retVal.Or(lambda);
}
return retVal;
}
</code></pre>
<p>2 things to note:</p>
<ol>
<li>There is <em>A LOT</em> of repeated code</li>
<li><code>String</code>, <code>DateTime</code> and <code>bool</code> are special in that you can't just do ==, >, and < on them
<ul>
<li><code>String</code> requires <code>string.Compare</code></li>
<li>For <code>DateTime</code>'s <code>==</code>, we don't want to require millisecond precision. In fact, for our purposes, just the date is good enough.</li>
<li><code>bool</code> only has <code>==</code> because <code><</code> and <code>></code> didn't make any sense to me.</li>
</ul></li>
</ol>
<p>Even without these special cases (that is, even if it were all the same) I still can't figure out a way to trim this down and it sure seems like I should be able to. It's going to get even messier when I add new compare types (like <code>!=</code>, <code>>=</code>, <code><=</code>, <code>StartsWith</code>, <code>Contains</code>, etc.)</p>
<p>Things I'm hoping to refactor:</p>
<ul>
<li><code>expression</code> in <code>Expression<Func<T, string, bool>> expression = (ex, value) => value.Trim() == cond.Item3;</code> is only used in the next line <code>MemberExpression newSelector = Expression.Property(expression.Parameters[0], cond.Item1);</code>, which in turn is only used to determine the type (as in <code>if (newSelector.Type == typeof(string))</code>). <code>newSelector</code> is overwritten later and (with the exception of string) <code>expression</code> is never used again.</li>
<li><p>The last 3 lines of each section are the same and so it would be nice if we could move that out somehow (but I don't know how we would do that since <code>expression2</code> is a different signature for each)</p>
<pre><code>newSelector = Expression.Property(expression2.Parameters[0], cond.Item1);
var body = expression2.Body.Replace(expression2.Parameters[1], newSelector);
lambda = Expression.Lambda<Func<T, bool>>(body, expression2.Parameters[0]);
</code></pre></li>
<li><p>Going along with the previous, I would love it if there was some sort of way to change
<code>Expression<Func<T, int, bool>> expression2;</code> to something like <code>Expression<Func<T, newSelector.Type, bool>> expression2;</code>, but from what I can tell, such a thing is not possible (obviously it isn't allowed exactly like that, but if there was some way to manipulate it through reflection or something...)</p></li>
</ul>
<p>Could this be refactored? I suppose this would be trivially simple if instead of using LINQ, I just built a raw SQL query, but I was hoping to avoid that, if possible.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T16:50:31.760",
"Id": "71646",
"Score": "1",
"body": "Welcome to the CR First Post review! +1 for a beautiful first post, I hope you enjoy your CR experience [and become addicted mwahahahaha] :)"
}
] |
[
{
"body": "<blockquote>\n <p>String requires string.Compare</p>\n</blockquote>\n\n<p>Not true. There's a more generic option:</p>\n\n<pre><code> if (typeof(IComparable).IsAssignableFrom(newSelector.Type))\n {\n switch (condition.Item2)\n {\n case CompareTypes.Equals:\n expression = (ex, value) => value.CompareTo(cond.Item3) == 0;\n break;\n case CompareTypes.GreaterThan:\n expression = (ex, value) => value.CompareTo(cond.Item3) > 0;\n break;\n case CompareTypes.LessThan:\n expression = (ex, value) => value.CompareTo(cond.Item3) < 0;\n break;\n default:\n throw new Exception(\"Unrecognized compare type\");\n }\n ...\n</code></pre>\n\n<p>That will handle <code>string</code>, <code>char</code>, <code>DateTime</code>, all numeric types, ... (NB I haven't tried compiling it: you might need to add suitable casts to <code>IComparable</code> inside the expressions).</p>\n\n<p>Your treatment of <code>DateTime</code> will require special-casing. One option would be to put that before <code>IComparable</code> in the if-chain. Another might be to apply a projection before applying the comparison; for most types it would be the identity projection, but for <code>DateTime</code> it would be <code>x => x.Date</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T17:19:26.230",
"Id": "71649",
"Score": "0",
"body": "I don't think that will translate into SQL by LINQ to Entities query provider."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T20:36:15.297",
"Id": "71703",
"Score": "0",
"body": "I plugged that in and it does appear to work, but ONLY when that expression (expression2 in all but string) is declared as `Expression<Func<T, XXX, bool>> expression2` where XXX is the same type as newSelector. This is my last bullet point; if we can figure that out, then this will be an excellent refactoring."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T17:18:38.980",
"Id": "41670",
"ParentId": "41661",
"Score": "3"
}
},
{
"body": "<p>Look at the <a href=\"http://www.albahari.com/nutshell/predicatebuilder.aspx\" rel=\"nofollow\">PredicateBuilder</a> on LINQKit.</p>\n\n<p>These code snippets are from the linked page:</p>\n\n<pre><code>public interface IValidFromTo\n{\n DateTime? ValidFrom { get; }\n DateTime? ValidTo { get; }\n}\n</code></pre>\n\n<blockquote>\n <p>Now we can define a single generic IsCurrent method using that interface as a >constraint:</p>\n</blockquote>\n\n<pre><code>public static Expression<Func<TEntity, bool>> IsCurrent<TEntity>()\n where TEntity : IValidFromTo\n{\n return e => (e.ValidFrom == null || e.ValidFrom <= DateTime.Now) &&\n (e.ValidTo == null || e.ValidTo >= DateTime.Now);\n}\n</code></pre>\n\n<blockquote>\n <p>The final step is to implement this interface in each class that supports >ValidFrom and ValidTo. If you're using Visual Studio or a tool like SqlMetal to >generate your entity classes, do this in the non-generated half of the partial >classes:</p>\n</blockquote>\n\n<pre><code>public partial class PriceList : IValidFromTo { }\npublic partial class Product : IValidFromTo { }\n</code></pre>\n\n<p>To directly answer your last bullet point, Your Func's type signature can look like <code>Func<...IType, bool></code> to construct predicates, with the <code>IType</code> as an interface that can accept multiple different types. The problem is you'll have to go back in your model and add that interface to any entities you'd want to query.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-10-26T16:11:08.243",
"Id": "145332",
"ParentId": "41661",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T16:08:45.317",
"Id": "41661",
"Score": "7",
"Tags": [
"c#",
"entity-framework",
"reflection",
"linq-to-sql",
"lambda"
],
"Title": "A generic way to use LINQ to Entity with types and operations unknown until run time"
}
|
41661
|
<p><strong>What is MDX?</strong></p>
<blockquote>
<p>"Multidimensional Expressions (MDX) is a query language for OLAP
databases, much like SQL is a query language for relational databases.
It is also a calculation language, with a syntax similar to spreadsheet
formulas." <strong>Source: Wikipedia</strong></p>
</blockquote>
<p>It was originally developed as a language for Microsoft's OLAP engine (then called OLAP Services, now renamed Analysis Services) but has since been adopted by a wide range of vendors for use with their OLAP tools.</p>
<p><strong>Resources</strong></p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms145506.aspx" rel="nofollow">MDX reference on MSDN</a></li>
<li><a href="http://www.ssas-info.com/analysis-services-articles/50-mdx" rel="nofollow">Analysis Services Resource Hub</a></li>
<li><a href="http://en.wikipedia.org/wiki/MultiDimensional_eXpressions" rel="nofollow">Wikipedia entry on MultiDimensional eXpressions</a></li>
</ul>
<p><strong>Books</strong></p>
<ul>
<li><a href="http://rads.stackoverflow.com/amzn/click/0071713360" rel="nofollow">Practical MDX Queries: For Microsoft SQL Server Analysis Services 2008</a></li>
<li><a href="http://rads.stackoverflow.com/amzn/click/1849681309" rel="nofollow">MDX with Microsoft SQL Server 2008 R2 Analysis Services Cookbook</a></li>
<li><a href="http://rads.stackoverflow.com/amzn/click/1599943395" rel="nofollow">SAS 9.2 OLAP Server: MDX Guide</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T16:17:56.423",
"Id": "41663",
"Score": "0",
"Tags": null,
"Title": null
}
|
41663
|
Multidimensional Expressions (MDX) is a query language for OLAP databases. It was developed by Microsoft but has later gained widespread support from other OLAP vendors.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T16:17:56.423",
"Id": "41664",
"Score": "0",
"Tags": null,
"Title": null
}
|
41664
|
<p>I have a file that seems to mix encoding in it. It seems like a Unicode encoded file, but the character length string is encoded like a UTF8 or similar. Here is an example:</p>
<pre><code>05 41 00 72 00 69 00 61 00 6C 00
5 A . r . i . a . l .
</code></pre>
<p>In this example it stores the string like Unicode, using the extra character, but the length of the string is half of what it should be, 05 instead of 0A, as if it were encoded as UTF8. </p>
<p>If I use:</p>
<pre><code>using (var reader = new BinaryReader(File.Open(fileName, FileMode.Open), Encoding.Unicode))
{
temp = reader.ReadString();
}
</code></pre>
<p>When I run this then temp = "Ar"</p>
<p>I have this code that works. But is there a better way?</p>
<pre><code>using (var reader = new BinaryReader(File.Open(fileName, FileMode.Open), Encoding.Unicode))
{
tempByte = reader.ReadByte();
var length = Convert.ToInt32(tempByte) * 2;
byteArray = reader.ReadBytes(length);
for (var ww = 0; ww < length; ww = ww + 2)
{
tempString = tempString + (char)byteArray[ww];
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T17:54:01.523",
"Id": "71661",
"Score": "0",
"body": "As far as I can see, that looks like UTF-16 encoding."
}
] |
[
{
"body": "<p>To me it looks like somebody just used <a href=\"http://msdn.microsoft.com/en-us/library/yzxa6408%28v=vs.100%29.aspx\" rel=\"nofollow\"><code>BinaryWriter.Write(String)</code></a> and you should be able to extract those strings with a UTF16 encoded <code>BinaryReader</code> using <a href=\"http://msdn.microsoft.com/en-us/library/system.io.binaryreader.readstring%28v=vs.110%29.aspx\" rel=\"nofollow\"><code>BinaryReader.ReadString()</code> method</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T12:22:15.567",
"Id": "71888",
"Score": "1",
"body": "This is where I'm stuck, if UTF16 is the encoding for this, I don't have this as an option in my encoding. I have ASCII, BigEndianUnicode, Default, UTF32, UTF7, UTF8 and Unicode. None of which decode this properly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T13:13:25.990",
"Id": "71891",
"Score": "0",
"body": "Try Unicode, it's UTF16 (or UCS2, should be similar for most use cases)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T12:10:46.810",
"Id": "41792",
"ParentId": "41666",
"Score": "-1"
}
},
{
"body": "<p><code>BinaryReader.ReadString()</code> expects the string prefixed with the number of bytes to read, not the number of characters (I think this is because of variable-length encodings, especially UTF-8, but also UTF-16).</p>\n\n<p>So, you can't use <code>ReadString()</code> directly, but you also don't have to convert the characters byte by byte like you do (which wouldn't work for non-ASCII characters anyway).</p>\n\n<p>For this, you can use <a href=\"http://msdn.microsoft.com/en-us/library/system.io.binaryreader.readchars\" rel=\"nofollow\"><code>ReadChars()</code></a>, which takes as a parameter the number of characters (not bytes) to read.</p>\n\n<p>You also need to figure out what format is the number of bytes saved in. It could be a simple single-byte number (which means the string can have at most 255 characters), or it could be <a href=\"https://en.wikipedia.org/wiki/Variable-length_quantity\" rel=\"nofollow\">VLQ</a>-encoded, which you can read using <a href=\"http://msdn.microsoft.com/en-us/library/system.io.binaryreader.read7bitencodedint\" rel=\"nofollow\"><code>Read7BitEncodedInt()</code></a>. Though that method is <code>protected</code>, so I'm going to assume the former for simplicity.</p>\n\n<p>So, the code could look like this:</p>\n\n<pre><code>using (var reader = new BinaryReader(File.Open(fileName, FileMode.Open), Encoding.Unicode))\n{\n int characterCount = reader.ReadByte();\n char[] characters = reader.ReadChars(characterCount);\n return new string(characters);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T17:11:48.337",
"Id": "42520",
"ParentId": "41666",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "42520",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T16:24:42.847",
"Id": "41666",
"Score": "3",
"Tags": [
"c#",
"unicode"
],
"Title": "Custom encoding for BinaryReader"
}
|
41666
|
<p>I am currently using this C# method to retrieve MAC addresses from a user's computer as a sort of unique identification. It retrieves the MAC address based on the fact that the physical card is connected to the PCI interface.</p>
<pre><code>public static string returnMAC()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select MACAddress, PNPDeviceID FROM Win32_NetworkAdapter WHERE MACAddress IS NOT NULL AND PNPDEVICEID IS NOT NULL");
ManagementObjectCollection mObject = searcher.Get();
foreach (ManagementObject obj in mObject)
{
string pnp = obj["PNPDeviceID"].ToString();
if (pnp.Contains("PCI\\"))
{
string mac = obj["MACAddress"].ToString();
mac = mac.Replace(":", string.Empty);
return mac;
}
}
return "Nothing happened...";
}
</code></pre>
<p>A method I used previously was pulled straight from MSDN, but due to some issues it inherently had (like pulling the wireless' MAC instead of the LAN line), I switched it out for this one.</p>
<p>I have tested this method on Windows 7 and 8.1 systems, and it works fine in retrieving the physical MAC address. With that said - it uses SQL queries to search for strings, instead of a more typical method that uses <code>System.Net.XXX</code> - a more "built-in" and "native" method. Correct me if I am wrong on this.</p>
<p>Is there any way to make this better? I can't think of what would make it better, but on the top of my head - LINQ queries? Native methods? I'm not sure.</p>
|
[] |
[
{
"body": "<pre><code>public static string returnMAC()\n</code></pre>\n\n<p>The <a href=\"http://msdn.microsoft.com/en-us/library/ff926074.aspx\" rel=\"nofollow\">C# coding conventions</a> state that functions should be UpperCamelCase. Additionally that function name is not optimal, <code>returnMAC</code>, return it from where? More appropriate would be <code>GetMAC</code> or <code>RetrieveMAC</code>.</p>\n\n<hr>\n\n<p>You should add <a href=\"http://msdn.microsoft.com/en-us/library/b2s063f7.aspx\" rel=\"nofollow\">XML documentation</a> to this method.</p>\n\n<hr>\n\n<pre><code>ManagementObjectSearcher searcher = new ManagementObjectSearcher(\"Select MACAddress, PNPDeviceID FROM Win32_NetworkAdapter WHERE MACAddress IS NOT NULL AND PNPDEVICEID IS NOT NULL\");\n</code></pre>\n\n<p>This could benefit from using a <a href=\"http://msdn.microsoft.com/en-us/library/aa691090%28v=vs.71%29.aspx\" rel=\"nofollow\">literal/verbatim string</a>:</p>\n\n<pre><code>ManagementObjectSearcher searcher = new ManagementObjectSearcher(@\"\nSELECT\n MACAddress,\n PNPDeviceID\nFROM\n Win32_NetworkAdapter\nWHERE\n MACAddress IS NOT NULL AND\n PNPDEVICEID IS NOT NULL\");\n</code></pre>\n\n<hr>\n\n<pre><code>ManagementObjectCollection mObject = searcher.Get();\n\nforeach (ManagementObject obj in mObject)\n</code></pre>\n\n<p>Both variable names are not great. You should avoid naming something <code>obj</code> if it is not an <code>Object</code>. Also you have the variable <code>mObject</code> which is a <code>ManagementObjectCollection</code> but can easily be confused to be a <code>ManagementObject</code>. Despite not being a great alternative either, <code>collection</code> and <code>item</code> might be better...though, only slightly.</p>\n\n<pre><code>ManagementObjectCollection collection = searcher.Get();\n\nforeach (ManagementObject item in collection)\n</code></pre>\n\n<hr>\n\n<pre><code>string pnp = obj[\"PNPDeviceID\"].ToString();\n</code></pre>\n\n<p>Again, I would have rather named this variable <code>pnpId</code> or <code>deviceId</code>.</p>\n\n<hr>\n\n<pre><code>string pnp = obj[\"PNPDeviceID\"].ToString();\nif (pnp.Contains(\"PCI\\\\\"))\n{\n string mac = obj[\"MACAddress\"].ToString();\n mac = mac.Replace(\":\", string.Empty);\n return mac;\n}\n</code></pre>\n\n<p>This whole block can be shortened without losing much readability:</p>\n\n<pre><code> if (item[\"PNPDeviceID\"].ToString().Contains(\"PCI\\\\\"))\n {\n return item[\"MACAddress\"].ToString().Replace(\":\", string.Empty);\n }\n</code></pre>\n\n<p>Though, it seems a little bit messy at first sight, I think it's within an acceptable level.</p>\n\n<hr>\n\n<pre><code>return \"Nothing happened...\";\n</code></pre>\n\n<p>A more appropriate return value would be <code>\"\"</code> or <code>\"No PCI device found.\"</code>.</p>\n\n<p>Of course, the most appropriate action would be to throw an exception, as that should not happen during normal operation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T18:12:24.673",
"Id": "71666",
"Score": "0",
"body": "Thanks! The naming schemes are definitely something I can work on. In regards to the actual lower-level code stuff like retrieving MAC addresses, are there better ways?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T18:18:29.250",
"Id": "71668",
"Score": "0",
"body": "@theGreenCabbage: I never had to retrieve the MAC address, so I can't really tell."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T17:50:02.223",
"Id": "41673",
"ParentId": "41667",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T16:33:50.767",
"Id": "41667",
"Score": "3",
"Tags": [
"c#",
"sql"
],
"Title": "Retrieving MAC addresses based on PCI interface connections and SQL queries"
}
|
41667
|
<p>I have implemented a method to compute a convex quadrilateral area in R3. The method works fine, but I am having numerical precision problems in the 8th decimal place. Take a look on the method:</p>
<pre><code>internal static double GetTriangleArea(double ax, double ay, double az,
double bx, double by, double bz,
double cx, double cy, double cz
)
{
/**
* AB = B-A = (ux, uy, uz)
* AC = C-A = (wx, wy, wz)
*
* S = 0.5*sqrt{(uy*wz - uz*wy)² + (uz*wx - ux*wz)² + (ux*wy - uy*wx)²}
* */
var ux = bx - ax;
var uy = by - ay;
var uz = bz - az;
var wx = cx - ax;
var wy = cy - ay;
var wz = cz - az;
var t1 = uy*wz - uz*wy;
var t2 = uz*wx - ux*wz;
var t3 = ux*wy - uy*wx;
var s = 0.5*Math.Sqrt(t1*t1 + t2*t2 + t3*t3);
return s;
}
internal static double GetConvexQuadrilateralArea(double ax, double ay, double az,
double bx, double by, double bz,
double cx, double cy, double cz,
double dx, double dy, double dz)
{
var triangle1 = GetTriangleArea(ax, ay, az, bx, by, bz, cx, cy, cz);
var triangle2 = GetTriangleArea(ax, ay, az, cx, cy, cz, dx,dy,dz);
return triangle1 + triangle2;
}
</code></pre>
<p>And this is the test:</p>
<pre><code>[TestMethod]
public void ParallelogramOfBaseBAndHeightHMustHaveAreaEqualToBTimesH()
{
var random = new Random(1);
const double scale = 10000;
for (var counter = 0; counter < 1000; counter++)
{
double baseLength = random.NextDouble() * scale;
double height = random.NextDouble() * scale;
double dx = random.NextDouble()*scale;
var a = new[] { 0, 0, 0 };
var b = new[] { baseLength, 0, 0 };
var c = new[] { baseLength+dx, height, 0 };
var d = new[] { 0F+dx, height, 0 };
double expected = baseLength * height;
var result = MathUtils.GetConvexQuadrilateralArea(a[0], a[1], a[2], b[0], b[1], b[2], c[0], c[1], c[2],
d[0], d[1], d[2]);
Assert.AreEqual(expected, result, Epsilon*scale,
string.Format("sideA: {0}, height: {1}, dx: {2}", baseLength, height, dx));
}
}
</code></pre>
<p>This test fails with the following message: Expected a difference no greater than <1E-09> between expected value 74813926.2967871 and actual value 74813926.2967871. sideA: 8552.44307245707, height: 8747.66726454146, dx: 4721.64729829954.</p>
<p>My question is: is there a way to increase the numerical precision of my implementation while still using double precision numbers?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T17:51:55.450",
"Id": "71659",
"Score": "2",
"body": "No, use `Decimal`. ... Okay, I'm sure there would be ways, hacky and complicated ways, but I think the only appropriate solution is to use `Decimal`. Also, this question seems kinda off-topic if that's your only question."
}
] |
[
{
"body": "<p>Debugging <a href=\"https://stackoverflow.com/questions/753948/why-is-floating-point-arithmetic-in-c-sharp-imprecise\">floating-point precision issues</a> is, as @Bobby mentioned, off-topic for this site, so this is going to be <em>just a code review</em> :)</p>\n\n<p>The first thing that strikes me, is the cryptic two-letter identifiers.</p>\n\n<p>Let's start with the signature for <code>GetTriangleArea</code>. You're taking <strong>9 parameters</strong>, this is bad. In reality you really need 3 <em>groups of 3 numbers</em>. Your code has failed to make this abstraction, and this is why you end up with a1-a2-a3 -style identifiers.</p>\n\n<p>What if <code>GetTriangleArea</code> had a signature like this?</p>\n\n<pre><code>internal static double GetTriangleArea(Point3D pointA, Point3D pointB, Point3D pointC)\n</code></pre>\n\n<p>Given a <code>Point3D</code> <em>struct</em> with members <code>X</code>, <code>Y</code> and <code>Z</code>, the rest of the code would be much less cryptic.</p>\n\n<p>The same applies to <code>GetConvexQuadrilateralArea</code>, which could look much less crowded like this:</p>\n\n<pre><code>internal static double GetConvexQuadrilateralArea(Point3D pointA, Point3D pointB, Point3D pointC, Point3D pointD)\n</code></pre>\n\n<p>Lastly, I'm not sure, but I think <code>GetConvexQuadrilateralArea</code> is lying - the method isn't <em>actively</em> verifying the <em>convex-ness</em> of the points it's given, which may or may not be problematic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T19:44:12.137",
"Id": "71683",
"Score": "0",
"body": "does using struct to abstract parameters cause a performance penalty?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T19:47:19.957",
"Id": "71686",
"Score": "1",
"body": "[Using a `struct` incurs zero overhead](http://stackoverflow.com/questions/6181456/overhead-of-using-structs-as-wrappers-for-primitives-for-type-checking), so no. `struct` defines a *value type*, the story would be different if it were a `class` ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T09:49:28.557",
"Id": "71753",
"Score": "1",
"body": "@user38397: This is called \"premature optimization\", never worry about performance unless you have to."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T17:34:17.537",
"Id": "71806",
"Score": "0",
"body": "I have to. I am talking of about 100 milion of these quadrilaterals."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T19:12:19.203",
"Id": "41679",
"ParentId": "41668",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T16:53:37.483",
"Id": "41668",
"Score": "2",
"Tags": [
"c#",
".net"
],
"Title": "Numerical precision of implementation for convex quadrilateral area"
}
|
41668
|
<p>I just want an indication as to whether or not I'm on the right track regarding PHP OOP, at least on a basic level. Positive criticism welcome.</p>
<p>P.S. Excuse the visuals of the code. This is how I usually remember code.</p>
<pre><code><html>
<?php
//Blueprint
class Human{
// properties of human
private $gender;
private $name;
private $age;
private $talk;
public function __construct($gender, $name, $age, $talk){
$this->gender = $gender;
$this->name = $name;
$this->age = $age;
$this->talk = $talk;
}
public function getGender(){
return $this->gender;
}
public function getName(){
return $this->name;
}
public function getAge(){
return $this->age;
}
public function getTalk(){
return $this->talk;
}
}
class female extends Human{
//properties of female
private $bum;
private $feet;
public function __construct($gender, $name, $age, $talk, $bum, $feet){
parent::__construct($gender, $name, $age, $talk);
$this->bum = $bum;
$this->feet = $feet;
}
public function getBumSize(){
return $this->bum;
}
public function getFeetSize(){
return $this->feet;
}
}
class male extends Human{
//properties of male
private $facialHair;
private $adamsApple;
public function __construct($gender, $name, $age, $talk, $facialHair, $adamsApple){
parent::__construct($gender, $name, $age, $talk);
$this->beard = $facialHair;
$this->throat = $adamsApple;
}
public function getBeard(){
return $this->beard;
}
public function getThroat(){
return $this->throat;
}
}
//instantiate objects
$malePerson = new male('male', 'John Doe', '32', 'clear', 'beard', 'adams apple in my throat');
$femalePerson = new female('female', 'Jane Doe', '28', 'loud', 'big and round', 'small');
echo "Hi, My name is {$malePerson->getName()}, {$malePerson->getAge()} years of age, I talk {$malePerson->getTalk()}
so i guess that makes me {$malePerson->getGender()} a.k.a man....I also have
a {$malePerson->getThroat()} and a {$malePerson->getBeard()} which is very very long .lol";
echo "<br>";
echo "Hi, My name is {$femalePerson->getName()}, {$femalePerson->getAge()} years of age, I talk {$malePerson->getTalk()} so i
guess that makes me {$femalePerson->getGender()} a.k.a mamalicious....I also have
{$femalePerson->getFeetSize()} feet and a {$femalePerson->getBumSize()} bum.lol";
?>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T00:05:56.147",
"Id": "71734",
"Score": "4",
"body": "The Human class must be abstract. Think it like this, you can \"create\" a Female or a Male, even a Transgender :P, but they are Humans. You **can not create** such thing as **a human**, therefore it must be abstract."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T19:24:38.557",
"Id": "71814",
"Score": "0",
"body": "It needs to be said: subclassing for gender in the first place feels a bit broken to me, rather than just having the gender as a property of a human. There is not enough actual difference between men and women, in my mind, to justify segregating them like that. The biggest useful thing it's doing here is revealing a bit about how you think of women... :P"
}
] |
[
{
"body": "<p>Your modeling approach seems right so far for me. Yet some minor remarks in general:</p>\n\n<ul>\n<li>I'd consider it good practice to start class names in upper-case. Either way, you should decide and stick for one way: <code>Human <-> female</code> </li>\n<li>I'm no native speaker. Yet as far as I do know, <code>bum</code> is slang which should be avoided as someone might feel offended or simply not understand it. </li>\n<li><code>// properties of human</code> < that's an awfully obvious statement. It takes up time and space yet provides no information. </li>\n<li>I'd consider it standard to have a whitespace between a class declaration and the starting bracket: <code>class Human {</code>. Same goes for function declarations: <code>function getTalk() {</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T18:46:16.537",
"Id": "71669",
"Score": "0",
"body": "you're right about the slang my bad, thank you for your observations much appreciated"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T18:35:53.747",
"Id": "41677",
"ParentId": "41669",
"Score": "10"
}
},
{
"body": "<p>First of all: Extract your classes into extra files and <code>require_once</code> them as necessary. I found the Java style of having one class per file a very good one.</p>\n\n<hr>\n\n<p>Second: Learn and start to use <a href=\"http://en.wikipedia.org/wiki/PHPDoc\" rel=\"nofollow\">PHPDoc</a> to document your code.</p>\n\n<hr>\n\n<pre><code>//Blueprint\n</code></pre>\n\n<p>That's not a helpful comment...only write a comment if it is helpful.</p>\n\n<hr>\n\n<pre><code>// properties of human\nprivate $gender;\nprivate $name;\nprivate $age;\nprivate $talk;\n</code></pre>\n\n<p>Such structural comments are unnecessary if your class is correctly structured and indented.</p>\n\n<hr>\n\n<pre><code>$this->gender = $gender;\n$this->name = $name;\n$this->age = $age;\n$this->talk = $talk;\n</code></pre>\n\n<p>Personally I don't like this kind of intending. It <em>can</em> make code easier to read, but in a pure \"assign all parameters to all fields\" constructors it seems kinda unnecessary.</p>\n\n<hr>\n\n<pre><code>class female extends Human{\n</code></pre>\n\n<p>Is it a typo that <code>female</code> is lower case?</p>\n\n<hr>\n\n<pre><code>private $bum;\n</code></pre>\n\n<p>If it holds the size of the bum, then it should be called <code>$bumSize</code>. The same goes for <code>$feet</code>.</p>\n\n<hr>\n\n<pre><code>$malePerson = new male('male', 'John Doe', '32', 'clear', 'beard', 'adams apple in my throat');\n</code></pre>\n\n<p>Apart from the unnecessary intending, this is a good example <a href=\"http://c2.com/cgi/wiki?StringlyTyped\" rel=\"nofollow\">stringly typed programming</a>. You're using a string for <em>everything</em> even though the age should be an integer.</p>\n\n<p>Let's have a look at the basic variables a <code>Human</code> consists of:</p>\n\n<ul>\n<li><code>$gender</code> Should an enumeration with two values, <code>Male</code> and <code>Female</code>.</li>\n<li><code>$name</code> Names are strings, so it's okay.</li>\n<li><code>$age</code> Is an integer and should therefor be an integer.</li>\n<li><code>$talk</code> Is also a string.</li>\n</ul>\n\n<p>And let's go forth with the <code>Male</code>:</p>\n\n<ul>\n<li><code>$facialHair</code> Should be an enum, or an integer to indicate strength.</li>\n<li><code>$adamsApple</code> Not sure what this is.</li>\n</ul>\n\n<p>Also forget what I just said about <code>$gender</code>, <code>Human</code> should be an abstract class and <code>getGender()</code> should be an abstract method that is implemented by the next class.</p>\n\n<hr>\n\n<pre><code><html>\n <?php Some code with echo... ?>\n</html>\n</code></pre>\n\n<p>That's not a well-formed HTML document.</p>\n\n<pre><code><html>\n <head>\n <title>Title of your page</title>\n </head>\n <body>\n Content goes here.\n </body>\n</html>\n</code></pre>\n\n<p>Ideally you would perform initializations before the <code>html</code> tag and then just use everything prepared in the <code>body</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T18:57:57.890",
"Id": "71671",
"Score": "0",
"body": "thanks for pointing out the scenario of stringly typed. regarding enums and abstract classes, i have not covered that before, that will be my next study topic"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T19:39:19.247",
"Id": "71680",
"Score": "0",
"body": "Perhaps I should have read your answer completely before posting my own, I just noticed that I brought up one thing that you already mentioned. But oh well, it is quite important but at least we don't need a big flashy gif this time :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T19:41:47.507",
"Id": "71682",
"Score": "0",
"body": "@SimonAndréForsberg: Nah, it's okay. I consider every answer a review of it's own, if something repeats, there's nothing to worry about. And yes, hopefully we will never need that again. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T13:52:43.020",
"Id": "71783",
"Score": "1",
"body": "`That's not a valid HTML document.` Actually it is valid, HTML, HEAD and BODY tags can be omitted. For HTML when its contents don't start with a comment, for HEAD when it's empty or if the first thing in it is an element, and BODY when it's empty or it's first element is not a comment, not a space and not an element also used in HEAD. It does need a <!DOCTYPE html> tag to make it valid HTML. http://www.w3.org/TR/html/semantics.html#the-html-element and it's containing links to the head and body elements show when they can be omitted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T19:03:37.587",
"Id": "71812",
"Score": "0",
"body": "@RinzeSmits: Even the restrictions about elements starting with a comment are overstating it; they are only for cases where you care which element is the comment's parent (for instance, if you depend on the comment to be at the beginning of the body as opposed to the end of the head. But being that dependent on comments feels to me like an error all its own). If you don't care, then you can still omit the tags, and the parser will consider the comment to be part of the previous element (or outside the document, which is also allowed)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T10:15:32.363",
"Id": "72476",
"Score": "0",
"body": "@Bobby it's called *[indenting](http://en.wikipedia.org/wiki/Indenting)*, not *intending* ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T10:51:53.230",
"Id": "72482",
"Score": "0",
"body": "@avalancha: Hhaarrrrrrr...my old nemesis strikes again."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T18:41:17.860",
"Id": "41678",
"ParentId": "41669",
"Score": "13"
}
},
{
"body": "<p>If you would put one or more <code>introduceYourself()</code> functions inside your class, then you wouldn't need that many getter-methods. It is easier, and often recommended, to tell the object to do something, don't ask for it's information and then do something with that information. This is a principle called: Tell, don't ask.</p>\n\n<p>Why do you pass $gender variable to your constructor? Aren't all males male and all females female?</p>\n\n<p>Your <code>a.k.a.</code> text is hard-coded into the calling code and not a property of any human. Switching the <code>$malePerson</code> to become a female would print <code>that makes me female a.k.a man</code>. You would have to modify code in several places to fix this, which indicates that this is a \"code smell\".</p>\n\n<p>I really think there are more interesting aspects of females than storing their \"bum\" size. Try their hair color instead.</p>\n\n<p>Rewriting your code a little would create something like this:</p>\n\n<pre><code>$malePerson = new male('male', 'John Doe', '32', 'clear', 'beard', 'adams apple in my throat');\n$femalePerson = new female('female', 'Jane Doe', '28', 'loud', 'big and round', 'small');\n$malePerson->introduceYourself();\n$femalePerson->introduceYourself();\n</code></pre>\n\n<p>As for the introduceYourself code, it could look something like this:</p>\n\n<pre><code>public function introduceYourself() {\n echo \"Hi, my name is $name, $age years of age I talk $talk so I guess that makes me {$this->getGender()}...\";\n}\n</code></pre>\n\n<p>You could override the <code>getGender()</code> method for males and females so that instead of passing the variable to the constructor, the class returns the proper value for this.</p>\n\n<pre><code>public function getGender(){\n return \"female\";\n}\n</code></pre>\n\n<p>You might want to read up on <a href=\"http://www.php.net/manual/en/language.oop5.abstract.php\" rel=\"nofollow\">Class Abstraction</a> in the PHP Manual and consider making your <code>Human</code> class into an abstract class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T22:07:04.200",
"Id": "71720",
"Score": "4",
"body": "Simon, thanks for the comment. The Tell, don't ask principle, it actually makes sense, never thought about it before. It will certainly improve my future code"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T19:33:00.913",
"Id": "41681",
"ParentId": "41669",
"Score": "9"
}
},
{
"body": "<p>An abstract class forces the parent class to be extended. For instance, in general, you cannot have a human that does not have a declared gender so you can write your code as such:</p>\n\n<pre><code>abstract class Human {\n private $name;\n\n function __construct($name) {\n $this->name = $name;\n }\n\n\n abstract protected function getGender(); // let's say the gender is a secret, only the human and his/her ancestors know what gender this person is ;-)\n protected function getName() {\n return $this->name;\n }\n\n protected function echoInfo() {\n echo \"My name is \" . $this->getName() . \" and because you are a really close friend, I will let you know I am a \" . $this->getGender() . \".\";\n }\n}\n\n\nclass FemaleHuman extends Human {\n protected function getGender() { return \"female\"; }\n}\n\nclass MaleHuman extends Human {\n protected function getGender() { return \"male\"; }\n}\n\n\n$me = new MaleHuman(\"Jonathan\");\n\n$me->echoInfo(); // returns My name is Jonathan and because you are a really close friend, I will let you know that I am a male.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T04:26:36.853",
"Id": "41712",
"ParentId": "41669",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41681",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T17:03:46.447",
"Id": "41669",
"Score": "13",
"Tags": [
"php",
"object-oriented",
"beginner"
],
"Title": "Human class implementation"
}
|
41669
|
<p>I've updated code from a couple weeks back so I've come back to get more feedback. The original post can be found over here:</p>
<p><a href="https://codereview.stackexchange.com/questions/41021/approximating-sorting-groups-of-dates-into-buckets-general-js-patterns-style">Approximating/Sorting groups of dates into buckets</a></p>
<pre><code>/*
* @Author: Gowiem
* @Date: 2013-12-17 14:21:17
*/
var Hist = Hist || {};
// Timeline Utils
//////////////////
Hist.TLUtils = (function() {
var timeConversions = { "year": 31557600000,
"month": 2628000000,
"day": 86400000 };
var pubConvertTime = function(howMany, type) {
if (timeConversions.hasOwnProperty(type)) {
return howMany * timeConversions[type];
} else {
console.assert(false, "Hist.TLUtils.convertTime was given unknown type: ", type);
}
};
var pubRoundToDecade = function(date, shouldFloor) {
var year = date.getFullYear(),
remainder = year % 10,
roundedYear = shouldFloor ? (year - remainder) - 10 : (year - remainder) + 10,
roundedDate = new Date(date.getTime()).setFullYear(roundedYear);
return roundedDate;
};
var pubGenerateRandomId = function() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
};
return {
roundToDecade: pubRoundToDecade,
convertTime: pubConvertTime,
generateRandomId: pubGenerateRandomId
};
})();
// Timeline Objects
////////////////////
Hist.TLO = Hist.TLO || {};
Hist.TLO.range = function(beginEpoch, endEpoch) {
return {
begin: new Date(beginEpoch),
end: new Date(endEpoch),
differenceInYears: new Date(endEpoch).getYear() - new Date(beginEpoch).getYear(),
halfwayDate: new Date(beginEpoch + ((endEpoch - beginEpoch)/2)),
toString: function() {
return "Range - begin: " + this.begin.toString() + " end: " + this.end.toString() + " halfwayDate: " + this.halfwayDate.toString();
}
};
};
// Our Collection of Point Objects
Hist.TLO.pointCollection = function(pages) {
var collection = {},
allPoints = [],
current = [],
pointPositions = {},
point,
// Util Aliases
roundToDecade = Hist.TLUtils.roundToDecade,
// TLO Aliases
timelinePoint = Hist.TLO.timelinePoint,
multiPoint = Hist.TLO.multiPoint;
// Loop through the given pages and construct our timeline points
pages.forEach(function(page, idx) {
point = timelinePoint(page);
if (point.isValid()) {
allPoints.push(point);
current.push(point);
}
});
// Iterates through the timeline points to find their x and y positions
// and stores them in pointPositions for later use.
// Returns { point.id => { x: xPos, y: yPos }, ... }
var buildPointPositions = function(timelineRange) {
var self = this,
rangeDifference = timelineRange.differenceInYears,
yPositions = {},
xPos, yPos, approximaterMod;
// Ranges:
// 80+ years: buckets of 5 years
// 60+ years: buckets of 4 years
// 45+ years: buckets of 3 years
// 30+ years: buckets of 2 years
// 20+ years: Buckets of 1 years
// TODO: Below are messed up. Need to be fixed
// 10+ years: Buckets of
// 4+ years: Buckets of
// 4- years: No Range, Only stack if in same month
if (rangeDifference >= 80) {
approximaterMod = 10;
console.log("=========== range is 80+");
} else if (rangeDifference >= 60) {
approximaterMod = 8;
console.log("=========== range is 60+");
} else if (rangeDifference >= 45) {
approximaterMod = 6;
console.log("=========== range is 45+");
} else if (rangeDifference >= 30) {
approximaterMod = 4;
console.log("=========== range is 30+");
} else if (rangeDifference >= 20) {
approximaterMod = 2;
console.log("=========== range is 20+");
} else if (rangeDifference >= 10) {
approximaterMod = 6;
console.log("=========== range is 10+");
} else if (rangeDifference >= 4) {
approximaterMod = 2;
console.log("=========== range is 4+");
} else {
approximaterMod = null
console.log("=========== range is 4-");
}
this.current.forEach(function(point, outerIndex) {
xPos = null;
if (rangeDifference > 20) {
xPos = point.approxDateYear(approximaterMod);
} else if (rangeDifference >= 4) {
xPos = point.approxDateMonth(approximaterMod);
} else {
xPos = point.date;
}
if (xPos) {
if (yPositions[xPos.toString()]) {
yPos = yPositions[xPos.toString()];
yPositions[xPos.toString()]++;
} else {
yPos = 0;
yPositions[xPos.toString()] = 1;
}
// Set the x and y position of the current point
self.pointPositions[point.id] = { 'x': xPos, 'y': yPos }
}
});
}
var clearPointPositions = function() {
this.pointPositions = {};
}
// TODO: Probably a smarter way of making this reusable for both 'this.current'
// and the pointsDup in buildPointPosn. Can't think of it now.
var hidePointWithId = function(pId, points) {
var pointId = parseInt(pId),
points = points || this.current;
return points.filter(function(p) {
return pointId !== p.id;
});
}
var filterInRange = function(range) {
this.current = this.allPoints.filter(function(point, idx) {
return point.withinRange(range);
});
}
var addMultiPoints = function(yearsToAdd) {
var self = this,
mPoint;
yearsToAdd = yearsToAdd.unique();
yearsToAdd.forEach(function(year, idx) {
mPoint = multiPoint(year);
self.current.push(mPoint);
self.pointPositions[mPoint.id] = { x: year, y: Hist.TL.config.maxOfStacked };
});
}
var replaceMaxStacked = function() {
var yearsToAddMultiPoint = [],
positionKeys = Object.keys(this.pointPositions),
self = this,
xPos,
yPos;
positionKeys.forEach(function(pId, idx) {
xPos = self.pointPositions[pId]['x'];
yPos = self.pointPositions[pId]['y'];
if (yPos >= Hist.TL.config.maxOfStacked) {
yearsToAddMultiPoint.push(xPos);
self.current = self.hidePointWithId(pId);
}
});
// Now that we've remove the points which were stacked too high we can
// add back the multiPoints in their place.
this.addMultiPoints(yearsToAddMultiPoint);
}
// Fields
collection.allPoints = allPoints;
collection.current = current;
collection.pointPositions = pointPositions;
// Methods
collection.buildPointPositions = buildPointPositions;
collection.clearPointPositions = clearPointPositions;
collection.filterInRange = filterInRange;
collection.hidePointWithId = hidePointWithId;
collection.replaceMaxStacked = replaceMaxStacked;
collection.addMultiPoints = addMultiPoints;
return collection;
}
// Our Point object
Hist.TLO.timelinePoint = function(page) {
var point = {};
// This is the kind of code you have to write when people use a table to
// represent a simple string. Seriously though, da fuq!
// TODO: I can do this simpler with an array.. doh.
var findType = function(categoryId) {
switch (categoryId) {
case 1:
return 'person';
case 2:
return 'project';
case 3:
return 'organization';
case 4:
return 'event';
default:
return null;
}
};
point.id = page['pk'];
point.name = page['fields']['name'] || page['name'];
point.vanityUrl = page['fields']['vanity_url'] || page['vanityUrl'];
point.description = page['fields']['description'] || page['description'];
point.date = moment(page['fields']['date_established']) || moment();
point.type = findType(page['fields']['type']) || page['type'];
point.pointImage = "/static/img/timeline/" + point.type + "-button.png";
var toString = function() {
return "Point -> id: " + this.id + " name: " + this.name + " date: " + this.date.format('l') + " type: " + this.type;
};
var isValid = function() {
return this.type !== null && !!page['fields']['date_established'];
};
var approxDateYear = function(mod) {
var year = this.date.year(),
remainder = year % mod,
halfMod = mod / 2;
if (remainder <= halfMod) {
return new Date(year - remainder, 0);
} else {
return new Date(year - remainder + halfMod, 0);
}
};
var approxDateMonth = function(mod) {
var month = this.date.month(),
remainder = month % mod,
halfMod = mod / 2;
if (remainder <= halfMod) {
return new Date(this.date.year(), month - remainder);
} else {
return new Date(this.date.year(), month - remainder + halfMod);
}
};
var withinRange = function(range) {
return this.date.isAfter(range.begin) && this.date.isBefore(range.end) ||
this.date.isSame(range.begin) ||
this.date.isSame(range.end);
};
var isSameMonthAsPoint = function(point) {
return this.date.isSame(point.date, 'year') && this.date.isSame(point.date, 'month');
}
var isSameDayAsPoint = function(point) {
return this.date.isSame(point.date, 'year') && this.date.isSame(point.date, 'month') && this.date.isSame(point.date, 'day');
}
point.toString = toString;
point.isValid = isValid;
point.withinRange = withinRange;
point.isSameMonthAsPoint = isSameMonthAsPoint;
point.isSameDayAsPoint = isSameDayAsPoint;
point.approxDateYear = approxDateYear;
point.approxDateMonth = approxDateMonth;
return point;
}
Hist.TLO.multiPoint = function(year) {
var pointDefaults = { name: "Multiple Available", vanityUrl: null,
description: "Multiple Available", type: 'multi',
fields: {} },
point = Hist.TLO.timelinePoint(pointDefaults);
point.id = Hist.TLUtils.generateRandomId();
point.date = moment(new Date(year, 5));
return point;
}
// Timeline
////////////
Hist.TL = (function() {
var margin = {top: 90, right: 30, bottom: 90, left: 30},
width = 960,
height = 300,
maxOfStacked = 4,
pointSize = 25,
yPosMargin = 30,
pointClicked = false,
timelinePoints,
brush,
xAxis,
xScale,
beginning,
ending,
chart,
// Alias our TimelineUtils methods
roundToDecade = Hist.TLUtils.roundToDecade,
// Alias our Timeline Objects
pointCollection = Hist.TLO.pointCollection,
timelinePoint = Hist.TLO.timelinePoint,
multiPoint = Hist.TLO.multiPoint;
var initD3Chart = function() {
var jsDates = timelinePoints.current.map(function(p) { return p.date.toDate(); });
beginning = roundToDecade(d3.min(jsDates), true);
ending = roundToDecade(d3.max(jsDates));
chart = d3.select('#timeline')
.attr('width', width)
.attr('height', height)
.append("g")
.attr("transform", "translate(" + margin.left + ",0)");
xScale = d3.time.scale()
.nice(d3.time.year, 100)
.domain([beginning, ending])
.range([0, width - margin.right - margin.left]);
xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom");
chart.append("g")
.attr("class", "x axis")
.attr('transform', 'translate(0,' + (height - margin.bottom) + ')')
.call(xAxis);
timelinePoints.buildPointPositions(Hist.TLO.range(beginning, ending));
// Replace the points which are stacked too high with multiPoints
timelinePoints.replaceMaxStacked();
var points = chart.selectAll(".timeline-point").data(timelinePoints.current);
points.enter()
.append("image")
.attr("class", "timeline-point")
.attr("id", function(p) { return 'point-' + p.id; })
.attr("x", getXPosition)
.attr("y", getYPosition)
.attr("cx", getXPosition)
.attr("cy", getYPosition)
.attr("height", pointSize)
.attr("width", pointSize)
.attr("xlink:href", function(p) { return p.pointImage; })
.on("mouseover", showActiveState)
.on("mouseout", hideActiveState)
.on("click", setClicked);
initContextArea();
}
var draw = function(range) {
var points;
// Create out pointPositions object
timelinePoints.clearPointPositions();
timelinePoints.buildPointPositions(range);
// Replace the points which are stacked too high with multiPoints
timelinePoints.replaceMaxStacked();
// Remove the current points
chart.selectAll(".timeline-point").remove();
// Set the newly filtered points as our new data
points = chart.selectAll(".timeline-point").data(timelinePoints.current);
points.enter()
.append("image")
.attr("class", "timeline-point")
.attr("id", function(p) { return 'point-' + p.id; })
.attr("x", getXPosition)
.attr("y", getYPosition)
.attr("cx", getXPosition)
.attr("cy", getYPosition)
.attr("height", pointSize)
.attr("width", pointSize)
.attr("xlink:href", function(p) { return p.pointImage; })
.on("mouseover", showActiveState)
.on("mouseout", hideActiveState)
.on("click", setClicked);
}
// D3 Plotting Helpers
///////////////////////
var getXPosition = function(point) {
var date = timelinePoints.pointPositions[point.id]['x'];
return xScale(date) - (pointSize / 2);
}
var getYPosition = function(point) {
// height - bottom => xAxis line
// xAxis line - yPosMargin => Starting yPos for a 0 count point
// starting yPos - (yPos[id] * pointSize) => final yPosition
return height - margin.bottom - yPosMargin - (pointSize * timelinePoints.pointPositions[point.id]['y']);
}
// SVG Brush Helpers
/////////////////////
var initContextArea = function() {
var contextWidth = 600,
contextHeight = 30,
contextTickSize = 30,
contextXAxis,
contextXScale,
contextArea,
context;
contextXScale = d3.time.scale()
.range([0, contextWidth])
.domain(xScale.domain());
contextXAxis = d3.svg.axis()
.scale(contextXScale)
.tickSize(contextTickSize)
.tickPadding(5)
.orient("bottom");
contextArea = d3.svg.area()
.interpolate("monotone")
.x(function(d) { return contextXScale(d); })
.y0(contextHeight)
.y1(0);
brush = d3.svg.brush()
.x(contextXScale)
.extent([beginning, ending])
.on("brushend", brushended);
context = d3.select("#timeline").append("g")
.attr("class", "context")
.attr("transform", "translate(" + (width / 2 - contextWidth / 2) + "," + (height - margin.bottom + 25) + ")");
context.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0,0)")
.call(contextXAxis);
gBrush = context.append("g")
.attr("class", "brush")
.call(brush)
.call(brush.event);
gBrush.selectAll("rect")
.attr('transform', 'translate(0,0)')
.attr("height", contextTickSize);
}
var brushended = function() {
var extent0 = brush.extent(),
begin = extent0[0],
end = extent0[1],
range = Hist.TLO.range(begin, end);
xScale.domain([begin, end]);
xAxis.scale(xScale);
chart.select(".x.axis").call(xAxis);
timelinePoints.filterInRange(range);
draw(range);
}
// Timeline Interaction Helpers
////////////////////////////////
// TODO: Pull out to own module and merge with Hist.TL on init
var initDomEventHandlers = function() {
// Clicked away from a point handler, sets the state to inactive
$("body").live("click", function(){
var activePoint = $('#timeline').data('active-point'),
activeEl;
setUnclicked();
if (activePoint) {
activeEl = $('#point-' + activePoint.id)[0];
hideActiveState.call(activeEl, activePoint);
}
});
}
var setClicked = function(point) {
pointClicked = true;
// Stop the event from bubbling up to body where we have a click handler to
// deactivate the current point. d3.event is the current event for this click
d3.event.stopPropagation();
}
var setUnclicked = function() {
pointClicked = false;
}
// Active State - Mousing over or clicked
var showActiveImage = function(element, point) {
var hoverImageUrl = point.pointImage.replace(/(.*)\.png/, "$1-hover.png");
d3.select(element).attr("xlink:href", hoverImageUrl);
}
var addDescriptionToPoint = function(description) {
if (description.length <= 200) {
$('.regular-point .description').text(description);
} else {
$('.regular-point .description').text(description.substring(0, 200) + "...");
}
}
var showPopup = function(element, point) {
var d3Element = d3.select(element),
leftPos = parseInt(d3Element.attr('x')),
topPos = parseInt(d3Element.attr('y')),
leftOffset,
topOffset,
popupLeft;
// Hide both popups so we aren't showing both.
$('.popup').hide();
if (point.type !== 'multi') {
// Setup the content now so we can grab the height and use it to calculate the topOffset
$('.regular-point h3').text(point.name);
addDescriptionToPoint(point.description);
$('.regular-point .date').text(point.date.format("dddd, MMMM Do YYYY"));
$('.regular-point a').attr('href', "/pages/" + point.vanityUrl);
$('.regular-point').removeClass()
.addClass(point.type)
.addClass("popup")
.addClass("regular-point")
.show();
} else {
$('.multi-point').show();
}
popupHeight = $('#popup-container').height();
leftOffset = (pointSize / 2);
topOffset = (pointSize / 2) + popupHeight + 11; // +11 px is for padding I think..
// Now that we have the offset we can find the absolute position of the popup
popupLeft = leftPos + pointSize + leftOffset + 'px';
popupTop = topPos + pointSize - topOffset + 'px';
$('#popup-container').css({ left: popupLeft, top: popupTop }).show()
}
var showActiveState = function(point) {
// We just moused into a point, clear the last clicked point (if any)
setUnclicked();
if ($('#timeline').data('active-point')) {
// Passing null here as hideActiveImage will find the element from the given point.id
hideActiveImage(null, $('#timeline').data('active-point'));
}
// Set the hover point image and configure/show the popup
showActiveImage(this, point);
showPopup(this, point);
// Store the currently active point so we can deactive it later
$('#timeline').data('active-point', point);
}
// Deactive State
//////////////////
var hideActiveImage = function(element, point) {
// If we weren't passed the element then find it by the given point.id, otherwise select it
d3El = element === null ? d3.select('#point-' + point.id) : d3.select(element);
d3El.attr("xlink:href", point.pointImage);
}
var hidePopup = function() {
$('#popup-container').hide();
}
var hideActiveState = function(point) {
// If we are currently focusing on a point (have clicked it) then we don't
// want to hide the active state.
if (!pointClicked) {
hideActiveImage(this, point);
hidePopup();
}
}
// Public Interface
////////////////////
return {
init: function() {
if (Hist.rawPages != null) {
timelinePoints = pointCollection(Hist.rawPages);
initD3Chart();
initDomEventHandlers();
}
},
config: {
maxOfStacked: maxOfStacked
}
}
})();
</code></pre>
<p><a href="http://jsfiddle.net/GowGuy47/9j98E/5/" rel="nofollow noreferrer">jsFiddle</a></p>
<p>Here are the few things I'm looking to get feedback on:</p>
<ul>
<li><p><code>pointCollection#buildPointPositions</code> - This is the main issue I struggled with originally. It was previously running in \$O(n^2)\$ but I've gotten it down to \$O(n)\$ (I think) and it's much faster now. I'm still not extremely happy with it so critique away. </p></li>
<li><p>General JavaScript pattern/style</p></li>
<li><p>D3.js specific stuff. How could I have made this cooler? Could I have animated the timeline points moving positions somehow instead of removing everything and redrawing? Any comments on the D3 code in general? This is the first thing I've wrote with that library so I'm interested in that feedback. </p></li>
</ul>
|
[] |
[
{
"body": "<p>For this</p>\n\n<pre><code>if (rangeDifference >= 80) {\n approximaterMod = 10;\n console.log(\"=========== range is 80+\");\n} else if (rangeDifference >= 60) {\n approximaterMod = 8;\n console.log(\"=========== range is 60+\");\n} else if (rangeDifference >= 45) {\n approximaterMod = 6;\n console.log(\"=========== range is 45+\");\n} else if (rangeDifference >= 30) {\n approximaterMod = 4;\n console.log(\"=========== range is 30+\");\n} else if (rangeDifference >= 20) {\n approximaterMod = 2;\n console.log(\"=========== range is 20+\");\n} else if (rangeDifference >= 10) {\n approximaterMod = 6; \n console.log(\"=========== range is 10+\");\n} else if (rangeDifference >= 4) {\n approximaterMod = 2;\n console.log(\"=========== range is 4+\");\n} else {\n approximaterMod = null\n console.log(\"=========== range is 4-\");\n}\n</code></pre>\n\n<p>You could use a datastructure to store your values:</p>\n\n<pre><code>var ranges = [\n {limit: 80, mod: 10}, \n {limit: 60, mod: 8}, \n {limit: 45, mod: 6}, \n {limit: 30, mod: 4}, \n {limit: 20, mod: 2}, \n {limit: 10, mod: 6}, \n {limit: 4, mod: 2}, \n {limit: null, mod: null}\n ];\nfor(var i = 0; i < ranges.length; i++){\n var range = ranges[i];\n if(rangeDifference >= range.limit || range.limit === null){\n approximaterMod = range.mod;\n if(range.limit !== null){\n console.log(\"=========== range is \"+range.limit+\"+\");\n } else {\n console.log(\"=========== range is \"+ranges[i-1].limit+\"-\");\n }\n break;\n }\n}\n</code></pre>\n\n<p>By doing so, it's easier to see what difference maps to what mod value. It looks like a complex for loop at the moment, but that's because of the handling for your console logging... if we could take that out, it would look like so:</p>\n\n<pre><code>var ranges = [\n {limit: 80, mod: 10}, \n {limit: 60, mod: 8}, \n {limit: 45, mod: 6}, \n {limit: 30, mod: 4}, \n {limit: 20, mod: 2}, \n {limit: 10, mod: 6}, \n {limit: 4, mod: 2}\n ];\napproximaterMod = null;\nfor(var i = 0; i < ranges.length; i++){\n var range = ranges[i];\n if(rangeDifference >= range.limit){\n approximaterMod = range.mod;\n break;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-25T13:12:10.290",
"Id": "121080",
"ParentId": "41671",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T17:24:52.247",
"Id": "41671",
"Score": "3",
"Tags": [
"javascript",
"performance",
"datetime",
"d3.js"
],
"Title": "Approximating Date for a D3.js timeline"
}
|
41671
|
<p>Recently I started learning programming and I created this program. I've added something to it with every new lesson.</p>
<p>How is my code-writing? Do I make mistakes I shouldn't make?</p>
<p><a href="https://docs.google.com/file/d/0B2KzxpPhm9AQalZ2YXViVkZ4Q1k/edit" rel="nofollow">The program itself</a></p>
<pre><code>static void Main()
{
{
Console.WriteLine("Select language:\n");
Console.WriteLine("1. Bulgarian");
Console.WriteLine("2. English\n");
Console.Write("Number: ");
byte language = byte.Parse(Console.ReadLine());
//....
//Skipped to
//English
if (language == 2)
{
Console.Clear();
string restart = "Press any key to exit the program...";
Console.CursorVisible = true;
string chislo = "Please press the number that corresponds to the function:";
Console.WriteLine(chislo);
Console.WriteLine();
Console.WriteLine("1. Balance calculator");
Console.WriteLine("2. Calculating numbers");
Console.WriteLine("3. Comparing numbers");
Console.WriteLine("4. Time and Date");
Console.WriteLine("5. Calculation of the number of words and characters from a text/sentence \n");
Console.WriteLine("Settings:\n");
Console.WriteLine("6. Change the color of the console \n");
Console.Write("Number: ");
string chisloFunkciq = Console.ReadLine();
int chisloFunkciqParse;
if (int.TryParse(chisloFunkciq, out chisloFunkciqParse))
{
Console.Clear();
//Funkciq Saldo
if (chisloFunkciqParse == 1)
{
Console.WriteLine("You chose \"Balance calculator\" \n");
bool check = true;
while (check == true)
{
Console.Write("Enter the opening balance: ");
string nachalnoSaldo = Console.ReadLine();
double chisloNachalnoSaldo;
if (double.TryParse(nachalnoSaldo, out chisloNachalnoSaldo))
{
Console.WriteLine();
Console.WriteLine("Your opening balance is {0:C} \n", chisloNachalnoSaldo);
}
else
{
Console.CursorVisible = false;
Console.Clear();
Console.Beep();
Console.WriteLine("\"{0}\" is not a number. Please try again. \n", nachalnoSaldo);
continue;
}
//Prihodi
Console.Write("Enter revenue: ");
string prihodi = Console.ReadLine();
Console.WriteLine();
double chisloPrihodi;
if (double.TryParse(prihodi, out chisloPrihodi))
{
Console.WriteLine("Your revenue is {0:C} \n", chisloPrihodi);
}
else
{
Console.CursorVisible = false;
Console.Clear();
Console.Beep();
Console.WriteLine("\"{0}\" is not a number. Please try again.\n", prihodi);
continue;
}
//Izrazhodvano saldo
Console.Write("Enter consumption balance: ");
string izrazhodvanoSaldo = Console.ReadLine();
Console.WriteLine();
double chisloKrainoSaldo;
if (double.TryParse(izrazhodvanoSaldo, out chisloKrainoSaldo))
{
Console.WriteLine("Your consumption balance is {0:C} \n", chisloKrainoSaldo);
}
else
{
Console.CursorVisible = false;
Console.Clear();
Console.Beep();
Console.WriteLine("\"{0}\" is not a number. Please try again. \n", izrazhodvanoSaldo);
continue;
}
//Rezultat
double rezultat = (chisloNachalnoSaldo + chisloPrihodi) - chisloKrainoSaldo;
Console.WriteLine("The remaining balance is {0:C} \n", rezultat);
check = false;
Console.CursorVisible = false;
Console.WriteLine(restart);
Console.ReadKey();
Console.Clear();
}
}
// Funkciq Calculator
if (chisloFunkciqParse == 2)
{
Console.WriteLine("You chose \"Calculating numbers\" \n");
double otgovor = 0;
Console.Write("Please enter the first number: ");
double purvoChislo = double.Parse(Console.ReadLine());
Console.WriteLine();
Console.Write("Please enter a character (+, -, * ili /): ");
string znak = Console.ReadLine();
Console.WriteLine();
Console.Write("Please enter the second number: \n");
double vtoroChislo = double.Parse(Console.ReadLine());
switch (znak)
{
case "+":
otgovor = purvoChislo + vtoroChislo;
break;
case "-":
otgovor = purvoChislo - vtoroChislo;
break;
case "*":
otgovor = purvoChislo * vtoroChislo;
break;
case "/":
otgovor = purvoChislo / vtoroChislo;
break;
}
Console.WriteLine("{0} {1} {2} = {3}", purvoChislo, znak, vtoroChislo, otgovor);
Console.WriteLine(restart);
Console.ReadKey();
Console.Clear();
}
//Sravnavane na chisla (2,3 ili 4)
if (chisloFunkciqParse == 3)
{
Console.Clear();
Console.WriteLine("You chose \"Comparing numbers\" \n");
Console.WriteLine("1. Comparing 2 numbers");
Console.WriteLine("2. Comparing 3 numbers");
Console.WriteLine("3. Comparing 4 numbers");
int chisloBroi = int.Parse(Console.ReadLine());
switch (chisloBroi)
{
case 1:
int sravPurvoChislo;
int sravVtoroChislo;
int sravTretoChislo;
int sravChetvurtoChislo;
Console.WriteLine("You chose \"Comparing 2 numbers\" \n");
Console.Write("Please enter the first number: ");
sravPurvoChislo = int.Parse(Console.ReadLine());
Console.WriteLine();
Console.WriteLine("Please enter the second number: ");
sravVtoroChislo = int.Parse(Console.ReadLine());
Console.WriteLine("{0} is bigger than {1}", Math.Max(sravPurvoChislo, sravVtoroChislo), Math.Min(sravPurvoChislo, sravVtoroChislo));
Console.WriteLine(restart);
Console.ReadKey();
Console.Clear();
break;
case 2:
Console.Clear();
Console.WriteLine("You chose \"Comparing 3 numbers\" \n");
Console.Write("Please enter the first number: ");
sravPurvoChislo = int.Parse(Console.ReadLine());
Console.WriteLine();
Console.Write("Please enter the second number: ");
sravVtoroChislo = int.Parse(Console.ReadLine());
Console.WriteLine();
Console.Write("Please enter the third number: ");
sravTretoChislo = int.Parse(Console.ReadLine());
Console.WriteLine("The largest of these numbers is {0}, and the smallest is {1}", Math.Max(Math.Max(sravPurvoChislo, sravVtoroChislo), sravTretoChislo), Math.Min(Math.Min(sravPurvoChislo, sravVtoroChislo), sravTretoChislo));
Console.WriteLine(restart);
Console.ReadKey();
Console.Clear();
break;
case 3:
Console.Clear();
Console.WriteLine("You chose \"Comparing 4 numbers\" \n");
Console.Write("Please enter the first number: ");
sravPurvoChislo = int.Parse(Console.ReadLine());
Console.WriteLine();
Console.Write("Please enter the second number: ");
sravVtoroChislo = int.Parse(Console.ReadLine());
Console.WriteLine();
Console.Write("Please enter the third number: ");
sravTretoChislo = int.Parse(Console.ReadLine());
Console.WriteLine();
Console.Write("Please enter the fourth number: ");
sravChetvurtoChislo = int.Parse(Console.ReadLine());
int purviIzraz = Math.Max(sravPurvoChislo, sravVtoroChislo);
int vtoriIzraz = Math.Max(sravTretoChislo, sravChetvurtoChislo);
Console.WriteLine("The largest of these numbers is {0}, and the smallest is {1}", Math.Max(purviIzraz, vtoriIzraz), Math.Min(purviIzraz, vtoriIzraz));
Console.WriteLine(restart);
Console.ReadKey();
Console.Clear();
break;
}
}
//Funkciq Data
if (chisloFunkciqParse == 4)
{
Console.WriteLine("Today is {0} \n", DateTime.Now);
Console.WriteLine(restart);
Console.ReadKey();
Console.Clear();
}
//Funkciq Presmqtane na broi dumi i znaci ot tekst
if (chisloFunkciqParse == 5)
{
Console.Write("Please enter a text/sentence ");
string izrechenie = Console.ReadLine();
Console.WriteLine();
int broiDumi = izrechenie.Split(' ').Length;
int broiZnaci = izrechenie.Length;
if (broiDumi == 1)
{
Console.Write("This text contains {0} word and ", broiDumi);
}
else
{
Console.Write("The text contains {0} words and ", broiDumi);
}
if (broiZnaci == 1)
{
Console.WriteLine("{0} character", broiZnaci);
}
else
{
Console.WriteLine("{0} characters", broiZnaci);
}
Console.WriteLine();
Console.WriteLine(restart);
Console.ReadKey();
Console.Clear();
}
//Cvqt Konzola
if (chisloFunkciqParse == 6)
{
bool check = true;
while (check == true)
{
Console.WriteLine("Choose the number corresponding to the color you want:\n");
Console.WriteLine("1. Red");
Console.WriteLine("2. Green");
Console.WriteLine("3. Yello");
Console.WriteLine("4. Return to the previous settings (Black)\n");
Console.Write("Number: ");
string cvqtChislo = Console.ReadLine();
int cvqtChisloParse;
if (int.TryParse(cvqtChislo, out cvqtChisloParse))
{
switch (cvqtChisloParse)
{
case 1:
Console.BackgroundColor = ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.Black;
Console.Clear();
Console.WriteLine("You chose red");
Console.WriteLine();
Main();
break;
case 2:
Console.BackgroundColor = ConsoleColor.Green;
Console.ForegroundColor = ConsoleColor.Black;
Console.Clear();
Console.WriteLine("You chose green");
Console.WriteLine();
Main();
break;
case 3:
Console.BackgroundColor = ConsoleColor.Yellow;
Console.ForegroundColor = ConsoleColor.Black;
Console.Clear();
Console.WriteLine("You chose yellow");
Console.WriteLine();
Main();
break;
case 4:
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Gray;
Console.Clear();
Console.WriteLine("You chose the default color (black)");
Console.WriteLine();
Main();
break;
default:
Console.CursorVisible = false;
Console.Clear();
Console.Beep();
break;
}
continue;
}
else
{
Console.CursorVisible = false;
Console.Clear();
Console.Beep();
}
}
}
if (chisloFunkciqParse > 6)
{
Console.CursorVisible = false;
Console.Beep();
Console.Clear();
Main();
}
}
else
{
Console.Clear();
Console.WriteLine("You did not specify a number. Please try again \n");
Console.CursorVisible = false;
Console.Beep();
Main();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T19:40:08.797",
"Id": "71681",
"Score": "1",
"body": "Hey there. How about putting up specific parts of your code you would like reviewed. I think you will find this question will get closed otherwise. If there are lots of parts you would like reviewed you could make multiple questions etc"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T19:45:46.753",
"Id": "71685",
"Score": "0",
"body": "Indeed right, @dreza. For more information as to why, see [this meta-question](http://meta.codereview.stackexchange.com/questions/1308/can-i-put-my-code-on-a-third-party-site-and-link-to-the-site-in-my-question) We would love to review your code, new user, but please extract some parts of the code and post them within the question itself :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T19:54:06.497",
"Id": "71697",
"Score": "1",
"body": "That's better, thank you, new user! Just by looking over the code quickly I think there's several things that can be simplified in it. One of our C# reviewers will probably assist you shortly :) Thank you for flying Code Review airlines, we hope you have a pleasant flight!"
}
] |
[
{
"body": "<p>One thing that I don't like about your code is the recursive call to <code>Main();</code> inside of <code>Main()</code>.</p>\n\n<p>I don't think this is healthy, if the application is run for an extended period of time, or run over and over again you will have issues with memory management. </p>\n\n<p>What happens is the first time through you start a thread and then never fully release the thread before you call another thread, so you lock the memory that was being used and it isn't deallocated/destroyed. </p>\n\n<p>Instead of doing this, you should wrap the entire application in a single <code>while</code> loop based on a Boolean variable that you can change to false when you want to exit the program.</p>\n\n<hr>\n\n<p>I am not completely sure what is going on here.</p>\n\n<pre><code>static void Main()\n {\n {\n Console.WriteLine(\"Select language:\\n\");\n Console.WriteLine(\"1. Bulgarian\");\n Console.WriteLine(\"2. English\\n\");\n Console.Write(\"Number: \");\n byte language = byte.Parse(Console.ReadLine());\n //....\n</code></pre>\n\n<ol>\n<li>Why is there two starting Brackets?</li>\n<li>Why do you indent the first bracket?\n<ul>\n<li>is this preference in the coding?</li>\n<li>personally this would confuse me a little bit</li>\n</ul></li>\n</ol>\n\n<p>I would write it like this</p>\n\n<pre><code>static void Main()\n{\n Console.WriteLine(\"Select language:\\n\");\n Console.WriteLine(\"1. Bulgarian\");\n Console.WriteLine(\"2. English\\n\");\n Console.Write(\"Number: \");\n byte language = byte.Parse(Console.ReadLine());\n //....\n</code></pre>\n\n<p>And with that, I think that you are missing a bracket at the end if you intentionally doubled up the bracket (I think doubling up the brackets might irritate the compiler; I have never tried so I don't know for sure).</p>\n\n<p>Other than that, the syntax looks good and isn't missing any semi-colons, and doesn't have any other weird indentations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T20:59:10.347",
"Id": "71711",
"Score": "1",
"body": "Thanks for the suggestions! As for the brackets, I deleted some of the code so it can fit here and I didn't delete the brackets, sorry about that :) I've never made such a big program and things have turned into a spaghetti bowl, but I am getting used to it. So buy adding a loop you mean creating this: `bool check = true while (check == true) { //include everything here ? }`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T21:07:30.250",
"Id": "71713",
"Score": "0",
"body": "Yes. Inside the block you can alter `check` so that the code can exit the loop when you need it to."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T21:15:41.997",
"Id": "71715",
"Score": "1",
"body": "Ok I think I get it, thank you very much :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T20:23:59.757",
"Id": "41689",
"ParentId": "41680",
"Score": "7"
}
},
{
"body": "<p>I would at least break out the functions listed in the second menu into their own methods. With option 1 : Balance Calculator for example, you could break out all of the code within this statement:</p>\n\n<pre><code>if (chisloFunkciqParse == 1) \n{\n RunBalanceCalculator();\n}\n\nprivate void RunBalanceCalculator()\n{\n //TODO Paste everything that was originally in the above if statement.\n}\n</code></pre>\n\n<p>This will at least break your code out into logical groupings by function. If this were a real system and not just a learning program, I would also recommend that you break out presentation from the logic as well, but that is for after you get more familiar with object oriented programming.</p>\n\n<p>Also, some of the code could be condensed so that you're following the <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\">DRY</a> principle. For example, the code for option 3 could be made dynamic with a function like this:</p>\n\n<pre><code>private void CompareNumbers(params int[] numbers)\n{\n //TODO Write the algorithm to compare all of the numbers in the array\n} \n</code></pre>\n\n<p>Then, you can call this method from each of the case statements condensing similar code into one place making it easier to maintain if there is a bug. This will also bring forth the need for validating the input you get. The current code looks like it would break if the user typed a non-numeric character.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T23:38:18.210",
"Id": "71731",
"Score": "0",
"body": "All of my +1. The first thing I thought on seeing this method was 'Dear lord, that thing is huge!'"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T08:44:57.880",
"Id": "71750",
"Score": "0",
"body": "Haha! Ok, I'll do that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T22:46:30.857",
"Id": "41697",
"ParentId": "41680",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T19:32:57.013",
"Id": "41680",
"Score": "5",
"Tags": [
"c#",
"beginner",
"console"
],
"Title": "Console-based menu system"
}
|
41680
|
<p>I have a SQL query that returns a recordset with between 2 and 5 million records and I need to write that to a .csv file.</p>
<p>I wrote the following procedure and I'm curious to see if there is a better / more efficient way to do this.</p>
<pre><code>Dim conn As New OracleConnection()
...
Sub DBExecuteQueryWriteToFile(ByVal SQLCommand As String, ByVal FileName As String, Optional ByVal Delimiter As String = ",")
Dim cmd = New OracleCommand(SQLCommand, conn)
Dim sb As New StringBuilder
Dim x As Integer = 0
Dim CountRow As Integer = 0
If File.Exists(FileName) Then
File.Delete(FileName)
End If
Using FileObject As New FileStream(FileName, FileMode.OpenOrCreate)
Using MStream As New MemoryStream()
Using StreamWriterObj As New StreamWriter(MStream)
Using Reader As OracleDataReader = cmd.ExecuteReader()
Dim FieldCount As Integer = Reader.FieldCount - 1
Do While Reader.Read()
sb.Append(Reader.Item(0))
For i = 1 To FieldCount
sb.Append(Delimiter)
sb.Append(Reader.Item(i))
Next
sb.Append(vbCrLf)
'Write every 25000 rows of data to the file from the buffer
If x = 25000 Then
StreamWriterObj.Write(sb.ToString().ToCharArray())
MStream.Seek(0, SeekOrigin.Begin)
MStream.WriteTo(FileObject)
sb = New StringBuilder()
CountRow = CountRow + x
x = 0
End If
x = x + 1
Loop
'Write any remaining data from the buffer to the file
StreamWriterObj.Write(sb.ToString().ToCharArray())
MStream.WriteTo(FileObject)
Reader.Close()
StreamWriterObj.Close()
MStream.Close()
FileObject.Close()
End Using
End Using
End Using
End Using
End Sub
</code></pre>
<p>Any and all comments and help are geatly appreciated and, also, even though this is written in VB, I'm equally as comfortable with C# solutions.</p>
|
[] |
[
{
"body": "<p>My suggestion would be to break the code that writes to the file out into a separate thread. This would allow you to read the next 25,000 rows while simultaneously writing the 25,000 rows that you've already retrieved. There is a caveat here though that you will want to wait until the previous file writing thread finishes before spawning a new file writing thread so you don't mess up the writing of the file. The performance gains could be minor to significant using this approach depending on the speed of your query, network, CPU and hard drive. If writing to a file is just as fast as returning the next 25,000 rows, you may not find the performance gains worth the additional work of managing a separate thread depending on the amount of milliseconds it takes to do each task. Ultimately though, the best speed you will be able to attain is going to be that of which you can write the file without interruption by the data pull.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T13:50:10.050",
"Id": "72280",
"Score": "0",
"body": "Definitely worthwhile looking into and definitely a smart idea I hadn't thought of!! - Thank you!!! +1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T21:53:16.100",
"Id": "41694",
"ParentId": "41683",
"Score": "1"
}
},
{
"body": "<p>You can simplify the code greatly without loosing any performance, more likely gaining instead.</p>\n\n<p>There is no need to use <code>StringBuilder</code> - you can write directly to the <code>StreamWriter</code> - it will be faster since there will be no need of copy the whole data twice.</p>\n\n<p>Next, there is no need to use <code>MemoryStream</code> - you are using it to buffer data before writing it to the disk. The same can be achieved by specifying the buffer size when creating <code>FileStream</code>. You should play around with the buffer size to see what is fastest on your environment - usually 4KB is used, in the sample below it is 1MB, but you have to try it on your hardware.</p>\n\n<p>You should also play around with the <a href=\"http://msdn.microsoft.com/en-us/library/system.io.fileoptions%28v=vs.110%29.aspx\" rel=\"nofollow\">options how to open</a> <code>FileStream</code>. You should try what impact <code>Asynchronous</code> and <code>WriteThrough</code> has on your solution.</p>\n\n<p>Of course, as the other answer proposed, separating reading from database and writing to the file in two threads might work as well. Try and measure three separate scenarios - just reading from the database (measure separately the query (<code>ExecuteReader()</code> and first <code>Read()</code> and then reading the other rows - because it might be that most of the time is spending to initially execute the query, not to iterate through the data), just writing to the file (dummy data) and then combined. This way you will see if there is actual reason to put the two operations in parallel.</p>\n\n<pre><code>Dim conn As New OracleConnection()\n...\nSub DBExecuteQueryWriteToFile(ByVal SQLCommand As String, ByVal FileName As String, Optional ByVal Delimiter As String = \",\")\n\n Dim cmd = New OracleCommand(SQLCommand, conn)\n Dim bufferSize = 1024*1024; // 1Mb\n\n If File.Exists(FileName) Then\n File.Delete(FileName)\n End If\n\n Using FileObject As New FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, bufferSize)\n Using StreamWriterObj As New StreamWriter(FileObject)\n Using Reader As OracleDataReader = cmd.ExecuteReader()\n Dim FieldCount As Integer = Reader.FieldCount - 1\n\n Do While Reader.Read()\n StreamWriterObj.Write(Reader.Item(0))\n For i = 1 To FieldCount\n StreamWriterObj.Write(Delimiter)\n StreamWriterObj.Write(Reader.Item(i))\n Next\n StreamWriterObj.WriteLine();\n Loop\n\n End Using\n End Using\n End Using\nEnd Sub\n</code></pre>\n\n<p>P.S. few other issues in your code:</p>\n\n<ol>\n<li><code>StringBuilder().ToString().ToCharArray()</code> - no need to convert to char array.</li>\n<li><code>new StringBuilder()</code> - instead of reusing the memory already allocated to the existing builder, you are throwing that away and creating new one.</li>\n<li><code>MStream.Seek()</code> - you are seeking to the beginning of the stream but are not setting <code>Length</code> to 0. So if the second block written there is smaller than first one, junk data will be written to the file.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T13:49:31.127",
"Id": "72279",
"Score": "0",
"body": "ABSOLUTELY AMAZING ANSWER!!! - Thank you **SO MUCH** for taking the time to describe everything and the sample code... Truly, a perfect answer!!! THANK YOU!!!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T18:42:20.273",
"Id": "41746",
"ParentId": "41683",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41746",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T19:42:02.817",
"Id": "41683",
"Score": "4",
"Tags": [
"vb.net"
],
"Title": "Efficent way to Query a DB and write to text file - Large Recordset"
}
|
41683
|
<p>I know of <code>BlockingCollection</code> in .net, but this is rather for my understanding of the pattern. Is this implementation correct ?</p>
<p><strong>Consumer</strong></p>
<pre><code>class Consumer
{
readonly Queue<int> _q;
public Consumer(Queue<int> q)
{
this._q = q;
}
public void Consume()
{
for (int i = 0; i < 10; i++)
{
while (_q.Count == 0)
{
}
Console.WriteLine("consuming " + _q.Dequeue());
}
}
}
</code></pre>
<p><strong>Producer</strong></p>
<pre><code>class Producer
{
readonly Queue<int> _q;
readonly int _maxSize;
public Producer(Queue<int> q, int maxSize)
{
this._q = q;
this._maxSize = maxSize;
}
public void Produce()
{
for (int i = 0; i < 10; i++)
{
while (_q.Count == _maxSize)
{
}
Console.WriteLine("producing " + (i + 1));
_q.Enqueue(i + 1);
}
}
}
</code></pre>
<p><strong>Client</strong></p>
<pre><code>class Program
{
static void Main(string[] args)
{
Queue<int> q = new Queue<int>();
var prod = new Producer(q, 10);
var consumer = new Consumer(q);
var producerThread = new Thread(new ThreadStart(prod.Produce));
producerThread.Start();
var consumerThread = new Thread(new ThreadStart(consumer.Consume));
consumerThread.Start();
}
}
</code></pre>
<p>The way I see it, this handles the race condition in <a href="http://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem#Inadequate_implementation">Inadequate implementation</a> by introducing <code>while</code> instead of <code>if</code></p>
<p>The program runs fine on my machine, so is this correct or am i missing something? why the need for synchronization?</p>
|
[] |
[
{
"body": "<p>The bigest problem is that code <code>while(true){}</code> will eat up all CPU that is available for the thread. Try running your program on a single core machine (it will run fine because you are only producing 10 items but try producing infinite number - they should still be consumed properly). The minimum change should be <code>while(condition) Thread.Yield()</code> or <code>Thread.Sleep()</code>. Yielding will still eat up all CPU but sleeping will put your thread down for longer than might be needed - this is why synchronization is used - to notify the other thread instead of making it sleep and try guessing when the new data will arrive.</p>\n\n<p>More important issue that requires synchronization is that <code>Queue.Enqueue()</code> and <code>Queue.Dequeue()</code> will most probably not be atomic operations - what happens if you enqueue an item while it is dequeing? This is why classes like <code>ConcurrentQueue</code> have been created in .NET Framework.</p>\n\n<p>Next problem is a situation with multiple consumers. Assume two consumers and one item in the queue. If both of them run at the same time, they will both at the same time detect that <code>q.Count == 1</code>. Now the first of them dequeues the only item from the queue. Now the second one tries to dequeue but there is nothing there anymore - it will throw an exception.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T18:02:49.530",
"Id": "41745",
"ParentId": "41684",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41745",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T19:50:34.330",
"Id": "41684",
"Score": "5",
"Tags": [
"c#",
"multithreading",
"reinventing-the-wheel"
],
"Title": "Lock-free producer/consumer implementation"
}
|
41684
|
<p>This code is for Android but I guess anyone can take a chance at it.</p>
<p>It does what I want it to do. Just that I am not comfortable with its deep level of nesting and too much of value swapping.</p>
<p>Can this be optimized for readability or in compactness?</p>
<pre><code>for(int imagenum, imagenum <76, imagenum++){
if (orientation.contentEquals("landscape")
|| orientation.contentEquals("reverse landscape")) {
params.height = imageheight;
params.width = imagewidth;
imageButton.setImageResource(R.drawable.imageback);
if (imagenum <= 38) {
params.leftMargin = imagenum * xspaceforeachimage;
params.topMargin = 0;
} else {
params.leftMargin = (imagenum - 39) * xspaceforeachimage;
params.topMargin = topMargin;
}
} else if (orientation.contentEquals("portrait")
|| orientation.contentEquals("reverse portrait")) {
params.height = imagewidth;
params.width = imageheight;
imageButton.setImageResource(R.drawable.imagebacklaid);
if (imagenum <= 38) {
params.leftMargin = 0;
params.topMargin = imagenum * xspaceforeachimage;
} else {
params.leftMargin = topMargin;
params.topMargin = (imagenum - 39) * xspaceforeachimage;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T18:29:31.643",
"Id": "71689",
"Score": "0",
"body": "What type does `orientation` have?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T18:31:01.610",
"Id": "71690",
"Score": "0",
"body": "It has type `String`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T18:33:50.613",
"Id": "71691",
"Score": "0",
"body": "Something tells me something big is missing from your code above...did you truncate it? If that is literally your code, you don't need a for loop at all--just calculate everything with `imagenum=75`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T18:36:07.080",
"Id": "71692",
"Score": "0",
"body": "You can able to use this line \n orientation.contains(\"landscape\"); \ninstead of this line \n if (orientation.contentEquals(\"landscape\") || orientation.contentEquals(\"reverse landscape\")) \n\nuse same thing for \"portrait\" condition."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T18:37:22.110",
"Id": "71693",
"Score": "0",
"body": "and add a boolean reversed to orientation if you want to know if its reversed"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T18:39:58.583",
"Id": "71694",
"Score": "0",
"body": "@Tenfour04 - what makes me you say that you can calculate everything with imagenum = 75.That is absurd. This code lays down 78 buttons on the screen at different locations. with image num=75, the left and top margin for each button will be the same and they will overlap each other."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T18:47:00.983",
"Id": "71695",
"Score": "1",
"body": "I know it's absurd; that's why I asked if you truncated something. `imageButton` and `params` are never reassigned inside your for loop, so they will result with whatever you give them in the last run of the loop."
}
] |
[
{
"body": "<p>This doesn't save many lines of code, but I think it's more readable and maintainable:</p>\n\n<pre><code>boolean landscape = orientation.contains(\"landscape\");\n\nfor(int imagenum = 0; imagenum <76; imagenum++){\n\n /* Missing code that assigns params and imageButton using imageNum? */\n\n int shortSideMargin = imagenum * xspaceforeachimage;\n int longSideMargin = 0;\n if (imagenum >= 39) { //new row or column, shift back and over\n shortSideMargin -= 39 * xspaceforeachimage;\n longSideMargin = topMargin;\n }\n\n if (landscape) {\n params.height = imageheight;\n params.width = imagewidth;\n params.leftMargin = shortSideMargin;\n params.topMargin = longSideMargin;\n imageButton.setImageResource(R.drawable.imageback);\n } else {\n params.height = imagewidth;\n params.width = imageheight;\n params.leftMargin = longSideMargin;\n params.topMargin = shortSideMargin;\n imageButton.setImageResource(R.drawable.imagebacklaid);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T19:02:24.413",
"Id": "71696",
"Score": "0",
"body": "thanks buddy..definitely much cleaner and readable than mine. thanks for taking time to redo that :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T18:59:52.653",
"Id": "41686",
"ParentId": "41685",
"Score": "1"
}
},
{
"body": "<p>you have:</p>\n\n<pre><code>orientation.contentEquals(\"landscape\"\n</code></pre>\n\n<p>better practice for null safe:</p>\n\n<pre><code>\"landscape\".equals(orientation)\n</code></pre>\n\n<p>even better, use constants or enums!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T01:20:04.117",
"Id": "43573",
"ParentId": "41685",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "41686",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T18:23:36.063",
"Id": "41685",
"Score": "1",
"Tags": [
"java",
"optimization",
"android"
],
"Title": "Setting image margins and location based on orientation"
}
|
41685
|
<p>For educational purposes I wrote a little piece of code to rotate greyscale images as "low level" as possible, that is, not using any <code>rotate()</code> function, but doing the math. I was wondering if it could be improved in any way, specially in order to achieve better performance. I'm not concerned with the libraries or the programming language chosen to perform this task, I am aware that they aren't the best option if what I want is performance. I'm only concerned with the code itself.</p>
<p>It basically maps the pixels on the new image to the ones in the original image and interpolates using nearest neighbor or bilenear.</p>
<pre><code>def affine_t(x, y, a, b, c, d, e, f):
# A lot faster than numpy.dot([[a,b],[c,d]],[x,y])+[e,f]
return round(a*x + b*y + e, 3), round(c*x + d*y + f, 3)
def mrotate(r, cx=0, cy=0):
# Returns the coefficients to an affine transformation which rotates
# a point clockwise by r radians in respect to a central point. For counter
# clockwise, just pass r as -r.
return (math.cos(r), -math.sin(r), math.sin(r), math.cos(r), cx, cy)
def lin_interp(x, x0, x1, y0, y1):
# Faster than numpy.interp()
return y0 + (y1 - y0)*((x-x0)/(x1-x0))
def bilinear(bmp, ox, oy):
# Try to interpolate. If the pixel falls on the image boundary, use the
# nearest pixel value (nearest neighbor).
try:
x0, x1, y0, y1 = int(ox), int(ox)+1, int(oy), int(oy)+1
a = lin_interp(ox, x0, x1, bmp[y0][x0], bmp[y0][x1])
b = lin_interp(ox, x0, x1, bmp[y1][x0], bmp[y1][x1])
except IndexError:
return nn(bmp, ox, oy)
return int(lin_interp(oy, y0, y1, a, b))
def nn(bmp, ox, oy):
return bmp[oy][ox] # bmp is numpy.array, it casts float indexes to int
def rotate(bmp, r, mx=0, my=0, filename=None, interpol=None):
"""Rotate bitmap bmp r radians clockwise from the center. Move it mx, my."""
# Get the bitmap's original dimensions and calculate the new ones
oh, ow = len(bmp), len(bmp[0])
nwl = ow * math.cos(r)
nwr = oh * math.sin(r)
nhl = ow * math.sin(r)
nhu = oh * math.cos(r)
nw, nh = int(math.ceil(nwl + nwr)), int(math.ceil(nhl+nhu))
cx, cy = ow/2.0 - 0.5, oh/2.0 - 0.5 # The center of the image
# Some rotations yield pixels offscren. They will be mapped anyway, so if
# the user moves the image he gets what was offscreen.
xoffset, yoffset = int(math.ceil((ow-nw)/2.0)), int(math.ceil((oh-nh)/2.0))
for x in xrange(xoffset,nw):
for y in xrange(yoffset,nh):
ox, oy = affine_t(x-cx, y-cy, *mrotate(-r, cx, cy))
if ox > -1 and ox < ow and oy > -1 and oy < oh:
pt = bilinear(bmp, ox, oy) if interpol else nn(bmp, ox, oy)
draw.point([(x+mx,y+my),],fill=pt)
if filename is not None:
im.save(filename)
</code></pre>
<p>The complete code, used to generate the examples below:</p>
<p><a href="http://pastebin.com/2j7BQyzi" rel="noreferrer">http://pastebin.com/2j7BQyzi</a></p>
<p>Some example rotations, first image is the original, to the left is one rotated 90 degrees and the one below is rotated 45 degrees.</p>
<p>Using Nearest Neighbors:</p>
<p><img src="https://i.stack.imgur.com/zZSMB.png" alt="enter image description here"></p>
<p>Using Bilinear:</p>
<p><img src="https://i.stack.imgur.com/s0cZx.png" alt="enter image description here"></p>
<p>Note: The original "Lenna.png" image was first resized to 0.5 the original size using bilinear interpolation and flatten to a greyscale.</p>
|
[] |
[
{
"body": "<h3>1. Comments on your code</h3>\n\n<ol>\n<li><p>For most of your functions, you've written a comment describing what it does. It's usual in Python to put this in a docstring, so that a user can get at it from the interactive interpreter using the <a href=\"http://docs.python.org/3/library/functions.html#help\" rel=\"noreferrer\"><code>help</code></a> function.</p></li>\n<li><p>The function <code>rotate</code> relies on a global variable <code>draw</code>. This makes it hard to reuse and test. (And you couldn't use it in a multi-threaded program.)</p></li>\n<li><p>The function <code>rotate</code> carries out multiple tasks: it rotates the bitmap; translates it; draws the result to an <code>Image</code> object; and saves it to a file. It would make the code easier to use and more general if you separated these functions.</p></li>\n<li><p>The comments suggest that you have not understood how to use NumPy. For example, you write that your function <code>lin_interp</code> is \"Faster than <code>numpy.interp()</code>\". Which no doubt it is for the case of a single point. But when properly vectorized, NumPy will beat pure Python.</p>\n\n<p>For a very simple example, consider a pure-Python implementation of the dot product operation:</p>\n\n<pre><code>def dot(v, w):\n return sum(x * y for x, y in zip(v, w))\n</code></pre>\n\n<p>Let's compare the speed with <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html\" rel=\"noreferrer\"><code>numpy.dot</code></a>. The pure-Python version is substantially faster for very small arrays:</p>\n\n<pre><code>>>> import numpy as np\n>>> from timeit import timeit\n>>> timeit(lambda:dot([1, 2], [3, 4]))\n2.1183970817364752\n>>> timeit(lambda:np.dot([1, 2], [3, 4]))\n11.150392828974873\n</code></pre>\n\n<p>but the NumPy version is hundreds of times faster for large arrays:</p>\n\n<pre><code>>>> v = np.arange(1000)\n>>> w = np.arange(1000)\n>>> timeit(lambda:dot(v, w), number=1000)\n1.4182810601778328\n>>> timeit(lambda:np.dot(v, w), number=1000)\n0.0053491611033678055\n</code></pre>\n\n<p>So in order to get a performance benefit out of NumPy, you have to <em>vectorize</em> your algorithm so that each step of the algorithm operates on many elements simultaneously.</p></li>\n<li><p>Here's another example. In this extract you iterate over a grid of coordinates (<em>x</em>, <em>y</em>) and rotate each coordinate by −<em>r</em> radians about the point (<em>cx</em>, <em>cy</em>):</p>\n\n<pre><code>for x in xrange(xoffset,nw):\n for y in xrange(yoffset,nh):\n ox, oy = affine_t(x-cx, y-cy, *mrotate(-r, cx, cy))\n</code></pre>\n\n<p>Let's put that in a function for timing purposes:</p>\n\n<pre><code>def rotate1(a, theta, ox, oy):\n \"\"\"Rotate array of 2-dimensional coordinates by theta radians about\n the point (ox, oy).\n\n \"\"\"\n for x, y in a:\n affine_t(x-ox, y-oy, *mrotate(theta, ox, oy))\n</code></pre>\n\n<p>To be as generous as possible with the timing results, I haven't even attempted to store or return a result. Let's try that out on an array of a million coordinates:</p>\n\n<pre><code>>>> grid = np.meshgrid(np.arange(1000), np.arange(1000))\n>>> coords = np.vstack(grid).reshape(2, -1).T\n>>> timeit(lambda:rotate1(coords, np.pi / 4, 500, 500), number=1)\n94.44321689195931\n</code></pre>\n\n<p>Here's how the same operation looks when vectorized:</p>\n\n<pre><code>def rotate2(x, y, theta, ox, oy):\n \"\"\"Rotate arrays of coordinates x and y by theta radians about the\n point (ox, oy).\n\n \"\"\"\n s, c = np.sin(theta), np.cos(theta)\n x, y = x - ox, y - oy\n return x * c - y * s + ox, x * s + y * c + oy\n</code></pre>\n\n<p>Instead of looping over the coordinates and applying all the stages of the transformation to one coordinate at a time, we apply each stage of the transformation to all the coordinates simultaneously.</p>\n\n<pre><code>>>> timeit(lambda:rotate2(grid[0], grid[1], np.pi / 4, 500, 500), number=1)\n0.06842728098854423\n</code></pre>\n\n<p>So although your comment says that <code>affine_t</code> is \"A lot faster than numpy\", in fact, when properly vectorized, NumPy runs more than 1300 times faster.</p></li>\n</ol>\n\n<h3>2. Revised code</h3>\n\n<p>If I was doing this for real, then obviously I'd use <a href=\"http://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imrotate.html#scipy.misc.imrotate\" rel=\"noreferrer\"><code>scipy.misc.imrotate</code></a> or <a href=\"http://scikit-image.org/docs/dev/api/skimage.transform.html#rotate\" rel=\"noreferrer\"><code>skimage.transform.rotate</code></a> or whatever. But considered only as an exercise, here's how I'd program this (in the nearest neighbour case, which is quite enough for one answer).</p>\n\n<pre><code>import numpy as np\n\ndef rotate_coords(x, y, theta, ox, oy):\n \"\"\"Rotate arrays of coordinates x and y by theta radians about the\n point (ox, oy).\n\n \"\"\"\n s, c = np.sin(theta), np.cos(theta)\n x, y = np.asarray(x) - ox, np.asarray(y) - oy\n return x * c - y * s + ox, x * s + y * c + oy\n\ndef rotate_image(src, theta, ox, oy, fill=255):\n \"\"\"Rotate the image src by theta radians about (ox, oy).\n Pixels in the result that don't correspond to pixels in src are\n replaced by the value fill.\n\n \"\"\"\n # Images have origin at the top left, so negate the angle.\n theta = -theta\n\n # Dimensions of source image. Note that scipy.misc.imread loads\n # images in row-major order, so src.shape gives (height, width).\n sh, sw = src.shape\n\n # Rotated positions of the corners of the source image.\n cx, cy = rotate_coords([0, sw, sw, 0], [0, 0, sh, sh], theta, ox, oy)\n\n # Determine dimensions of destination image.\n dw, dh = (int(np.ceil(c.max() - c.min())) for c in (cx, cy))\n\n # Coordinates of pixels in destination image.\n dx, dy = np.meshgrid(np.arange(dw), np.arange(dh))\n\n # Corresponding coordinates in source image. Since we are\n # transforming dest-to-src here, the rotation is negated.\n sx, sy = rotate_coords(dx + cx.min(), dy + cy.min(), -theta, ox, oy)\n\n # Select nearest neighbour.\n sx, sy = sx.round().astype(int), sy.round().astype(int)\n\n # Mask for valid coordinates.\n mask = (0 <= sx) & (sx < sw) & (0 <= sy) & (sy < sh)\n\n # Create destination image.\n dest = np.empty(shape=(dh, dw), dtype=src.dtype)\n\n # Copy valid coordinates from source image.\n dest[dy[mask], dx[mask]] = src[sy[mask], sx[mask]]\n\n # Fill invalid coordinates.\n dest[dy[~mask], dx[~mask]] = fill\n\n return dest\n</code></pre>\n\n<p>Here's <code>fabio.jpg</code>, a 200×200 image (<a href=\"http://en.wikipedia.org/wiki/File:Fabio_Lanzoni_with_nephews.jpg\" rel=\"noreferrer\">courtesy of Oasisisgood at en.wikipedia</a>, licensed under CC-BY-SA):</p>\n\n<p><img src=\"https://i.stack.imgur.com/2S1E1.jpg\" alt=\"Fabio Lanzoni\"></p>\n\n<p>and here are some rotated versions:</p>\n\n<pre><code>>>> from scipy.misc import imread, imsave\n>>> img = imread('fabio.jpg')\n>>> for angle in (45, 75, 90, 120):\n... imsave('fabio-{}.jpg'.format(angle),\n... rotate_image(img, angle * np.pi / 180, 100, 100))\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/KdmG6.jpg\" alt=\"Fabio rotated by 45 degrees\">\n<img src=\"https://i.stack.imgur.com/vyKy7.jpg\" alt=\"Fabio rotated by 75 degrees\">\n<img src=\"https://i.stack.imgur.com/ekEVT.jpg\" alt=\"Fabio rotated by 90 degrees\">\n<img src=\"https://i.stack.imgur.com/74k1F.jpg\" alt=\"Fabio rotated by 120 degrees\"></p>\n\n<p>The rotation of this 200×200 image takes about <sup>1</sup>/<sub>60</sub> of a second:</p>\n\n<pre><code>>>> timeit(lambda:rotate_image(img, np.pi / 4, 100, 100), number=1)\n0.01648401003330946\n</code></pre>\n\n<p>(<a href=\"http://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imrotate.html#scipy.misc.imrotate\" rel=\"noreferrer\"><code>scipy.misc.imrotate</code></a> is about 4 times faster than this when using <code>interp='nearest'</code>.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T21:56:59.847",
"Id": "72188",
"Score": "0",
"body": "Perfect. I did find it odd that numpy was taking longer than my function. I had never done any image manipulation so the only thing I could think of was to do it point by point. As for the comments, global variables, etc I didn't bother since it was just an exercise, I know it's messy. Thanks! (I can't award the bounty yet because of the min time limit, I'll do it as soon as possible)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:57:22.613",
"Id": "41903",
"ParentId": "41688",
"Score": "13"
}
}
] |
{
"AcceptedAnswerId": "41903",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T20:23:12.220",
"Id": "41688",
"Score": "15",
"Tags": [
"python",
"optimization",
"algorithm",
"image"
],
"Title": "Rotating greyscale images"
}
|
41688
|
<p>This is a variant of the solution posted <a href="https://codereview.stackexchange.com/questions/40686/state-pattern-c-template-short-and-elegant-hierarchical-fsm-solution">here</a>, without state creation/destruction penalty.</p>
<p>Note that my comment in the original question about the simplification provided by C++11's inherited constructors applies here too, but I have not updated the code in this question accordingly. That is left as an exercise to the reader.</p>
<p><strong>The variant</strong></p>
<p>I like the event/action syntax of the solution I proposed in my question. However, I really dislike the runtime penalty of creating/destroying states on the fly (I have made no measurement, but I dislike the principle).</p>
<p>I present hereafter a variant where the event/action syntax simplicity is pretty much kept (although slightly modified), but all states are created in advance. To keep my syntax, the states obviously need to be context-aware, which makes my solution anti-flyweight (one instance of every single concrete state per instance of a state machine). My feeling is that the cost in RAM is more affordable to the applications I have in mind than the runtime penalty. Another cost of this variant is a more complex declaration for states: declaration of state instances, need for a state to refer not only to the state machine but also to the nearest superstate.</p>
<p>Obviously, a straight application of the GoF's state pattern is an alternative for applications that need both flyweight and runtime efficiency (at the expense of event/action syntax simplicity).</p>
<p>Please comment on this.</p>
<p><strong>genericstate.h</strong></p>
<pre><code>#ifndef GENERICSTATE_H
#define GENERICSTATE_H
template <typename StateMachine, class State, class SuperState = StateMachine>
class GenericState
{
public:
static void init(State *&state, State &initState) {
state = &initState;
initState.entry();
}
protected:
explicit GenericState(StateMachine &m, State *&state) :
m(m), s(m), state(state) {}
explicit GenericState(StateMachine &m, State *&state, SuperState &s) :
m(m), s(s), state(state) {}
void change(State &targetState) {
exit();
init(state, targetState);
}
private:
virtual void entry() {}
virtual void exit() {}
protected:
StateMachine &m;
SuperState &s;
private:
State *&state;
};
#endif // GENERICSTATE_H
</code></pre>
<p><strong>machine.h</strong></p>
<pre><code>#ifndef MACHINE_H
#define MACHINE_H
#include <string>
#include <iostream>
#include "genericstate.h"
class Machine
{
public:
Machine() :
high(*this, levelState), low(*this, levelState),
left(*this, directionState), right(*this, directionState) {}
~Machine() {}
void start();
public:
enum Color {
BLUE,
RED
};
public:
void liftUp() { levelState->liftUp(); }
void bringDown() { levelState->bringDown(); }
void paint(Color color) { directionState->paint(color); }
void turnRight() { directionState->turnRight(); }
void turnLeft() { directionState->turnLeft(); }
private:
static void print(const std::string &str) { std::cout << str << std::endl; }
static void unhandledEvent() { print("unhandled event"); }
void changedColor() { print("changed color"); }
private:
class LevelState : public GenericState<Machine, LevelState> {
protected:
explicit LevelState(Machine &m, LevelState *&state) :
GenericState<Machine, LevelState>(m, state) {}
public:
virtual void liftUp() { unhandledEvent(); }
virtual void bringDown() { unhandledEvent(); }
} *levelState;
struct High : public LevelState {
explicit High(Machine &m, LevelState *&state) :
LevelState(m, state) {}
void entry() { print("entering High"); }
void liftUp() { print("already High"); }
void bringDown() { change(s.low); }
void exit() { print("leaving High"); }
} high;
struct Low : public LevelState {
explicit Low(Machine &m, LevelState *&state) :
LevelState(m, state) {}
void entry() { print("entering Low"); }
void liftUp() { change(s.high); }
void bringDown() { print("already Low"); }
void exit() { print("leaving Low"); }
} low;
private:
class Left;
class ColorState : public GenericState<Machine, ColorState, Left> {
protected:
explicit ColorState(Machine &m, ColorState *&state, Left &s) :
GenericState<Machine, ColorState, Left>(m, state, s) {}
public:
virtual void paint(Color color) { (void)color; unhandledEvent(); }
};
struct Red : public ColorState {
explicit Red(Machine &m, ColorState *&state, Left &s) :
ColorState(m, state, s) {}
void entry() { m.changedColor(); }
void paint(Color color);
};
struct Blue : public ColorState {
explicit Blue(Machine &m, ColorState *&state, Left &s) :
ColorState(m, state, s) {}
void entry() { m.changedColor(); }
void paint(Color color);
};
private:
class DirectionState : public GenericState<Machine, DirectionState> {
protected:
explicit DirectionState(Machine &m, DirectionState *&state) :
GenericState<Machine, DirectionState>(m, state) {}
public:
virtual void paint(Color color) { (void)color; unhandledEvent(); }
virtual void turnRight() { unhandledEvent(); }
virtual void turnLeft() { unhandledEvent(); }
} *directionState;
struct Left : public DirectionState {
friend class Red;
friend class Blue;
explicit Left(Machine &m, DirectionState *&state) :
DirectionState(m, state),
red(m, colorState, *this), blue(m, colorState, *this) {}
void entry() { ColorState::init(colorState, red); }
void paint(Color color) { colorState->paint(color); }
void turnRight() { change(s.right); }
private:
ColorState *colorState;
Red red;
Blue blue;
} left;
struct Right : public DirectionState {
explicit Right(Machine &m, DirectionState *&state) :
DirectionState(m, state) {}
void turnLeft() { change(s.left); }
} right;
};
#endif // MACHINE_H
</code></pre>
<p><strong>machine.cpp</strong></p>
<pre><code>#include "machine.h"
void Machine::start()
{
LevelState::init(levelState, high);
DirectionState::init(directionState, left);
}
void Machine::Red::paint(Machine::Color color)
{
if (color == BLUE) change(s.blue);
else ColorState::paint(color);
}
void Machine::Blue::paint(Machine::Color color)
{
if (color == RED) change(s.red);
else ColorState::paint(color);
}
</code></pre>
|
[] |
[
{
"body": "<p>I'm not too familiar with inheritance, but here are some stylistic things I've noticed:</p>\n\n<ul>\n<li><p>There is no need to use the <code>public</code>, <code>private</code>, and <code>protected</code> keywords repeatedly in the same class declaration. It just makes it harder to read and adds nothing of value. You should just use the needed keywords once, and you can optionally leave out the <code>private</code> keyword since classes are <code>private</code> by default (this may also be less-readable overall, but it's up to you).</p>\n\n<p>This may also be an indication that you have a little too much in your class declarations, as you are trying to organize everything. You may consider putting these inherited <code>struct</code>s into separate files and then forward-declaring them in the needed classes after including them in the headers.</p></li>\n<li><p><strong>machine.h:</strong></p>\n\n<p>Member functions that are not supposed to modify data members, such as <code>print()</code>, should be <code>const</code> to prevent any accidental modifications. It probably also doesn't need to be <code>static</code>.</p>\n\n<pre><code>void print(const std::string &str) const { std::cout << str << std::endl; }\n</code></pre>\n\n<p>These function names are misleading as they don't perform any of these actions:</p>\n\n<blockquote>\n<pre><code>void entry() { print(\"entering High\"); }\nvoid bringDown() { print(\"already Low\"); }\nvoid exit() { print(\"leaving Low\"); }\nvoid entry() { print(\"entering Low\"); }\nvoid bringDown() { print(\"already Low\"); }\nvoid exit() { print(\"leaving Low\"); }\n</code></pre>\n</blockquote>\n\n<p>If you still need these functions, despite the fact that they <em>only</em> print some hard-coded text, then at least give them more accurate names to indicate that they're printing something and not actually performing an action.</p></li>\n<li><p><strong>machine.cpp:</strong></p>\n\n<p>This is not a very maintainable style:</p>\n\n<blockquote>\n<pre><code>if (color == BLUE) change(s.blue);\nelse ColorState::paint(color);\n</code></pre>\n</blockquote>\n\n<p>In case you may need to add additional lines, use curly braces:</p>\n\n<pre><code>if (color == BLUE)\n{\n change(s.blue);\n}\nelse\n{\n ColorState::paint(color);\n}\n</code></pre>\n\n<p>This should also be done with the other related function.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-08T14:21:37.037",
"Id": "56449",
"ParentId": "41690",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T20:43:29.480",
"Id": "41690",
"Score": "6",
"Tags": [
"c++",
"inheritance",
"state-machine",
"state"
],
"Title": "A variant of state pattern + C++ template FSM without state creation/destruction penalty"
}
|
41690
|
<p>I'm currently using the following code to manage calls to WCF services that are unreliable, and or suffer performance load issues due to contention.</p>
<p>Right now this code is limited to solving issue with types that return <code>void</code>. It exponentially backs off from a subsequent call from the server, preventing unhelpful "hammering" of the server.</p>
<p><strong>Question</strong> </p>
<ul>
<li><p>Is there any possible way I can abstract this into something more generic for varying return types?</p></li>
<li><p>Have I caught all the appropriate exceptions worthy of a retry?</p></li>
<li><p>What is the most appropriate way I can communicate to the calling process what is going on with this code, perhaps offering an opportunity to cancel early?</p></li>
<li><p>Any other enhancements you may think of...</p></li>
</ul>
<p><strong>Usage Example:</strong></p>
<pre><code>Service<IOrderService>.Use(orderService=>
{
orderService.PlaceOrder(request);
}
</code></pre>
<p><strong>Source code</strong></p>
<pre><code>public delegate void UseServiceDelegate<T>(T proxy);
public static class Service<T>
{
public static ChannelFactory<T> _channelFactory = new ChannelFactory<T>("");
public static void Use(UseServiceDelegate<T> codeBlock)
{
IClientChannel proxy = (IClientChannel)_channelFactory.CreateChannel();
bool success = false;
Exception mostRecentEx = null;
int millsecondsToSleep = 1000;
for(int i=0; i<5; i++) // Attempt a maximum of 5 times
{
try
{
codeBlock((T)proxy);
proxy.Close();
success = true;
break;
}
// The following is typically thrown on the client when a channel is terminated due to the server closing the connection.
catch (ChannelTerminatedException cte)
{
mostRecentEx = cte;
proxy.Abort();
// delay (backoff) and retry
Thread.Sleep(millsecondsToSleep * (i + 1));
}
// The following is thrown when a remote endpoint could not be found or reached. The endpoint may not be found or
// reachable because the remote endpoint is down, the remote endpoint is unreachable, or because the remote network is unreachable.
catch (EndpointNotFoundException enfe)
{
mostRecentEx = enfe;
proxy.Abort();
// delay (backoff) and retry
Thread.Sleep(millsecondsToSleep * (i + 1));
}
// The following exception that is thrown when a server is too busy to accept a message.
catch (ServerTooBusyException stbe)
{
mostRecentEx = stbe;
proxy.Abort();
// delay (backoff) and retry
Thread.Sleep(millsecondsToSleep * (i + 1));
}
catch (TimeoutException timeoutEx)
{
mostRecentEx = timeoutEx;
proxy.Abort();
// delay (backoff) and retry
Thread.Sleep(millsecondsToSleep * (i + 1));
}
catch (CommunicationException comException)
{
mostRecentEx = comException;
proxy.Abort();
// delay (backoff) and retry
Thread.Sleep(millsecondsToSleep * (i + 1));
}
catch(Exception )
{
// rethrow any other exception not defined here
// You may want to define a custom Exception class to pass information such as failure count, and failure type
proxy.Abort();
throw ;
}
}
if (success == false && mostRecentEx != null)
{
proxy.Abort();
throw new Exception("WCF call failed after 5 retries.", mostRecentEx );
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-01-26T21:51:40.823",
"Id": "290843",
"Score": "0",
"body": "May be [Polly](https://github.com/App-vNext/Polly) could help: > Polly is a .NET resilience and transient-fault-handling library that allows developers to express policies such as Retry, Circuit Breaker, Timeout, Bulkhead Isolation, and Fallback in a fluent and thread-safe manner. Polly targets .NET 4.0, .NET 4.5 and .NET Standard 1.0. http://www.thepollyproject.org"
}
] |
[
{
"body": "<p>One clean up is to consolidate the common code in the catch blocks, by putting it into a function. Other ideas:</p>\n\n<ul>\n<li>5 tries is not many for WCF in general. I would increase it to 50 or so. If you do this, you need a ceiling to multiple applied to to the minimum sleep time.</li>\n<li>The milliseconds to sleep should be initialized to a semi-random value: a minimum value, plus a random fraction of an additional amount. Usually I make the additional amount equal to the minimum value. This will keep all your clients from hammering the server with the same rhythm, in the event all clients start at the same time.</li>\n</ul>\n\n<p>With regards to questions:</p>\n\n<ol>\n<li>Make the method generic, with a type parameter defining the return value.</li>\n<li>I usually have only two catch blocks, one for FaultException to communicate exceptions explicitly from server to client, and one for Exception, to catch everything else. The Exception block is where you initiate a retry. Read about <a href=\"http://msdn.microsoft.com/en-us/library/system.servicemodel.faultcontractattribute%28v=vs.110%29.aspx\" rel=\"nofollow\">FaultContractAttribute</a>.</li>\n<li>The only good way to allow cancellation is to run all of this in a background thread, possibly using BackgroundWorker.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T02:22:10.303",
"Id": "41710",
"ParentId": "41692",
"Score": "3"
}
},
{
"body": "<p>WCF has a built-in feature to deal with unreliable networks and such: <a href=\"http://msdn.microsoft.com/en-us/library/aa480191.aspx\" rel=\"nofollow\" title=\"reliable messaging\">reliable messaging</a>.\nSee the link for an explanation...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T17:17:28.527",
"Id": "74090",
"Score": "2",
"body": "link-only answers are discouraged. please try to sum up the main points of the link you provided in case the page becomes unavailable (even if highly unlikely ;))"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T15:56:09.897",
"Id": "42513",
"ParentId": "41692",
"Score": "2"
}
},
{
"body": "<p>It's not enough to just catch the exception. Just catching it doesn't prevent your users to wait for the whole timeout duration. You need to build your application so that it will \"fail fast\" in an event of timeout. Take a look at this <a href=\"http://dennis-nerush.blogspot.co.il/2015/12/everybody-has-plan-until-they-get.html\" rel=\"nofollow\">post</a>. It shows how you can achieve this using the Polly open source.\nHere is part of code. Full explanation is in the post:</p>\n\n<pre><code> public NavigationHistoryController(INavigationHistoryProvider historyProvider)\n {\n _historyProvider = historyProvider;\n _policy = Policy.Handle<SqlException>(ex => ex.Number == TimeoutExceptionCode).CircuitBreaker(10, TimeSpan.FromMinutes(10));\n }\n\n public List<History> GetHistory()\n {\n try\n {\n return _policy.Execute(() => _historyProvider.Get());\n }\n catch (SqlException exception)\n {\n return null;\n }\n catch (BrokenCircuitException)\n {\n return new List<History>();\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-05T16:07:20.420",
"Id": "112987",
"ParentId": "41692",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T21:36:40.680",
"Id": "41692",
"Score": "5",
"Tags": [
"c#",
"error-handling",
"wcf"
],
"Title": "Consistent way to handle transient timeouts with WCF calls (timeouts, unreliable network, server load, etc)"
}
|
41692
|
<p>I took a training challenge on Codility that checks for the proper nesting of brackets in a string. The brackets to be checked are <code>{,},(,),[,]</code>. I have written the following Java program which passes in O(n) time and space, but I have a feeling that the extra space I use can be reduced. Also I think that there must be a data structure that can handle this scenario more efficiently. Using an ArrayList instead of an array might help. What I need here is a critique of my code.</p>
<pre><code>import java.util.HashMap;
class Solution {
public int solution(String S) {
char[] stack = new char[S.length()];
int last = -1;
HashMap hm = new HashMap();
hm.put('}', '{');
hm.put(')', '(');
hm.put(']', '[');
for(int i=0; i<S.length(); i++){
char next = S.charAt(i);
if(next == '}' || next == '{' || next == ')' || next == '(' ||
next == ']' || next == '[')
{
if(last!=-1 && hm.containsKey(next) && stack[last] == hm.get(next)){
last--;
}
else{
last++;
stack[last] = S.charAt(i);
}
}
}
if(last == -1){
return 1;
}
return 0;
}
}
</code></pre>
|
[] |
[
{
"body": "<h3>Naming</h3>\n\n<ul>\n<li>Class name: <code>Solution</code> A solution for what?</li>\n<li>Method name: <code>solution</code> - again I ask: <strong>Solution for what?</strong></li>\n<li>Parameter name: <code>S</code> - And what on earth is <code>S</code>? Parameter names are by convention named beginning with a lowercase letter.</li>\n</ul>\n\n<p>None of these three names are descriptive names. It is easier to read and understand code when the names tell a bit about what it is that the code does. Now, naming things are hard, and something that programmers do a lot. For this case, consider names such as <code>BracketNestingVerifier</code>, <code>verify</code> and <code>input</code>. You might even be able to come up with better names.</p>\n\n<h3>General things</h3>\n\n<ul>\n<li><p>Use <strong>Generics</strong> for your <code>HashMap</code>. Since Java 1.5, it's been possible to define which kind of HashMap it is. Is it a HashMap of <code><Integer, String></code>? <code><String, Byte></code>? No, in your case; it's <code>HashMap<Character, Character></code></p></li>\n<li><p>Why do the method return an <code>int</code> when it would make much more sense to return a true/false <code>boolean</code>? Returning a boolean allows you to simplify the end of your method</p>\n\n<pre><code>if (last == -1) { // note the fixed spacing ;)\n return 1;\n}\nreturn 0;\n</code></pre>\n\n<p>To simply <code>return (last == -1);</code></p></li>\n</ul>\n\n<h3>Spacing</h3>\n\n<p>I find that code like this:</p>\n\n<pre><code>for(int i=0; i<S.length(); i++){\n</code></pre>\n\n<p>Is much more readable if you use spacing (and a better variable name for <code>S</code> of course)</p>\n\n<pre><code>for (int i = 0; i < input.length(); i++) {\n</code></pre>\n\n<h3>Algorithm</h3>\n\n<p>Now, about that algorithm... You have a variable called <code>stack</code> and yet it isn't a stack structure, it's only an array. Using a somewhat real stack structure can be helpful. In the code below, I have used the <code>LinkedList</code> class to provide this structure (Even though there is also a <code>Stack</code> class, I like the <code>Deque</code> interface and wanted to go with <code>LinkedList</code>).</p>\n\n<p>In this code, I have improved the variable names, the return type, and I am using a <code>HashSet</code> to store all \"special\" characters in. The <code>contains</code> method of a HashSet is performing in constant speed, so you should not experience any significant lack of performance. I noticed that in your if-statement, you had hard-coded the values that were put into your <code>HashMap</code>, this is what made me want to add the <code>HashSet</code>.</p>\n\n<p>To make this work, I had to flip the key/values of your HashMap. The key is now the starting character, and the target is the expected ending character.</p>\n\n<p>The loop through the string here is pretty simple and straight-forward:</p>\n\n<ul>\n<li>Have we waited for this character? If so, remove it from the list of expected characters we are waiting for (The \"stack\")</li>\n<li>If the above is not true, does this character have a matching ending character? If it does, add it to the stack</li>\n<li>Again, if the above also is not true, is this character regarded as a special character? If it is, then we know here already that we have failed so we can return from the method.</li>\n</ul>\n\n<p></p>\n\n<pre><code>public boolean simonsVerify(String input) {\n HashMap<Character, Character> matches = new HashMap<Character, Character>();\n matches.put('{', '}');\n matches.put('(', ')');\n matches.put('[', ']');\n\n Set<Character> specialChars = new HashSet<Character>();\n Deque<Character> expected = new LinkedList<Character>();\n for (Entry<Character, Character> ee : matches.entrySet()) {\n specialChars.add(ee.getKey());\n specialChars.add(ee.getValue());\n }\n\n for (int i = 0; i < input.length(); i++) {\n char next = input.charAt(i);\n Character expect = expected.peekLast();\n if (expect != null && expect == next) {\n expected.removeLast();\n }\n else if (matches.containsKey(next)) {\n expected.addLast(matches.get(next));\n }\n else if (specialChars.contains(next)) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n\n<p>Here is the testing (with JUnit) I used, for both your original code and also for my method:</p>\n\n<pre><code>@Test\npublic void testVerifying() {\n assertTrue(verify(\"{,},({,}),[,]\"));\n\n assertFalse(verify(\"{(,},({,}),[,]\"));\n assertFalse(verify(\"{,)},({gfdgfd}),[,]\"));\n assertFalse(verify(\"{(,}),({,}),[,]\"));\n\n assertTrue(verify(\"{,},(,),[[,]]\"));\n assertTrue(verify(\"{,},(,),[,]\"));\n assertTrue(verify(\"{{,}},(,),[,]\"));\n assertTrue(verify(\"{,},((,)),[,]\"));\n assertTrue(verify(\"{,},(,),[,]\"));\n assertTrue(verify(\"(), {{{,}}},(,),[,]\"));\n}\n</code></pre>\n\n<p>There might even be a better way to do this algorithm, this is just my way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T22:19:05.750",
"Id": "71721",
"Score": "0",
"body": "Well, this was a coding challenge at Codility.com and the return type had to be an int to pass the test cases :). So I am not \"entirely\" at fault :D. But all your points definitely make a lot of sense. I have not been an active part of the online community, but I think it will definitely help me learn a lot. Thanks!!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T22:21:27.723",
"Id": "71722",
"Score": "0",
"body": "Why no spaces in \"i=0\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T22:24:18.853",
"Id": "71723",
"Score": "0",
"body": "@AlexisWilke Because I missed them :) Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T22:57:31.247",
"Id": "71726",
"Score": "0",
"body": "@Pankaj Just added a review of the algorithm itself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T02:33:04.177",
"Id": "71739",
"Score": "1",
"body": "`specialChars` should just be a set of the closing delimiters, and should be renamed accordingly. You would only reach `if (specialChars.contains(next))` when `next` is not an opening delimiter."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T21:54:49.123",
"Id": "41695",
"ParentId": "41693",
"Score": "6"
}
},
{
"body": "<p>Using an array as a simplistic stack can work, as long as you are confident that your input is reasonably sized. However, I think your code is repetitive: the giant <code>if</code> condition fails to take advantage of the <code>HashMap</code>.</p>\n\n<pre><code>public class DelimiterMatcher {\n private static final HashMap<Character, Character> DELIMITERS = new HashMap<Character, Character>();\n static {\n DELIMITERS.put('(', ')');\n DELIMITERS.put('{', '}');\n DELIMITERS.put('[', ']');\n }\n private static final Collection<Character> CLOSING_DELIMITERS = DELIMITERS.values();\n\n public static boolean hasMatchingDelimiters(String s) {\n char[] stack = new char[s.length() / 2 + 1];\n int last = 0;\n try {\n for (int i = 0; i < s.length(); i++) {\n char next = s.charAt(i);\n Character closingDelimiter;\n if (next == stack[last]) {\n // Found expected closing delimiter. Pop it from the stack.\n --last;\n } else if ((closingDelimiter = DELIMITERS.get(next)) != null) {\n // Found opening delimiter. Push the corresponding closing\n // delimiter onto the stack.\n stack[++last] = closingDelimiter;\n } else if (CLOSING_DELIMITERS.contains(next)) {\n // Found unexpected closing delimiter\n return false;\n }\n }\n return last == 0;\n } catch (ArrayIndexOutOfBoundsException tooManyOpenOrCloseDelimiters) {\n return false;\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T00:56:08.333",
"Id": "41704",
"ParentId": "41693",
"Score": "6"
}
},
{
"body": "<p>Just to add different approach for the given problem. I was thinking that it is the typical problem using the stack so I am adding an approach that is using the system stack and recursion instead the user stack. I incorporated the great idea of the maps from the previous answer.</p>\n\n<pre><code>private static final Map<Character, Character> DELIMITERS = new HashMap<Character, Character>();\n\nstatic {\n DELIMITERS.put('(', ')');\n DELIMITERS.put('{', '}');\n DELIMITERS.put('[', ']');\n}\nprivate static final Collection<Character> CLOSING_DELIMITERS = DELIMITERS.values();\n\npublic static void main(String[] args) {\n String s = \"{(65)45dfa\";\n final CharacterIterator it = new StringCharacterIterator(s);\n\n System.out.println(new CorrectBrackets().areDelimitersCorrect(CharacterIterator.DONE, it, it.current()));\n}\n\npublic boolean areDelimitersCorrect(Character closingDelimiter, CharacterIterator it, Character currentCharacter) {\n boolean correctDelimitersInside = true;\n while (currentCharacter != CharacterIterator.DONE && correctDelimitersInside) {\n if ( currentCharacter.equals(closingDelimiter) ){\n return true;\n }\n //If it is not my closing delimiter but it is some other closing delimiter then it is wrong\n if ( CLOSING_DELIMITERS.contains(currentCharacter) ){\n return false;\n }\n //If there is an opening one lets recurse.\n if (DELIMITERS.containsKey(currentCharacter)) {\n correctDelimitersInside = areDelimitersCorrect(DELIMITERS.get(currentCharacter), it, it.next());\n }\n currentCharacter = it.next();\n }\n\n //Check if all the inside was correct plus if I am closing correctly.\n return correctDelimitersInside && currentCharacter.equals(closingDelimiter);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T15:47:16.527",
"Id": "41738",
"ParentId": "41693",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41695",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T21:38:03.837",
"Id": "41693",
"Score": "10",
"Tags": [
"java",
"algorithm",
"strings",
"programming-challenge"
],
"Title": "Checking brackets nesting in a string"
}
|
41693
|
<h1>Description</h1>
<p>This code is for 'fighting' two objects against each other. I am normally using it to <a href="http://chat.stackexchange.com/transcript/message/13543046#13543046">make my AIs fight each other</a> in one game or another.</p>
<p>In case you are wondering: Yes, I am using this in my <a href="http://www.zomis.net/ttt" rel="nofollow noreferrer">Tic Tac Toe Ultimate</a> game to determine the skills of the AIs, my TTT Ultimate implementation for the current <a href="https://codereview.meta.stackexchange.com/questions/1471/weekend-challenge-reboot/1472#1472">coding-challenge</a> will be put up here for review later on). This particular Fighting code is however completely independent and is used in many of my other current projects.</p>
<h3>Class Summary (489 lines in 7 files, making a total of 14319 bytes)</h3>
<ul>
<li>FightInterface.java: Interface to be implemented to determine the winner of a fight</li>
<li>FightResults.java: Class to store the results from a bunch of fights</li>
<li>GameFight.java: Class that provides the core functionality to create fights and get results</li>
<li>GuavaExt.java: Some utility methods, which makes use of Guava, hence the name.</li>
<li>PlayerResults.java: Results for a specific player</li>
<li>IndexResults.java: Results for when a player plays at a specific index (as there can in some games be differences if you're the first player to play or the second)</li>
<li>WinsLosses.java: Stores wins, losses, and draws.</li>
</ul>
<h1>Code</h1>
<p>This code can also be found on <a href="https://github.com/Zomis/Fighting" rel="nofollow noreferrer">GitHub</a></p>
<p><strong>FightInterface.java:</strong> (20 lines, 550 bytes)</p>
<pre><code>/**
* Interface to provide implementation for determining the winner of a fight
*/
public interface FightInterface<PL> {
/**
* The fight number for the first fight
*/
int FIRST_FIGHT = 1;
/**
* Make two fighters fight each other
*
* @param players The players that should fight each other
* @param fightNumber Which fight number in the series this is, starting at 1.
* @return The winner of the fight, or null if it is a draw
*/
PL determineWinner(PL[] players, int fightNumber);
}
</code></pre>
<p><strong>FightResults.java:</strong> (126 lines, 3995 bytes)</p>
<pre><code>public class FightResults<PL> {
private final Map<PL, PlayerResults<PL>> playerData = new HashMap<PL, PlayerResults<PL>>();
private final boolean separateIndexes;
private final String label;
private final long timeStart;
private long timeEnd;
public FightResults(String label, boolean separateIndexes) {
this.label = label;
this.separateIndexes = separateIndexes;
this.timeStart = System.nanoTime();
}
/**
* @return A list of all the player results, with the worst performing player first and the best player last.
*/
public List<PlayerResults<PL>> getResultsAsc() {
List<PlayerResults<PL>> list = new ArrayList<PlayerResults<PL>>(playerData.values());
Collections.sort(list);
return list;
}
/**
* @return An ordered {@link LinkedHashMap} ranking all fighters with their associated win percentage with the best performing player first
*/
public LinkedHashMap<PL, Double> getPercentagesDesc() {
LinkedHashMap<PL, Double> result = new LinkedHashMap<PL, Double>();
for (Entry<PL, PlayerResults<PL>> ee : entriesSortedByValues(playerData, true)) {
result.put(ee.getKey(), ee.getValue().calcTotal().getPercentage());
}
return result;
}
private static class ProduceValue<PL> implements Function<PL, PlayerResults<PL>> {
@Override
public PlayerResults<PL> apply(PL arg0) {
return new PlayerResults<PL>(arg0);
}
}
void finished() {
this.timeEnd = System.nanoTime();
}
private final ProduceValue<PL> prodValue = new ProduceValue<PL>();
public void saveResult(PL[] fighters, PL winner) {
final int DEFAULT_INDEX = 0;
for (int i = 0; i < fighters.length; i++) {
PL pp1 = fighters[i];
PlayerResults<PL> result = GuavaExt.mapGetOrPut(playerData, pp1, prodValue);
for (int j = 0; j < fighters.length; j++) {
if (i == j)
continue;
result.addResult(separateIndexes ? i : DEFAULT_INDEX , fighters[j], winner);
}
}
}
@Override
public String toString() {
return playerData.toString();
}
/**
* @return A human-readable text about the results of this fight
*/
public String toStringMultiLine() {
StringBuilder str = new StringBuilder();
if (this.label != null) {
str.append(this.label);
str.append("\n");
}
str.append(super.toString());
str.append("\n");
for (Entry<PL, PlayerResults<PL>> ee : entriesSortedByValues(playerData, false)) {
str.append(ee.getKey());
str.append("\n");
str.append(ee.getValue().toStringMultiLine());
str.append("\n");
}
double timeSpent = (timeEnd - timeStart) / 1000000.0;
str.append("Time spent: " + (timeSpent) + " milliseconds\n");
return str.toString();
}
/**
* Sort a map by it's values
*
* @param map The map to sort
* @param descending True to sort in descending order, false to sort in ascending order
* @return A SortedSet containing all the entries from the original map.
*/
public static <K, V extends Comparable<? super V>> SortedSet<Map.Entry<K, V>> entriesSortedByValues(Map<K, V> map, final boolean descending) {
SortedSet<Map.Entry<K, V>> sortedEntries = new TreeSet<Map.Entry<K, V>>(
new Comparator<Map.Entry<K, V>>() {
@Override
public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) {
int res;
if (descending)
res = e1.getValue().compareTo(e2.getValue());
else res = e2.getValue().compareTo(e1.getValue());
return res != 0 ? -res : 1; // Special fix to preserve items with equal values
}
}
);
sortedEntries.addAll(map.entrySet());
return sortedEntries;
}
}
</code></pre>
<p><strong>GameFight.java:</strong> (85 lines, 3267 bytes)</p>
<pre><code>public class GameFight<PL> {
private final boolean separateIndexes;
private String label;
/**
* @param label The name of this fight, which will be showed in the output
* @param useSeparateIndexes True to alternate fighters between index 0 and index 1.
*/
public GameFight(String label, boolean useSeparateIndexes) {
this.separateIndexes = useSeparateIndexes;
this.label = label;
}
public GameFight(String label) {
this(label, false);
}
public GameFight() {
this(null);
}
/**
* Creates 1 vs. 1 games for each possible combination of fighters and fights them against each other.
*
* @param fighters An array of the fighters
* @param gamesPerGroup How many fights each 1 vs. 1 pair should make.
* @param fightStrategy An interface providing implementation to determine the winner of a fight
* @return The results of the fighting
*/
public FightResults<PL> fightEvenly(PL[] fighters, int gamesPerGroup, FightInterface<PL> fightStrategy) {
FightResults<PL> results = new FightResults<PL>(label, separateIndexes);
List<List<PL>> groups = GuavaExt.processSubsets(Arrays.asList(fighters), 2);
for (List<PL> group : groups) {
PL[] currentFighters = Arrays.copyOf(fighters, 2);
currentFighters[0] = group.get(0);
currentFighters[1] = group.get(1);
if (currentFighters[0] == currentFighters[1])
throw new IllegalStateException("Fighters cannot be equal at the moment");
// Fight the games
for (int i = 1; i <= gamesPerGroup; i++)
results.saveResult(currentFighters, fightStrategy.determineWinner(currentFighters, i));
if (separateIndexes) {
currentFighters[0] = group.get(1);
currentFighters[1] = group.get(0);
for (int i = 1; i <= gamesPerGroup; i++)
results.saveResult(currentFighters, fightStrategy.determineWinner(currentFighters, i));
}
}
results.finished();
return results;
}
/**
* Perform a specific number of randomly selected 1 vs. 1 fights.
*
* @param fighters Array of fighters that can be chosen to participate in fights
* @param count The number of fights to make in total
* @param fightStrategy An interface providing implementation to determine the winner of a fight
* @return The results of the fighting
*/
public FightResults<PL> fightRandom(PL[] fighters, int count, FightInterface<PL> fightStrategy) {
FightResults<PL> results = new FightResults<PL>(label, separateIndexes);
Random random = new Random();
for (int i = 1; i <= count; i++) {
PL[] currentFighters = Arrays.copyOf(fighters, 2);
List<PL> playerOptions = new ArrayList<PL>(Arrays.asList(fighters));
currentFighters[0] = playerOptions.remove(random.nextInt(playerOptions.size()));
currentFighters[1] = playerOptions.remove(random.nextInt(playerOptions.size()));
if (currentFighters[0] == currentFighters[1])
throw new IllegalStateException("Fighters cannot be equal at the moment");
results.saveResult(currentFighters, fightStrategy.determineWinner(currentFighters, i));
}
results.finished();
return results;
}
}
</code></pre>
<p><strong>GuavaExt.java:</strong> (70 lines, 2160 bytes)</p>
<pre><code>/**
* Utility methods that make a lot of usage of Guava.
*/
public class GuavaExt {
public static <K, V> V mapGetOrPut(Map<K, V> map, K key, Function<K, V> valueProducer) {
if (map.containsKey(key))
return map.get(key);
V value = valueProducer.apply(key);
map.put(key, value);
return value;
}
/**
* Creates a list of all subsets containing the specified number of elements
*
* @param set The items to create combinations of
* @param subsetSize The size of each of the lists in the result
* @return List of lists containing all the combinations of lists with the specified size
*/
public static <T> List<List<T>> processSubsets(List<T> set, int subsetSize) {
if (subsetSize > set.size()) {
subsetSize = set.size();
}
List<List<T>> result = Lists.newArrayList();
List<T> subset = Lists.newArrayListWithCapacity(subsetSize);
for (int i = 0; i < subsetSize; i++) {
subset.add(null);
}
return processLargerSubsets(result, set, subset, 0, 0);
}
private static <T> List<List<T>> processLargerSubsets(List<List<T>> result, List<T> set, List<T> subset, int subsetSize, int nextIndex) {
if (subsetSize == subset.size()) {
result.add(ImmutableList.copyOf(subset));
} else {
for (int j = nextIndex; j < set.size(); j++) {
subset.set(subsetSize, set.get(j));
processLargerSubsets(result, set, subset, subsetSize + 1, j + 1);
}
}
return result;
}
public static <T> Collection<List<T>> permutations(List<T> list, int size) {
Collection<List<T>> all = Lists.newArrayList();
if (list.size() < size) {
size = list.size();
}
if (list.size() == size) {
all.addAll(Collections2.permutations(list));
} else {
for (List<T> p : processSubsets(list, size)) {
all.addAll(Collections2.permutations(p));
}
}
return all;
}
}
</code></pre>
<p><strong>IndexResults.java:</strong> (47 lines, 1071 bytes)</p>
<pre><code>/**
* The results for when a fighter is at a specific index
*/
public class IndexResults<PL> {
private final Map<PL, WinsLosses> results = new HashMap<PL, WinsLosses>();
void informAbout(PL opponent, Boolean winner) {
WinsLosses winLoss = results.get(opponent);
if (winLoss == null) {
winLoss = new WinsLosses();
results.put(opponent, winLoss);
}
if (winner == null) {
winLoss.draw();
}
else if (winner)
winLoss.win();
else winLoss.loss();
}
public String toStringMultiLine() {
StringBuilder str = new StringBuilder();
for (Entry<PL, WinsLosses> ee : results.entrySet()) {
str.append("vs. ");
str.append(ee.getKey());
str.append(": ");
str.append(ee.getValue());
str.append("\n");
}
return str.toString();
}
@Override
public String toString() {
return results.toString();
}
public WinsLosses calcTotal() {
return new WinsLosses(results.values());
}
}
</code></pre>
<p><strong>PlayerResults.java:</strong> (76 lines, 2082 bytes)</p>
<pre><code>public class PlayerResults<PL> implements Comparable<PlayerResults<PL>> {
private final PL player;
public PL getPlayer() {
return player;
}
PlayerResults(PL player) {
this.player = player;
}
private final Map<Integer, IndexResults<PL>> results = new HashMap<Integer, IndexResults<PL>>();
private final Function<Integer, IndexResults<PL>> producer = new Function<Integer, IndexResults<PL>>() {
@Override
public IndexResults<PL> apply(Integer arg0) {
return new IndexResults<PL>();
}
};
void addResult(int myIndex, PL opponent, PL winner) {
IndexResults<PL> result = GuavaExt.mapGetOrPut(results, myIndex, producer);
Boolean winStatus = null;
if (winner == this.player) // allow for drawed games as winner = null.
winStatus = true;
else if (winner != null)
winStatus = false;
result.informAbout(opponent, winStatus);
}
public String toStringMultiLine() {
StringBuilder str = new StringBuilder();
for (Entry<Integer, IndexResults<PL>> ee : results.entrySet()) {
str.append("as index ");
str.append(ee.getKey());
str.append(": (");
str.append(ee.getValue().calcTotal());
str.append(")\n");
str.append(ee.getValue().toStringMultiLine());
}
return str.toString();
}
@Override
public String toString() {
return results.toString();
}
public WinsLosses calcTotal() {
int wins = 0;
int losses = 0;
int draws = 0;
for (Entry<Integer, IndexResults<PL>> ee : results.entrySet()) {
WinsLosses tot = ee.getValue().calcTotal();
wins += tot.getWins();
draws = tot.getDraws();
losses += tot.getLosses();
}
return new WinsLosses(wins, losses, draws);
}
public double calculatePercentage() {
return calcTotal().getPercentage();
}
@Override
public int compareTo(PlayerResults<PL> o) {
return Double.compare(this.calculatePercentage(), o.calculatePercentage());
}
}
</code></pre>
<p><strong>WinsLosses.java:</strong> (65 lines, 1194 bytes)</p>
<pre><code>/**
* Class to keep track of wins, losses, and draws.
*/
public class WinsLosses {
private int wins;
private int losses;
private int draws;
public WinsLosses() {
this(0, 0, 0);
}
public WinsLosses(int wins, int losses, int draws) {
this.wins = wins;
this.losses = losses;
this.draws = draws;
}
public WinsLosses(Collection<WinsLosses> total) {
this(0, 0, 0);
for (WinsLosses winlose : total) {
wins += winlose.wins;
losses += winlose.losses;
draws += winlose.draws;
}
}
void win() {
wins++;
}
void loss() {
losses++;
}
public int getTotal() {
return wins + draws + losses;
}
public int getLosses() {
return losses;
}
public int getWins() {
return wins;
}
public double getPercentage() {
double drawsBonus = draws / 2.0;
return (wins + drawsBonus) / (double) getTotal();
}
@Override
public String toString() {
return String.format("%d wins, %d draws, %d losses (%.2f %%)", wins, draws, losses, getPercentage() * 100);
}
void draw() {
draws++;
}
public int getDraws() {
return draws;
}
}
</code></pre>
<h1>Dependencies</h1>
<ul>
<li>com.google.common.*: Google's Guava Library</li>
</ul>
<h1>Usage / Test</h1>
<p>This code creates simple fighters that each randomize a value from 0 to n and each fighter can have a specified bonus added to it's "score". In each fight, the fighter with the highest score wins.</p>
<p><strong>FightingTest.java:</strong> (70 lines, 2289 bytes)</p>
<pre><code>public class FightingTest {
public static class Fighter {
private final int random;
private final int bonus;
public Fighter(int fightRandom) {
this(fightRandom, 0);
}
public Fighter(int fightRandom, int fightBonus) {
this.random = fightRandom;
this.bonus = fightBonus;
}
public int fightValue(Random rand) {
return rand.nextInt(this.random) + this.bonus;
}
@Override
public String toString() {
return "(Fighter: " + random + "+" + bonus + ")";
}
}
@Test
public void test() {
final Random random = new Random(42); // since this is a test we want the results to be stable
GameFight<Fighter> fight = new GameFight<Fighter>();
Fighter[] fighters = new Fighter[]{
new Fighter(1), new Fighter(2), new Fighter(3, 2), new Fighter(4),
new Fighter(5), new Fighter(6), new Fighter(7), new Fighter(8), new Fighter(9),
};
FightResults<Fighter> results = fight.fightEvenly(fighters, 10000, new FightInterface<Fighter>() {
@Override
public Fighter determineWinner(Fighter[] players, int fightNumber) {
int a = players[0].fightValue(random);
int b = players[1].fightValue(random);
return a > b ? players[0] : players[1];
}
});
System.out.println(results.toStringMultiLine());
System.out.println(results.getPercentagesDesc());
List<PlayerResults<Fighter>> sortedResults = results.getResultsAsc();
assertEquals(1, sortedResults.get(0).getPlayer().random);
assertEquals(2, sortedResults.get(1).getPlayer().random);
assertEquals(4, sortedResults.get(2).getPlayer().random);
assertEquals(5, sortedResults.get(3).getPlayer().random);
assertEquals(6, sortedResults.get(4).getPlayer().random);
assertEquals(3, sortedResults.get(5).getPlayer().random);
assertEquals(2, sortedResults.get(5).getPlayer().bonus);
assertEquals(7, sortedResults.get(6).getPlayer().random);
assertEquals(8, sortedResults.get(7).getPlayer().random);
}
}
</code></pre>
<p>Output produced by test:</p>
<pre><code>net.zomis.fight.FightResults@f84b0a
(Fighter: 1+0)
as index 0: (0 wins, 0 draws, 80000 losses (0,00 %))
vs. (Fighter: 9+0): 0 wins, 0 draws, 10000 losses (0,00 %)
vs. (Fighter: 3+2): 0 wins, 0 draws, 10000 losses (0,00 %)
vs. (Fighter: 4+0): 0 wins, 0 draws, 10000 losses (0,00 %)
vs. (Fighter: 5+0): 0 wins, 0 draws, 10000 losses (0,00 %)
vs. (Fighter: 7+0): 0 wins, 0 draws, 10000 losses (0,00 %)
vs. (Fighter: 6+0): 0 wins, 0 draws, 10000 losses (0,00 %)
vs. (Fighter: 8+0): 0 wins, 0 draws, 10000 losses (0,00 %)
vs. (Fighter: 2+0): 0 wins, 0 draws, 10000 losses (0,00 %)
(Fighter: 2+0)
as index 0: (14995 wins, 0 draws, 65005 losses (18,74 %))
vs. (Fighter: 9+0): 555 wins, 0 draws, 9445 losses (5,55 %)
vs. (Fighter: 3+2): 0 wins, 0 draws, 10000 losses (0,00 %)
vs. (Fighter: 4+0): 1257 wins, 0 draws, 8743 losses (12,57 %)
vs. (Fighter: 5+0): 1014 wins, 0 draws, 8986 losses (10,14 %)
vs. (Fighter: 1+0): 10000 wins, 0 draws, 0 losses (100,00 %)
vs. (Fighter: 7+0): 727 wins, 0 draws, 9273 losses (7,27 %)
vs. (Fighter: 6+0): 793 wins, 0 draws, 9207 losses (7,93 %)
vs. (Fighter: 8+0): 649 wins, 0 draws, 9351 losses (6,49 %)
(Fighter: 4+0)
as index 0: (32297 wins, 0 draws, 47703 losses (40,37 %))
vs. (Fighter: 9+0): 1596 wins, 0 draws, 8404 losses (15,96 %)
vs. (Fighter: 3+2): 2549 wins, 0 draws, 7451 losses (25,49 %)
vs. (Fighter: 5+0): 2952 wins, 0 draws, 7048 losses (29,52 %)
vs. (Fighter: 1+0): 10000 wins, 0 draws, 0 losses (100,00 %)
vs. (Fighter: 7+0): 2161 wins, 0 draws, 7839 losses (21,61 %)
vs. (Fighter: 6+0): 2453 wins, 0 draws, 7547 losses (24,53 %)
vs. (Fighter: 8+0): 1843 wins, 0 draws, 8157 losses (18,43 %)
vs. (Fighter: 2+0): 8743 wins, 0 draws, 1257 losses (87,43 %)
(Fighter: 5+0)
as index 0: (40963 wins, 0 draws, 39037 losses (51,20 %))
vs. (Fighter: 9+0): 2216 wins, 0 draws, 7784 losses (22,16 %)
vs. (Fighter: 3+2): 4075 wins, 0 draws, 5925 losses (40,75 %)
vs. (Fighter: 4+0): 7048 wins, 0 draws, 2952 losses (70,48 %)
vs. (Fighter: 1+0): 10000 wins, 0 draws, 0 losses (100,00 %)
vs. (Fighter: 7+0): 2822 wins, 0 draws, 7178 losses (28,22 %)
vs. (Fighter: 6+0): 3251 wins, 0 draws, 6749 losses (32,51 %)
vs. (Fighter: 8+0): 2565 wins, 0 draws, 7435 losses (25,65 %)
vs. (Fighter: 2+0): 8986 wins, 0 draws, 1014 losses (89,86 %)
(Fighter: 6+0)
as index 0: (47861 wins, 0 draws, 32139 losses (59,83 %))
vs. (Fighter: 9+0): 2731 wins, 0 draws, 7269 losses (27,31 %)
vs. (Fighter: 3+2): 5005 wins, 0 draws, 4995 losses (50,05 %)
vs. (Fighter: 4+0): 7547 wins, 0 draws, 2453 losses (75,47 %)
vs. (Fighter: 5+0): 6749 wins, 0 draws, 3251 losses (67,49 %)
vs. (Fighter: 1+0): 10000 wins, 0 draws, 0 losses (100,00 %)
vs. (Fighter: 7+0): 3546 wins, 0 draws, 6454 losses (35,46 %)
vs. (Fighter: 8+0): 3076 wins, 0 draws, 6924 losses (30,76 %)
vs. (Fighter: 2+0): 9207 wins, 0 draws, 793 losses (92,07 %)
(Fighter: 3+2)
as index 0: (49760 wins, 0 draws, 30240 losses (62,20 %))
vs. (Fighter: 9+0): 3315 wins, 0 draws, 6685 losses (33,15 %)
vs. (Fighter: 4+0): 7451 wins, 0 draws, 2549 losses (74,51 %)
vs. (Fighter: 5+0): 5925 wins, 0 draws, 4075 losses (59,25 %)
vs. (Fighter: 1+0): 10000 wins, 0 draws, 0 losses (100,00 %)
vs. (Fighter: 7+0): 4306 wins, 0 draws, 5694 losses (43,06 %)
vs. (Fighter: 6+0): 4995 wins, 0 draws, 5005 losses (49,95 %)
vs. (Fighter: 8+0): 3768 wins, 0 draws, 6232 losses (37,68 %)
vs. (Fighter: 2+0): 10000 wins, 0 draws, 0 losses (100,00 %)
(Fighter: 7+0)
as index 0: (53585 wins, 0 draws, 26415 losses (66,98 %))
vs. (Fighter: 9+0): 3428 wins, 0 draws, 6572 losses (34,28 %)
vs. (Fighter: 3+2): 5694 wins, 0 draws, 4306 losses (56,94 %)
vs. (Fighter: 4+0): 7839 wins, 0 draws, 2161 losses (78,39 %)
vs. (Fighter: 5+0): 7178 wins, 0 draws, 2822 losses (71,78 %)
vs. (Fighter: 1+0): 10000 wins, 0 draws, 0 losses (100,00 %)
vs. (Fighter: 6+0): 6454 wins, 0 draws, 3546 losses (64,54 %)
vs. (Fighter: 8+0): 3719 wins, 0 draws, 6281 losses (37,19 %)
vs. (Fighter: 2+0): 9273 wins, 0 draws, 727 losses (92,73 %)
(Fighter: 8+0)
as index 0: (58305 wins, 0 draws, 21695 losses (72,88 %))
vs. (Fighter: 9+0): 3925 wins, 0 draws, 6075 losses (39,25 %)
vs. (Fighter: 3+2): 6232 wins, 0 draws, 3768 losses (62,32 %)
vs. (Fighter: 4+0): 8157 wins, 0 draws, 1843 losses (81,57 %)
vs. (Fighter: 5+0): 7435 wins, 0 draws, 2565 losses (74,35 %)
vs. (Fighter: 1+0): 10000 wins, 0 draws, 0 losses (100,00 %)
vs. (Fighter: 7+0): 6281 wins, 0 draws, 3719 losses (62,81 %)
vs. (Fighter: 6+0): 6924 wins, 0 draws, 3076 losses (69,24 %)
vs. (Fighter: 2+0): 9351 wins, 0 draws, 649 losses (93,51 %)
(Fighter: 9+0)
as index 0: (62234 wins, 0 draws, 17766 losses (77,79 %))
vs. (Fighter: 3+2): 6685 wins, 0 draws, 3315 losses (66,85 %)
vs. (Fighter: 4+0): 8404 wins, 0 draws, 1596 losses (84,04 %)
vs. (Fighter: 5+0): 7784 wins, 0 draws, 2216 losses (77,84 %)
vs. (Fighter: 1+0): 10000 wins, 0 draws, 0 losses (100,00 %)
vs. (Fighter: 7+0): 6572 wins, 0 draws, 3428 losses (65,72 %)
vs. (Fighter: 6+0): 7269 wins, 0 draws, 2731 losses (72,69 %)
vs. (Fighter: 8+0): 6075 wins, 0 draws, 3925 losses (60,75 %)
vs. (Fighter: 2+0): 9445 wins, 0 draws, 555 losses (94,45 %)
Time spent: 164.853973 milliseconds
{(Fighter: 9+0)=0.777925, (Fighter: 8+0)=0.7288125, (Fighter: 7+0)=0.6698125, (Fighter: 3+2)=0.622, (Fighter: 6+0)=0.5982625, (Fighter: 5+0)=0.5120375, (Fighter: 4+0)=0.4037125, (Fighter: 2+0)=0.1874375, (Fighter: 1+0)=0.0}
</code></pre>
<h1>Questions</h1>
<ul>
<li>Is the public interface for these classes clear? Do they seem easy to use?</li>
<li>Does these classes seem useful to you?</li>
<li>Anything that can be improved, at all, anywhere, somehow? (In one way, the more the better)</li>
</ul>
|
[] |
[
{
"body": "<p>A couple things I would say:</p>\n\n<ul>\n<li><code>int FIRST_FIGHT = 1</code> is\n<ul>\n<li>declared improperly; it should be <code>public static final</code> (it will <em>act</em> this way without the explicit declaration, but I think it makes it clearer to add those modifiers; less to think about)</li>\n<li>never used</li>\n<li>not zero-based (any reason?)</li>\n<li>a little overkill on the constants front, especially if you switch to zero-based, where numeric primitive types are by default initialized to zero</li>\n</ul></li>\n<li>Type parameter <code>PL</code> should be <code>P</code> unless you have a good reason otherwise. (<code>T</code> might be even better, but that's up to you.)</li>\n<li>You shouldn't use <code>PL[]</code> because it's not type-safe. Use <code>List<PL></code> or <code>Collection<PL></code> instead (both from <em>java.util</em> package).</li>\n<li><p>Your test case isn't really comprehensive. I've found the most robust tests to be of the following format:</p>\n\n<pre><code>final int TEST_COUNT = 100_000; // or higher\nfinal Random r = new Random();\n// set up some counters here\nfor (int i=0; i < TEST_COUNT; i++) {\n int result = r.nextInt(3);\n switch (result) {\n case 0: // do \"P1 win\" logic and break;\n case 1: // do \"draw\" logic and break;\n case 2: // do \"P1 loses\" logic and break;\n }\n boolean conditionsExpected = /* ... */ ;\n assertTrue(conditionsExpected);\n}\n</code></pre>\n\n<p>This could be in addition to your current test, but it's always good to test things at high loads. This also handles edge conditions and stuff like that. (Make sure your <code>TEST_COUNT</code> is always a good deal higher than the highest argument to <code>r.nextInt</code>.)</p></li>\n<li>Your test case shouldn't really print out anything. If you're testing the logic of <code>toStringMultiLine</code>, do some string parsing. If it's just there for debugging, probably remove it.</li>\n<li>Your exceptions don't generally say much about <em>why</em> the fighters \"can't be equal\" at the moment.</li>\n<li><p>If you're in Java 7 or higher, use that diamond operator <code><></code> to turn this</p>\n\n<pre><code>private final Map<PL, PlayerResults<PL>> playerData = new HashMap<PL, PlayerResults<PL>>();\n</code></pre>\n\n<p>into this:</p>\n\n<pre><code>private final Map<PL, PlayerResults<PL>> playerData = new HashMap<>();\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T11:13:13.397",
"Id": "71757",
"Score": "0",
"body": "When declaring \"fields\" in an interface, they automatically become `public static final`. I found it more reasonable to be 1-based as it's not an array, it's just meant as a human understandable counter. It is used in another project that uses this code. `PL` is used as a short form for \"Player\", but `T` could work also. In what way is it not type-safe to use `PL[]`? Since PL is a generic type, it becomes the more specific type when using specific types. Unfortunately I am using Java 6 for Android compatibility. Your other suggestions seem good."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T14:08:14.560",
"Id": "71784",
"Score": "0",
"body": "I'm not sure in what way my testing code isn't 'comprehensible' though? Are you suggesting that I remove the FightInterface implementation from my test and extract it to the testmethod itself? That would make the test useless as the test is meant to show how my Fighting classes are used. I'm not really sure about what you mean here..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T20:58:13.750",
"Id": "71822",
"Score": "0",
"body": "Fields: yes, but I think it makes it more readable; your choice. `PL`: I understand, but [(strong) convention is one-character type parameter names](http://docs.oracle.com/javase/tutorial/java/generics/types.html), usually starting with `T` for *type*, but `P` would be okay as well. Type-safety: **very important,** please [see this](http://stackoverflow.com/a/1817544/732016) and [this](http://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createArrays). Java6: okay."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T21:01:28.607",
"Id": "71824",
"Score": "0",
"body": "I meant \"[comprehensive](https://www.google.com/#q=define:comprehensive),\" not \"comprehensible.\" The code is completely readable, but you're only testing a couple values, so it would be easy for something to slip through the cracks. The point of testing is to catch edge cases and stuff; using a ton of random trials simulates real-world use. See [here](https://github.com/WChargin/apcs/blob/7d7e218a3456cafaf36f759b74f72ce6ef3f2493/HashTables/src/hash/RobustSimpleMapTest.java#L64) for an example of testing against a built-in implementation with 1000 trials and three possible operations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T21:32:08.490",
"Id": "71830",
"Score": "0",
"body": "*Why does two words sound so similar but mean something entirely different?* Well, now I've learned more English at least. The naming convention makes sense, will fix that. Consider the testing more an example of usage instead of testing every single piece of the code. Increasing the number of trials further I can agree with, but what more assertions should be added for these classes? Also, any comments to the *usefulness* of the code?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T00:30:19.823",
"Id": "41701",
"ParentId": "41698",
"Score": "9"
}
},
{
"body": "<h2>Android support</h2>\n\n<blockquote>\n <p>Unfortunately I am using Java 6 for Android compatibility. </p>\n</blockquote>\n\n<p>I'm not sure why you would want to run that code on Android. It seems it would better fit running as a service on a server or as a standalone program on the machine. This seems to be used to fine-tuned some AI strategies or way of working, so I don't see how that would be relevant in an Android app.</p>\n\n<h2>Interface definition</h2>\n\n<pre><code>/**\n * Make two fighters fight each other\n * \n * @param players The players that should fight each other\n * @param fightNumber Which fight number in the series this is, starting at 1.\n * @return The winner of the fight, or null if it is a draw\n */\nT determineWinner(T[] players, int fightNumber);\n</code></pre>\n\n<p>I like the Javadoc on that method, it was clear and it really telling on what that method should do as a contract. The thing is, I don't find the name reflecting on what that method is describing. In my mind, determining a winner does not imply that there is a responsibility to make them \"fight\". I would prefer making it more clear with like <code>executeFight</code> or <code>fight</code>, I'm not sure what would be best but I hope you see my point.</p>\n\n<p>Returning <code>null</code> is not the best thing in the world if you can avoid it. Since you're no longer bound to the Android platform, you could at least return an <code>Optional</code>. That would force the user to handle the <code>null</code> value. You could think about a better way to return the data, but I would start with <code>Optional</code> and see how things go from there.</p>\n\n<h2>FightResults</h2>\n\n<pre><code> if (descending) \n res = e1.getValue().compareTo(e2.getValue());\n else res = e2.getValue().compareTo(e1.getValue());\n</code></pre>\n\n<p>I'm not sure that not using bracket is helping here. I would suggest to use brackets. </p>\n\n<p><code>str.append(\"\\n\");</code> I would use the more platform friendly <code>System.lineSeperator()</code></p>\n\n<p>Other than that, I really like the <code>entriesSortedByValues</code> but the signature is hard to make sense at first sight. </p>\n\n<hr>\n\n<p>I've looked at the classes, but I must say the code is clear and really good. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-11-14T09:01:27.677",
"Id": "342457",
"Score": "2",
"body": "You're right, in the past 3-4 years since I started writing this code, I've never once ran it on Android, or GWT or anything else that enforces Java 6. Java 8 FTW!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-11-14T01:57:04.447",
"Id": "180371",
"ParentId": "41698",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "41701",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T23:19:33.893",
"Id": "41698",
"Score": "16",
"Tags": [
"java"
],
"Title": "Ready? Set. Fight!"
}
|
41698
|
<p>This random generator uses cryptographically secure numbers/chars instead of <code>Math.random()</code>. The Javascript code with jQuery works well but I affect clean code ;) It would be great if you could help me to optimize the code (e.g. in speed).</p>
<pre><code>(function () {
var $length, $result, $new, $chars;
$(document).ready(function () {
$length = $('#pw-length');
$result = $('#pw-result');
$new = $('#get-new-pw');
$chars = $('#pw-chars');
// display the result on page load
getRandomString();
// generate new password
$new.click(function () {
getRandomString();
return false;
});
// allow only numbers in the length-input-field
$length.on('keyup focusout', function () {
$length.val($length.val().replace(/[^0-9]/g, ''));
});
});
function randomString(length) {
var charset = $chars.val(),
length = parseInt($length.val()),
i,
result = "";
// First we're going to try to use a built-in CSPRNG
if (window.crypto && window.crypto.getRandomValues) {
values = new Uint32Array(length);
window.crypto.getRandomValues(values);
for (i = 0; i < length; i++) {
result += charset[values[i] % charset.length];
}
}
// IE calls it msCrypto
else if (window.msCrypto && window.msCrypto.getRandomValues) {
values = new Uint32Array(length);
window.msCrypto.getRandomValues(values);
for (i = 0; i < length; i++) {
result += charset[values[i] % charset.length];
}
}
// -> No built-in functionality -> use the function Math.random()
else {
for (i = 0; i < length; i++) {
result += charset[Math.floor(Math.random() * charset.length)];
}
}
return result;
}
// Display the result
function getRandomString() {
$result.html(randomString(10));
}
}());
</code></pre>
<p>I also uploaded it <a href="http://jsbin.com/jolot/4/watch?html,js,output" rel="nofollow">here</a> for testing.
And of course the corresponding HTML:</p>
<pre><code><input type="text" id="pw-chars" value="AaBbCcDdEeFfGgHhiJjKkLMmNnoPpQqRrSsTtUuVvWwXxYyZz23456789!?$%#&@^+-~*=_.,:;()" />
<input type="text" id="pw-length" value="10" />
<button id="get-new-pw">New</button>
<div id="pw-result"></div>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T19:11:56.943",
"Id": "71813",
"Score": "1",
"body": "If you're concerned that the generation should be cryptographically secure, then you should not simply default to a \"non-safe\" behavior without informing the user about it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T19:31:51.337",
"Id": "71815",
"Score": "0",
"body": "@Bobby: I didn't include this part, because I think it's not necessary :)"
}
] |
[
{
"body": "<p>I agree with @Bobby. If the function can silently fall back to a less secure source of randomness, then it's not really offering any extra security, and you might as well not bother with <code>mscrypto</code> at all.</p>\n\n<p>Verbesserungsvorschlag:</p>\n\n<pre><code>function randomString(length, allowRandomSourceFallback) {\n ...\n}\n</code></pre>\n\n<p>If <code>allowRandomSourceFallback</code> is falsy and <code>mscrypto</code> is unavailable, throw an exception.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T21:33:57.793",
"Id": "41759",
"ParentId": "41700",
"Score": "2"
}
},
{
"body": "<p>You have a bug: the <code>length</code> parameter to <code>randomString()</code> isn't doing anything, since you discard its value immediately. You should separate your concerns into two functions: one \"pure\" function that takes a <code>length</code> parameter and generates a random string of that length, and another function that does all the DOM interaction and uses the first function.</p>\n\n<p>There are three repeated implementations inside <code>randomString()</code>, which is very repetitive. Don't repeat yourself. I repeat, don't repeat yourself. ☺ Instead, find a way to collapse all three cases into one.</p>\n\n<p>The result should be displayed using <a href=\"http://api.jquery.com/text/\" rel=\"nofollow\"><code>jQuery.text()</code></a> instead of <code>jQuery.html()</code>.</p>\n\n<pre><code>(function () {\n var $length, $result, $new, $chars;\n\n $(document).ready(function () {\n $length = $('#pw-length');\n $result = $('#pw-result');\n $new = $('#get-new-pw');\n $chars = $('#pw-chars');\n\n // display the result on page load\n getRandomString();\n // generate new password\n $new.click(function () {\n getRandomString();\n return false;\n });\n\n // allow only numbers in the length-input-field\n $length.on('keyup focusout', function () {\n $length.val($length.val().replace(/[^0-9]/g, ''));\n });\n });\n\n // Crypto provider stub for use as a fallback\n function dumbCrypto(randomIntLimit) {\n return {\n getRandomValues: function(values) {\n for (var i = 0; i < array.length; i++) {\n values[i] = Math.floor(Math.random() * randomIntLimit);\n }\n }\n };\n }\n\n function randomString(length, charset, allowRandomSourceFallback) {\n // Prefer to use a built-in CSPRNG. Neither window.crypto nor\n // window.msCrypto is standard.\n var crypto = (window.crypto && window.crypto.getRandomValues) ? window.crypto :\n (window.msCrypto && window.msCrypto.getRandomValues) ? window.msCrypto :\n allowRandomSourceFallback ? dumbCrypto(charset.length) : null;\n if (crypto === null) {\n throw \"No secure crypto provider available\";\n }\n\n // window.crypto and window.msCrypto require a typed array (which is\n // surely supported if window.crypto or window.msCrypto is defined).\n var values = Uint32Array ? new Uint32Array(length) : new Array(length);\n\n crypto.getRandomValues(values);\n var result = \"\";\n for (var i = 0; i < length; i++) {\n result += charset[values[i] % charset.length];\n }\n return result;\n }\n\n // Produce and display the result\n function getRandomString() {\n $result.text(randomString($length.val(), $chars.val()));\n }\n}());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T00:49:38.053",
"Id": "71855",
"Score": "0",
"body": "Since you used HTML 5 in your demo, you should also take advantage of [`<input type=\"number\">`](http://jsbin.com/jolot/6/edit?html,js,output)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T14:54:37.530",
"Id": "71913",
"Score": "0",
"body": "Thank you so much but the code does not seem to work in (the latest) firefox and IE!? http://jsbin.com/jolot/11/watch"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T21:59:52.713",
"Id": "41763",
"ParentId": "41700",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T00:23:00.587",
"Id": "41700",
"Score": "10",
"Tags": [
"javascript",
"jquery",
"performance",
"random",
"cryptography"
],
"Title": "Can this secure, random generator be improved?"
}
|
41700
|
<p>In a project, I have a lot of HTML forms without validation and I want to add a front end validation, in a quick way. I start looking for a library and I met <a href="http://parsleyjs.org/" rel="nofollow">Parsley.js</a>. It's a good library, but if I decided to use it I would have to modify all the forms in my application. </p>
<p>So there is where this code is born. It's for automatically binding a set of rules you define to a form.</p>
<pre><code>//Only basic types and validators.
$.fn.parsley.mapping = {
//Types
'alphanum': {'parsley-type': 'alphanum'},
'email': {'parsley-type': 'email'},
'url': {'parsley-type': 'url'},
'number': {'parsley-type': 'number'},
'digits': {'parsley-type': 'digits'},
'dateIso': {'parsley-type': 'dateIso'},
'phone': {'parsley-type': 'phone'},
//Validators
'required': {'parsley-required': 'true'},
'notblank': {'parsley-notblank': 'true'},
'minlength': {'parsley-minlength': '?'},
'maxlength': {'parsley-maxlength': '?'},
'min': {'parsley-min': '?'},
'max': {'parsley-max': '?'}
}
//Only inputs and textareas
$.fn.parsley.fields = 'input:visible, textarea:visible';
!function ($) {
$.fn.generalValidation = function( validationRules ) {
var name, validations, validationName, validationValue, att, key, value
, form = $( this )
, addValidations = function( validationRules ){
if(validationRules === undefined){
console.log('Error!!! You need to add the validation rules parameter');
validationRules = {};
}
$( form ).find( $.fn.parsley.fields ).each(function(){
name = $( this ).attr('name');
validations = validationRules[name];
if(validations == undefined) return true;
for(validation in validations){
validationName = validations[validation];
validationValue = '';
if(validationName.indexOf(':') !== -1){
validationValue = validationName.substr(validationName.indexOf(':')+1, validationName.length);
validationName = validationName.substr(0, validationName.indexOf(':'));
}
att = $.fn.parsley.mapping[validationName];
if(att !== undefined){
$.map(att, function (v, k) { key = k; value = v; });
value = (value === '?') ? validationValue : value;
$(this).attr(key, value);
}
}
});
return true;
}
, callParsley = function( form ) {
form.parsley();
};
if(addValidations( validationRules )){
callParsley( form );
}
}
} ( window.jQuery );
</code></pre>
<p><a href="http://jsfiddle.net/BV5sp/" rel="nofollow">Here is a JSFiddle</a>.</p>
<p>This is my first plugin in jQuery. Would you improve something in the code? Do you find this useful?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T02:40:10.880",
"Id": "72435",
"Score": "0",
"body": "I'd recommend keeping the old code embedded here. That's more important than keeping the new code as the answers are based on the old code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T02:40:37.683",
"Id": "72436",
"Score": "0",
"body": "Please avoid invalidating existing answers by modifying your question with updated code. Let the answers sink in, refactor as needed, and then post the updated code in a new question. More votes for everyone! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T02:46:56.640",
"Id": "72438",
"Score": "0",
"body": "@lol.upvote Thanks for pointing this. I'm going to take it into consideration next time. (I know I shouldn't say thanks :P)"
}
] |
[
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li><p>The following is not DRY at all, you have to find a way to not do this:<br></p>\n\n<pre><code>//Types\n'alphanum': { 'parsley-type': 'alphanum' },\n'email': { 'parsley-type': 'email' },\n'url': { 'parsley-type': 'url' },\n'number': { 'parsley-type': 'number' },\n'digits': { 'parsley-type': 'digits' },\n'dateIso': { 'parsley-type': 'dateIso' },\n'phone': { 'parsley-type': 'phone' },\n</code></pre>\n\n<p>I am pretty sure you can throw all that way by changing to the below statement:</p>\n\n<pre><code>att = $.fn.parsley.mapping[validationName] || { 'parsley-type': validationName };\n</code></pre></li>\n<li>Also, <code>$.fn.parsley.mapping</code> could use some aligning to look better</li>\n<li>You are calling <code>$.map</code> without capturing the array it returns, perhaps you meant to use <code>forEach</code> ? Also, it seems that your code will not work correctly if there is more than 1 property in <code>parsley.mapping</code>.You keep assign to the same <code>key</code> and <code>value</code>.</li>\n<li><p>Your <code>var</code> statement is too messy:<br></p>\n\n<pre><code>var name, validations, validationName, validationValue, att, key, value, form = $(this),\n addValidations = function (validationRules) {\n</code></pre></li>\n<li>Comparisons with <code>undefined</code> should be either with <code>===</code> or by doing a falsey check so use either <code>if(validations === undefined)</code> or <code>if(!validations)</code></li>\n<li>There is no <code>var validation</code> for <code>for(validation in validations){</code></li>\n<li>There are plenty of comma and semicolon problems, you should use jshint to find & solve them</li>\n</ul>\n\n<p>All in all, I like the value of your wrapper, but I think it needs some more polishing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T02:39:13.827",
"Id": "72434",
"Score": "0",
"body": "@konjin I just update my question with the new code following some of your suggestions and JSHint. I can't figure it out how to get rid of the map function in the for, both (you and JSHint) don't like it haha."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T01:04:33.620",
"Id": "41768",
"ParentId": "41703",
"Score": "3"
}
},
{
"body": "<p>What about jquery validate?\nYou shouldn't have to change any forms... If you're changing the form to accommodate the JavaScript you're not doing it right.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T01:48:23.450",
"Id": "72425",
"Score": "0",
"body": "Hey, all the plugins or whatever I looked you have to modify your form and add the rules for the validation. Can you point me out one that does not require that? (Googled jquery validate but I don't know what are you referring)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T05:02:24.640",
"Id": "72445",
"Score": "0",
"body": "Read the first two paragraphs: http://jqueryvalidation.org/documentation/. You can set the rules in an object that is passed to validate () rather than in the form."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T18:47:53.757",
"Id": "41823",
"ParentId": "41703",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "41768",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T00:55:42.120",
"Id": "41703",
"Score": "5",
"Tags": [
"javascript",
"jquery",
"validation"
],
"Title": "jQuery wrapper of Parsley.js"
}
|
41703
|
<p>For example, suppose in a view class we need to instantiate some UI components and then populate the fields. Something like:</p>
<pre><code>var View = function() {
this._initUI();
this._populateFields();
};
View.prototype = {
_initUI: function() {
this.textField = new TextField();
this.comboBox = new Combobox();
},
_populateFields: function() {
this.textField.setText('foo');
this.comboBox.setVal('bar');
}
};
</code></pre>
<p>This doesn't quite smell right, as you must call <code>_initUI</code> before <code>_populateFields</code>, and it's pretty hidden that <code>_initUI</code> will be creating some instance variables that will later be used by <code>_populateFields</code>.</p>
<p>What's your opinion of a better way of doing this?</p>
|
[] |
[
{
"body": "<p>You could have a flag that is set when <code>_initUI</code> is called. The first line of <code>_initUI</code> would check the flag and exit if it's already set; the second line would set it. Then any method which needs <code>_initUI</code> to have been called can simply, safely, call it without fear of double-initializing things.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T01:14:48.817",
"Id": "41706",
"ParentId": "41705",
"Score": "3"
}
},
{
"body": "<p>I am not sure it is something to be worried about, if you really want to address this and if your <code>_initUI</code> is really that short you could inline the <code>_initUI</code> function:</p>\n\n<pre><code>var View = function() {\n this.textField = new TextField();\n this.comboBox = new Combobox();\n this._populateFields();\n};\n\nView.prototype = {\n _populateFields: function() {\n this.textField.setText('foo');\n this.comboBox.setVal('bar');\n }\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T00:31:45.023",
"Id": "41767",
"ParentId": "41705",
"Score": "3"
}
},
{
"body": "<p>What you're saying is <code>_populateFields</code> is <em>dependent</em> on <code>_initUI</code>. You could model this dependency in a few ways. You could call <code>_initUI</code> from <code>_populateFields</code>:</p>\n\n<pre><code>_populateFields: function() {\n _initUI();\n ...etcetera...\n}\n</code></pre>\n\n<p>If you have a library that defines <code>assert</code> in Javascript you could add a flag and an assert:</p>\n\n<pre><code>_initUI: function() {\n initialized = true;\n ...etcetera...\n}\n_populateFields: function() {\n assert(initialized);\n ...etcetera...\n}\n</code></pre>\n\n<p>This gives you the advantage of being able to call <code>_populateFields</code> multiple times without calling <code>_initUI</code> again, as well as letting you separate the calls in time. </p>\n\n<p>You could combine the two, calling <code>_initUI</code> conditionally at the start of <code>_populateFields</code> if it hasn't been called yet. </p>\n\n<pre><code>_initUI: function() {\n initialized = true;\n ...etc...\n}\n\n_populateFields: function() {\n if (!initialized) {\n _initUI();\n }\n ...etc...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T18:09:50.477",
"Id": "42179",
"ParentId": "41705",
"Score": "3"
}
},
{
"body": "<p>If you can assure that the view should be initialized on construction time, why not use the constructor or return a already initialized object? </p>\n\n<pre><code>var View = function() {\n var textField = new TextField(),\n comboBox = new Combobox();\n\n return {\n populateFields: function () {\n textField.setText('foo');\n comboBox.setVal('bar');\n }\n };\n};\n</code></pre>\n\n<p>This eliminates all flags to check if the view is initialized and hides the initialization so noone can call it (as I assume it is private). </p>\n\n<p>If you can't assure that it's ok to initialize the view on construction time, an internal flag is probably the easy way to go. Yet I'd go with the assertion way. Calling <code>populateField</code> on an un-initialized view indicates a bug/flaw in your application logic. This is not the right scenario for lazy initialization. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T18:26:02.667",
"Id": "42181",
"ParentId": "41705",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T00:56:17.563",
"Id": "41705",
"Score": "7",
"Tags": [
"javascript"
],
"Title": "What is the best way to refactor out “temporal dependence” of instance methods?"
}
|
41705
|
<p>What is an island?
A group of connected 1s forms an island. For example, the below matrix contains 5 islands:</p>
<pre><code>{{1, 1, 0, 0, 0},
{0, 1, 0, 0, 1},
{1, 0, 0, 1, 1},
{0, 0, 0, 0, 0},
{1, 0, 1, 0, 1}}
</code></pre>
<p>I'm looking for code review, best practices, optimizations etc.</p>
<pre><code>public final class CountIslands {
private CountIslands() {}
private static enum Direction {
NW(-1, -1), N(0, -1), NE(-1, 1), E(0, 1), SE(1, 1), S(1, 0), SW(1, -1), W(-1, 0);
int rowDelta;
int colDelta;
Direction(int rowDelta, int colDelta) {
this.rowDelta = rowDelta;
this.colDelta = colDelta;
}
public int getRowDelta() {
return rowDelta;
}
public int getColDelta() {
return colDelta;
}
}
private static boolean isValid(int newRow, int newCol, Direction direction, int[][] m, boolean[][] visited) {
// visited was constructed from matrix so we are sure that checking visitor for row lengh would do no harm.
if (newRow < 0 || newRow >= visited.length) return false;
if (newCol < 0 || newCol >= visited[0].length) return false;
if (visited[newRow][newCol]) return false;
return m[newRow][newCol] == 1;
}
private static void dfs(int row, int col, int[][] m, boolean[][] visited) {
visited[row][col] = true;
for (Direction direction : Direction.values()) {
int newRow = row + direction.getRowDelta();
int newCol = col + direction.getColDelta();
if (isValid(newRow, newCol, direction, m, visited)) {
dfs(newRow, newCol, m, visited);
}
}
}
/**
* Returns the number of 1 islands.
*
* @param m the input matrix
* @return the number of 1 islands.
*/
public static int count(int[][] m) {
final boolean[][] visited = new boolean[m.length][m[0].length];
int count = 0;
for (int row = 0; row < m.length; row++) {
for (int col = 0; col < m[0].length; col++) {
if (m[row][col] == 1 && !visited[row][col]) {
dfs(row, col, m, visited);
count++;
}
}
}
return count;
}
public static void main(String[] args) {
int[][] m = { { 1, 1, 0, 0 }, { 0, 0, 0, 1 }, { 0, 0, 1, 1 } };
System.out.println("Expected 2, Actual " + count(m));
int[][] m1 = { { 1, 1, 0, 0 }, { 0, 0, 1, 1 }, { 0, 0, 1, 1 } };
System.out.println("Expected 1, Actual " + count(m1));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T02:06:03.170",
"Id": "71737",
"Score": "5",
"body": "You've been on this site for a while now, and you ask pretty good question's. I haven't seen you on our [chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor), you should come visit us sometime. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T23:47:44.970",
"Id": "71850",
"Score": "0",
"body": "I was not aware that such a chat room existed and thanks for letting me know about it. I will visit it. Thanks"
}
] |
[
{
"body": "<p>So, I looked at the problem spec, expecting to see a 3-word description o the title of the problem, and not much else, followed by 'Looking for optimizations, and confirmation that compelxity is <em>O(n log(n) )</em>.</p>\n<p>Fortunately, I was disappointed ;-) Your description is improved over previous questions, and I can actually follow it without having to google-search for references and hints. It would have been improved slightly if you had spelled out carefully that diagonally touching <code>1</code> values combine to form an island... but this is a nit-pick.</p>\n<p>Then, I did the normal-for-me task of thinking 'How would I solve this', and I thought for a moment, and decided I would:</p>\n<ol>\n<li>scan the matrix cell-by-cell</li>\n<li>if you encounter a 1, use recursion to follow all it's adjacent 1 values</li>\n<li>mark all visited cells as 'seen'</li>\n<li>consider that process a 'hit' for an island</li>\n<li>scan the remaining unseen cells for the next unseen island. (go to 1).</li>\n</ol>\n<p>So, I looked through your code, and, it took me a moment, but I found <strong>all</strong> of those processes in your solution.</p>\n<p>So, you have solved this the same way I would have tackled it. The algorithm is 'good', and all that is then left, is to look at how you have implemented it...</p>\n<ul>\n<li>I like the Enum for the directions. It is a good solution.</li>\n<li>I think your variable names have improved recently. I much prefer seeing <code>row</code> and <code>col</code> instead of <code>x</code> and <code>y</code>, etc. It is more descriptive, and it helps.</li>\n<li><code>count()</code> could be <code>countIslands()</code> because that is what is being counted.</li>\n</ul>\n<p>That's a pretty short list of nit-picky things. In all, this is a good program.</p>\n<p>There is one suggestion I have for your recursion, and that is that there are multiple 'styles' of recursive methods. If you choose one method, and use it consistently (except for those times the other methods are better), it helps. My suggestion is that you should settle on what I call optimistic recursion.... which is the opposite case of what <a href=\"http://en.wikipedia.org/wiki/Recursion_%28computer_science%29#Short-circuiting_the_base_case\" rel=\"noreferrer\">Wikipedia calls 'short-circuit recursion'</a>. What I am saying, is that 'standard' recursion checks the recursive state, and, if it is valid, it does it's work, and it then calls recursion. The short-circuit system does the state-check of the new state <strong>before</strong> recursing in to that new state.</p>\n<p>By way of example, a standard (what I call optimistic) recursion for this problem would be:</p>\n<pre><code>private static void dfs(int row, int col, int[][] m, boolean[][] visited) {\n // check recursion state... and expect it to have failures.\n if (row < 0 || row >= m.length || col < 0 || col >= m[0].length) {\n // invalid state, index-out-of-bounds\n return;\n }\n // OK, row/column are valid... more checks\n if (visited[row][col]) {\n // already seen this valid position.\n return;\n }\n // mark the position seen\n visited[row][col] = true;\n // if it's not an island....\n if (0 == m[row][col]) {\n return;\n }\n // OK, we are still on the island, let's optimistically search around....\n for (Direction direction : Direction.values()) {\n dfs(row + direction.getRowDelta(), col + direction.getColDelta(), m, visited);\n }\n}\n</code></pre>\n<p>This optimistic approach simplifies the call structure significantly.... (and eliminates the isValid() method).</p>\n<p>Food for thought.</p>\n<p>Finally, I don't like calling your method <code>dfs</code>.... it's not a depth-first-search.... since that applies to a tree. The 'cells' in the 'landscape' are not linked in a tree structure, as one cell could be a neighbour to many other cells. A better name would be <code>scan</code>, or even just <code>search</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T11:31:44.863",
"Id": "71760",
"Score": "0",
"body": "Good review, I just have to say that I actually prefer `x` and `y` before `col` and `row`. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-31T21:06:33.983",
"Id": "366468",
"Score": "0",
"body": "A priceless advice! it made my code look dead simple(I am not using enum) and easier to reason about, my interview is next week wish I could have practiced this approach more."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T02:16:35.973",
"Id": "41709",
"ParentId": "41707",
"Score": "11"
}
},
{
"body": "<p>Besides what @rolfl has said, I only have one nit-pick. I consider this to be a pretty big one though.</p>\n\n<p>Put this at the beginning of your main method:</p>\n\n<pre><code>Direction.NW.rowDelta = 4;\nDirection.S.colDelta = -2;\n</code></pre>\n\n<p>Congratulations, you have now screwed up your program!</p>\n\n<p>Switching the deltas for any direction should not be allowed, it <strong>should not compile</strong>. To make it that way, you have to add <code>private final</code> to your field declarations in your enum (Technically you only need final but it never hurts to put in private there as well)</p>\n\n<pre><code>private final int colDelta;\nprivate final int rowDelta;\n</code></pre>\n\n<p>After making that change and trying to modify the deltas from anywhere, you will see that <em>there</em> is the compiler error that we all love!</p>\n\n<p>Besides this, I have only good things to say. I like your <code>Direction</code> enum, it is good enough to be a public enum in a completely separate file actually - I believe you can re-use it for other purposes. It was very easy to understand your question, your code is overall well written. Good job.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T11:31:08.907",
"Id": "41726",
"ParentId": "41707",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "41709",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T01:18:58.250",
"Id": "41707",
"Score": "14",
"Tags": [
"java",
"matrix"
],
"Title": "Count the one islands in the matrix"
}
|
41707
|
<p>I'm still at a very beginner level and I'm constantly working on small things to try and develop my skills. I'm hoping someone could just give me a quick review if there's anything obviously horrible about the code from my main PHP class. It's not feature-complete, but I'm hoping at this point I should be able to get a good review that will help me prevent future mistakes.</p>
<p>My <a href="https://bitbucket.org/wshrews/gif2html5/src" rel="nofollow">full source can be found here</a> and a live demo is temporarily working here:</p>
<pre class="lang-none prettyprint-override"><code>http://162.243.44.206/gif2html5/
</code></pre>
<hr>
<pre><code>class Gif2Html5
{
private $uploadDir;
private $fileSizeLimitBytes;
private $isWindows;
function __construct($uploadDir, $fileSizeLimitMB = 4)
{
$this->uploadDir = $uploadDir;
$this->fileSizeLimitBytes = $fileSizeLimitMB * 1048576;
$this->isWindows = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? true : false;
}
public function create()
{
if (!isset($_FILES['uploadImage'])) {
echo "Please select the file you want to upload.";
return;
}
if (filesize($_FILES['uploadImage']['tmp_name']) > $this->fileSizeLimitBytes) {
echo "The file you uploaded exceeds the size limit of " . $this->fileSizeLimitBytes / 1048576 . "MB";
return;
}
if ($_FILES['uploadImage']['error'] == UPLOAD_ERR_OK) {
$deleteKey = $this->generateRandomString(15);
do {
$randomDir = $this->generateRandomString(5);
} while (file_exists($this->uploadDir . $randomDir));
$newDir = $this->uploadDir . $randomDir . '/';
mkdir($newDir, 0777, true);
$uploadFile = $newDir . $randomDir . '.gif';
if (!imagecreatefromgif($_FILES['uploadImage']['tmp_name'])) {
echo "The uploaded image is not a valid .gif file.";
return;
}
if (!move_uploaded_file($_FILES['uploadImage']['tmp_name'], $uploadFile)) {
echo "There was a problem moving the file to the upload directory.";
return;
}
if (!$fp = fopen($newDir . $deleteKey . '.txt', 'wb')) {
echo "There was a problem generating the delete key. Please try again later.";
return;
} else {
fclose($fp);
}
if ($this->isWindows) {
$exif = 'libraries/exif/WIN/exiftool.exe -v ';
$h264 = 'libraries/ffmpeg/WIN/bin/ffmpeg.exe -r ';
$webm = 'libraries/ffmpeg/WIN/bin/ffmpeg.exe -r ';
} else {
$exif = 'libraries/exif/LINUX/exiftool -v ';
$h264 = 'libraries/ffmpeg/LINUX/ffmpeg -r ';
$webm = 'libraries/ffmpeg/LINUX/ffmpeg -r ';
}
/*
* ------------------------------------------------------------------------
* Use exiftool to determine gif framecount and duration and calculate FPS.
* http://sno.phy.queensu.ca/~phil/exiftool/
* ------------------------------------------------------------------------
*/
$exif .= $uploadFile;
$c1 = $this->isWindows ? str_replace("/", "\\", $exif) : $exif;
exec($c1, $out, $return);
try {
$x = explode(" = ", $out[sizeof($out) - 1]);
$y = explode(" = ", $out[sizeof($out) - 2]);
if(strtoupper(substr($x[0], 2, 11)) === "FRAMECOUNT"){
$fps = 10;
} else if(strtoupper(substr($y[0], 2, 10)) === "FRAMECOUNT") {
$fps = $y[1] / $x[1];
} else {
throw new Exception('Potentially non-animated .gif file.');
}
} catch (Exception $e) {
echo "There was a problem converting the uploaded .gif file.";
return;
}
list($width, $height) = getimagesize($uploadFile);
if ($width % 2 != 0) {
--$width;
}
if ($height % 2 != 0) {
--$height;
}
/*
* -----------------------------------------------
* Use ffmpeg to convert the gif to webm and h264.
* http://www.ffmpeg.org/
* http://ffmpeg.gusari.org/static/
* http://ffmpeg.zeranoe.com/builds/
* -----------------------------------------------
*/
$h264 .= $fps . ' -i ' . $uploadFile . ' -y -strict experimental -acodec aac -ac 2 -ab 160k -vcodec libx264 -s ' . $width . 'x' . $height . ' -pix_fmt yuv420p -preset slow -profile:v baseline -level 30 -maxrate 10000000 -bufsize 10000000 -b 1200k -f mp4 -threads 0 ' . $newDir . $randomDir . '.mp4';
$webm .= $fps . ' -i ' . $uploadFile . ' -c:v libvpx -b 2000k ' . $newDir . $randomDir . '.webm';
$c2 = $this->isWindows ? str_replace("/", "\\", $h264) : $h264;
$c3 = $this->isWindows ? str_replace("/", "\\", $webm) : $webm;
exec($c2);
exec($c3);
echo "./image/" . $randomDir . '/' . $deleteKey;
return;
}
switch ($_FILES['uploadImage']['error']) {
case 2:
echo "The file you uploaded exceeds the size limit of " . $this->fileSizeLimitBytes / 1048576 . "MB";
break;
case 3:
echo "The file upload failed part way - please try again.";
break;
case 4:
echo "No file was uploaded. Please select a file and try again.";
break;
default:
echo "An error occurred while uploading the file.";
break;
}
return;
}
public function get($id)
{
$requestedDir = $this->uploadDir . $id;
$fileNoExt = $requestedDir . '/' . $id;
$data['id'] = $id;
if (@file_exists($requestedDir)) {
$data['gif'] = @file_exists($fileNoExt . '.gif') ? true : false;
$data['h264'] = @file_exists($fileNoExt . '.mp4') ? true : false;
$data['webm'] = @file_exists($fileNoExt . '.webm') ? true : false;
return $data;
} else {
return false;
}
}
public function delete($id, $key)
{
$requestedDelete = $this->uploadDir . $id . '/' . $key . '.txt';
if (@file_exists($requestedDelete)) {
if($this->isWindows){
$cmd = "RMDIR /s /q " . str_replace("/", "\\", $this->uploadDir . $id);
exec ($cmd);
} else {
system('/bin/rm -rf ' . escapeshellarg($this->uploadDir . $id));
}
return true;
} else {
return false;
}
}
function generateRandomString($stringLength)
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $stringLength; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><code>$this->isWindows = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? true : false;</code> : Your check already evaluates to true. Essentially this reads as <code>if (true) then true else false</code>. It could be shorted to <code>$this->isWindows = strtoupper(substr(PHP_OS, 0, 3))</code>. </li>\n<li>Your class has too many responsibilities: input validation, analyzing the gif, converting the gif, retrieving information for existing files as well as deleting files. I'd split this up into three classes: a service class for orchestrating the conversation, a file management class for retrieving information about existing files, deleting or creating them, and a converter class responsible for converting an existing and gif. This class should only check for constraints required by the conversation, not stuff like file-size and so on. (Single Responsibility Principle)</li>\n<li>It's probably a good idea to have two classes for converation: one for linux and one for windows. Of course they should generalize common behavior in an abstract parent class. A nice side-effect would be to be able to add other conversion methods (or OS) easily without modifying the code (open/close principle).</li>\n<li>You are depending and modifying the global application state. The reusability of this class(es) is limited to a very specific use-case as the file needs to be in <code>$_FILES</code> and the information is <code>echo</code>d. I could not resuse this class somewhere else (e.g. for converting gifs in my command line tool). </li>\n<li>I suppose the <code>generateRandomString</code> method is a helper-method. It probably should be private.</li>\n<li>The gag-operator (<code>@</code>) is highly discouraged. Fix the problem instead of hiding it.</li>\n<li>Validate your keys and ids. A possible attack vector would be directory traversal: <code>->delete('../../../../../etc/', '');</code> or a like. </li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T13:51:16.647",
"Id": "71782",
"Score": "0",
"body": "Thank you. I'm still at the stage where I find it difficult how to break up an application. My only question from your points is how do I avoid using $_FILES?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T13:18:17.080",
"Id": "72064",
"Score": "0",
"body": "@SIL40: You can't $_FILES at all costs. Yet you could the caller decide to use $_FILES instead of the callee. This way your class doesn't know how the file got at the given location (be it by $_FILES or by already existing file) nor does it know the names of the form elements. And this class really doesn't need to know. In the MVC-Pattern this would be the job of the controller (with this class being your model or service)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T09:59:09.367",
"Id": "41724",
"ParentId": "41711",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41724",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T03:44:29.433",
"Id": "41711",
"Score": "5",
"Tags": [
"php",
"beginner"
],
"Title": "GIF to HTML5 video conversion"
}
|
41711
|
<p>I'd like to see how I can improve this code, as I know it's bad practice to have cell reuse identifiers like this, but I could not find any other way to keep the cells that contain images from calling the server again instead of reading the cached image.</p>
<pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = [NSString stringWithFormat:@"cell%d%d",indexPath.section,indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
UIImageView *profileImageView = [[UIImageView alloc]initWithFrame:CGRectMake(12, 4, 60, 60)];
profileImageView.image = [UIImage imageNamed:@"Profile"];
profileImageView.layer.cornerRadius = 30.0;
profileImageView.layer.masksToBounds = YES;
profileImageView.contentMode = UIViewContentModeScaleAspectFit;
UILabel *userNameLabel = [[UILabel alloc]init];
userNameLabel.frame = CGRectMake(82, 0, 228, 68);
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
[cell.contentView addSubview:profileImageView];
[cell.contentView addSubview:userNameLabel];
cell.selectionStyle = UITableViewCellSelectionStyleDefault;
if (indexPath.section == 0)
{
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIView *requestsView = [[UIView alloc]initWithFrame:CGRectMake(240, 0, 80, 68)];
UIButton *approveButton = [UIButton buttonWithType:UIButtonTypeSystem];
approveButton.frame = CGRectMake(0, 16, 36, 36);
[approveButton addTarget:self action:@selector(approveButtonChanged:) forControlEvents:UIControlEventTouchUpInside];
[approveButton setTintColor:[UIColor companyBlue]];
[approveButton setImage:[UIImage imageNamed:@"Approve"] forState:UIControlStateNormal];
[requestsView addSubview:approveButton];
UIButton *denyButton = [UIButton buttonWithType:UIButtonTypeSystem];
denyButton.frame = CGRectMake(42, 16, 36, 36);
[denyButton addTarget:self action:@selector(denyButtonChanged:) forControlEvents:UIControlEventTouchUpInside];
[denyButton setTintColor:[UIColor companyRed]];
[denyButton setImage:[UIImage imageNamed:@"Deny"] forState:UIControlStateNormal];
[requestsView addSubview:denyButton];
userNameLabel.frame = CGRectMake(82, 0, 167, 68);
NSInteger row = (NSInteger)[indexPath row];
NSArray *keys = [self.tableDataSource objectForKey:@"Requests"];
id aKey = [keys objectAtIndex:row];
userNameLabel.text = [aKey objectForKey:@"User"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[aKey objectForKey:@"URL"]]];
request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
request.timeoutInterval = 5.0;
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:
^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if (data)
{
dispatch_async(dispatch_get_main_queue(), ^
{
profileImageView.image = [UIImage imageWithData:data];
});
}
}];
[cell.contentView addSubview:requestsView];
}
if (indexPath.section == 1)
{
NSInteger row = (NSInteger)[indexPath row];
NSArray *keys = [self.tableDataSource objectForKey:@"Friends"];
id aKey = [keys objectAtIndex:row];
NSString *firstName = [aKey objectForKey:@"First"];
NSString *lastName = [aKey objectForKey:@"Last"];
if (firstName.length < 1 && lastName.length < 1)
{
userNameLabel.text = [aKey objectForKey:@"User"];
}
else if (firstName.length > 0 && lastName.length > 0)
{
NSString *combined = [NSString stringWithFormat:@"%@ %@",firstName,lastName];
userNameLabel.text = combined;
}
else if (firstName.length < 1 && lastName.length > 0)
{
userNameLabel.text = lastName;
}
else
{
userNameLabel.text = firstName;
}
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[aKey objectForKey:@"URL"]]];
request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
request.timeoutInterval = 5.0;
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:
^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if (data)
{
dispatch_async(dispatch_get_main_queue(), ^
{
profileImageView.image = [UIImage imageWithData:data];
});
}
}];
}
if (indexPath.section == 2)
{
NSInteger row = (NSInteger)[indexPath row];
NSArray *keys = [self.tableDataSource objectForKey:@"Blocked"];
id aKey = [keys objectAtIndex:row];
userNameLabel.text = [aKey objectForKey:@"User"];
}
}
return cell;
}
</code></pre>
<p>Update new code:</p>
<pre><code>if (!self.pictureArray || !self.pictureArray.count)
{
self.pictureArray = [NSMutableArray arrayWithCapacity:[[self.tableDataSource objectForKey:@"Friends"]count]+[[self.tableDataSource objectForKey:@"Requests"]count]];
}
if (![self.pictureArray objectAtIndex:indexPath.row])
{
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:
^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if (data)
{
dispatch_async(dispatch_get_main_queue(), ^
{
[self.pictureArray insertObject:[UIImage imageWithData:data]
atIndex:indexPath.row];
profileImageView.image = [self.pictureArray objectAtIndex:indexPath.row];
});
}
}];
}
else
{
profileImageView.image = [self.pictureArray objectAtIndex:indexPath.row];
}
</code></pre>
|
[] |
[
{
"body": "<p>So, first thing's first... we definitely need to break this down into groups of smaller methods which are all called from the <code>cellForRowAtIndexPath:</code>. The general rule of thumb is that you should be able to fit an entire method on your screen at the same time without the need to scroll in any direction... and I'm even stricter than that myself.</p>\n\n<p>For example:</p>\n\n<pre><code>UIImageView *profileImageView = [[UIImageView alloc]initWithFrame:CGRectMake(12, 4, 60, 60)];\nprofileImageView.image = [UIImage imageNamed:@\"Profile\"];\nprofileImageView.layer.cornerRadius = 30.0;\nprofileImageView.layer.masksToBounds = YES;\nprofileImageView.contentMode = UIViewContentModeScaleAspectFit;\n\n// ....\n\n[cell.contentView addSubview:profileImageView];\n</code></pre>\n\n<p>We can improve this in many ways. First, add this method.</p>\n\n<pre><code>- (UIImageView *)profileImageView {\n profImgVw = [[UIImageView alloc] initWithFrame:\n CGRectMake(12.0f, 4.0f, 60.0f, 60.0f)];\n // we don't need to set the image if we're just going to change it later\n //profImgVw.image = [UIImage imageNamed:@\"Profile\"];\n profImgVw.layer.cornerRadius = 30.0f;\n profImgVw.layer.masksToBounds = YES;\n profImgVw.contentMode = UIViewContentModeScaleAspectFit;\n\n return profImgVw;\n}\n</code></pre>\n\n<p>Now we can replace some lines in the <code>cellForRowAtIndexPath:</code> to look like this:</p>\n\n<pre><code>UIImageView *profileImageView = [self profileImageView];\n\n// after this method call but before the following method call, you\n// will need to set the image of the profileImageView.\n\n[cell.contentView addSubview:profileImageView];\n</code></pre>\n\n<p>And we've already cut 5 lines out of your <code>cellForRowAtIndexPath:</code> in an attempt to get it down to a more manageable size in terms of readability and maintainability.</p>\n\n<p>You should work through the rest of the method to make tweaks like this.</p>\n\n<hr>\n\n<p>Now then, as to your specific question regarding how to keep around images instead of having to download them again every time the cell is displayed? My approach would be to store them in an <code>NSMutableArray</code> or perhaps an <code>NSMutableDictionary</code>. Whichever one you'd be more comfortable with in terms of pulling the data out. But here's some pseudo-code to get you started...</p>\n\n<pre><code>@property (nonatomic,strong) NSMutableArray *imgArray;\n</code></pre>\n\n<p>Create a <code>@property</code> in the <code>.m</code> file. Now, in our <code>viewDidLoad</code> or somewhere before we've started filling the table, we want to give the <code>imgArray</code> a capacity:</p>\n\n<pre><code>self.imgArray = [NSMutableArray arrayWithCapacity:someCapacity];\n</code></pre>\n\n<p>Where <code>someCapacity</code> is calculated in the same way you calculate the number of rows for the table view section 1.</p>\n\n<p>Now then, in the <code>cellForRowAtIndexPath:</code> method when we're potentially downloading the images, we're going to do something a little similar to the approach I took in the example <code>profileImageView</code> method I showed you.</p>\n\n<pre><code>if (![self.imgArray objectAtIndex:indexPath.row]) {\n // we've never loaded the img before, so we need to download it\n // download it, then assign it to the array\n [self.imgArray insertObject:[UIImage imageWithData:data]\n atIndex:indexPath.row];\n profileImageView.image = [self.imgArray objectAtIndex:indexPath.row];\n} else {\n // image is already in self.imgArray, so just grab it from there\n profileImageView.image = [self.imgArray objectAtIndex:indexPath.row];\n}\n</code></pre>\n\n<p>Now we only need to keep the images in memory and we can let the table view recycle all the other elements of the array that don't need to be downloaded and can easily be redrawn on the fly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T05:31:22.000",
"Id": "71744",
"Score": "0",
"body": "I tried implementing the new image view method, but now no images are shown. Perhaps this is because my reuse identifiers are bad practice in the original question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T12:47:55.293",
"Id": "71768",
"Score": "0",
"body": "Yes. Your approach to reuse identifiers means the cells aren't actually being reused at all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T12:49:52.337",
"Id": "71769",
"Score": "0",
"body": "As another note, you probably shouldn't actually add the `profileImageView` as a subview until you've set the final image. After looking at your code again, I think that the way I implemented the method won't work for your case because you're actually setting a different image to each one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T21:01:08.760",
"Id": "71823",
"Score": "0",
"body": "Please see my updated code above in original question; I'm still confused as to if I'm on the right path of reusing the cells correctly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T22:44:47.043",
"Id": "71842",
"Score": "0",
"body": "Okay I feel that you've pointed my in the right direction. However, the imgArray is always empty when I try to set it's capacity to match the table data source on view did load"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T22:53:01.523",
"Id": "71845",
"Score": "0",
"body": "It will be empty at first. It's empty until you load an image from the web. You then save that image in the array. Every time after the first time, it pulls the image from the array rather than from the way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T22:53:48.520",
"Id": "71846",
"Score": "0",
"body": "My problem is that it crashes before I can get to that point because the array's capacity isn't getting set with the table data source's count before the table methods get called."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T22:55:08.427",
"Id": "71847",
"Score": "0",
"body": "Then you'll have to show me the code where you're trying to set the capacity."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T23:12:18.183",
"Id": "71848",
"Score": "0",
"body": "See my updated code I just posted in original question"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T23:50:44.217",
"Id": "71851",
"Score": "0",
"body": "Nevermind, I used NSCache instead. Thank you sir for your help!"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T05:17:03.990",
"Id": "41716",
"ParentId": "41713",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "41716",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T04:44:09.847",
"Id": "41713",
"Score": "4",
"Tags": [
"objective-c",
"ios"
],
"Title": "UITableView cellForRowAtIndexPath"
}
|
41713
|
<p>Trying to get an understanding of proper unit testing, I've read up quite a bit and found myself writing tests like the ones that follow. Based on "best practices" etc., how am I doing as far as naming the tests, ensuring that each test is correctly limited in what it does, and providing good test coverage? Following those points:</p>
<ol>
<li>I've been naming the tests rather verbosely based on the suggestion that a random person who doesn't know this code (myself in six months) should be able to figure out what each test does from just its name -- note each test has <code>Struct</code> in its name because there are two methods with this signature, and the other (with a nearly-identical set of tests) takes classes.</li>
<li>I've written a few more single-line tests than I'd like and will be refactoring most of this soon, but to keep the tests limited, I'm trying hard to make sure that every test only verifies a single aspect of the interface.</li>
<li>And last, the <code>IsWithinRange</code> method having been written to verify something is ... well .. "within a range"... I've gone out of my way to test the minimum and maximum accepted values, a value in between, and values just past each end, as well as checking each type of exception I expect the method to throw. Is there anything else I'm not testing and should?</li>
</ol>
<p>The full source for the project is on <a href="https://github.com/amazingant/Validation">GitHub</a> if anyone wants to look for more information, but the basic idea is that this <code>Validate</code> class is used to check values at the beginning of a method, and all exceptions for invalid data are returned as a single <code>ValidationException</code>. The full concept came from an <a href="http://blog.getpaint.net/2008/12/06/a-fluent-approach-to-c-parameter-validation/">article by Rick Brewster</a>, and I've just run with it for a bit and written up more ways to check values as I found need for them.</p>
<p><strong>The unit tests currently in question:</strong></p>
<pre><code> [TestMethod]
public void PassingValidToStruct_IsWithinRange_Passes()
{
Validate.Begin().IsWithinRange((Int32?)5, "value", 0, 10).Check();
}
[TestMethod]
public void PassingMinToStruct_IsWithinRange_Passes()
{
Validate.Begin().IsWithinRange((Int32?)0, "value", 0, 10).Check();
}
[TestMethod]
public void PassingMaxToStruct_IsWithinRange_Passes()
{
Validate.Begin().IsWithinRange((Int32?)10, "value", 0, 10).Check();
}
[TestMethod]
public void MinMaxValueSameToStruct_IsWithinRange_Passes()
{
Validate.Begin().IsWithinRange((Int32?)5, "value", 5, 5).Check();
}
[TestMethod]
public void PassingTooSmallToStruct_IsWithinRange_Fails()
{
var valid = Validate.Begin().IsWithinRange((Int32?)-1, "value", 0, 10);
ExceptionAssert.Throws<ValidationException>(() => valid.Check());
}
[TestMethod]
public void PassingTooLargeToStruct_IsWithinRange_Fails()
{
var valid = Validate.Begin().IsWithinRange((Int32?)11, "value", 0, 10);
ExceptionAssert.Throws<ValidationException>(() => valid.Check());
}
[TestMethod]
public void PassingNullToStruct_IsWithinRange_Fails()
{
var valid = Validate.Begin().IsWithinRange((Int32?)null, "value", 0, 10);
ExceptionAssert.Throws<ValidationException>(() => valid.Check());
}
[TestMethod]
public void PassingNullNameToStruct_IsWithinRange_Throws()
{
ExceptionAssert.Throws<ValidationException>(() => Validate.Begin().IsWithinRange((Int32?)5, null, 0, 10));
}
[TestMethod]
public void PassingEmptyNameToStruct_IsWithinRange_Throws()
{
ExceptionAssert.Throws<ValidationException>(() => Validate.Begin().IsWithinRange((Int32?)5, "", 0, 10));
}
[TestMethod]
public void PassingNullMinToStruct_IsWithinRange_Throws()
{
ExceptionAssert.Throws<ValidationException>(() => Validate.Begin().IsWithinRange((Int32?)5, "value", null, 10));
}
[TestMethod]
public void PassingNullMaxToStruct_IsWithinRange_Throws()
{
ExceptionAssert.Throws<ValidationException>(() => Validate.Begin().IsWithinRange((Int32?)5, "value", 0, null));
}
[TestMethod]
public void PassingMinMaxBackwardsToStruct_IsWithinRange_Throws()
{
ExceptionAssert.Throws<ArgumentException>(() => Validate.Begin().IsWithinRange((Int32?)5, "value", 10, 0));
}
</code></pre>
<p><strong>And the method in question:</strong></p>
<pre><code> internal const String ArgumentOutOfRange = "{0}'s value of \"{1}\" is out of range; must be a value from \"{2}\" to \"{3}\"";
/// <summary>
/// Checks a comparable value to ensure that it is within the specified range
/// </summary>
/// <typeparam name="T">Any object type which is a struct, and which implements IComparable</typeparam>
/// <param name="validation">The validation instance to carry forward</param>
/// <param name="value">An instance of T? to check</param>
/// <param name="name">The name of the value</param>
/// <param name="min">An instance of T? which acts as the minimum accepted value</param>
/// <param name="max">An instance of T? which acts as the maximum accepted value</param>
/// <exception cref="ArgumentException">Thrown if min is greater than max</exception>
/// <exception cref="ValidationException">Thrown if min or max is null, or the name is an empty string</exception>
/// <exception cref="ArgumentOutOfRange">Passed on in the return when the value is not within the expected range</exception>
/// <exception cref="ArgumentNullException">Passed on in the return when the value is null</exception>
public static Validation IsWithinRange<T>(this Validation validation, T? value, String name, T? min, T? max) where T : struct, IComparable
{
Validate.Begin()
.IsNotNullOrEmpty(name, "name")
.IsNotNull(min, "min")
.IsNotNull(max, "max")
.Check();
if (min.Value.CompareTo(max.Value) > 0)
throw new ArgumentException("min must be equal to or less than max");
if (!value.HasValue)
return validation.GetInstance().AddException(new ArgumentNullException(name, String.Format(ArgumentNull, name)));
if (min.Value.CompareTo(value.Value) > 0 || max.Value.CompareTo(value.Value) < 0)
return validation.GetInstance().AddException(new ArgumentOutOfRangeException(name, String.Format(ArgumentOutOfRange, name, value.Value, min.Value, max.Value)));
return validation;
}
</code></pre>
|
[] |
[
{
"body": "<p>There's not a universal answer to your question. Instead it's more a matter of finding the point along the continuum that you like and get the most benefit from. If you're testing something extremely complex, fiddly, and prone to updates, it can be well worth splitting out individual tests. If it's less complex, you might find it's conceptually easier to merge a few of your tests (in your case, perhaps merging into a <code>Struct_IsWithinRange_Passes</code> and a <code>Struct_IsWithinRange_Fails</code>. I find this helps find gaps in the testing, as in your case you test several inputs but only a single set of bounds. Thus your original tests would not catch the admittedly unlikely case of hardcoding the bounds.</p>\n\n<pre><code>[TestMethod]\nStruct_IsWIthinRange_Passes()\n{\n // Numbers at either end or anywhere in the middle of the range must pass\n Validate.Begin().IsWithinRange((Int32?)0, \"value\", 0, 10).Check();\n Validate.Begin().IsWithinRange((Int32?)5, \"value\", 0, 10).Check();\n Validate.Begin().IsWithinRange((Int32?)10, \"value\", 0, 10).Check();\n\n // This is even true for large ranges or negative numbers\n Validate.Begin().IsWithinRange((Int32?)Int32.MaxValue, \"value\", 0, Int32.MaxValue).Check();\n Validate.Begin().IsWithinRange((Int32?)Int32.MinValue, \"value\", In32.MinValue, -1).Check();\n}\n\n[TestMethod]\nStruct_IsWithinRange_Fails()\n{\n // Numbers just outside the range must fail\n var valid = Validate.Begin().IsWithinRange((Int32?)-1, \"value\", 0, 10);\n ExceptionAssert.Throws<ValidationException>(() => valid.Check());\n\n var valid = Validate.Begin().IsWithinRange((Int32?)11, \"value\", 0, 10);\n ExceptionAssert.Throws<ValidationException>(() => valid.Check());\n\n // As must null values\n var valid = Validate.Begin().IsWithinRange((Int32?)null, \"value\", 0, 10);\n ExceptionAssert.Throws<ValidationException>(() => valid.Check());\n\n // Even with extremely large ranges\n var valid = Validate.Begin().IsWithinRange((Int32?)Int32.MaxValue, \"value\", 0, Int32.MaxValue - 1);\n ExceptionAssert.Throws<ValidationException>(() => valid.Check());\n\n var valid = Validate.Begin().IsWithinRange((Int32?)Int32.MinValue, \"value\", Int32.MinValue + 1, -1);\n ExceptionAssert.Throws<ValidationException>(() => valid.Check());\n}\n</code></pre>\n\n<p>I was once taught that the theoretical ideal is one in which a single bug introduced results in a single unit test failure so that by seeing the failure you can identify exactly what to go fix. I personally don't find that very feasible in most code, and am perfectly happy with being less granular.</p>\n\n<p>The next step you will wish to consider is whether it's worth making this kind of unit test data-driven. Namely is it worth sacrificing the line information about which test fails to make it easier to test additional values? It would reduce the repetition greatly, especially in the failure case, but it's less clear whether it is a win.</p>\n\n<pre><code>[TestMethod]\nStruct_IsWithinRange_Fails()\n{\n var tests = new[] {\n new { Value = (Int32?)-1, Min = 0, Max = 10 },\n new { Value = (Int32?)11, Min = 0, Max = 10 },\n new { Value = (Int32?)null, Min = 0, Max = 10 },\n new { Value = (Int32?)Int.MaxValue, Min = 0, Max = Int.MaxValue - 1},\n new { Value = (Int32?)Int.MinValue, Min = Int.MinValue + 1, Max = -1},\n };\n\n foreach (var test in tests)\n {\n var valid = Validate.Begin().IsWithinRange(test.Value, \"value\", test.Min, test.Max);\n ExceptionAssert.Throws<ValidationException>(() => valid.Check());\n }\n}\n</code></pre>\n\n<p>As a side note, it's worth mentioning that my additional failure case checks don't themselves verify that a range other than 0-10 is being verified, and none of these test the range is well-formed.</p>\n\n<p>In other contexts I've been taught that unit tests should serve as a living document of the interface you are guaranteeing to your callers. For example you describe that the validation process packages up all reasons a value fails validation. However your tests do not verify this at all. They do not differentiate between the various exceptions that <code>IsWithinRange</code> may add.</p>\n\n<p>More concretely, you have to consider what you are accepting as valid use of this code. Is a caller allowed to look at the exact types of exception, or is it expected to just iterate over the list of exceptions and display them to a user? If the former, you might write some tests that verify the exception types. If the latter, you might write a test that generates multiple exceptions and just verifies it can iterate the list, and that the count is greater than zero.</p>\n\n<p>Regardless, don't get too bogged down in the meta-game here. The purpose of unit tests is to catch unintentional side effects of changes to your code that might result in invalidating its callers assumptions. Once you catch one, you either fix it, or for intentional changes, you document them and ripple their effect throughout your codebase (or your users' codebases) as necessary. Everything else you do with unit tests is either a nice bonus, or extra work.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T03:36:41.757",
"Id": "71864",
"Score": "0",
"body": "Thanks for the supportive feedback. A handful of other tests I've written look like the data-driven test you suggested, and most of what you said goes with things I've thought; good to know I'm thinking the right thoughts. The extra points you brought up about checking the actual contents of the ValidationException objects and making sure the bounds aren't hard-coded however, I didn't think of. So thanks for that too. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T14:15:52.900",
"Id": "41733",
"ParentId": "41714",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "41733",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T04:57:06.697",
"Id": "41714",
"Score": "8",
"Tags": [
"c#",
"unit-testing"
],
"Title": "Are these the right type of unit tests to write?"
}
|
41714
|
<p>I have a class called <code>Machine</code>. It contains a list of parts and a list of actions. The list of parts will contain instances of the <code>Part</code> class subclasses and the list of actions will contain instances of my <code>Action</code> class subclasses. Each <code>Part</code> subclass will have its corresponding <code>Action</code> subclass. None of the subclasses are available at compile time. When a <code>Machine</code> instance starts all its parts should perform their action.</p>
<p>An action will perform the same manipulation for each <code>Part</code> subclass so I am trying to create a factory class that will create a single instance for each <code>Action</code> subclass. My first thought was to use an interface for <code>Action</code>, but then I would have to create an <code>Action</code> instance for each <code>Part</code> instance I create, or make each class that implemented <code>Action</code> responsible for making itself a singleton. I am not sure if a factory is the best solution and if I am implementing the pattern correctly.</p>
<p>Neither <code>Action</code> nor <code>Part</code> subclasses are available to me so I am using generics. I am new to Java so I am not sure if I am using them correctly - Eclipse gives me several Raw type warnings (I indicated where). Here is my code:</p>
<pre><code>import java.util.ArrayList;
public class GenericsTest
{
public static void main(String[] args) throws InstantiationException,
IllegalAccessException
{
ArrayList<Part> parts = new ArrayList<Part>();
Rotate rotate = ActionFactory.getAction(Rotate.class);
Move move = ActionFactory.getAction(Move.class);
int i;
for (i = 0; i < 1000; i++)
{
Gear gear = new Gear();
gear.value1 = i;
gear.actions.add(rotate);
parts.add(gear);
Lever lever = new Lever();
lever.value2 = i + 2000;
lever.actions.add(move);
parts.add(lever);
}
Machine machine = new Machine();
machine.parts.addAll(parts);
machine.start();
}
}
class Machine
{
public void start()
{
for (Part part : parts)
{
// Raw type warning
for (Action action : part.actions)
{
// Raw type warning
action.execute(part);
}
}
}
public ArrayList<Part> parts = new ArrayList<Part>();
}
abstract class Part
{
// Raw type warning
public ArrayList<Action> actions = new ArrayList<Action>();
}
abstract class Action<T extends Part>
{
abstract public void execute(T part);
}
class ActionFactory<T extends Action>
{
public static <T> T getAction(Class<T> c) throws InstantiationException,
IllegalAccessException
{
T returnAction = null;
for (Action action : actions)
{
if (action.getClass() == c)
{
// Unchecked cast warning
returnAction = (T) action;
}
}
if (returnAction == null)
{
returnAction = c.newInstance();
actions.add((Action) returnAction);
}
return returnAction;
}
private static ArrayList<Action> actions = new ArrayList<Action>();
}
/*
* Subject1, Subject2, Action1 and Action2, somewhere else:
*/
class Gear extends Part
{
public int value1;
}
class Lever extends Part
{
public int value2;
}
class Rotate extends Action<Gear>
{
@Override
public void execute(Gear part)
{
System.out.println("rotate action executed, value 1: " + part.value1);
}
}
class Move extends Action<Lever>
{
@Override
public void execute(Lever part)
{
System.out.println("move action executed, value 2: " + part.value2);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T14:18:23.637",
"Id": "71785",
"Score": "4",
"body": "Just a question. How do you know class Gear and class Lever in the GenericsTests when you said that the Gear and Lever are somewhere else?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T17:19:47.607",
"Id": "71802",
"Score": "0",
"body": "I used Gear (and Lever) just as an example. It could be any class inherited from Part."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T18:26:56.523",
"Id": "71809",
"Score": "1",
"body": "I really don't see how \"None of the subclasses are available at compile time.\" To me, it looks like all your subclasses are available at compile time. What exactly do you mean here?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T18:38:42.953",
"Id": "71810",
"Score": "0",
"body": "I would just provide the machine and the base classes or interfaces, and other users would define the concrete parts and actions they are able to perform, then create a machine instance add parts to it and start it."
}
] |
[
{
"body": "<p>I don't understand exactly the purpose of the code but having two similar object inheritance tree (<code>Action</code>s and <code>Part</code>s) smells a little bit. It also seems a sample code and I guess it violates the single responsibility principle (the behaviour of a part is separated to two classes) and it might also violates the Liskov substitution principle too (if you have an <code>Action</code> you can't use it with any kind of <code>Part</code>). I'd consider moving the action code to the <code>Part</code> class or creating generic <code>Action</code> classes which ignore unhandled <code>Part</code>s (by class type). Anyway, it's hard to say something more useful without the purpose of the code. See also: <a href=\"https://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\" rel=\"nofollow noreferrer\">SOLID</a>, <a href=\"http://c2.com/cgi/wiki?ParallelInheritanceHierarchies\" rel=\"nofollow noreferrer\">Parallel Inheritance Hierarchies</a>.</p>\n\n<p>Other notes:</p>\n\n<ol>\n<li><p><code>ArrayList<...></code> reference types should be simply <code>List<...></code>. See: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p>\n\n<pre><code>List<Part> parts = new ArrayList<Part>();\n</code></pre></li>\n<li><p>Public fields usually leads to harder maintenance. See: <a href=\"https://stackoverflow.com/q/7959129/843804\">What's the deal with Java's public fields?</a></p></li>\n</ol>\n\n<p>Some other ideas to consider:</p>\n\n<ol>\n<li><p>Create a separate <code>Action</code> instance for every part and action. Pass the <code>Part</code> instance to the constructor of your <code>Action</code>. For example:</p>\n\n<pre><code>Action rotate = new Rotate(gear);\n</code></pre>\n\n<p>Store the actions in a list and then you can call <code>execute</code> on the <code>rotate</code> instance:</p>\n\n<pre><code>for (final Action action: actions) {\n action.execute();\n}\n</code></pre>\n\n<p>It's type-safe, clients can't create an <code>Action</code> with a wrong <code>Part</code> type.</p></li>\n<li><p>I'd move the <code>actions</code> list from the <code>Part</code> object to somewhere else. Why should a part know what actions does a machine do with it? It seems to me that this responsibility should be stored somewhere else. The <code>Macine</code> is the closest object now (but it might deserve separate class).</p></li>\n<li><p>If the <code>Action</code> classes do not have any state consider moving their code inside the <code>Part</code> object. (The basic idea of OOP is that the data and the logic which operates with the data should be together in a class.) You can mark the action method with an <code>@Action</code> annotation and parse it runtime. </p>\n\n<pre><code>public class Gear {\n\n ...\n\n @Action\n public void rotate() {\n ...\n }\n}\n</code></pre>\n\n<p>I guess you still need a class which stores the actions which a machine should do:</p>\n\n<pre><code>public class Action {\n private Part part;\n private String actionMethodName;\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T17:47:00.510",
"Id": "41743",
"ParentId": "41725",
"Score": "4"
}
},
{
"body": "<p>This is a complicated setup you have, and this problem has been successfully solved in a few ways.... but, all of the mechanisms have two things in common....</p>\n\n<ol>\n<li>Interfaces.</li>\n<li>Factories</li>\n</ol>\n\n<p>The three technical problems I see with your code are:</p>\n\n<ul>\n<li><p>false generics: You have the factory <code>class ActionFactory<T extends Action></code> which implies that the factory has something to do with actions, and with a generic type called 'T'.</p>\n\n<p>This is simply not true.... The generic type on your class is completely ignored. You do not even need to create an instance of the class. The two static methods on the class have their own <code>T</code> generic type, and the <code>T</code> on those methods have absoutely nothing to do with the <code>T</code> on the class.</p></li>\n<li><p>even though I think the Part should be an interface, which would 'fix' this, there is no way you should have (in <code>Part</code>_ : <code>public ArrayList<Action> actions = new ArrayList<Action>();</code>. This should be a hidden (and final) field that is accessed with getters and setters:</p>\n\n<pre><code>public void addAction(Action<? extends T> action);\n....\npublic List<Action<...>> getActions();\n</code></pre></li>\n<li><p>The <code>Part</code> and <code>Action<T extends Part></code> should both be interfaces.</p></li>\n</ul>\n\n<p>This is a challenging problem to face. There are going to be places where the generics are wrong, right now they are off in ways that make the code very hard to understand.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T18:01:17.417",
"Id": "41744",
"ParentId": "41725",
"Score": "4"
}
},
{
"body": "<p>I think that this <code>ActionFactory</code> might work for you.</p>\n\n<ul>\n<li>The <code>ActionFactory</code> has only one method, and it is <code>static</code>, so make the constructor private to prevent the factory from being instantiated. The <code>ActionFactory</code> itself needs no type parameters.</li>\n<li>The type parameter for <code>getAction()</code> should have a constraint requiring <code>T</code> to be a subclass of <code>Action</code>. Then <code>actions.add(…)</code> would not need to cast.</li>\n<li>Instead of keeping an <code>ArrayList</code> of <code>Action</code>s, keep a <code>Map</code> instead for a simple lookup.</li>\n<li>There would still be an unchecked cast warning, which I believe is unavoidable. Just suppress it with an annotation.</li>\n</ul>\n\n\n\n<pre><code>class ActionFactory\n{\n private static final Map<Class, Action> singletons = new HashMap<Class, Action>();\n\n private ActionFactory() {}\n\n public static <T extends Action> T getAction(Class<T> c)\n throws InstantiationException, IllegalAccessException\n {\n @SuppressWarnings(\"unchecked\")\n T action = (T)singletons.get(c);\n\n if (action == null)\n {\n action = c.newInstance();\n singletons.put(c, action);\n }\n\n return action;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T09:43:31.097",
"Id": "71878",
"Score": "0",
"body": "Thank you all for your suggestions. It seems obvious now that my Part/Action code should be one class, but I'm not sure how to implement this yet. When I come up with something I'll post an new question here."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T07:45:28.560",
"Id": "41779",
"ParentId": "41725",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "41743",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T11:26:18.503",
"Id": "41725",
"Score": "6",
"Tags": [
"java",
"design-patterns",
"beginner",
"generics"
],
"Title": "Factory for classes unknown at compile time"
}
|
41725
|
<p>I have a condition in my code where I need to put a lot of nested <code>else if</code> statements. However, I have managed to reduce some <code>if</code> cases by applying ternary operator, so that code looks nice and is readable. But still I am not satisfied with the result. I would like to remove rest of the <code>if</code> cases too and make the code better.</p>
<p>Can anyone suggest more optimization in this code block?</p>
<pre><code>if (!string.IsNullOrEmpty(SessionValues.AccessToken))
{
eventstatuscode = "logged";
EventStatus eventStatus = rb.GetEventStatus();
if (eventStatus != null)
{
if (!string.IsNullOrEmpty(eventStatus.cancelDate))
{
eventstatuscode = DateTime.Parse(eventDetails.signUpDeadline) < DateTime.Now ? "expired": eventstatuscode;
}
else if (string.IsNullOrEmpty(eventStatus.cancelDate))
{
eventstatuscode = eventStatus.onWaitingList ? "waitinglist" : eventstatuscode;
eventstatuscode = eventStatus.onWaitingList == false ? "accepted" : eventstatuscode;
}
}
else
{
eventstatuscode = DateTime.Parse(eventDetails.signUpDeadline) < DateTime.Now ? "expired" : eventstatuscode;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T12:52:15.053",
"Id": "71770",
"Score": "1",
"body": "Is the class EventStatus under your control or is it a framework class? Also what is a type of eventDetails?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-09T22:16:32.077",
"Id": "258444",
"Score": "0",
"body": "Consider adding some context behind this code (the purpose of it)."
}
] |
[
{
"body": "<p>Let's take a look at the input and output you have in that code segment:</p>\n\n<p>Input:</p>\n\n<ul>\n<li><code>rb</code>, or technically only the <code>EventStatus</code> of rb, which becomes <code>eventStatus</code>.</li>\n<li><code>eventDetails</code></li>\n</ul>\n\n<p>Output:</p>\n\n<ul>\n<li><code>eventstatuscode</code></li>\n</ul>\n\n<p>Perfect, we have a clear input and a clear output, let's make it a method!</p>\n\n<p>Using a method will allow us to use multiple return statements to simplify your code.</p>\n\n<pre><code>private String GetStatusCode(EventStatus eventStatus, EventDetails eventDetails)\n{\n if (eventStatus == null || !string.IsNullOrEmpty(eventStatus.cancelDate))\n {\n return DateTime.Parse(eventDetails.signUpDeadline) < DateTime.Now ? \"expired\" : \"logged\";\n }\n // no need to check else as we return directly in the above check.\n\n return eventStatus.onWaitingList ? \"waitinglist\" : \"accepted\";\n}\n</code></pre>\n\n<p>I reduced these two lines to one line, as you check for true first and then you check for false. I believe this should not make things different in your current code.</p>\n\n<p>Another very important suggestion though:</p>\n\n<p><strong>Make your eventstatuscode an enum</strong></p>\n\n<pre><code>public enum EventStatusCode \n{\n Logged, Expired, WaitingList, Accepted;\n}\n</code></pre>\n\n<p>As <a href=\"https://codereview.stackexchange.com/questions/41572/better-way-to-handle-adding-a-record/\">other questions on Code Review has proven</a>, hard-coding strings can easily lead to mistakes. If you only misspell \"waitinglist\" somewhere, it will lead to bugs in your program. Using enums will allow such bugs to be caught by the compiler instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T12:40:25.250",
"Id": "71767",
"Score": "1",
"body": "Just to add a comment. I would say the two ternary operations at the end are very hard (not quick) to work out what will be returned. Particularly since both are checking the property onWaitingList but one checks directly and other one uses a comparison with FALSE."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T13:00:06.490",
"Id": "71771",
"Score": "0",
"body": "@Vojta You have a point there, as I wasn't sure whether it was a pure boolean or a nullable-boolean I didn't replace it, but it does look like it could be written `eventStatus.onWaitingList ? \"waitinglist\" : \"accepted\"`. Is that the reason for my down-vote?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T13:23:05.183",
"Id": "71773",
"Score": "0",
"body": "I am sorry, I am not a C# programmer so did not know about nullable booleans. I guess it is a nice feature but I am pretty sure that it would cause a headache to C# programmer as well to work out the proper return type (it was the reason for down-vote). However a suggestion. After you proposed the Enum you could have a method getStatus() in the enum class and return the proper string instead of having the ternary operations. That should work for C# right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T13:26:22.750",
"Id": "71774",
"Score": "0",
"body": "@Vojta Unlike Java, C# enums can't have methods in them. So that's not possible. I am not very good in C# but I do know some of it, so I am not entirely sure if nullable booleans would cause any problems here. I will edit my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T13:28:22.323",
"Id": "71775",
"Score": "0",
"body": "I did not know that about the enums and method. Then what about the map with the key being the enum and the value being the status in String? Then you could use \nreturn map.get(eventStatus); ."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T13:30:55.387",
"Id": "71776",
"Score": "0",
"body": "@Vojta Yes, that would be a good solution for converting the enum to it's string representation, or a simple `switch` statement could also work. *If* a String representation really is needed (I don't know if the string will be shown to the user or not with the code in the question)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T13:38:55.010",
"Id": "71778",
"Score": "0",
"body": "I would say the switch would kinda not follow the purpose of having the code shorter. I generally try to avoid switches with the usage of maps (if you don't need super fast code), because then the code is short for choosing - just one line. And with addition of another options is just one line when filling the map. Plus if you need to choose/switch at more places you don't have to copy paste the switch - just use the map.get(). Just pointing out what I have experienced with switches and maps."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T13:41:47.527",
"Id": "71779",
"Score": "0",
"body": "@Vojta Of course the `switch` statement should be placed within a method to prevent code duplication. That would make both the switch version and the map (called Dictionary in C#) version to be pretty much the same in both code required to set it up, extensibility, and code needed to call it. I consider them both as equally good options."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T17:25:09.967",
"Id": "71803",
"Score": "0",
"body": "Just so it's said, you're declaring `eventStatus` twice -- once in the parameter list, and once in the body."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T17:33:59.370",
"Id": "71805",
"Score": "0",
"body": "@cHao Thanks, removed the one in the body."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T12:19:46.333",
"Id": "41728",
"ParentId": "41727",
"Score": "12"
}
},
{
"body": "<p>Before deciding to use more ternary operators in your code, let's understand what if/else is about:</p>\n\n<p>When the expression in the <code>if</code> clause is resolved to <code>true</code>, the block right after it is executed. If that expression is resolved to <code>false</code>, and there is an <code>else</code> block indicated, that block is executed.</p>\n\n<p>An <code>else if</code> clause is needed if when the first condition is <code>false</code> there is still more than one execution option, based on a second(different) condition.</p>\n\n<p>In your code you keep checking one condition, and then the opposite one, although this is totally redundant. if <code>(x==false)</code> is <code>true</code> then <code>(x==true)</code> is always <code>false</code>, and vice versa. Asking the same question and then the opposite is not only redundant, but also a maintenance risk, since you need to change the condition, you need to remember also changing the opposite one.</p>\n\n<p>Also you should try to make all your conditions positive conditions - refrain from asking <code>if(!string.IsNullOrEmpty(eventStatus.cancelDate))</code> - it is far better to switch the <code>if</code> and <code>else</code> blocks and ask <code>if(string.IsNullOrEmpty(eventStatus.cancelDate))</code> - the <strong>!</strong> operator (\"not\") is easy to miss, and may cause confusion. Of course, if only one block is implemented - no <code>else</code> block is better than no <code>if</code> block - leave the condition as it is.</p>\n\n<p>To sum the above, a better code would look like this:</p>\n\n<pre><code>if (!string.IsNullOrEmpty(SessionValues.AccessToken))\n{\n eventstatuscode = \"logged\";\n EventStatus eventStatus = rb.GetEventStatus();\n if (eventStatus != null)\n {\n if (string.IsNullOrEmpty(eventStatus.cancelDate))\n {\n eventstatuscode = eventStatus.onWaitingList ? \"waitinglist\" : \"accepted\";\n } else {\n eventstatuscode = DateTime.Parse(eventDetails.signUpDeadline) < DateTime.Now ? \"expired\": eventstatuscode;\n }\n }\n else\n {\n eventstatuscode = DateTime.Parse(eventDetails.signUpDeadline) < DateTime.Now ? \"expired\" : eventstatuscode;\n }\n}\n</code></pre>\n\n<p>Now it is easier to see that the same line is indicated twice - the <code>\"expired\"</code> line. By combining the two <code>if</code> clauses - we can reduce that to only once (this is called being DRY):</p>\n\n<pre><code>if (!string.IsNullOrEmpty(SessionValues.AccessToken))\n{\n eventstatuscode = null;\n EventStatus eventStatus = rb.GetEventStatus();\n if (eventStatus != null && string.IsNullOrEmpty(eventStatus.cancelDate))\n {\n eventstatuscode = eventStatus.onWaitingList ? \"waitinglist\" : \"accepted\";\n }\n else\n {\n eventstatuscode = DateTime.Parse(eventDetails.signUpDeadline) < DateTime.Now ? \"expired\" : \"logged\";\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T12:32:06.153",
"Id": "71766",
"Score": "1",
"body": "Oh, you're right. One line was duplicated there, I gotta update my answer :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T12:20:02.347",
"Id": "41729",
"ParentId": "41727",
"Score": "18"
}
},
{
"body": "<p>Following on from Uri's answer, which was ...</p>\n\n<pre><code>if (!string.IsNullOrEmpty(SessionValues.AccessToken))\n{\n eventstatuscode = null;\n EventStatus eventStatus = rb.GetEventStatus();\n if (eventStatus != null && string.IsNullOrEmpty(eventStatus.cancelDate))\n {\n eventstatuscode = eventStatus.onWaitingList ? \"waitinglist\" : \"accepted\";\n }\n else\n {\n eventstatuscode = DateTime.Parse(eventDetails.signUpDeadline) < DateTime.Now ? \"expired\" : \"logged\";\n }\n}\n</code></pre>\n\n<p>... you can condense that further using the ternary expressions you asked about, to remove the rest of the if statements (untested code ahead):</p>\n\n<pre><code>EventStatus eventStatus = rb.GetEventStatus();\neventstatuscode = (eventStatus != null && string.IsNullOrEmpty(eventStatus.cancelDate))\n ? (eventStatus.onWaitingList) ? \"waitinglist\" : \"accepted\"\n : (DateTime.Parse(eventDetails.signUpDeadline) < DateTime.Now) ? \"expired\" : \"logged\";\n</code></pre>\n\n<p>I don't recommend that though: because IMO Uri's version is almost equivalent and is easier to read.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T15:20:01.223",
"Id": "41735",
"ParentId": "41727",
"Score": "9"
}
},
{
"body": "<p>Looking at the initial code, it seems like we are doing two things:</p>\n\n<ol>\n<li>Check if the user is authenticated</li>\n<li>Parse the status code</li>\n</ol>\n\n<p>I have assumed the code is under your control. If not, most of the methods can be implemented as extension methods while keeping the syntax.</p>\n\n<p>After refactoring, this is the top level code:</p>\n\n<pre><code>if (!Authenticated()) return;\n\nvar eventStatus = rb.GetEventStatus();\nvar deadline = DateTime.Parse(eventDetails.signUpDeadline);\n\neventstatuscode = eventStatus.GetStatusCode(deadline);\n</code></pre>\n\n<p>Checking for authentication is simply:</p>\n\n<pre><code>static bool Authenticated()\n{\n return !string.IsNullOrEmpty(SessionValues.AccessToken);\n}\n</code></pre>\n\n<p>The <code>EventStatus</code> class got a new method to parse the status code. There are four status codes of interest, and I like to be explicit on each one:</p>\n\n<pre><code>public string GetStatusCode(DateTime deadline)\n{\n if (HasExpired(deadline)) return \"expired\";\n if (IsOnWaitingList()) return \"waitinglist\";\n if (IsAccepted()) return \"accepted\";\n return \"logged\";\n}\n</code></pre>\n\n<p>The evaluation of each status code is extracted to individual methods. The whole class now looks like this:</p>\n\n<pre><code>internal class EventStatus\n{\n readonly string cancelDate;\n readonly bool onWaitingList;\n\n public EventStatus(string cancelDate, bool onWaitingList)\n {\n this.cancelDate = cancelDate;\n this.onWaitingList = onWaitingList;\n }\n\n public string GetStatusCode(DateTime deadline)\n {\n if (HasExpired(deadline)) return \"expired\";\n if (IsOnWaitingList()) return \"waitinglist\";\n if (IsAccepted()) return \"accepted\";\n return \"logged\";\n }\n\n bool HasExpired(DateTime deadline)\n {\n return !Active() && Expired(deadline);\n }\n\n bool IsOnWaitingList()\n {\n return Active() && onWaitingList;\n }\n\n bool IsAccepted()\n {\n return Active() && !onWaitingList;\n }\n\n bool Active()\n {\n return String.IsNullOrEmpty(cancelDate);\n }\n\n static bool Expired(DateTime deadline)\n {\n return deadline < DateTime.Now;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-25T15:09:02.357",
"Id": "74866",
"ParentId": "41727",
"Score": "2"
}
},
{
"body": "<p>One technique that in my opinion makes the code way simpler is to exit as soon as possible (or \"fail early\", or \"handle-the-error-first\", if you'd like). This avoids having multiple nested blocks in your code, plus keeps your mind \"clean\" because you can be sure that, if the code followed under a given position, you can always be sure the right conditions have been met (and you don't have to worry about them any longer).</p>\n\n<p>For instance, I would rewrite the code as </p>\n\n<pre><code>if (string.IsNullOrEmpty(SessionValues.AccessToken))\n return; // fail early\n\n// now we don't have to worry about SessionValues.AccessToken\n\neventstatuscode = \"logged\";\nEventStatus eventStatus = rb.GetEventStatus();\nif (eventStatus == null)\n{\n eventstatuscode = DateTime.Parse(eventDetails.signUpDeadline) < DateTime.Now ? \"expired\" : eventstatuscode;\n return;\n}\n\n// now we don't have to worry about eventStatus\nif (string.IsNullOrEmpty(eventStatus.cancelDate))\n{\n eventstatuscode = eventStatus.onWaitingList ? \"waitinglist\" : eventstatuscode;\n eventstatuscode = eventStatus.onWaitingList == false ? \"accepted\" : eventstatuscode;\n return;\n}\n\neventstatuscode = DateTime.Parse(eventDetails.signUpDeadline) < DateTime.Now ? \"expired\": eventstatuscode;\n</code></pre>\n\n<p>Some people might not like this because someone has told them to avoid having multiple return points in a function. But for me, the above is much clearer. Every time I am reading a code that branches into an if-else, I have to keep both in my head, read the if, then go back, read the else as if the 'if' never happened, then start wondering what would be the output if the \"if\" conditions were met, then the else... back and forth.</p>\n\n<p>This way I can read the if, and when I see it leads to a return, I know I will be able to forget that block to understand the rest of the function. One less thing to have in mind in order to understand the flow of the algorithm. I would apply the same to the ternary operation blocks, likely removing them if they don't lead to any reading improvements.</p>\n\n<p>Plus, whenever I find myself in the middle of the function, I can always know that the bad conditions have already been handled (otherwise the execution cursor wouldn't be in that position in the first place). And if the execution shouldn't be there but is, I can quickly realize where the bug was (in the condition checks in the beginning of the function).</p>\n\n<p>By the way, I hope I didn't introduce any mistakes in this refactoring as I didn't test it. I believe I might have, because usually I rely heavily on unit testing to get those refactoring artifacts!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-25T16:06:52.367",
"Id": "74870",
"ParentId": "41727",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41729",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T11:54:04.980",
"Id": "41727",
"Score": "16",
"Tags": [
"c#"
],
"Title": "Reduce code complexity by applying ternary operator"
}
|
41727
|
<p>I tried to check if my vector struct is normalized, and I ended up with this code:</p>
<pre><code>public bool IsNormalized
{
get
{
double len = Length; // Math.Sqrt ((X * X) + (Y * Y) + (Z * Z)); -- X, Y, Z are in double format
const double min = 1 - 1e-14;
const double max = 1 + 1e-14;
return (len >= min && len <= max);
}
}
</code></pre>
<p>Is this solution OK? I read double has 15 digits precision, but 1+1E<sup>-15</sup> give 1, so I changed to E<sup>14</sup>.</p>
<p>Is this all good? I need best accuracy.</p>
|
[] |
[
{
"body": "<p>This seems ok, depending on how precise you want it to be (some margin of error will always be needed since this <em>is</em> floating-point, but how much will depend on your needs)</p>\n\n<p>Alternatively, you could check <code>Math.Abs(1 - len) < 1e-14</code>, but I suspect the same precision problems will remain.</p>\n\n<p>I was somewhat surprised that <code>1 + 1e-15</code> equals 1, though, because doubles have 52 bits of precision, which should be more than enough to store a difference of 15 digits (<code>-log2(1/10^15)</code> gives me around <code>49.8</code>, which is less than 52 bits).</p>\n\n<p>So I double checked and 1 - 1.0e-15 does <strong>not</strong> give me 1.</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n Console.WriteLine(1 - 1.0e-15); //Does NOT print 1\n Console.Read();\n }\n}\n</code></pre>\n\n<p>Same thing for 1 + 1.0e-15 (though this one is trickier)</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n Console.WriteLine(1 + 1.0e-15); //Prints 1\n Console.WriteLine(1 + 1.0e-15 == 1); //...but this prints False\n Console.Read();\n }\n}\n</code></pre>\n\n<p>I suspect Console.WriteLine is only printing a limited number of digits: less than the ones double can represent.</p>\n\n<p>As a final note, Sqrt(1) == 1, so instead of using the Length you could use the SquaredLength and save a (potentially expensive) <code>Sqrt</code> operation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T15:32:25.520",
"Id": "71792",
"Score": "0",
"body": "Thanks for your investigation. I looked in debugger now, and, like you said, it's not equal 1. So I will stick to 1E-15. Also thanks for the SquaredLength tip. I did not understand why it was exposed in some Vector 3D implementations, but now I know it's very useful in my IsNormalized property."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T15:34:42.403",
"Id": "71793",
"Score": "1",
"body": "You're welcome. Note that my Sqrt tip is only needed if you're being bottlenecked. For most \"casual\" uses, your function works perfectly (and is perhaps more readable)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T13:40:55.363",
"Id": "71893",
"Score": "0",
"body": "\"I suspect Console.WriteLine is only printing a limited number of digits: less than the ones double can represent.\" - This should be a well known fact - console is intended to interface with human operators, not examine the miniature of double. If you want more information, look into the double ToString options."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T15:22:36.183",
"Id": "41736",
"ParentId": "41732",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "41736",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T13:47:09.480",
"Id": "41732",
"Score": "4",
"Tags": [
"c#",
"floating-point"
],
"Title": "Checking if vector is normalized"
}
|
41732
|
<p>Is this bad practice? Also, how can it be improved?</p>
<pre><code>#!/usr/bin/env bash
RUBY_VERSION=2.1.0
printf "Installing Ruby $RUBY_VERSION\\n"
if [ -d ruby_build ]; then
rm -Rf ruby_build
fi
if [[ `command -v ruby` && `ruby --version | colrm 11` == "ruby $RUBY_VERSION" ]] ; then
echo "You already have this version of Ruby: $RUBY_VERSION"
exit 113
fi
sudo apt-get build-dep -y ruby1.9.1
mkdir ruby_build && cd ruby_build
curl -O "http://ftp.ruby-lang.org/pub/ruby/2.1/ruby-$RUBY_VERSION.tar.gz"
tar xf "ruby-$RUBY_VERSION.tar.gz"
cd "ruby-$RUBY_VERSION"
./configure
make
sudo checkinstall -y --pkgversion "$RUBY_VERSION" --provides "ruby-interpreter" --replaces="ruby-1.9.2"
cd ../.. && rm -Rf ruby_build
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-28T18:01:30.683",
"Id": "200576",
"Score": "0",
"body": "It really seems like this is a job for [rvm](https://rvm.io/) unless there is some other logic you can't show us. It can be set to build from source."
}
] |
[
{
"body": "<p>First,I would like to point out that not all .deb-based distributions are as fond of <code>sudo</code> as Ubuntu is. For example, Debian doesn't use <code>sudo</code> out of the box.</p>\n\n<p>It appears that you're trying to build a newer version of Ruby than is available in the stock package repository. In that case, why not make a proper .deb package with its .dsc and publish it in a private APT repository? Then, everything integrates properly into the distribution the way package management is supposed to work, including the build process and subsequent updates. Everyone will have a better experience when you work <em>with</em> the system instead of against it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T05:45:46.613",
"Id": "71869",
"Score": "0",
"body": "Hmm, actually setting up my own PPA might not be too bad a solution. Can even make most of it public (such as NodeJS, Ruby, CouchDB &etc); just keeping the internal components private."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-29T13:22:35.660",
"Id": "200764",
"Score": "0",
"body": "Agreed, setting up a private PPA is the best approach, however that option was dismissed as something to be done later down the track. Well it is over 1.5 years later, so I suppose this is down the track!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T20:29:45.680",
"Id": "41753",
"ParentId": "41734",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41753",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T15:18:22.743",
"Id": "41734",
"Score": "2",
"Tags": [
"bash",
"installer"
],
"Title": "Ruby install script; packages+installs as a .deb or .rpm from source"
}
|
41734
|
<p>I'm trying to model a puzzle in order to resolve it with the Choco solver.</p>
<p>One of the constraint I'm coding is cyclical (it's triplet which follow themselves) like the following example:</p>
<pre><code>s.post(LogicalConstraintFactory.ifThen(
IntConstraintFactory.member(mvt[i], new int[]{1, 2, 3}),
IntConstraintFactory.not_member(mvt[i + 1], new int[]{1, 2, 3})
));
s.post(LogicalConstraintFactory.ifThen(
IntConstraintFactory.member(mvt[i], new int[]{4, 5, 6}),
IntConstraintFactory.not_member(mvt[i + 1], new int[]{4, 5, 6})
));
s.post(LogicalConstraintFactory.ifThen(
IntConstraintFactory.member(mvt[i], new int[]{7, 8, 9}),
IntConstraintFactory.not_member(mvt[i + 1], new int[]{7, 8, 9})
));
// and so one...
</code></pre>
<p>I think that my library isn't very known so the mathematics equivalent is :</p>
<pre><code>if(foo[i] is in {1, 2, 3}) then
foo[i+1] shouldn't be in {1, 2, 3}
if(foo[i] is in {4, 5, 6}) then
foo[i+1] shouldn't be in {4, 5, 6}
...
</code></pre>
<p>Any idea of how I can model this problem with modulo (to avoid writing each triplet)?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T15:47:49.813",
"Id": "71794",
"Score": "0",
"body": "How consistent are your int values... is it always triples, and always starting from 1 (i.e. always `[1,2,3],[4,5,6],[....],...` )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T15:50:32.443",
"Id": "71795",
"Score": "0",
"body": "@rolfl Yes, it's always triplet and starting from 1"
}
] |
[
{
"body": "<p>If the process is consistently 123, then 456, etc. and the check is always 'if a value is in one triplet, then the next value is not allowed in the same triplet, then you can have the following simple function:</p>\n\n<pre><code>int thisval = mvt[i];\n// because thisval triplets are 1-based, you need to offset by -1 on the modulo\nint excludemin = (thisval - ((thisval - 1) % 3));\nint excludemax = excludemin + 3;\nif (mvt[i+1] >= excludemin && mvt[i+1] < excludemax) {\n // this is not supposed to happen....\n // the i+1 element is inside the same triplet.\n}\n</code></pre>\n\n<p>I am not sure how this would fit in your paradigm.... but, it is just one test for your whole system</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T15:54:30.977",
"Id": "41739",
"ParentId": "41737",
"Score": "4"
}
},
{
"body": "<p>I'm not familiar with the choco solver, but would this solve your problem?</p>\n\n<pre><code>s.post(IntConstraintFactory.not_member(mvt[i+1], \n new int[] { (mvt[i]/3)*3 + 1, (mvt[i]/3)*3 + 2, (mvt[i]/3)*3 + 3}));\n</code></pre>\n\n<p>Another option might be:</p>\n\n<pre><code>s.post(LogicalConstraintFactory.not(\n IntConstraintFactory.eucl_div(mvt[i+1]-1, 3, (int)(mvt[i]-1)/3)));\n</code></pre>\n\n<p>From the <a href=\"https://github.com/chocoteam/choco3/blob/develop/choco-solver/src/main/java/solver/constraints/IntConstraintFactory.java\" rel=\"nofollow\">documentation</a>:</p>\n\n<pre><code>/**\n * Ensures DIVIDEND / DIVISOR = RESULT, rounding towards 0 -- Euclidean division\n *\n * @param DIVIDEND dividend\n * @param DIVISOR divisor\n * @param RESULT result\n */\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T16:40:11.810",
"Id": "41741",
"ParentId": "41737",
"Score": "4"
}
},
{
"body": "<p>If your triplets were zero-based (i.e., {0, 1, 2}, {3, 4, 5}, …) then the answer might have been more obvious. As it is, you have to apply an offset of -1, then divide by three to figure out which triplet an element belongs to.</p>\n\n<pre><code>if ((mvt[i] - 1) / 3 == (mvt[i + 1] - 1) / 3) {\n // This shouldn't happen: mvt[i] and mvt[i + 1] are in the same triplet\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T17:26:59.507",
"Id": "71804",
"Score": "0",
"body": "That's the sentiment that I want to express, but I see that `mvt` consists of `IntVar`s, not `int`s, so you can't just perform ordinary arithmetic on them. However, I can't figure out how to express that using Choco solver constraints — and neither has anyone else so far."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T17:38:39.990",
"Id": "71808",
"Score": "0",
"body": "You can consider `IntVar` as `int`, I'll perform by myself the arithmetic to choco library translation. Don't care about it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T16:49:55.240",
"Id": "41742",
"ParentId": "41737",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "41741",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T15:38:38.063",
"Id": "41737",
"Score": "6",
"Tags": [
"java",
"optimization",
"mathematics"
],
"Title": "Code reduction possible with modulo operator?"
}
|
41737
|
<p>This one time pad encryption program I have written (basically just an XOR "encryption" program) seems to be working fine, compiling nicely (gcc -o ./OTP.c), and doing what it's supposed to. However I would like to improve it as much as possible which is why I am posting this.</p>
<p>I am particularly insecure about the memory allocation. Any suggestions regarding improvements are more than welcome!</p>
<p>The code in its entirety is found below and can also be found on Github: <a href="https://github.com/PrivacyProject/OTP-Encryption/tree/81dd496cc57875ae374bbdcc0562f5bc68cfaf15">PrivacyProject/OTP-Encryption</a>.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/mman.h>
int main(int argc, char **argv)
{
struct stat statbuf;
struct stat keybuf;
char buffer [20];
int key;
int data;
int output;
int count;
char ans;
int * buf;
FILE * keyfile;
FILE * sourcefile;
FILE * destfile;
if(geteuid() !=0)
{
printf("Root access is required to run this program\n\n");
exit(0);
}
if(argc<4)
{
printf("\n");
printf(" OTP 1.0 \n\n");
printf(" This program encrypts a file using a random key\n");
printf(" and generates an output file with the resulting\n");
printf(" cipher. Decryption is achieved by running the\n");
printf(" output file as source file with the same key.\n\n");
printf(" WARNING: The security of the encryption provided\n");
printf(" by this program is entirely dependent on the key\n");
printf(" file. The keyfile should meet the requirements\n");
printf(" below:\n");
printf(" - Be of the same size or larger than the\n");
printf(" source file.\n");
printf(" - Be completely random, preferably generated by \n");
printf(" a Hardware Random Number Generator.\n");
printf(" - NEVER be reused!\n\n");
printf(" The author takes no responsibility for use of\n");
printf(" this program. Available under GNU General Public\n");
printf(" Licence v.2\n\n");
printf(" USAGE: OTP <source file> <output file> <keyfile>\n\n");
return (0);
}
/* Check number of arguments. */
if(argc>4)
{
printf("Too many arguments.\n");
printf("USAGE: OTP <source file> <output file> <keyfile>\n");
exit(1);
}
/* Allocate memory required by processes */
buf = (int*) malloc (sizeof(int));
if (buf == NULL)
{
perror("Error");
exit(1);
}
/* Lock down pages mapped to processes */
printf("Locking down processes...\n\n");
if(mlockall (MCL_CURRENT | MCL_FUTURE) < 0)
{
perror("mlockall");
exit (1);
}
/* Check if sourcefile can be opened. */
if((sourcefile = fopen(argv[1], "rb"))== NULL)
{
printf("Can't open source file\n");
perror("Error");
printf("USAGE: OTP <source file> <output file> <keyfile>\n");
exit (1);
}
/* Get size of sourcefile */
fstat(fileno(sourcefile), &statbuf);
/* Check if keyfile can be opened. */
if((keyfile = fopen(argv[3], "rb"))== NULL)
{
printf("Can't open keyfile.\n");
perror("Error");
printf("USAGE: OTP <source file> <output file> <keyfile>\n");
exit(1);
}
/* Get size of keyfile */
fstat(fileno(keyfile), &keybuf);
/* Check if keyfile is the same size as, or bigger than the sourcefile */
if((keybuf.st_size) < (statbuf.st_size))
{
printf("Source file is larger than keyfile.\n");
printf("This significantly reduces cryptographic strength.\n");
printf("Do you wish to continue? (Y/N)\n");
fgets(buffer, 20, stdin);
sscanf(buffer, "%c", &ans);
if(ans == 'n' || ans == 'N')
{
exit (1);
}
if(ans == 'y' || ans == 'Y')
{
printf("Proceeding with Encryption/Decryption.\n");
}
else
{
printf("No option selected. Exiting...\n");
exit (1);
}
}
/* Check if destfile can be opened. */
if((destfile = fopen(argv[2], "wb"))== NULL)
{
printf("Can't open output file.\n");
perror("Error");
exit(1);
}
/* Encrypt/Decrypt and write to output file. */
while(count < (statbuf.st_size))
{
key=fgetc(keyfile);
data=fgetc(sourcefile);
output=(key^data);
fputc(output,destfile);
count++;
}
/* Close files. */
fclose(keyfile);
fclose(sourcefile);
fclose(destfile);
printf("Encryption/Decryption Complete.\n\n");
/* delete Source file option. */
printf("Do you wish to delete the source file? (Y/N)\n");
fgets(buffer, 20, stdin);
sscanf(buffer, "%c", &ans);
if(ans == 'y' || ans == 'Y')
{
if ( remove(argv[1]) == 0)
{
printf("File deleted successfully.\n");
}
else
{
printf("Unable to delete the file.\n");
perror("Error");
exit(1);
}
}
/* delete keyfile option. */
printf("Do you wish to delete the keyfile? (Y/N)\n");
fgets(buffer, 20, stdin);
sscanf(buffer, "%c", &ans);
if(ans == 'y' || ans == 'Y')
{
if ( remove(argv[3]) == 0)
{
printf("File deleted successfully.\n");
}
else
{
printf("Unable to delete the file.\n");
perror("Error");
exit(1);
}
}
/* cleanup */
printf("Releasing memory.\n");
free (buf);
return(0);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-18T13:44:44.183",
"Id": "305368",
"Score": "0",
"body": "Sorry, but I don't understand why did you initialize the `buf` variable but have never used it?"
}
] |
[
{
"body": "<p>When you \"remove\" a file, its contents still reside on disk; only its directory entry is removed. Instead of just unlinking the source file, consider overwriting it with random bytes first. (These days, with SSD wear leveling, filesystem snapshots, and log-structured filesystems, it's harder to securely wipe data completely from a filesystem. However, it's still worth trying, in my opinion.)</p>\n\n<p>Your warning is inaccurate. When the key file is shorter than the source file, it doesn't reduce the cryptographic strength; it obliterates it. In my opinion, the most ethical behaviour is to treat it as a fatal error and generate no output file at all.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T21:35:02.667",
"Id": "71831",
"Score": "1",
"body": "It's processing `statbuf.st_size` bytes of the source; does it really truncate the output? Or does it xor the extra bytes with invalid but predictable output from `fgetc(keyfile)` i.e. `EOF`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T21:50:37.440",
"Id": "71834",
"Score": "0",
"body": "@ChrisW OMG you're right. It just bit-flips all of the excess text."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T21:54:36.333",
"Id": "71836",
"Score": "2",
"body": "That might be more secure that reusing the \"one-time\" pad."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T20:59:25.430",
"Id": "41754",
"ParentId": "41748",
"Score": "7"
}
},
{
"body": "<p><strong>Indentation:</strong></p>\n\n<p>Make sure to keep your indentation consistent. You only do it in certain places, mostly towards the end. You should do it everywhere as needed, which will make your code much easier to read and follow.</p>\n\n<p><strong><code>main()</code> and functions</strong>:</p>\n\n<p>You do everything in <code>main()</code>, which is bad practice because it just makes the program hard to read and maintain. That is a beginner thing, so it's understandable. As soon as you can, you should start using separate functions to handle most of the work. This will vastly improve this program and will help with future programs, especially larger ones.</p>\n\n<p>In general, <code>main()</code> should display the introductory text, open files (terminate if it fails), close the files, call other functions to do the cryptography work, return anything if needed, and then terminate. Adding comments <em>is</em> a good start, but is still no substitute for using functions. For the files and command line arguments, they can be passed to the functions and used there.</p>\n\n<p><strong><code>return</code> and <code>exit()</code></strong></p>\n\n<p>I prefer returning from <code>main()</code> over calling <code>exit()</code>, but for whichever you choose, you should be consistent with it. This was already mentioned by @syb0rg and in better detail, but is still worth keeping in mind. Consistency is key.</p>\n\n<p>You don't need the parenthesis in <code>return (0)</code>. It doesn't require use of it. Just use <code>return 0</code>.</p>\n\n<p>You could optionally return <code>EXIT_SUCCESS</code> or <code>EXIT_FAILURE</code>, which return 0 and 1 respectively.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T21:00:27.853",
"Id": "41755",
"ParentId": "41748",
"Score": "9"
}
},
{
"body": "<p>Instead of checking that the EUID is 0, just do <code>mlockall()</code> and check for <code>EPERM</code>. Don't assume that <em>only</em> the root user is allowed to lock memory, and don't assume that the root user <em>will</em> be allowed to lock memory. There may be security modules, such as SELinux, that cause such assumptions to be wrong.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T21:14:45.463",
"Id": "41757",
"ParentId": "41748",
"Score": "8"
}
},
{
"body": "<h2>Things you did well on:</h2>\n\n<ul>\n<li><p>You make good use of comments.</p></li>\n<li><p>You try to make the user experience as smooth as possible, printing out a lot of useful information.</p></li>\n</ul>\n\n<hr>\n\n<h2>Things you could improve:</h2>\n\n<p>A few notes that others haven't covered:</p>\n\n<ul>\n<li><p>Running your program through <a href=\"http://valgrind.org/\" rel=\"nofollow\">Valgrind</a>, I didn't see any memory leaks besides where your <code>if</code> conditions fail and you exit <code>main()</code>.</p>\n\n<blockquote>\n<pre><code> if((sourcefile = fopen(argv[1], \"rb\")) == NULL)\n {\n printf(\"Can't open source file\\n\");\n perror(\"Error\");\n printf(\"USAGE: OTP <source file> <output file> <keyfile>\\n\");\n exit(1);\n }\n</code></pre>\n</blockquote>\n\n<p>The majority of modern (and all major) operating systems will free memory not freed by the program when it ends. However, relying on this is bad practice and it is better to free it explicitly. Relying on the operating system also makes the code less portable.</p>\n\n<pre><code>if((sourcefile = fopen(argv[1], \"rb\")) == NULL)\n{\n puts(\"Can't open source file.\");\n perror(\"Error\");\n free(buf)\n return -5;\n}\n</code></pre></li>\n<li><p><a href=\"https://en.wikipedia.org/wiki/One-time_pad\" rel=\"nofollow\">Your encryption method is secure</a>, banking on the fact that the all of the conditions for your program are met.</p>\n\n<p>But I always think worst case scenario, where the user doesn't follow your program's optimal conditions. If you want to use secure encryption techniques, you can benefit from a cryptography expert's work. This means you will have to implement an external library (such as <a href=\"https://www.openssl.org/\" rel=\"nofollow\">OpenSSL</a>). <a href=\"http://misc-file.googlecode.com/svn/vm/aes_cbc_encrypt.cpp\" rel=\"nofollow\">Here is an example</a> if you want to go that route.</p></li>\n<li><p>You have an implicit declaration of function <code>geteuid()</code>, which is invalid in the C99 standard.</p>\n\n<pre><code>#include <unistd.h>\n</code></pre></li>\n<li><p><code>fopen()</code>, a widely-used file I/O functions that you are using, got a facelift in C11. It now supports a new exclusive create-and-open mode (<code>“...x“</code>). The new mode behaves like <code>O_CREAT|O_EXCL</code> in POSIX and is commonly used for lock files. The <code>“...x”</code> family of modes includes the following options:</p>\n\n<ul>\n<li><p><code>wx</code> create text file for writing with exclusive access.</p></li>\n<li><p><code>wbx</code> create binary file for writing with exclusive access.</p></li>\n<li><p><code>w+x</code> create text file for update with exclusive access.</p></li>\n<li><p><code>w+bx</code> or <code>wb+x</code> create binary file for update with exclusive access.</p></li>\n</ul>\n\n<p>Opening a file with any of the exclusive modes above fails if the file already exists or cannot be created. Otherwise, the file is created with exclusive (non-shared) access. Additionally, a safer version of <code>fopen()</code> called <code>fopen_s()</code> is also available. That is what I would use in your code if I were you, but I'll leave that up for you to decide and change.</p></li>\n<li><p>You can cut down on a few lines of code by initializing similar types on one line. This will keep you more organized.</p>\n\n<blockquote>\n<pre><code> struct stat statbuf;\n struct stat keybuf;\n\n char buffer [20];\n int key;\n int data;\n int output;\n int count;\n char ans;\n int * buf;\n FILE * keyfile;\n FILE * sourcefile;\n FILE * destfile;\n</code></pre>\n</blockquote>\n\n<p>Also, initialize your <code>int</code> values when you declare them. Pointer values will default to <code>NULL</code>.</p>\n\n<pre><code>struct stat statbuf, keybuf;\n\nchar buffer [20];\nchar ans;\nint key = 0, data = 0, output = 0, count = 0;\nint *buf;\nFILE *keyfile, *sourcefile, *destfile;\n</code></pre></li>\n<li><p>You check if <code>argc</code> is greater or less than 4.</p>\n\n<blockquote>\n<pre><code>if(argc<4)\n{\n // huge printf() block\n return (0);\n}\n// ...\nif(argc>4)\n{\n printf(\"Too many arguments.\\n\");\n printf(\"USAGE: OTP <source file> <output file> <keyfile>\\n\");\n exit(1);\n}\n</code></pre>\n</blockquote>\n\n<p>Just check for the inequality of 4 and print the block statement.</p>\n\n<pre><code>if (argc != 4)\n{\n // printf() block\n return 0;\n}\n</code></pre></li>\n<li><p>I would have extracted all of the encryption to one method and all of the file validation in another method, but I'll leave that for you to implement. </p></li>\n<li><p>You can remove the <code>!= 0</code> for maximum C-ness, but this is to your discretion and tastes.</p>\n\n<blockquote>\n<pre><code> if(geteuid() != 0)\n</code></pre>\n</blockquote></li>\n<li><p>It is more common to <code>return 0;</code> rather than to <code>exit(0)</code>. Both will call the registered <code>atexit</code> handlers and will cause program termination though. You have both spread throughout your code. Choose one to be consistent. Also, you should return different values for different errors, so you can pinpoint where something goes wrong in the future.</p></li>\n<li><p>Use <code>puts()</code> instead of <code>printf()</code> with a bunch of <code>'\\n'</code> characters.</p>\n\n<blockquote>\n<pre><code> printf(\" and generates an output file with the resulting\\n\");\n</code></pre>\n</blockquote>\n\n<pre><code>puts(\" and generates an output file with the resulting\");\n</code></pre></li>\n<li><p>You compare some pointers to <code>NULL</code> in some test conditions.</p>\n\n<blockquote>\n<pre><code> if (buf == NULL)\n</code></pre>\n</blockquote>\n\n<p>You can simplify them.</p>\n\n<pre><code>if (!buf)\n</code></pre></li>\n<li><p>Your <code>perror()</code> messages could be more descriptive.</p></li>\n<li><p>You compare some input to the uppercase and lowercase versions of characters.</p>\n\n<blockquote>\n<pre><code> if (ans == 'n' || ans == 'N')\n</code></pre>\n</blockquote>\n\n<p>You could use the <code>tolower()</code> function in <code><ctype.h></code> to simplify it a bit.</p>\n\n<pre><code>if (tolower(ans) == 'n')\n</code></pre></li>\n<li><p>Already mentioned, but please indent your code properly. It will make your code a lot easier to read and maintain. You can find IDE's out there that will do it automatically for you when told.</p></li>\n</ul>\n\n<hr>\n\n<h2>Final code (with my changes implemented):</h2>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <ctype.h>\n#include <sys/stat.h>\n#include <sys/mman.h>\n\nint main(int argc, char **argv)\n{\n struct stat statbuf, keybuf;\n\n char buffer[20];\n char ans;\n int key = 0, data = 0, output = 0, count = 0;\n int *buf;\n FILE *keyfile, *sourcefile, *destfile;\n\n if(geteuid() != 0)\n {\n puts(\"Root access is required to run this program.\");\n return -1;\n }\n\n if(argc != 4)\n {\n puts(\"OTP 1.0 \\n\");\n\n puts(\"This program encrypts a file using a random key\");\n puts(\"and generates an output file with the resulting\");\n puts(\"cipher. Decryption is achieved by running the\");\n puts(\"output file as source file with the same key.\\n\");\n\n puts(\"WARNING: The security of the encryption provided\");\n puts(\"by this program is entirely dependent on the key\");\n puts(\"file. The keyfile should meet the requirements\");\n puts(\"below:\");\n puts(\" - Be of the same size or larger than the\");\n puts(\" source file.\");\n puts(\" - Be completely random, preferably generated by\");\n puts(\" a Hardware Random Number Generator.\");\n puts(\" - NEVER be reused!\\n\");\n puts(\"The author takes no responsibility for use of\");\n puts(\"this program. Available under GNU General Public\");\n puts(\"Licence v.2\\n\");\n\n puts(\"usage: OTP <source file> <output file> <keyfile>\");\n return 0;\n }\n\n /* Allocate memory required by processes */\n buf = (int*) malloc (sizeof(int));\n if (!buf)\n {\n perror(\"Error\");\n free(buf);\n return -3;\n }\n\n /* Lock down pages mapped to processes */\n puts(\"Locking down processes...\");\n if(mlockall (MCL_CURRENT | MCL_FUTURE) < 0)\n {\n perror(\"mlockall\");\n free(buf);\n return -4;\n }\n\n /* Check if sourcefile can be opened. */\n if((sourcefile = fopen(argv[1], \"rb\")) == NULL)\n {\n puts(\"Can't open source file.\");\n perror(\"Error\");\n free(buf);\n return -5;\n }\n\n /* Get size of sourcefile */\n fstat(fileno(sourcefile), &statbuf);\n\n /* Check if keyfile can be opened. */\n if((keyfile = fopen(argv[3], \"rb\")) == NULL)\n {\n puts(\"Can't open keyfile.\");\n perror(\"Error\");\n free(buf);\n return -6;\n }\n\n /* Get size of keyfile */\n fstat(fileno(keyfile), &keybuf);\n\n /* Check if keyfile is the same size as, or bigger than the sourcefile */\n if((keybuf.st_size) < (statbuf.st_size))\n {\n puts(\"Source file is larger than keyfile.\");\n puts(\"This significantly reduces cryptographic strength.\");\n puts(\"Do you wish to continue? (Y/N)\");\n fgets(buffer, 20, stdin);\n sscanf(buffer, \"%c\", &ans);\n if (tolower(ans) == 'n')\n {\n free(buf);\n return 0;\n }\n else if (tolower(ans) == 'y') puts(\"Proceeding with Encryption/Decryption.\");\n else\n {\n puts(\"No option selected. Exiting...\");\n free(buf);\n return -7;\n }\n }\n\n /* Check if destfile can be opened. */\n if ((destfile = fopen(argv[2], \"wb\")) == NULL)\n {\n puts(\"Can't open output file.\");\n perror(\"Error\");\n free(buf);\n return -8;\n }\n\n /* Encrypt/Decrypt and write to output file. */\n while (count < (statbuf.st_size))\n {\n key=fgetc(keyfile);\n data=fgetc(sourcefile);\n\n output=(key^data);\n\n fputc(output,destfile);\n count++;\n }\n\n /* Close files. */\n fclose(keyfile);\n fclose(sourcefile);\n fclose(destfile);\n\n puts(\"Encryption/Decryption Complete.\");\n\n /* delete Source file option. */\n puts(\"Do you wish to delete the source file? (Y/N)\");\n fgets(buffer, 20, stdin);\n sscanf(buffer, \"%c\", &ans);\n if (tolower(ans) == 'y')\n {\n if (remove(argv[1]) == 0) puts(\"File deleted successfully.\");\n else\n {\n puts(\"Unable to delete the file.\");\n perror(\"Error\");\n free(buf);\n return -9;\n }\n }\n\n /* delete keyfile option. */\n puts(\"Do you wish to delete the keyfile? (Y/N)\");\n fgets(buffer, 20, stdin);\n sscanf(buffer, \"%c\", &ans);\n if(tolower(ans) == 'y')\n {\n if (remove(argv[3]) == 0) puts(\"File deleted successfully.\");\n else\n {\n puts(\"Unable to delete the file.\");\n perror(\"Error\");\n free(buf);\n return -10;\n }\n }\n\n /* cleanup */\n puts(\"Releasing memory.\");\n free (buf);\n return(0);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T21:43:29.210",
"Id": "71833",
"Score": "3",
"body": "`if (geteuid())` has a connotation that `geteuid()` returns a notional Boolean value, whereas `if (geteuid() != 0)` looks more like a check against a particular value. They both generate exactly the same code, but I consider the latter more readable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T21:51:59.183",
"Id": "71835",
"Score": "0",
"body": "how about replace \" \" with `\\t`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T21:56:33.900",
"Id": "71837",
"Score": "0",
"body": "@SSpoke Not a bad idea. Unfortunately, I removed the spaces in the final code I posted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T22:45:19.990",
"Id": "71843",
"Score": "4",
"body": "Nitpick regarding \"Your encryption isn't very secure\": As long as the three conditions mentioned in the usage notes are met, the encryption is [unbreakable](http://en.wikipedia.org/wiki/One-time_pad), making the the *most* secure algorithm possible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T22:48:31.650",
"Id": "71844",
"Score": "0",
"body": "@Heinzi Correct. I will make an edit to clarify."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T23:38:55.960",
"Id": "71849",
"Score": "2",
"body": "Way to got over and above anything I could have hoped for! I have learned a lot from this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T04:04:12.483",
"Id": "71865",
"Score": "0",
"body": "On `return` vs. `exit()`: I first learned C decades ago, and the convention I was taught was to always `return 0;` at the end of `main()` and for a normal exit status, and to `exit()` with some integer code for an error exit status, especially when exiting from some function other than `main()` (where `return` wouldn't actually exit the program anyway). I would love to know if this convention is flawed in some way, but that's probably a question for elsewhere."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T04:09:43.217",
"Id": "71866",
"Score": "0",
"body": "@MichaelHampton I was mainly stressing that the OP be consistent with whatever he chose to use in his program, since he would switch off. One way I see that convention being flawed is if the error isn't fatal in the function other than main, where it should return an `int` status for the program to then handle and recover from."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T21:26:36.963",
"Id": "41758",
"ParentId": "41748",
"Score": "16"
}
},
{
"body": "<p>In terms of algorithm, the following loop has what I would consider a big problem. If keyfile is shorter than sourcefile, then the end of sourcefile ends up being encrypted with EOF and thus the XOR will use -1. It's really much less encrypted that you had in mind, I would think. (Note: I know the code asks you whether you want to go on or not, but I think there is a simple solution, see below.)</p>\n\n<pre><code>/* Encrypt/Decrypt and write to output file. */\nwhile (count < (statbuf.st_size))\n{\n key=fgetc(keyfile);\n data=fgetc(sourcefile);\n\n output=(key^data);\n\n fputc(output,destfile);\n count++;\n}\n</code></pre>\n\n<p>Also, you do not set count to zero before looping with it. That being said, I would use something like this instead which does not use <code>count</code> anyway:</p>\n\n<pre><code>while((data = fgetc(sourcefile) != EOF)\n{\n key = fgetc(keyfile);\n if(key == EOF)\n {\n rewind(keyfile);\n key = fgetc(keyfile); // cycle key file\n }\n\n output = key ^ data;\n\n fputc(output, destfile);\n}\n</code></pre>\n\n<p>(Side note: count is zero in your case because count is a \"primordial variable\" and those are using \"clean memory\" (zeroed) from the kernel, but in a sub-sub-function, you would have noticed the problem!)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T10:30:18.050",
"Id": "71881",
"Score": "1",
"body": "Recycling the key file makes it no longer a one-time pad, and the encryption is no longer unbreakable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T10:32:26.170",
"Id": "71882",
"Score": "0",
"body": "I agree, but using EOF to pad the rest of the file is even uglier. If you want to enforce a one-time pad then err if the size of keyfile is less than the size of destfile."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T10:57:41.653",
"Id": "71885",
"Score": "0",
"body": "I tried implementing your suggestion, and while compiling it made the program unable to decrypt the output file. I agree that the program should err when too hot keys are used and will implement that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T00:00:20.720",
"Id": "71967",
"Score": "0",
"body": "@youjustreadthis, I'm not too sure why it could not decrypt. You could compare the output of your old version and this version using `cmp -l old-output new-output` to see whether the bytes look different. Of course, if the key is smaller, it will look different from the end of the key to the end of the file being encrypted."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T09:42:04.167",
"Id": "41788",
"ParentId": "41748",
"Score": "7"
}
},
{
"body": "<p>An OTP derives its strength entirely from the secrecy and one-timeness of the key.</p>\n\n<p>Regardless of your code implementation (which looks decent and has some very decent improvements suggested) it is fundamentally flawed as reliable cryptosystem since you have absolutely no way of knowing what's happening (or already happened) to your pad when you \"destroy\" it. It may have been sniffed on the wire, versioned on a filesystem, backed-up, etc.</p>\n\n<p>This does not address your question (about code improvement), which I think others have answered well, just a reminder that just because your code is good it may not serve its intended purpose.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T04:43:55.410",
"Id": "71996",
"Score": "0",
"body": "Hmm, you make a good point on maintaining the security of the key that I somewhat glossed over. +1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T03:14:46.027",
"Id": "41846",
"ParentId": "41748",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41758",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T19:54:03.373",
"Id": "41748",
"Score": "15",
"Tags": [
"c",
"beginner",
"memory-management",
"cryptography"
],
"Title": "Small one time pad encryption program"
}
|
41748
|
<p>I'm trying to implement a system of restricted access. Right now I'm focusing on the "<a href="http://en.wikipedia.org/wiki/Session_fixation" rel="nofollow">session fixation</a>". I am concerned about the following aspects:</p>
<ol>
<li><p>Control of a "fingerprint" of the user created by mixing UserAgent, IPAddress and a salt key. If the fingerprint were to change, destroy the user's session.</p></li>
<li><p>Using the same session id for a certain number of times, after which regeneration session id.</p></li>
<li><p>Regenerate the session id every time change the level of user authentication</p></li>
</ol>
<p>What I want to know is whether my approach is right and if it is safe enough.
I apologize if the code is long, I tried to remove all the unnecessary parts.</p>
<p><strong>I do not want a code review, but the opinions about it ... particularly if the mine is a safe approach.</strong></p>
<hr>
<pre><code><?php
class oLogonUser
{
const SESSION_LIMIT = 10;
const SESSION_SALT = 'AS86F(,sa)8as7d+/234N&&"$£%';
function __construct()
{
// init session
$this->InitSession();
// check if user logged
if( $this->isUserLogged() )
{
// Check if finger print is valid
if( !$this->isValidFingerPrint() )
$this->LogOutUser(); // log out
}
}
private function InitSession()
{
// check if session already start
if( session_id() == '' )
session_start();
// Set user's fingerprint
$this->setUserFingerPrint();
// Session counter
if( isset($_SESSION['UserSessionCounter']) )
$_SESSION['UserSessionCounter'] = (int)$_SESSION['UserSessionCounter'] + 1;
else
$_SESSION['UserSessionCounter'] = 0;
// if session counter exeed limit, regenerate session id
if( $_SESSION['UserSessionCounter'] > self::SESSION_LIMIT )
{
$_SESSION['UserSessionCounter'] = 0;
session_regenerate_id();
}
}
private function isValidFingerPrint()
{
// checking if the user fingerprint is the same as that stored in session
if( isset($_SESSION['UserFingerPrint']) )
return ( $_SESSION['UserFingerPrint'] === $this->getUserFingerPrint() );
return false;
}
private function getUserFingerPrint()
{
// return user fingerprint
return md5($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'] . self::SESSION_SALT );
}
private function setUserFingerPrint()
{
// store in session user fingerprint
if( !isset($_SESSION['UserFingerPrint']) )
$_SESSION['UserFingerPrint'] = $this->getUserFingerPrint();
}
public function LogOnUser($UserName, $Password)
{
//NB: in fact control the credentials in the database
if( $UserName == 'test' && $Password == 'test' )
$this->setUserLogged();
}
public function LogOutUser($UserName, $Password)
{
// destroy user session
session_destroy();
session_regenerate_id();
}
private function setUserLogged()
{
session_regenerate_id();
// set user logged
$_SESSION['UserLogged'] = TRUE;
}
public function isUserLogged()
{
// check if user is logged
return (isset($_SESSION['UserLogged']) && $_SESSION['UserLogged'] == TRUE );
}
}
// Test it
$objLogonUser = new oLogonUser();
if( !$objLogonUser->isUserLogged() )
$objLogonUser->LogOnUser('test', 'test');
echo session_id() . '<BR />';
print_r($_SESSION);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T21:17:25.610",
"Id": "71827",
"Score": "1",
"body": "Welcome! On this site, reviewers are allowed to comment on any aspect of the code. While it is still good to have your primary request addressed, code reviews can still be done."
}
] |
[
{
"body": "<p>Preferably, you would generate a random salt. Add a function to generate random salt, then be sure to call it in your constructor. If a user discovers you salt, that is a major security hole right now. </p>\n\n<p>In my opinion, it would be best to separate this class into a separate file for easier use in multiple situations. Also, a separate file with useful functions like generating salt could be useful.</p>\n\n<p>Your code is relatively secure, but you need a random salt generator. Otherwise, your code looks good.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T16:51:32.677",
"Id": "41985",
"ParentId": "41749",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41985",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T19:56:06.433",
"Id": "41749",
"Score": "2",
"Tags": [
"php",
"session"
],
"Title": "PHP session fixation"
}
|
41749
|
<p>My domain model consists mostly of simple DTOs, i.e. 'Data Transfer Objects' which <a href="http://rlacovara.blogspot.fr/2009/03/what-is-difference-between-dto-and-poco.html" rel="nofollow noreferrer">this article distinguishes from 'Plain Old C# Objects'</a>, like this one:</p>
<pre><code>public class Settings
{
public bool FullScreen = false;
public int WindowWidth = 800;
public int WindowHeight = 600;
}
</code></pre>
<p>I realize this model is "anemic," but it works well with the JSON serializer I use for persistence. Also, I'm still in the exploratory stage of development and I read that it's okay at this point to have a bunch of "property bags."</p>
<p>Other classes look less like DTOs and more like POCOs (or POJOs although I'm using C#):</p>
<pre><code>public class Sprite
{
[JsonProperty]
private readonly string assetName;
[JsonProperty]
private Vector2 position;
// other properties...
public Sprite( string assetName, Vector2 position )
{
this.assetName = assetName;
this.position = position;
}
public void Move( Vector2 direction )
{
// do move
}
// other methods...
}
</code></pre>
<p>Because this type of object needs to be persisted by the JSON serializer, the properties need either to be public or have a JsonProperty attribute. I went with the attribute in this case because I want to restrict access to its properties.</p>
<p>Is this a good design? Does it make sense for my "entities" (I'm not sure if that's the correct term) to look so different from one another? My gut told me no, so I tried extracting the stuff not needed by the serializer into a separate class outside of the namespace:</p>
<pre><code>public class SpriteModel
{
private readonly Sprite sprite;
public SpriteModel( Sprite sprite )
{
this.sprite = sprite;
}
public void Move( Vector2 direction )
{
// do move
}
public void GetSprite()
{
return sprite;
}
// other methods...
}
</code></pre>
<p>Now the Sprite class looks more like a DTO:</p>
<pre><code>public class Sprite
{
public string AssetName;
public Vector2 Position;
// other properties...
}
</code></pre>
<p>Someone <a href="https://softwareengineering.stackexchange.com/a/229054/60709">told me</a> that my domain model is actually the <code>SpriteModel</code> class now and not the <code>Sprite</code> class itself. I'm obviously confused about what to call these things exactly, and any clarification would be appreciated.</p>
<p>But my main question is: which of these approaches is better and why? Are they both terrible? And in that case is there another approach that I should use instead? If I go with the second approach, then I could have <code>SpriteModel</code> implement <code>ISpriteModel</code>, and the classes that use it could be more loosely coupled, which is a nice side benefit I think. But I don't want to go that route just for a side benefit that might not actually pay off (and could just add more complexity).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T20:22:24.133",
"Id": "71818",
"Score": "4",
"body": "Congratulations on asking question 12,000 on CodeReview, and a good question at that!"
}
] |
[
{
"body": "<p>I would say that one of the major differences between a DTO and a POCO is the fact that a DTO should be immutable because it is meant to be used for transferring only. See what are the differences between a POCO and a DTO in this <a href=\"https://stackoverflow.com/q/725348\">SO question</a>. That said, someone could suggest that your DTO implementation should be the following:</p>\n\n<pre><code>public class Settings\n{\n public bool FullScreen{get; private set;}\n public int WindowWidth{get; private set;}\n public int WindowHeight{get; private set;}\n public Setting(int width, int height, bool fullScreen){\n WindowWidth = width;\n WindowHeight = height;\n FullScreen = fullScreen\n }\n}\n</code></pre>\n\n<p>This is only if you want to be a purist in the implementation of a DTO because the usage of this is a pain, especially if your DTO class has many properties. The work around is the one you already have, although I would trade the fields for properties because properties respect the principle of encapsulation and are implemented with the same space in C# (in Java I wouldn't mind having public fields though).</p>\n\n<p>About your second issue, I would say that your real problem is to isolate the domain from its representation, be it JSON or something else. So how could you separate them? I would personally use the proxy pattern:</p>\n\n<pre><code>public class Sprite\n{\n public virtual string AssetName{get; set;}\n public virtual Vector2 Position{get; set;}\n}\n\npublic class SpriteJson : Sprite\n{\n public SpriteJson(Sprite sprite){\n AssetName = sprite.AssetName;\n Position = sprite.Position;\n }\n public SpriteJson(){}\n [JSonProperty]\n public override string AssetName{get; set;}\n [JSonProperty]\n public override Vector2 Position{get; set;}\n}\n</code></pre>\n\n<p>It may seem that you have too much redundancy, but it does isolate the objects from their representation. You could receive a Sprite object anywhere in your code, whether it is a SpriteJson object or not.</p>\n\n<p><strong>Edit</strong>: I think I only answered your question partially, so I edited my answer to provide more details.</p>\n\n<p>Leaving the representation aside, the logic associated with the object would be in your Sprite class:</p>\n\n<pre><code>public class Sprite\n{\n public virtual string AssetName{get; set;}\n public virtual Vector2 Position{get; set;}\n public void Move(Vector2 direction)\n {\n // do move\n }\n}\n</code></pre>\n\n<p>I think an object should always have the logic associated with it whenever it makes sense and is reasonable. There is no need for making a wrapper only to separate the logic (a useless abstraction, in my opinion). The question I linked also stated that POCO classes may contain logic operations. So when is it not reasonable? Imagine that your move code is highly dependent on another class and many of your objects also have their own move logic. In that case, it would be better to refactor the move code to another place so you wouldn't have code redundancy and eliminate those dependencies.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T00:15:00.517",
"Id": "71854",
"Score": "0",
"body": "I like the idea of having a `SpriteJson` class and will probably try that. I'm using fields instead of auto-properties because I can easily specify default values. If I used auto-properties and a constructor, it would arguably involve more code for such a simple thing. However, we've had this conversation [before](http://codereview.stackexchange.com/a/37093/29587) and I think I'm just starting to get my head around your answer to that question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T01:14:01.590",
"Id": "71857",
"Score": "1",
"body": "The only reason that I consider that is OK to have public fields is because the DTO is meant for transfering as I said. So you won't EVER change the DTO code (unless you want to add a new field) and thus encapsulation is not a concern. So if public fields make your life easier in DTO use them."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T21:46:03.483",
"Id": "41760",
"ParentId": "41750",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T20:13:18.623",
"Id": "41750",
"Score": "6",
"Tags": [
"c#",
"object-oriented",
"ddd",
"dto",
"poco"
],
"Title": "Implementing a domain model"
}
|
41750
|
<p>I have the following class: </p>
<p>MyProtocolClass.h</p>
<pre><code>#import <Foundation/Foundation.h>
@protocol MyExampleProtocol <NSObject>
@required
- (void)someRequiredMethod:(NSInteger)someValue;
@end
@interface MyProtocolClass : UIView
// interface stuff
@end
</code></pre>
<p>MyProtocolClass.m</p>
<pre><code>#import "MyProtocolClass.h"
@interface MyProtocolClass()
@property (nonatomic,assign) id<MyExampleProtocol> delegate;
@end
@implementation MyProtocolClass
// implementation stuff
- (IBAction)fooMethod:(id)sender {
[self.delegate someRequiredMethod:0];
}
- (IBAction)barMethod:(id)sender {
[self.delegate someRequiredMethod:1];
}
- (IBAction)fooBarMethod:(id)sender {
[self.delegate someRequiredMethod:2];
}
@end
</code></pre>
<p>And this is a fairly simple example. The problem here is that I have a view with three buttons, and each button has it's own method, which simply calls a method on the delegate with an index to tell the delegate which button was pressed.</p>
<p>Surely there's a way to simplify this code and improve its readability. A more complex view with several more interactive UI elements would quickly make this file very large if we have to add another 4 lines to the file for each interactive UI element we add to the screen.</p>
|
[] |
[
{
"body": "<p>You're right. There is a simpler way.</p>\n\n<p>First of all, instead of giving every interactive element its own method, let's give them all the same method.</p>\n\n<pre><code>- (IBAction)buttonPressed:(id)sender;\n</code></pre>\n\n<p>If they're not all buttons, a different method name is in line, but for this example, I'll assume them all to be buttons.</p>\n\n<p>Now then, whether you're creating these UI elements programmatically or via interface builder, the next important step is to give each element its own unique tag. In the Interface Builder, this is done under the \"Attributes Inspector\" (the icon that looks like a shield). The \"tag\" field is the second field under the \"View\" heading. It doesn't matter what tag you give the button. It only matters that the tags are unique.</p>\n\n<p>Setting the tag programmatically is as simple as this:</p>\n\n<pre><code>myButton.tag = 100;\n</code></pre>\n\n<p>Now, instead of a different method for each button (or other UI element), we can simply use a single button:</p>\n\n<pre><code>- (IBAction)buttonPressed:(id)sender {\n [self.delegate someRequiredMethod:sender.tag];\n}\n</code></pre>\n\n<p>Now we've condensed your code. But we can do even better.</p>\n\n<p>Let's create an <code>enum</code> so that we're not just sending arbitrary numbers, but instead we send values that the delegate can make more sense of (and if using a <code>switch</code>, Xcode will help the delegate be sure he accounts for every case).</p>\n\n<pre><code>typedef NS_ENUM(NSInteger, MyExampleButtonEnum) {\n ButtonIndexUnknown = 0,\n ButtonIndexTopLeft = 100,\n ButtonIndexTopRight = 101,\n ButtonIndexBottomLeft = 102,\n ButtonIndexBottomRight = 103\n};\n</code></pre>\n\n<p>This should be placed in the <code>.h</code> and before our <code>@protocol</code>. Then we can change our protocol to look like this instead:</p>\n\n<pre><code>@protocol MyExampleProtocol <NSObject>\n@required\n- (void)someRequiredMethod:(MyExampleButtonEnum)button;\n@end\n</code></pre>\n\n<p>Now we just have to set our button tags to match these enum values. The good news is, if we're doing it programmatically, we can use the enum itself to set the values. For example...</p>\n\n<pre><code>UIButton *topLeftButton = [[UIButton alloc] initWithFrame:someFrame];\ntopLeftButton.tag = ButtonIndexTopLeft;\n[topLeftButton addTarget:self action:@selector(buttonPressed:)\n forControlEvents:UIControlEventTouchUpInside]\n</code></pre>\n\n<p>And now we slightly modify our <code>buttonPressed:</code> method as such:</p>\n\n<pre><code>- (IBAction)buttonPressed:(id)sender {\n if (sender) {\n [self.delegate someRequiredMethod:sender.tag];\n } else {\n [self.delegate someRequiredMethod:ButtonIndexUnknown];\n }\n}\n</code></pre>\n\n<p>And our delegate can implement the delegate method in some fashion like this:</p>\n\n<pre><code>- (void)someRequiredMethod:(MyExampleButtonEnum)button {\n switch(button) {\n case ButtonIndexTopLeft:\n // do stuff\n break;\n case ButtonIndexTopRight:\n // do stuff\n break;\n case ButtonIndexBottomLeft:\n // do stuff\n break;\n case ButtonIndexBottomRight:\n // do stuff\n break;\n case ButtonIndexUnknown:\n default:\n // do stuff\n break;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T21:58:57.210",
"Id": "41762",
"ParentId": "41761",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "41762",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T21:58:57.210",
"Id": "41761",
"Score": "8",
"Tags": [
"objective-c",
"ios",
"event-handling"
],
"Title": "How can I condense several IBAction methods in a class with a delegate?"
}
|
41761
|
<p>I've solved <a href="http://projecteuler.net/problem=15" rel="nofollow">Project Euler #15</a> in Haskell, but I feel like there might be a better way to express my solution that I'm not seeing. I start out defining my types:</p>
<pre><code>import qualified Data.Map.Strict as Map
import Data.List
data Position = Position Int Int
deriving (Show, Eq, Ord)
start :: Position
start = Position 20 20
</code></pre>
<p>I probably should have used newtype on a tuple of Ints, but I think this is ok. I can then generate the list of moves available from a given position via:</p>
<pre><code>moves :: Position -> [Position]
moves (Position x y) | x == 0 && y == 0 = []
| x == 0 = [Position x (y - 1)]
| y == 0 = [Position (x - 1) y]
| otherwise = Position (x - 1) y : Position x (y - 1) : []
</code></pre>
<p>From there a naive implementation to solve for the number of paths would simply look like:</p>
<pre><code>naiveWays :: Position -> Int
naiveWays (Position 0 0) = 1
naiveWays pos = sum $ map naiveWays $ moves pos
</code></pre>
<p>Of course this is highly inefficient, and takes much to long to complete, so I tried to improve it using memoization. This is where I feel like I could probably use the most improvement:</p>
<pre><code>ways :: Position -> Int
ways = snd . memWays Map.empty
memWays :: Map.Map Position Int -> Position -> (Map.Map Position Int, Int)
memWays mem (Position 0 0) = (mem, 1)
memWays mem pos = loop lookupWays
where
lookupWays = Map.lookup pos mem
computeWays = mapAccumR memWays mem (moves pos)
mapWays = fst computeWays
sumWays = sum $ snd computeWays
loop (Just w) = (mem, w)
loop (Nothing) = (Map.insert pos sumWays mapWays, sumWays)
</code></pre>
<p>Basically <code>memWays</code> takes a Map of known solutions for the subproblems (number of paths from 2,2, etc), and a position and attempts to use it to find the shortest path. If the position is already in the map, it can simply look it up. Otherwise, it maps over the available moves, using the returned Map as an accumulator.</p>
<p>There actually is an even more efficient way to solve it, but I won't spoil that, and since I'm looking for Haskell practice, not math, I'm more interested in figuring out how I can make this approach cleaner.</p>
<p><strong>Edit</strong>: Thanks to 200_success for pointing out that I don't need to enumerate moves. <code>memWays</code> now looks like:</p>
<pre><code>memWays :: Map.Map Position Int -> Position -> (Map.Map Position Int, Int)
memWays mem (Position 0 _) = (mem, 1)
memWays mem (Position _ 0) = (mem, 1)
memWays mem pos@(Position x y) = loop $ Map.lookup pos mem
where right = memWays mem $ Position (x - 1) y
down = memWays (fst right) $ Position x (y - 1)
both = snd right + snd down
loop (Just paths) = (mem, paths)
loop Nothing = (Map.insert pos both $ fst down, both)
</code></pre>
<p>I feel like this looks a lot cleaner, though if anyone has suggestions for further improvement, I'd love to hear it.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T14:13:56.827",
"Id": "72283",
"Score": "1",
"body": "*Efficiency Review:* [Optimize the code using mathematical](https://www.youtube.com/watch?v=gENVB6tjq_M) concepts. I suggest you study some [***combinitorics***](https://en.wikipedia.org/wiki/Combinatorics)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-11T09:34:26.563",
"Id": "119838",
"Score": "0",
"body": "If you are registered at project euler and have submitted a valid solution for this problem you have access to the [thread for this problem in the project euler forum](https://projecteuler.net/thread=15). Ther you can find a lot and maybe faster solutions of this problem."
}
] |
[
{
"body": "<p>There's no need to list all the moves. Here is an unmemoized solution:</p>\n\n<pre><code>naiveWays :: Position -> Int\nnaiveWays (Position 0 _) = 1\nnaiveWays (Position _ 0) = 1\nnaiveWays (Position x y) = (naiveWays (Position (x - 1) y)) +\n (naiveWays (Position x (y - 1)))\n</code></pre>\n\n<p>Note that it also takes better advantage of pattern matching.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T22:49:08.953",
"Id": "41766",
"ParentId": "41764",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "41766",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T22:11:00.870",
"Id": "41764",
"Score": "5",
"Tags": [
"haskell",
"project-euler",
"combinatorics",
"programming-challenge"
],
"Title": "Project Euler #15 in haskell"
}
|
41764
|
<p>In particular, if someone could describe a better way to go from the tokenized list to the Expression tree, it would be super helpful. I would like to get rid of the casting in the parser but am not sure how.</p>
<p><a href="https://github.com/MindDesigns/bwscalc" rel="nofollow">Full code here</a></p>
<pre><code>package org.bws.calc;
import java.util.ArrayList;
import org.bws.calc.exception.ParseException;
import org.bws.calc.expression.Expression;
import org.bws.calc.expression.ValueExpression;
import org.bws.calc.tokens.OpToken;
import org.bws.calc.tokens.Token;
public class SimpleParser implements Parsable{
public Expression parse(ArrayList<Token> tokens){
if(tokens.size() == 1){
Token t = tokens.get(0);
try{
int intVal = Integer.parseInt(t.getValue());
return new ValueExpression(intVal);
}catch(NumberFormatException nfe){
throw new ParseException("expected int but found: "+t.getValue());
}
}
Expression left;
Expression right;
int index=0;
Token firstToken = tokens.get(index++);
if("(".equals(firstToken.getValue())){
int openParens =1;
while(openParens > 0 ){
if(index>tokens.size()-1){throw new ParseException("Missing right Parenthesis");}
Token token = tokens.get(index);
if("(".equals(token.getValue())){ ++openParens;}
if(")".equals(token.getValue())){ --openParens;}
++index;
}
if(index == tokens.size()){
return parse(new ArrayList<Token>(tokens.subList(1, index-1) ) );
}
left = parse(new ArrayList<Token>(tokens.subList(1,index-1)));
}else{
int tokenVal = Integer.parseInt(firstToken.getValue());
left = new ValueExpression(tokenVal);
}
Token op = tokens.get(index);
if(! (op instanceof OpToken) ){
throw new ParseException("Invalid Syntax. expected Operator but found:"+op);
}
OpToken opToken = (OpToken) op;
++index;
Token firstRightToken = tokens.get(index++);
if("(".equals(firstRightToken.getValue() ) ){
right = parse(new ArrayList<Token>(tokens.subList(index,tokens.size()-1)));
}else{
int tokenVal = Integer.parseInt(firstRightToken.getValue());
right = new ValueExpression(tokenVal);
}
return opToken.toExpression(left, right);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T09:14:50.047",
"Id": "71876",
"Score": "0",
"body": "In regard to the casting, I do not know Java enough, but I think that since it has no support for multiple derivation, it probably will be difficult. One way is to create a node that supports all the different data types you want to accept in your parser."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T09:24:32.430",
"Id": "71877",
"Score": "0",
"body": "I only see one cast, and it looks entirely reasonable."
}
] |
[
{
"body": "<p>Before I begin, let me say, it looks like a well engineered project. You've separated the work into a tokenizer, parser, and calculator, which is excellent. The unit tests were helpful as well. Congratulations.</p>\n\n<hr>\n\n<p>Before you begin to write a parser, you should define the grammar, which you should state as a long comment in your parser's JavaDoc. From my interpretation of your code, I see the following productions:</p>\n\n<pre><code>EXPRESSION = BINARY_EXPRESSION |\n TERM\n\nBINARY_EXPRESSION = EXPRESSION BINARY_OPERATOR TERM\n\nBINARY_OPERATOR = \"+\" | \"-\"\n\nTERM = VALUE_EXPRESSION |\n PARENTHESIZED_EXPRESSION\n\nVALUE_EXPRESSION = number\n\nPARENTHESIZED_EXPRESSION = \"(\" EXPRESSION \")\"\n</code></pre>\n\n<p>You don't support unary minus (negative numbers). That's OK; we'll keep it simple for now.</p>\n\n<hr>\n\n<p>It would be a good idea to add the following unit test:</p>\n\n<pre><code>@Test\npublic void evaluateThreeOperatorWithNoParens(){\n int result = c.evaluate(\"5-2+1\");\n Assert.assertEquals(4,result);\n}\n</code></pre>\n\n<p>If you had defined the grammar carelessly, such as the following…</p>\n\n<pre><code>EXPRESSION = VALUE_EXPRESSION |\n BINARY_EXPRESSION |\n PARENTHESIZED_EXPRESSION\n\nVALUE_EXPRESSION = number\n\nBINARY_EXPRESSION = EXPRESSION BINARY_OPERATOR EXPRESSION\n\nBINARY_OPERATOR = \"+\" | \"-\"\n\nPARENTHESIZED_EXPRESSION = \"(\" EXPRESSION \")\"\n</code></pre>\n\n<p>… then it would be ambiguous whether <code>\"5-2+1\"</code> should be interpreted as <code>(5-2)+1</code> or <code>5-(2+1)</code>. The <code>evaluateThreeOperatorWithNoParens()</code> test enforces the former interpretation.</p>\n\n<hr>\n\n<p>The main problem is your handling of parentheses. Scanning the entire token list in advance to check for matching parentheses is inelegant; you should be able to detect such syntax errors as part of your parsing routine. Also, having four if-statements checking for opening/closing parentheses is a sign of confusion.</p>\n\n<p>To enforce some structure to your parser, you should have a helper function for each production listed above.</p>\n\n<p>Instead of taking <code>.subList()</code>s, I think it would be more elegant to use a <code>ListIterator<Token></code> to keep track of your position. Also, there's no reason why your parser has to take an <code>ArrayList</code>, when any <code>List<Token></code> would be acceptable.</p>\n\n<p><code>Parsable</code> is an odd name for the interface. I'd consider a string to be parsable. Therefore, I suggest breaking with the \"-able\" suffix convention and just call it a <code>Parser</code>. (Plenty of interfaces in the standard Java API aren't named with an \"-able\" suffix either.)</p>\n\n<pre><code>/**\n * (JavaDoc describing the grammar goes here.)\n */\npublic class SimpleParser implements Parser {\n\n public Expression parse(List<Token> tokens) {\n ListIterator<Token> tokenIter = tokens.listIterator();\n Expression expr = parseExpression(tokenIter);\n if (tokenIter.hasNext()) {\n throw new ParseException(\"Extra text after expression: \" + tokenIter.next().getValue());\n }\n return expr;\n }\n\n private static Expression parseExpression(ListIterator<Token> tokenIter) {\n if (!tokenIter.hasNext()) {\n throw new ParseException(\"Premature end of expression\");\n }\n\n Expression expr = parseTerm(tokenIter);\n while (tokenIter.hasNext()) {\n Token op = tokenIter.next();\n if (op instanceof OpToken) {\n expr = parseBinaryExpression(expr, (OpToken)op, tokenIter);\n } else {\n tokenIter.previous();\n break;\n }\n }\n return expr;\n }\n\n private static Expression parseBinaryExpression(Expression leftExpr, OpToken op, ListIterator<Token> tokenIter) {\n return op.toExpression(leftExpr, parseTerm(tokenIter));\n }\n\n private static Expression parseTerm(ListIterator<Token> tokenIter) {\n Token t = tokenIter.next();\n if (\"(\".equals(t.getValue())) {\n return parseParenthesizedExpression(tokenIter);\n } else {\n return parseValueExpression(t);\n }\n }\n\n private static Expression parseValueExpression(Token t) {\n try {\n int intVal = Integer.parseInt(t.getValue());\n return new ValueExpression(intVal);\n } catch (NumberFormatException nfe) {\n throw new ParseException(\"expected int but found: \" + t.getValue());\n }\n }\n\n private static Expression parseParenthesizedExpression(ListIterator<Token> tokenIter) {\n Expression innerExpr = parseExpression(tokenIter);\n if (!tokenIter.hasNext() || !\")\".equals(tokenIter.next().getValue())) {\n throw new ParseException(\"Missing right parenthesis\");\n }\n return innerExpr;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T08:37:24.357",
"Id": "71873",
"Score": "0",
"body": "Wow, incredible answer. Your time has been much appreciated. This will be named the \"SuccessParser\" :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T08:47:39.173",
"Id": "71874",
"Score": "1",
"body": "Note: `BINARY_EXPRESSION = EXPRESSION \"+\"|\"-\" EXPRESSION` is incorrect. It should be: `BINARY_EXPRESSION = EXPRESSION \"+\" EXPRESSION | EXPRESSION \"-\" EXPRESSION`. The | only separate distinct rules. Another way is to have a BINARY_OPERATOR rule where you have \"+\" | \"-\" and then `BINARY_EXPRESSION = EXPRESSION BINARY_OPERATOR EXPRESSION`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T08:51:31.137",
"Id": "71875",
"Score": "0",
"body": "@AlexisWilke Thanks. Fixed in [Rev 4](http://codereview.stackexchange.com/revisions/41776/4)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T06:09:02.140",
"Id": "41776",
"ParentId": "41769",
"Score": "4"
}
},
{
"body": "<p>There is a grammar that I wrote to handle C-like expressions. This is very similar to what 200_success talks about. One aspect of this grammar, it gives you the exact priority of the different operators. With this you can clearly see that the unary \"+\" has priority over the binary \"+\".</p>\n\n<p>Also, since the multiplicative expression is called by the additive expression, the expression: 3 + 5 * 7 will properly be parsed as (5 * 7) + 3.</p>\n\n<p>The easiest to write code to transform that grammar to a tree, is to write one function per rule (i.e. a rule is for example expr_list). All the choices of one rule can be handled in that one function. First you read a token from your lexer, then call the \"start\" function (in my case it would be expr() or something like that). The start function when calls the function of the previous level if it cannot match the current token to one of the tokens the current function is expecting. So the expr() function would call the assignment() function. The assignment() would call the conditional_expr(), etc. In other words, you use the CPU stack to help generate the tree.</p>\n\n<p>When a token is matched, you go on with that possibility. If that possibility returns \"false\" in some way (i.e. that choice [a line represents a choice] did not match the following tokens) then drop it and try the next one. Once a whole choice was a match, you \"reduce it\", in other words, you create a node that represents it. For example, the IDENTIFIER in the unary_expr can be changed to a node of type \"variable\". And in the additive_expr, you would create an \"add\" node with two children (a left hand side and a right hand side.)</p>\n\n<p>It is a little bit of work when you want to handle quite complete grammars. But that's the basics and how pretty much all proper compilers are built.</p>\n\n<pre><code>// expr_list\nexpr_list ::= expr\n | expr_list \",\" expr\n\n// unary_expr\nunary_expr ::= \"!\" unary_expr\n | \"~\" unary_expr\n | \"+\" unary_expr\n | \"-\" unary_expr\n | \"(\" expr_list \")\"\n | IDENTIFIER \"(\" expr_list \")\"\n | IDENTIFIER\n | keyword_true\n | keyword_false\n | STRING\n | INTEGER\n | FLOAT\n\n// multiplicative_expr\nmultiplicative_expr ::= unary_expr\n | multiplicative_expr \"*\" unary_expr\n | multiplicative_expr \"/\" unary_expr\n | multiplicative_expr \"%\" unary_expr\n\n// additive_expr\nadditive_expr ::= multiplicative_expr\n | additive_expr \"+\" multiplicative_expr\n | additive_expr \"-\" multiplicative_expr\n\n// shift_expr\nshift_expr ::= additive_expr\n | shift_expr \"<<\" additive_expr\n | shift_expr \">>\" additive_expr\n\n// relational_expr\nrelational_expr ::= shift_expr\n | relational_expr \"<\" shift_expr\n | relational_expr \"<=\" shift_expr\n | relational_expr \">\" shift_expr\n | relational_expr \">=\" shift_expr\n | relational_expr \"<?\" shift_expr\n | relational_expr \">?\" shift_expr\n\n// equality_expr\nequality_expr ::= relational_expr\n | equality_expr \"==\" relational_expr\n | equality_expr \"!=\" relational_expr\n\n// bitwise_and_expr\nbitwise_and_expr ::= equality_expr\n | bitwise_and_expr \"&\" equality_expr\n\n// bitwise_xor_expr\nbitwise_xor_expr ::= bitwise_and_expr\n | bitwise_xor_expr \"^\" bitwise_and_expr\n\n// bitwise_or_expr\nbitwise_or_expr ::= bitwise_xor_expr\n | bitwise_or_expr \"|\" bitwise_xor_expr\n\n// logical_and_expr\nlogical_and_expr ::= bitwise_or_expr\n | logical_and_expr \"&&\" bitwise_or_expr\n\n// logical_xor_expr\nlogical_xor_expr ::= logical_and_expr\n | logical_xor_expr \"^^\" logical_and_expr\n\n// logical_or_expr\nlogical_or_expr ::= logical_xor_expr\n | logical_or_expr \"||\" logical_xor_expr\n\n// conditional_expr\n// The C/C++ definition is somewhat different:\n// logical-OR-expression ? expression : conditional-expression\nconditional_expr ::= logical_or_expr\n | conditional_expr \"?\" expr \":\" logical_or_expr\n\n// assignment\n// (this is NOT a C compatible assignment, hence I used \":=\")\nassignment ::= conditional_expr\n | TOKEN_ID_IDENTIFIER \":=\" conditional_expr\n\n// expr\nexpr ::= assignment\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T09:13:37.757",
"Id": "41786",
"ParentId": "41769",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "41776",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T01:25:47.273",
"Id": "41769",
"Score": "5",
"Tags": [
"java",
"parsing",
"recursion",
"math-expression-eval"
],
"Title": "Numeric expression parser - calculator"
}
|
41769
|
<p>For class, I had to use Java to draw a triangle and some concentric circles:</p>
<pre><code>import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class JComponentDemo {
private static final JComponent triangleComponent = new JComponent() {
private static final long serialVersionUID = 1L;
@Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.draw(new Line2D.Double(180, 100, 100, 0));
g2.draw(new Line2D.Double(20, 100, 100, 0));
g2.draw(new Line2D.Double(180, 100, 20, 100));
}
};
private static final JComponent ConcentricCircleMaker = new JComponent() {
private static final long serialVersionUID = 1L;
@Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
double[] circles = {40, 80, 120, 160, 200};
Color[] colors = {Color.red, Color.green, Color.orange, Color.MAGENTA, Color.cyan};
int count = 0;
for (double i : circles) {
g2.setColor(colors[count++]);
g2.draw(Factory.get().makeCircle(200 - i / 2, 200 - i, i));
}
}
};
public static void main(String[] args) {
JFrame frame = new JFrame("Drawing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(50, 50, 500, 500);
frame.setVisible(true);
frame.setContentPane(triangleComponent);
JOptionPane.showMessageDialog(null, "Click OK to Continue");
frame.setVisible(false);
frame.setContentPane(ConcentricCircleMaker);
frame.setVisible(true);
}
private static class Factory {
private static final FactorySingle factory;
static {
factory = new FactorySingle();
}
static FactorySingle get() {
return factory;
}
private static class FactorySingle {
public Ellipse2D.Double makeCircle(double x, double y, double length) {
return new Ellipse2D.Double(x, y, length, length);
}
}
}
}
</code></pre>
<p>I admit that I am terrible at commenting. I have some questions:</p>
<ol>
<li>Is it a good practice just to <code>import</code> everything so I don't have to go back and add stuff?</li>
<li>Is it bad just to let NetBeans do <code>serialVersionUID</code> for me? (I don't like yellow squiggles!)</li>
<li>Are those anonymous classes smart or unnecessarily confusing?</li>
<li>Am I instantiating more than I need to?</li>
<li>Is this the best way to handle graphics/<code>Graphics</code>?</li>
<li>Do all those fields have to be <code>final</code>?</li>
<li>Should I make all of the objects <code>final</code> that don't need to change?</li>
<li>I tried to implement a <code>Circle</code> factory singleton in order not to repeat code. Are there problems? Is this worth it?</li>
<li>In general, are there ways to make my code more succinct?</li>
</ol>
|
[] |
[
{
"body": "<blockquote>\n <p>Is it a good practice just to import everything so I don't have to go back and add stuff?</p>\n</blockquote>\n\n<p>In a modern IDE (e.g. NetBeans) you can just type in the class you intend to use and quick-fix the import. I usually do this so that I don't have spare imports laying around inadvertently. Also, you can use the source cleanup tool to remove unused imports when you're done. I do this in Eclipse, but I'm exceptionally sure that a similar option is in NetBeans. Importing only what you need reduces compilation time.</p>\n\n<blockquote>\n <p>Is it bad just to let NetBeans do serialVersionUID for me? (I don't like yellow squiggles!)</p>\n</blockquote>\n\n<p>Do you plan on \"serializing\" your class? Do you expect anyone else to? If so, you'll want that property to be set, so that different versions of your code can determine which version of the class you're deserializing to (or generate an error). You can use 1L for the first version, and increment it every time you add, remove, or change a member of the class. Or, you can just save that for <em>last</em> if you don't expect many changes when the class is done, and generate it then. If you really don't care about serializing the objects, just suppress the warning with an annotation.</p>\n\n<blockquote>\n <p>Are those anonymous classes smart or unnecessarily confusing?</p>\n</blockquote>\n\n<p>The general rule of thumb is: if it's less than (approximately) 10 lines of code, and not frequently used (e.g. is used only once), than anonymous classes are perfectly acceptable, and in fact, encouraged. For code that is bound to be reused often, a named class should be preferred. The Java designers knew that there would often be small classes that only had a few lines of code that, in practice, wouldn't make sense to have in their own source files when one could simply inline the class definition and instantiation at once. Also, because anonymous classes share scope with the outer class, they can get access to the necessary variables and methods without having to accept an instance of the class, modifying member access modifiers, etc.</p>\n\n<blockquote>\n <p>Am I instantiating more than I need to?</p>\n</blockquote>\n\n<p>There's no particular excess here, although this may not be the most efficient method you could have come up with. Unless you were under specific direction from a higher authority not to use certain constructs, such as BufferedImages, this almost qualifies as object abuse; components are generally meant to be a way to interact with users, not to just draw arbitrary objects. However, since we're only talking about two frames, it doesn't really matter, and I don't think it would be worth debating the merit of using components versus images.</p>\n\n<blockquote>\n <p>Is this the best way to handle graphics/Graphics?</p>\n</blockquote>\n\n<p>Normally, one should create a sort of \"canvas\", and draw onto that. Here, you're changing the entire content of the window just to flop graphics around. Since there's only two frames, this works out okay, but in a game running at 60FPS, your players would get a headache and/or seizures. You could just as easily have made two <code>BufferedImage</code> elements, and flipped between the two, using a common component that you could draw to.</p>\n\n<blockquote>\n <p>Do all those fields have to be final?</p>\n</blockquote>\n\n<p>Fields are final because you want to force certain behavior (e.g. a class cannot be inherited, a value can only be set once, etc). Assuming this was a module that you'd distribute to other developers to use, you'd want anything that should be locked down to be final. You might also use final to prevent yourself from writing code that accidentally modifies the variables. In short, it is a <em>good practice</em>, but it doesn't <em>make sense</em> logically <em>in this example</em>, because this program is sufficiently small enough that you wouldn't likely introduce such a logical error. I would recommend using final as frequently as necessary, but not necessarily here.</p>\n\n<blockquote>\n <p>Should I make all of the objects final that don't need to change?</p>\n</blockquote>\n\n<p>Like before, it doesn't really matter in this example. You make values final so as to avoid accidental or intentional changes to the values. Also remember that final can affect inheritance, so if this were a module to a larger application, you might not want to lock everything down with final. In this case, most everything could be final just to prove to yourself that your code isn't making any unintentional changes. I would actually recommend having everything <em>not</em> be final, and for good measure, not static either.</p>\n\n<blockquote>\n <p>I tried to implement a Circle factory singleton in order not to repeat code. Are there problems? Is this worth it?</p>\n</blockquote>\n\n<p>In a larger program, factories make sense. In this case, it makes no sense at all; the code needed to support the factory is larger than the savings of not having a factory at all. Consider this version (which does the same thing):</p>\n\n<pre><code>for (double i : circles) {\n g2.setColor(colors[count++]);\n g2.draw(new Ellipse2D.Double(200 - i / 2, 200 - i, i, i)));\n}\n</code></pre>\n\n<p>It is perfectly legal, and in fact desirable, to instantiate anonymous, short-lived objects that are passed directly into the parameter list of the function, which is essentially what you're doing anyways. This lets people know, clearly, that you're simply creating a circle, instead of having to refer to the factory's source code to get an answer as to what is going on.</p>\n\n<blockquote>\n <p>In general, are there ways to make my code more succinct?</p>\n</blockquote>\n\n<p>I believe I've outlined most of the problems in the prior answers, but let's go over them:</p>\n\n<ul>\n<li>Drop the use of the factory, it's simply overkill in this case.</li>\n<li>Drop the serial ids, especially in anonymous inner classes, as it is unlikely you'll <em>ever</em> serialize them. Warnings are okay, but you can use suppression annotations if you don't like the yellow squiggles (and I personally <em>hate</em> them; they're a guilt trip).</li>\n<li>Use just one component to draw onto (or, one to manage the current view state, if you prefer).</li>\n<li>Don't hide then show the frame. Instead, call invalidate() to force a repaint. No flickering.</li>\n<li>Loading graphics and stuff as an initialization generally makes sense, but not here, because you're just wasting memory (although, not a ton, since this program only weighs in at a few KB, but, the principal remains). You should defer generating the two components until the last possible moment.</li>\n<li>Generally speaking, your main app can be the JFrame; this is a normal design.</li>\n</ul>\n\n<p>Without switching to images and all that, I can simply rearrange your code to the far simpler:</p>\n\n<pre><code>import javax.swing.*;\nimport java.awt.*;\nimport java.awt.geom.*;\n\npublic class JComponentDemo extends JFrame {\n\n public JComponentDemo() {\n super(\"Drawing\");\n }\n\n public void start() {\n setDefaultCloseOperation(EXIT_ON_CLOSE);\n setBounds(50, 50, 500, 500);\n setVisible(true);\n setContentPane(\n new JComponent() {\n @Override\n public void paintComponent(Graphics g) {\n Graphics2D g2 = (Graphics2D) g;\n g2.draw(new Line2D.Double(180, 100, 100, 0));\n g2.draw(new Line2D.Double(20, 100, 100, 0));\n g2.draw(new Line2D.Double(180, 100, 20, 100));\n }\n });\n JOptionPane.showMessageDialog(null, \"Click OK to Continue\");\n setContentPane(new JComponent() {\n @Override\n public void paintComponent(Graphics g) {\n Graphics2D g2 = (Graphics2D) g;\n double[] circles = {40, 80, 120, 160, 200};\n Color[] colors = {Color.red, Color.green, Color.orange, Color.MAGENTA, Color.cyan};\n int count = 0;\n for (double i : circles) {\n g2.setColor(colors[count++]);\n g2.draw(new Ellipse2D.Double(200 - i / 2, 200 - i, i, i));\n }\n }\n });\n setVisible(true);\n }\n\n public static void main(String[] args) {\n new JComponentDemo().start();\n }\n}\n</code></pre>\n\n<p>Note that anonymous inner classes are only good for \"small\" things, so this design wouldn't scale well (imagine a UI with hundreds of components). Regardless, you would still want to instantiate those elements either in a constructor, or in a thread that allocates the objects as the program is starting up or running so that the elements are available when needed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T03:17:20.563",
"Id": "71863",
"Score": "8",
"body": "Welcome to Code Review! This was a spectacular first answer (+1), hopefully you can stick around to answer some more!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T03:06:52.483",
"Id": "41771",
"ParentId": "41770",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "41771",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T01:44:28.410",
"Id": "41770",
"Score": "8",
"Tags": [
"java",
"object-oriented",
"swing",
"graphics"
],
"Title": "Drawing a triangle and some concentric circles"
}
|
41770
|
<p>I have two registration paths in my app. They are very similar and I am curious if I should simplify 4 associated actions down into two actions that handle the same amount of work.</p>
<p>Here are my controller actions:</p>
<pre><code>def employer_registration
@employer_signup = EmployerSignup.new
end
def employee_registration
@employee_signup = EmployeeSignup.new
end
def create_employee
@employee_signup = EmployeeSignup.new(params[:employee_signup])
if @employee_signup.save
sign_in @employee_signup.user
redirect_to root_path, notice: 'You signed up successfully'
else
render action: :employee_registration
end
end
def create_employer
@employer_signup = EmployerSignup.new(params[:employer_signup])
if @employer_signup.save
sign_in @employer_signup.user
redirect_to root_path, notice: 'You signed up successfully.'
else
render action: :employer_registration
end
end
</code></pre>
<p>As you can see, the only difference between the two registration paths are the form object that's being used, <code>EmployeeSignup</code> and <code>EmployerSignup</code> respectively. As you would expect, views are actually very similar too, they just display a form that's appropriate to each form object.</p>
<p>I have full test suits for each of these registration paths and it seems like an exceptionally large amount of duplication.</p>
<p>Each path handles something different, one handles employees registering, the other handles employers - so I'm tempted to leave them separate. But, if thought of another way, they both handle one idea: User Registration. In that case I feel it would be wiser to reconcile the different paths into one path and have a simple parameter control which form object is being used depending on the desired path.</p>
<p>Is my code acceptable as is or would it be more reasonable to refactor it down into one 'new' action and one 'create' action?</p>
|
[] |
[
{
"body": "<p>Your setup is going to eventually be working around Rails configurations, which are built for the canonical <code>index, new, create, show, edit, update, delete</code>.</p>\n\n<p>Rails does resource routing for this very reason (read more in <a href=\"http://guides.rubyonrails.org/routing.html\" rel=\"nofollow\">the Rails Guide on Routing</a>). It's also very in-line with HTTP verb standards and will make turning this into a JSON API trivial, should you need one.</p>\n\n<p>Since your <code>Employer</code> and <code>Employee</code> are separate domain objects, I would make them separate controllers. This leaves some nice future options for other actions when you need them like <code>edit</code> and <code>destroy</code>.</p>\n\n<pre><code>class EmployerController < ApplicationController\n def new\n @employer_signup = EmployerSignup.new\n end\n\n def create\n @employer_signup = EmployerSignup.new(params[:employer_signup])\n\n if @employer_signup.save\n sign_in @employer_signup.user\n redirect_to root_path, notice: 'You signed up successfully.'\n else\n render action: :employer_registration\n end\n end\nend\n\nclass EmployeeController < ApplicationController\n def new\n @employee_signup = EmployeeSignup.new\n end\n\n def create\n @employee_signup = EmployeeSignup.new(params[:employee_signup])\n\n if @employee_signup.save\n sign_in @employee_signup.user\n redirect_to root_path, notice: 'You signed up successfully'\n else\n render action: :employee_registration\n end\n end\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:26:06.803",
"Id": "41899",
"ParentId": "41774",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T04:16:42.427",
"Id": "41774",
"Score": "0",
"Tags": [
"ruby",
"ruby-on-rails",
"controller"
],
"Title": "Employer registration"
}
|
41774
|
<p>As C# doesn't have generic specialisation like C++ template specialisation and I wanted a way to be able to do it, I came up with a little hack that goes a bit like this:</p>
<pre><code> public sealed class Specialisation<T>
{
private Specialisation() { }
private static Specialisation<T> instance = new Specialisation<T>();
public static Specialisation<T> Instance { get { return instance; } }
}
public interface ISpecialisable<T>
{
T SpecialisedMethod(Specialisation<T> t);
}
public class Specialised : ISpecialisable<int>, ISpecialisable<float>
{
public double Value;
public int SpecialisedMethod(Specialisation<int> t) { return (int)Value; }
public float SpecialisedMethod(Specialisation<float> t) { return (float)Value; }
}
public static class Program
{
public static void Main()
{
Specialised s = new Specialised();
s.Value = 12.3456789;
Console.WriteLine(s.SpecialisedMethod(Specialisation<int>.Instance));
Console.WriteLine(s.SpecialisedMethod(Specialisation<float>.Instance));
Console.ReadKey();
}
}
</code></pre>
<p>Other than this not being the 'right way' to do things and being a complete mistreatment of the method overloading system, are there any possible side effects that could happen as a result of this horrible hack?</p>
<p>EDIT:</p>
<p>An applied example of specialisation in such a manner:</p>
<pre><code> // assume Specialisation is unchanged
public interface IConvertible<T> // Not to be confused with System.IConvertible
{
T Convert(Specialisation<T> t);
}
public class ConvertMe : IConvertible<int>, IConvertible<float>
{
public double Value;
public int Convert(Specialisation<int> t) { return (int)Value; }
public float Convert(Specialisation<float> t) { return (float)Value; }
}
public static class Program
{
public static void Main()
{
ConvertMe c = new ConvertMe();
c.Value = 12.3456789;
Console.WriteLine(c.Convert(Specialisation<int>.Instance));
Console.WriteLine(c.Convert(Specialisation<float>.Instance));
Console.ReadKey();
}
}
</code></pre>
<p>EDIT:
Another example I just thought of as an extension of/alternative to the <code>IConvertible<T></code> example. This technique allows the normal generic method syntax to be used externally, whilst allowing the class developer to internally define specialisations.</p>
<pre><code>public interface IConvertible<T>
{
T Convert(Specialisation<T> t);
T Convert<T>();
}
// assume Specialisation<T> is unchanged
public class ConvertMe : IConvertible<int>, IConvertible<float>
{
public double Value;
int IConvertible<int>.Convert(Specialisation<int> t) { return (int)Value; }
float IConvertible<float>.Convert(Specialisation<float> t) { return (float)Value; }
public T Convert<T>() { return ((IConvertible<T>)this).Convert(Specialisation<T>.Instance); }
}
public static class Program
{
public static void Main()
{
ConvertMe c = new ConvertMe();
c.Value = 12.3456789;
Console.WriteLine(c.Convert<int>());
Console.WriteLine(c.Convert<float>());
Console.ReadKey();
}
}
</code></pre>
<p>This use of specialisation could be generalised to other applications in order to provide specialised behaviour. I won't add any more examples as the ones provided are long enough as it is, and I'm sure everyone here has the skill and imagination to find other applications of this pattern.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T05:11:56.090",
"Id": "71867",
"Score": "2",
"body": "\" are there any possible side effects that could happen as a result of this horrible hack?\" Do you mean like unemployment?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T05:16:10.177",
"Id": "71868",
"Score": "1",
"body": "I'm not employed anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T10:37:06.947",
"Id": "71883",
"Score": "4",
"body": "Could you explain why would you want to do this? How is your code better than `s.SpecialisedMethodForInt()`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T15:05:02.570",
"Id": "71915",
"Score": "2",
"body": "I find it pretty \"special\"... what is it used for? Why the `static` stuff?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T00:21:35.640",
"Id": "71974",
"Score": "0",
"body": "@svick By doing it this way, ISpecialisable only needs to be declared once and it can be used for any new classes or interfaces, thus it is more extensible than just creating new interfaces each time you come up with a new type to specialise to."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T00:35:06.050",
"Id": "71975",
"Score": "0",
"body": "@lol.upvote If the Specialisation class could be created dynamically then people would end up creating a new Specialisation every time they wanted to use a SpecialisedMethod, which would be wasteful as the object would end up being created and not really used, which is wasteful of time and memory. By using the Singleton pattern only one instance is ever made, thus memory is saved by only having one instance and time is saved by not having to waste time allocating heap space for a 'dummy' instance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T12:37:19.450",
"Id": "72061",
"Score": "0",
"body": "Just a thought - maybe `interface IConvertible<T> { T Convert(T targetType); }` could be used? There could be some issues with implicit conversions (int->long etc.) though. This has added value of enabling you to use anonymous types. Or you could provide implicit conversion from `targetType` to `Specialisation` enabling you to keep the original definition but much shorter usage."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T16:45:38.153",
"Id": "72116",
"Score": "0",
"body": "@Knaģis It could, but then you'd end up having to create an instance of T on the fly or cache an instance to use with the specialised function, which is why I decided to opt for the singleton pattern. I like the idea of the implicit conversion, but to me that rings out as an extra step of unnecessary complexity. If `ISpecialisable` could force the implementer to define an explicit cast, that might be one solution from the conversion aspect, but only in the conversion situation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:31:19.083",
"Id": "72125",
"Score": "0",
"body": "@Knaģis So, to convert to `int` you would write `Convert(0)`? That seems really confusing to me. And I don't think it allows you to use anonymous types, how would you create a class that implements `IConvertible<anonymous type>`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-23T14:22:47.087",
"Id": "103505",
"Score": "0",
"body": "Please, don't edit your question with completely new code, it invalidates the existing answers. See [this meta question for more details](http://meta.codereview.stackexchange.com/q/1763/2041)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-23T14:26:22.280",
"Id": "103506",
"Score": "0",
"body": "@svick Should I ask a new question and risk [duplicate question] or make the existing one even longer and risk complaints about it being to long?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-23T14:28:01.377",
"Id": "103507",
"Score": "0",
"body": "@Pharap You should ask a new question. It's okay to do that and it's not considered a duplicate question. See also [How to post a follow-up question?](http://meta.codereview.stackexchange.com/q/1065/2041)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-23T14:32:48.540",
"Id": "103508",
"Score": "0",
"body": "@svick Thank you, I will consider posting a follow up. To be safe though I may formulate another example so it's definitely bringing something new to the table."
}
] |
[
{
"body": "<p>I don't think that there any nasty hidden downsides to it. As you noted C# doesn't have real specialisations and the only way to have the same method just differing by return type is the way you chose - so if that's what you need then that's what you have to do.</p>\n<p>Only note is that I'd consider adding a non-generic class like this</p>\n<pre><code>public static class Specialisation\n{\n public static Specialisation<T> For<T>()\n {\n return Specialisation<T>.Instance;\n }\n}\n</code></pre>\n<p>Then you can use it like this:</p>\n<pre><code>Specialised s = new Specialised();\ns.Value = 12.3456789;\nConsole.WriteLine(s.SpecialisedMethod(Specialisation.For<int>()));\nConsole.WriteLine(s.SpecialisedMethod(Specialisation.For<float>()));\nConsole.ReadKey();\n</code></pre>\n<p>which reads a tiny bit nicer.</p>\n<p>You can hide the generic class as internal in your assembly and expose an <code>ISpecialisation</code> interface if you don't want users of your system exposed to the generic and non-generic versions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:22:55.047",
"Id": "72122",
"Score": "0",
"body": "I like the idea of the non-generic class. I'm partly against the `ISpecialisation` purely because other people can derive from it, which partly defeats the point of offering singletons to use as the generic parameters, but it does offer the user more flexibility. Flexibility to do what exactly I don't know, but flexibility nonetheless."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-02-17T07:21:01.793",
"Id": "41857",
"ParentId": "41775",
"Score": "3"
}
},
{
"body": "<p>First of all, I would question the need for such interface. It makes sense for a type to hold a value, but I think it doesn't make much sense for a type to decide to what types to convert that value, or how.</p>\n\n<p>Second, if you really do need this, then I would prefer each target type to have a separate method, like <code>ConvertToInt()</code> (or <code>ConvertToInt32()</code> if you follow the naming guidelines).</p>\n\n<p>You don't necessarily need an interface for this, but even if you do, you're exchanging a small inconvenience in implementation (having to write few very simple interfaces with some repetition) for a big inconvenience in usage (having to write that <code>Specialisation<int>.Instance</code> every time and making the code less readable). So, I think using this approach is worth it even with interfaces.</p>\n\n<p>Third, if you really do need this and you want to take advantage of generics, you could use explicit interface implementation and casting to decide to what type to convert. Something like:</p>\n\n<pre><code>public interface IConvertible<T>\n{\n T Convert();\n}\n\npublic sealed class ConvertMe : IConvertible<int>, IConvertible<float>\n{\n public double Value;\n int IConvertible<int>.Convert() { return (int)Value; }\n float IConvertible<float>.Convert() { return (float)Value; }\n}\n\npublic static class Program\n{\n public static void Main()\n {\n ConvertMe c = new ConvertMe();\n c.Value = 12.3456789;\n Console.WriteLine(((IConvertible<int>)c).Convert());\n Console.WriteLine(((IConvertible<float>)c).Convert());\n }\n}\n</code></pre>\n\n<p>This results in code that is shorter and more readable (I think) than your version.</p>\n\n<p>One issue with it is that if you don't make <code>ConvertMe</code> <code>sealed</code>, trying to convert to an unsupported type becomes a runtime exception, instead of a compile-time error.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T18:13:57.880",
"Id": "72155",
"Score": "0",
"body": "Personally I don't like the `ConvertToType` naming style because it produces multiple functions with the same purpose that semantically differ only in type (which is what the whole point of specialisation is - being able to define different behaviours dependent on type alone). The casting to an interface variation is definitely useful; personally I find it harder to read though because of the additional brackets it introduces. The point about making `ConvertMe` `sealed` is also valid, though it's not too bad considering that this is a hack - you'd expect limitations like that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T09:24:55.950",
"Id": "41864",
"ParentId": "41775",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "41857",
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T05:01:22.023",
"Id": "41775",
"Score": "14",
"Tags": [
"c#",
"c++",
"generics"
],
"Title": "Is this C# 'hack' a bad idea?"
}
|
41775
|
<p>The application I'm building can accept two types of updates: Application Update and Parameter Updates. If there is an application update, then parameter updates can be ignored. This is the code that I've written, and it's messy. How can I clean this up?</p>
<pre><code>mContext = this.getApplicationContext();
//experimental();
//check for updates
UpdateMode updateInstallationMode = Parameters.load(mContext).getUpdateMode();
if(updateInstallationMode==UpdateMode.MANUAL)
{
//User will manually install update - no further action needed to be performed by activity.
//proceed to next screen.
gotoNextActivity();
}else
{
boolean shouldConfirm = (updateInstallationMode == UpdateMode.CONFIRM);
lblStatus.setText(getString(R.string.checking_for_updates));
Error outUpdateError = new Error();
Map<String,String> availableUpdates = checkForUpdates(outUpdateError);
boolean appUpdatesAvailable = availableUpdates.containsKey("application");
boolean paramUpdatesAvailable = availableUpdates.containsKey("parameters");
boolean appUpdatesAccepted = Parameters.load(mContext).getUpdateType()==UpdateType.BOTH
|| Parameters.load(mContext).getUpdateType()==UpdateType.APPLICATION;
boolean paramUpdatesAccepted = Parameters.load(mContext).getUpdateType() == UpdateType.BOTH
|| Parameters.load(mContext).getUpdateType() == UpdateType.PARAMETERS;
if(appUpdatesAccepted && appUpdatesAvailable){
boolean shouldInstall = shouldConfirm? confirmInstallUpdate(UpdateType.APPLICATION):true;
if(shouldInstall){
downloadUpdate(UpdateType.APPLICATION,availableUpdates.get("application"));
}else{
gotoNextActivity();
}
}else if(paramUpdatesAccepted && paramUpdatesAvailable){
boolean shouldInstall = shouldConfirm? confirmInstallUpdate(UpdateType.PARAMETERS):true;
if(shouldInstall){
downloadUpdate(UpdateType.PARAMETERS,availableUpdates.get("parameters"));
}else{
gotoNextActivity();
}
}else{
lblStatus.setText(getString(R.string.app_up_to_date));
gotoNextActivity();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I assume that the code in the question is a method. If not extract it out to a method.</p>\n\n<ol>\n<li>\n\n<pre><code>boolean appUpdatesAccepted = Parameters.load(mContext).getUpdateType() == UpdateType.BOTH\n || Parameters.load(mContext).getUpdateType() == UpdateType.APPLICATION;\nboolean paramUpdatesAccepted = Parameters.load(mContext).getUpdateType() == UpdateType.BOTH\n || Parameters.load(mContext).getUpdateType() == UpdateType.PARAMETERS;\n</code></pre>\n\n<p>I'd start with removing some duplication here.</p>\n\n<pre><code>UpdateParameters updateParameters = Parameters.load(mContext);\n\n...\n\nfinal UpdateType updateType = updateParameters.getUpdateType();\nboolean appUpdatesAccepted = updateType == UpdateType.BOTH\n || updateType == UpdateType.APPLICATION;\nboolean paramUpdatesAccepted = updateType == UpdateType.BOTH\n || updateType == UpdateType.PARAMETERS;\n</code></pre>\n\n<p>I'm not familiar with Android, so <code>UpdateParameters</code> and <code>UpdateType</code> types could be something else.</p></li>\n<li><p>If you reorder the <code>boolean</code> variables you can find some more duplication:</p>\n\n<pre><code>final boolean appUpdatesAvailable = availableUpdates\n .containsKey(\"application\");\nfinal boolean appUpdatesAccepted = updateType == UpdateType.BOTH\n || updateType == UpdateType.APPLICATION;\n\nfinal boolean paramUpdatesAvailable = availableUpdates\n .containsKey(\"parameters\");\nfinal boolean paramUpdatesAccepted = updateType == UpdateType.BOTH\n || updateType == UpdateType.PARAMETERS;\n</code></pre>\n\n<p>This could be extracted out to a method:</p>\n\n<pre><code>private boolean isUpdateAvailable(\n final Map<String, String> availableUpdates,\n final UpdateParameters updateParameters, \n final UpdateType updateType, final String updateKey) {\n final UpdateType availableUpdateType = updateParameters\n .getUpdateType();\n final boolean appUpdatesAvailable = availableUpdates\n .containsKey(updateKey);\n final boolean appUpdatesAccepted = \n availableUpdateType == UpdateType.BOTH \n || availableUpdateType == updateType;\n return appUpdatesAvailable && appUpdatesAccepted;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>final boolean tryApplicationUpdate = \n isUpdateAvailable(availableUpdates, updateParameters, \n UpdateType.APPLICATION, \"application\");\nfinal boolean tryParametersUpdate = \n isUpdateAvailable(availableUpdates, updateParameters, \n UpdateType.PARAMETERS, \"parameters\");\nif (tryApplicationUpdate) {\n ...\n} else if (tryParametersUpdate) {\n ...\n} else {\n ...\n}\n</code></pre></li>\n<li><p>It's also possible to extract out the first two <code>if</code> blocks to a method, they are very similar to each other:</p>\n\n<pre><code>private void downloadUpdateIfConfirmed(\n final boolean shouldConfirm, \n final Map<String, String> availableUpdates,\n final UpdateType currentUpdateType, final String updateKey) {\n final boolean shouldInstall = shouldConfirm ? \n confirmInstallUpdate(currentUpdateType) : true;\n if (shouldInstall) {\n downloadUpdate(currentUpdateType, availableUpdates.get(updateKey));\n } else {\n gotoNextActivity();\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>if (tryApplicationUpdate) {\n downloadUpdateIfConfirmed(shouldConfirm, availableUpdates, \n UpdateType.APPLICATION, \"application\");\n} else if (tryParametersUpdate) {\n downloadUpdateIfConfirmed(shouldConfirm, availableUpdates, \n UpdateType.PARAMETERS, \"parameters\");\n} else {\n ...\n}\n</code></pre></li>\n<li><p>I'd move the <code>shouldConfirm</code> flag into the method (to reduce its scope, see <em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>); use <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\">guard clauses</a>; create another method which calls <code>gotoNextActivity()</code> to remove its duplication:</p>\n\n<pre><code>public void update() {\n doUpdate();\n gotoNextActivity();\n}\n\nprivate void doUpdate() {\n mContext = this.getApplicationContext();\n final UpdateParameters updateParameters = Parameters.load(mContext);\n final UpdateMode updateInstallationMode = \n updateParameters.getUpdateMode();\n if (updateInstallationMode == UpdateMode.MANUAL) {\n return;\n }\n lblStatus.setText(getString(RString.checking_for_updates));\n final Error outUpdateError = new Error();\n final Map<String, String> availableUpdates = \n checkForUpdates(outUpdateError);\n\n final boolean tryApplicationUpdate = \n isUpdateAvailable(availableUpdates, updateParameters,\n UpdateType.APPLICATION, \"application\");\n final boolean tryParametersUpdate = \n isUpdateAvailable(availableUpdates, updateParameters,\n UpdateType.PARAMETERS, \"parameters\");\n if (tryApplicationUpdate) {\n downloadUpdateIfConfirmed(updateInstallationMode, \n availableUpdates, UpdateType.APPLICATION, \"application\");\n return;\n }\n if (tryParametersUpdate) {\n downloadUpdateIfConfirmed(updateInstallationMode, \n availableUpdates, UpdateType.PARAMETERS, \"parameters\");\n return;\n }\n lblStatus.setText(getString(RString.app_up_to_date));\n}\n\nprivate void downloadUpdateIfConfirmed(\n final UpdateMode updateInstallationMode,\n final Map<String, String> availableUpdates, \n final UpdateType updateType, final String updateKey) {\n final boolean shouldConfirm = \n (updateInstallationMode == UpdateMode.CONFIRM);\n final boolean shouldInstall = shouldConfirm ? \n confirmInstallUpdate(updateType) : true;\n if (shouldInstall) {\n downloadUpdate(updateType, availableUpdates.get(updateKey));\n }\n}\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T06:10:35.933",
"Id": "72006",
"Score": "1",
"body": "Thanks so much! What I loved is that you took it step by step explaining your thought process along the way. That's really helpful - Excellent Answer!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T11:30:35.647",
"Id": "41791",
"ParentId": "41780",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "41791",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T08:01:24.350",
"Id": "41780",
"Score": "4",
"Tags": [
"java",
"android"
],
"Title": "How can I reduce the number of nested if statements in this code?"
}
|
41780
|
<p>It was a part of my coding challenge and the last one, but I failed because it failed to yield a result in two seconds for some of sample inputs (out of six samples, three passed but three failed for not meeting the time constraint). </p>
<p>Basically, you are supposed to find the maximum deviation from given number of consecutive integers. There are two inputs; the first argument is an array of integers and the second argument is the number of consecutive integers. And you print the maximum deviation. For example, if you have [10, 1, 5, 2, 6, 3] and 3 as arguments, the output should be 9 since [10, 1, 5] would yield the maximum deviation of 9 (10-1).</p>
<p>Can this be refactored to be faster?</p>
<pre><code>def find_deviation(integers, range)
max = 0
(0..integers.size-range).each do |n|
array = integers.slice(n, range)
diff = array.max - array.min
max = diff if diff > max
end
puts max
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T11:19:09.517",
"Id": "71886",
"Score": "1",
"body": "link to the code challenge to get the samples?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T08:32:17.957",
"Id": "72026",
"Score": "0",
"body": "@tokland, I don't have the access to the samples and I can't go back to the challenge once it's done."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:10:59.910",
"Id": "72118",
"Score": "0",
"body": "@yangtheman, ok, but at least a link? is it a public challenge?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T09:44:39.043",
"Id": "72472",
"Score": "1",
"body": "There's a discrepancy between your explanation and your code. You wrote that the maximum deviation for [10,1,5] is 5, because 10 - 5 = 5. However you compute the difference between the max and the min, which would be 10 - 1 = 9, and I think that's what you're really looking for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T16:46:51.900",
"Id": "72790",
"Score": "0",
"body": "@tokland, no, it wasn't a public challenge, so that's I can't share a link nor I can go back to the challenge."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T16:48:20.153",
"Id": "72791",
"Score": "0",
"body": "@user846250, oops. I made a mistake when I tried to make the array not sorted. Will fix it now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T20:24:57.903",
"Id": "74110",
"Score": "0",
"body": "If you found @tokland's answer helpful, please checkmark it."
}
] |
[
{
"body": "<p>Some notes:</p>\n\n<ul>\n<li><p><code>find_deviation(v, d)</code>: Try to write more meaningful names for variables. Specially, I'd give a plurar name to <code>v</code>, since it's a collection.</p></li>\n<li><p><code>max = 0</code>, <code>each</code>, inline <code>if</code>: All of this denote you think in imperative terms. Some notes on <a href=\"https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow\">functional programming with Ruby</a>.</p></li>\n</ul>\n\n<p>I'd write, with a functional approach:</p>\n\n<pre><code>def find_deviation(values, m)\n values.each_cons(m).map { |xs| xs.max - xs.min }.max\nend\n</code></pre>\n\n<p>Now, this function has exactly the same time complexity than yours (though it may be faster or slower depending on how Ruby works). The complexity is: len(values) = n -> O(n*m). Note that you can use Enumerable#minmax to avoid one traversal, but it's still the same complexity.</p>\n\n<p>To make it faster here's an idea, even though it's not trivial to implement: use a structure with O(log n) times for insertion/deletion/max/min (a binary search tree is ideal for this) to hold values of the sliding window, this way the overall complexity is O(n<em>log m). I guess some of the tests have big values of m so the trivial approach O(n</em>m) is too slow.</p>\n\n<p>[edit] Just for fun, I wrote a O(n log m) implementation in Haskell (I found no BST gem for Ruby):</p>\n\n<pre><code>deviation :: (Num a, Ord a) => [a] -> Int -> a \ndeviation [] _ = 0\ndeviation xs m = maximum $ [Tree.maximum w - Tree.minimum w | w <- windows]\n where\n windows = scanl shift (Tree.fromList $ take m xs) (zip xs (drop m xs))\n shift window (old, new) = Tree.insert (Tree.delete window old) new\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T08:56:51.730",
"Id": "72030",
"Score": "0",
"body": "Yeah, I don't think you can get away from having to examine all elements in the array. I don't know if implementing my own way of finding max and min would be faster than using Ruby's min and max method. I guess the key is not creating subset of arrays, but to operate on the given array (thus using binary search on sliding window). Let me see if I can test this hypothesis."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T20:16:50.910",
"Id": "74801",
"Score": "0",
"body": "I did some research of my own and updated my question. What do you think?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T21:30:00.897",
"Id": "74817",
"Score": "0",
"body": "\"you would still need to operate on all subsets of the given array, and it would be the slowest\" -> no, in my second suggestion you'd use trees, not arrays, so sorting/inclusion/removal operations would be logarithmic (nearly linear for all practical purposes)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T22:06:25.710",
"Id": "74826",
"Score": "0",
"body": "I see. Would it work even if given argument is an array? I don't know Haskell, but if given argument is an array, there is no other way around having to work with subsets of the given array?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T22:23:38.337",
"Id": "74831",
"Score": "0",
"body": "No, arrays may have some operations O(1), but most definitely not all three you need here. Check for example for Python: https://wiki.python.org/moin/TimeComplexity#list"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T12:28:41.037",
"Id": "41793",
"ParentId": "41781",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T08:17:42.800",
"Id": "41781",
"Score": "11",
"Tags": [
"performance",
"ruby",
"array"
],
"Title": "Finding maximum deviation"
}
|
41781
|
<p>I'm an intensive user of AWS EC2 instances, many instances are launched, stopped, repurposed, etc.</p>
<p>To connect to any instance using <code>SSH</code> I must keep track of their IPs.</p>
<p>The bash script I wrote (following the <a href="https://stackoverflow.com/questions/21424849/is-there-an-easy-way-to-connect-to-ec2-instances-using-their-name-tag">question I asked on SO</a>) uses <code>aws-cli</code> to do the heavy lifting for me, leaving me to remember only the logical names I've given to my instances.</p>
<p>Here is the main code, including the auto-completion code:</p>
<pre><code># connect to machine
function sash {
if [ -z $1 ]; then
echo "Please enter machine name"
return 1
fi
local instance ip pem
instance=$(aws ec2 describe-instances --filters "Name=tag:Name,Values=$1" "Name=instance-state-name,Values=running" --query 'Reservations[*].Instances[].[KeyName,PublicIpAddress]' --output text)
if [ -z "${instance}" ]; then
echo Could not find an instance named $1
return 1
else
ip=$(echo $instance | awk '{print $2}')
pem=$(echo $instance | awk '{print $1}')
echo "Connecting to $1 ($ip)"
ssh -i ~/.aws/$pem.pem ubuntu@$ip
fi
}
function clear_sash {
unset -v _sash_instances
}
# completion command
function _sash {
if [ -z "${_sash_instances}" ]; then
_sash_instances="$( aws ec2 describe-tags --filter Name=key,Values=Name Name=resource-type,Values=instance --query Tags[].Value --output text )"
fi
local curw
COMPREPLY=()
curw=${COMP_WORDS[COMP_CWORD]}
COMPREPLY=($(compgen -W "${_sash_instances}" -- $curw))
return 0
}
complete -F _sash sash
</code></pre>
<p>The main function (<code>sash</code>) takes the first parameter, and queries <code>aws ec2</code> for a machine with a 'Name' tag with that value, extracts its public ip and <code>pem</code> file, and calls the proper <code>ssh</code> command.</p>
<p>The auto-completion command (<code>_sash</code>) enumerates the names of all EC2 machines, and keeps them in a cache in the scope of the shell.</p>
<p>A small helper command (<code>clear_sash</code>) is used to clear the cache for the auto-complete.</p>
<p>Since this is the first function I've written in bash, I would love to hear some opinions on the code, style, caching decisions, etc.</p>
|
[] |
[
{
"body": "<p>It's mostly fine, but I would suggest some minor improvements.</p>\n\n<p>Give a proper name to <code>$1</code> early on, for example:</p>\n\n<pre><code>host=$1\nif [ -z $host ]; then\n echo \"Please enter machine name\"\n return 1\nfi\n</code></pre>\n\n<p>You use it in several places later and it will make the code more readable.</p>\n\n<hr>\n\n<p>Instead of this:</p>\n\n<pre><code>if [ -z \"${instance}\" ]; then\n</code></pre>\n\n<p>you can use <code>[[ ... ]]</code> instead and drop the double quotes:</p>\n\n<pre><code>if [[ -z $instance ]]; then\n</code></pre>\n\n<hr>\n\n<p>This is a bit ugly:</p>\n\n<blockquote>\n<pre><code>ip=$(echo $instance | awk '{print $2}')\npem=$(echo $instance | awk '{print $1}')\n</code></pre>\n</blockquote>\n\n<p>It's ugly because you're spawning two <code>awk</code> processes for the same input. You could use a single <code>read</code> instead:</p>\n\n<pre><code>read pem ip junk <<< $instance\n</code></pre>\n\n<p>Or perhaps slightly cleaner to read into an array:</p>\n\n<pre><code>read -a arr <<< $instance\nip=${arr[1]}\npem=${arr[0]}\n</code></pre>\n\n<p>The array solution is especially good if the indexes of ip and pem are dynamic, for example if they come from variables:</p>\n\n<pre><code>read -a arr <<< $instance\n# given: ip_idx=2 and pem_idx=1\nip=${arr[$ip_idx - 1]}\npem=${arr[$pem_idx - 1]}\n</code></pre>\n\n<p>(It would be cleaner to have the <code>*_idx</code> 0-based, but I used this example for the sake of illustrating simple arithmetics in array indexes.)</p>\n\n<p>For the record, here's my earlier uglier <code>awk</code> solution:</p>\n\n<pre><code>set -- $(awk '{print $1, $2}' <<< $instance)\npem=$1\nip=$2\n</code></pre>\n\n<p>This is not as good as <code>read</code>, because it spawns an <code>awk</code> process, and it overwrites the positional parameters <code>$1</code>, <code>$2</code>, ... Other variants using <code>$pem_idx</code> and <code>$ip_idx</code>:</p>\n\n<pre><code>set -- $(awk \"{print \\$$pem_idx, \\$$ip_idx}\" <<< $instance)\n# or:\nset -- $(awk -v ip_idx=$ip_idx -v pem_idx=$pem_idx '{print $(pem_idx), $(ip_idx)}' <<< $instance)\n</code></pre>\n\n<hr>\n\n<p>In this code:</p>\n\n<blockquote>\n<pre><code>local curw\nCOMPREPLY=()\ncurw=${COMP_WORDS[COMP_CWORD]}\nCOMPREPLY=($(compgen -W \"${_sash_instances}\" -- $curw))\n</code></pre>\n</blockquote>\n\n<p>The first <code>COMPREPLY=()</code> is unnecessary because you overwrite it soon after anyway.</p>\n\n<p>Also, I think it's better to write <code>local</code> on the same line as the assignment:</p>\n\n<pre><code>local curw=${COMP_WORDS[COMP_CWORD]}\n</code></pre>\n\n<p>Actually, since the line fits within 80 characters, I'm not sure I would use the local <code>curw</code> at all:</p>\n\n<pre><code>COMPREPLY=($(compgen -W \"${_sash_instances}\" -- ${COMP_WORDS[COMP_CWORD]}))\n</code></pre>\n\n<hr>\n\n<p>The final <code>return 0</code> is unnecessary if the last operation is successful. If the last operation is not successful, you probably want to let the function return failure anyway.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T21:00:18.373",
"Id": "48011",
"ParentId": "41782",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "48011",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T08:21:23.157",
"Id": "41782",
"Score": "8",
"Tags": [
"bash",
"amazon-web-services"
],
"Title": "Connecting to EC2 instances using the instance name instead of IP"
}
|
41782
|
<p>After asking a <a href="https://stackoverflow.com/questions/21642731/is-this-a-monad-in-java">similar question on Stack Overflow</a>, I'm picking up on the answer there to improve my monad. I'm not trying to solve the general case, just come up with one to see how it works. If I'm right, then I really like this pattern. I've already used it to rework some code I'm working on. So I hope it's right.</p>
<p>I was pretty strict about the signatures and not taking shortcuts that OO allows.</p>
<p>The (contrived) example is to provide semantics to represent a <code>Friend</code> relationship between two users. If there's an error, or the friendship is blocked, then processing stops. I have sample code that "lifts" Boolean, <code>String</code> and a custom <code>Friend</code> class into the monadic space, so I think that' a sign I'm on the right track. I've included the sample code lifting <code>String</code> into the monadic space.</p>
<p>My question is, did I get the monad implementation right? Please call out the places where I jumped the rails!</p>
<pre><code>public class FriendSpace<A> {
public boolean rejected = false;
public String errors = "";
public A original;
public interface Function<B, MA> {
MA apply(B b, MA a);
}
public FriendSpace<A> unit(A a) {
FriendSpace<A> that = new FriendSpace<A>();
that.original = a;
return that;
}
public <B> FriendSpace<A> bind(B b, Function<B, FriendSpace<A>> f) {
if (! errors.isEmpty()) {
// we have errors; skip the rest
return this;
}
if (rejected) {
// No means no
return this;
}
FriendSpace<A> next = f.apply(b, this);
return next;
}
@SuppressWarnings("unchecked")
public <B> FriendSpace<A> pipeline(B value,
FriendSpace.Function<B, FriendSpace<A>>... functions) {
FriendSpace<A> space = this;
for (FriendSpace.Function<B, FriendSpace<A>> f : functions) {
space = space.bind(value, f);
}
return space;
}
// toString omitted to save space
}
</code></pre>
<p>And here's an example where the (arbitrary) input is a <code>People</code> class, and the (arbitrary) class representing the friendship state is <code>String</code>.</p>
<pre><code>public class People {
public People(String from, String to) {
this.from = from;
this.to = to;
}
public String from;
public String to;
}
@SuppressWarnings("unchecked")
public static void main(String[] args) {
FriendSpace<String> proto = new FriendSpace<String>();
People people0 = new People("Bob", "Fred");
FriendSpace<String> space0 = proto.unit("");
FriendSpace<String> friends0 = space0.pipeline(people0, VERIFY, INVITE, ACCEPT);
System.err.println(friends0);
People people1 = new People("Bob", "Jenny");
FriendSpace<String> space1 = proto.unit("");
FriendSpace<String> friends1 = space1.pipeline(people1, VERIFY, INVITE, ACCEPT);
System.err.println(friends1);
People people2 = new People("Fred", "Jenny");
FriendSpace<String> space2 = proto.unit("");
FriendSpace<String> friends2 = space2.pipeline(people2, VERIFY, INVITE, BLOCK);
System.err.println(friends2);
People people3 = new People("Bob", "Tom");
FriendSpace<String> space3 = proto.unit("");
FriendSpace<String> friends3 = space3.pipeline(people3, VERIFY, INVITE, ACCEPT);
System.err.println(friends3);
}
public interface StringFunction extends FriendSpace.Function<People, FriendSpace<String>> {
}
static StringFunction VERIFY = new StringFunction() {
public FriendSpace<String> apply(People from, FriendSpace<String> to) {
String KNOWN_USERS = "Bob Fred Jenny";
if (! KNOWN_USERS.contains(from.from)) {
to.errors += "Unknown from: " + from.from;
}
if (! KNOWN_USERS.contains(from.to)) {
to.errors += "Unknown to: " + from.to;
}
return to;
}
};
static StringFunction INVITE = new StringFunction() {
public FriendSpace<String> apply(People from, FriendSpace<String> to) {
// Jenny has blocked Bob
if ("Jenny".equals(from.to) && "Bob".equals(from.from)) {
to.errors = "Jenny blocked Bob";
}
return to;
}
};
static StringFunction ACCEPT = new StringFunction() {
public FriendSpace<String> apply(People from, FriendSpace<String> to) {
// Good to go!
to.original = "YES";
return to;
}
};
static StringFunction BLOCK = new StringFunction() {
public FriendSpace<String> apply(People from, FriendSpace<String> to) {
to.original = "BLOCK";
to.rejected = true;
return to;
}
};
</code></pre>
|
[] |
[
{
"body": "<p>Well, lets find out by checking the <a href=\"https://en.wikipedia.org/wiki/Monad_%28computer_science%29#Monad_laws\"><em>monad laws</em></a>.</p>\n\n<ol>\n<li><p><code>(unit x) >>= f ≡ f x</code>, which translates to the Java</p>\n\n<pre><code>new FriendSpace<...>().unit(x).bind(..., f) ≡ f.apply(..., ...)\n</code></pre>\n\n<p>wait, why do <code>bind</code> and <code>Function.apply</code> take two arguments in your case?Note that the instance which you call a method on is an implicit argument. And why is the type of <code>apply :: (B, MA) → MA</code> incompatible with the proper usage <code>A → M<C></code>? It should look like</p>\n\n<pre><code>new Friendspace<A>(x).bind(f) ≡ f.apply(x)\n</code></pre></li>\n<li><p><code>m >>= unit ≡ m</code>, which translates to the Java</p>\n\n<pre><code>m.bind(..., new Function<..., ...>{\n public ... apply(..., ...){\n return new Friendspace<...>().unit(argumentToApplyFunction);\n }\n})\n≡\nm\n</code></pre>\n\n<p>Again, the arity of your methods is completely off. All the parts which don't make any sense have been marked with an ellipsis. Note that an equivalence relation <code>≡</code> is in no way required for monads, this notation is only chosen to emphasize that the two expressions should be equivalent for all purposes.</p>\n\n<p>It should look like:</p>\n\n<pre><code>Friendspace<A> m = ...;\n\nm.bind(new Function<A, Friendspace<A>>() {\n public Friendspace<A> apply(A x){\n return new Friendspace<A>(x);\n }\n})\n≡\nm\n</code></pre></li>\n<li><p><code>(m >>= f) >>= g ≡ m >>= ( \\x -> (f x >>= g) )</code>, which <em>should</em> translate to</p>\n\n<pre><code>Friendspace<A> m = ...;\nFunction<A, Friendspace<B>> f = ...;\nFunction<B, Friendspace<C>> g = ...;\n\nm.bind(f).bind(g)\n≡\nm.bind(new Function<A, Friendspace<C>>() {\n public Friendspace<C> apply(A x) {\n return f.apply(x).bind(g);\n }\n}) \n</code></pre>\n\n<p>This is basically a requirement that <code>bind</code> composes the result of each function application in a sensible way.</p></li>\n</ol>\n\n<p>Your class does not seem to be implementing the Monad pattern. A few pointers:</p>\n\n<ul>\n<li><p><code>unit</code> is basically just a constructor. It should either be a static method, or an actual constructor.</p></li>\n<li><p>The <code>bind</code> operation takes a monad <code>m :: M[A]</code> and a function <code>f :: A → M[B]</code>, and applies the function to each element contained in the monad. Each application returns a new monad, these are combined into a single one which then is the output of <code>bind</code>.</p></li>\n<li><p>It is often more useful and simple to implement <code>fmap :: (M[A], A → B) → M[B]</code>, as the transforming function doesn't need to know anything about the monad. If other languages like Haskell put a lot of emphasis on the <code>bind</code>, that's because <code>bind</code> is really important in its imperative “do-notation”, and because <code>fmap</code> can be easily derived from <code>bind</code>: <code>fmap f m = m >>= (f . return)</code>, our in our Java notation:</p>\n\n<pre><code>public <B> Monad<B> fmap(Function<A, B> f) {\n return this.bind(new Function<A, Monad<B>>() {\n public Monad<B> apply(A x) {\n return new Monad<B>(f.apply(x));\n }\n });\n}\n</code></pre></li>\n<li><p>Mixing monads with mutability can make for very confusing results. Monads are a clever way to compose operations, so using mutable data structures really isn't necessary when using monads.</p></li>\n<li><p>The Scala language has a well-designed <a href=\"http://scala-lang.org/files/archive/api/current/#scala.collection.immutable.package\">immutable collection library</a>. The classes are written in a way so that they can be used as monads. I suggest you play a bit with those to get a better feeling of monads.</p></li>\n</ul>\n\n<p>I created an <a href=\"http://ideone.com/S3r7v6\">example of a List monad</a> for you to look at. The <code>List</code> is slightly different from a normal monad, as it's additive, i.e. <code>[a, b] + [c, d] = [a, b, c, d]</code>. This makes implementing <code>bind</code> properly quite easy. I used a <code>List</code> for the example, because it's something you are probably familiar with, and the implementation of the linked list shouldn't detract too much from the monad implementation itself. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T15:39:26.493",
"Id": "71920",
"Score": "0",
"body": "Also, you make excellent points. I was trying to squint and ignore the implicit self argument ;) but I see how my arguments are wrong otherwise. Still, as \"also ran\" as it is, it gave me the kind of operation chaining I was looking for (!) So I think as I correct it, and understand the pattern better, it will get even stronger. Your insight is invalable -- thank you again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T17:50:39.463",
"Id": "71933",
"Score": "0",
"body": "By flatMap, do you mean fmap? flatMap is usually defined more like Haskell's bind."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T18:36:59.977",
"Id": "71939",
"Score": "0",
"body": "@fgb I don't know Haskell that much, aren't `fmap` and `flatMap` basically the same thing? It may very well be that I screwed up in that paragraph, feel free to [edit] until it's correct"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T20:30:42.590",
"Id": "71943",
"Score": "1",
"body": "No, `fmap` is just `map` defined on a functor. `flatMap` is `map` followed by `flatten`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T08:58:43.237",
"Id": "72032",
"Score": "0",
"body": "@amon a funny side note... I am playing with 2 monadic classes to get the signatures right, and more or less copied your monadic rule tests in. I got them working with the first class, copied them to the second class, did a global search/replace on the class name & magic! They worked without any other modification. I'm taking that as a good sign. But I want to stare at it some more."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T14:33:50.853",
"Id": "41803",
"ParentId": "41783",
"Score": "8"
}
},
{
"body": "<p>amon still gets credit for the win, but I thought I'd post this as a follow up.</p>\n\n<p>I have a fancier example here that's for handling downcasts and type conversions: <a href=\"http://wp.me/pPWOs-et\" rel=\"nofollow\">Monadic Downcast</a></p>\n\n<p>but I thought it would be fun to create an Any mondad that basically just wraps an object reference. Useful? Well, it permits late binding in Java, which is kind of a win. And I suppose it could be used as a initial code or a base class for something useful (haven't tried the latter).</p>\n\n<p>EDIT: I suppose all the arguments for using monads as interpreters apply here, too. For example, while the code sample below uses \"train wreck\" syntax to chain the operations: .bind().bind().bind()... you <em>could</em> put your functions into a Map and then build your operation chains in configuration text. And it allows aspect-style insertion of new concerns without recompiling the old functions... So this is more of a starting point than anything else.\n/EDIT</p>\n\n<p>The idea is that it's a Java monad that wraps a single object & provides a bind, so you can plug in new operations at runtime. Like I say, that's not revolutionary except for Java. ;)</p>\n\n<p>Next up -- javascript!!!</p>\n\n<pre><code>public class Any<A> {\n\n public final A get;\n\n /** generic function interface -- note no monadic restrictions here */\n public interface Function<A, B> {\n B apply(A a);\n }\n\n /** internal constuctor */\n Any(A get) {\n this.get = get;\n }\n\n /** of === unit ... lift a value into monadic space */\n public static <A> Any<A> unit(A a) {\n return new Any<A>(a);\n }\n\n /** bind :: m a -> (a -> m b) -> m b */\n public <B> Any<B> bind(Function<A, Any<B>> f) {\n return f.apply(get);\n }\n\n /** a nice to string */\n public String toString() {\n StringBuilder builder = new StringBuilder();\n builder.append(\"{Any \");\n if (get != null) {\n builder.append(get.getClass().getSimpleName());\n }\n builder.append(\": \");\n builder.append(get);\n builder.append(\" }\");\n return builder.toString();\n }\n}\n</code></pre>\n\n<p>Demonstration of the monadic rules:</p>\n\n<pre><code>public class Rules {\n\n /** int to string */\n static final Function<Integer, Any<String>> f = new Function<Integer, Any<String>>() {\n public Any<String> apply(Integer b) {\n return Any.unit(\"\" + b);\n }\n };\n\n /** string to int */\n static final Function<String, Any<Integer>> g = new Function<String, Any<Integer>>() {\n public Any<Integer> apply(String b) {\n return Any.unit(Integer.parseInt(b));\n }\n };\n\n /** unit int */\n static final Function<Integer, Any<Integer>> u = new Function<Integer, Any<Integer>>() { \n public Any<Integer> apply(Integer b) {\n return Any.unit(b);\n }\n };\n\n /** associative */\n static final Function<Integer, Any<Integer>> r = new Function<Integer, Any<Integer>>() { \n public Any<Integer> apply(Integer b) {\n return f.apply(b).bind(g);\n }\n };\n\n /** test the monadic rules */\n public static void main(String[] args) {\n\n Any<Integer> m = Any.unit(1);\n\n leftIdentity(m);\n rightIdentity(m);\n associativity(m);\n }\n\n /** Left identity: return a >>= f ≡ f a */\n private static void leftIdentity(Any<Integer> m) {\n Any<String> left = m.bind(f);\n Any<String> right = f.apply(1);\n System.err.println(left + \" \" + right);\n assert left.toString().equals(right.toString());\n }\n\n /** Right identity: m >>= return ≡ m */\n private static void rightIdentity(Any<Integer> m) {\n Any<Integer> left = m.bind(u);\n Any<Integer> right = m;\n System.err.println(left + \" \" + right);\n assert left.toString().equals(right.toString());\n }\n\n /** associativity: (m >>= f) >>= g ≡ m >>= (\\x -> f x >>= g) */\n private static void associativity(Any<Integer> m) {\n Any<Integer> left = m.bind(f).bind(g);\n Any<Integer> right = m.bind(r);\n System.err.println(left + \" \" + right);\n assert left.toString().equals(right.toString());\n }\n}\n</code></pre>\n\n<p>And a sample usage. A boiled-down version of the solution amon provided:</p>\n\n<pre><code>public class Sample {\n\n public static final Function<Integer, Any<Integer>> SQUARE = new Function<Integer, Any<Integer>>() {\n public Any<Integer> apply(Integer a) {\n return Any.unit(a * a);\n }\n };\n\n public static final Function<Integer, Any<String>> STRINGIFY = new Function<Integer, Any<String>>() {\n public Any<String> apply(Integer a) {\n return Any.unit(\"\" + a);\n }\n };\n\n public static void main(String[] args) {\n Any<Integer> i = Any.unit(5);\n Any<String> s = i.bind(SQUARE).bind(STRINGIFY);\n assert s.get.equals(\"25\");\n System.err.println(s);\n }\n}\n</code></pre>\n\n<p>lol that's a lot more typing than Haskell requires. But still a lot less work than getting my team to adopt Haskell ;)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T02:36:52.120",
"Id": "41931",
"ParentId": "41783",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "41803",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T08:24:49.477",
"Id": "41783",
"Score": "6",
"Tags": [
"java",
"generics",
"monads"
],
"Title": "A monad in Java (FriendSpace and People)"
}
|
41783
|
<p>I have a interface with the following implementation</p>
<pre><code>public abstract class PersonInterface
{
public abstract void Update(PersonModel person);
public abstract void Delete(int id);
public virtual PersonModel Find(int id)
{
return new List<PersonModel>().Find(x => x.Id == id);
}
public virtual IEnumerable<Models.Person.Person> GetAll()
{
return new List<Models.Person.Person>();
}
}
</code></pre>
<p>Since the application will handle client and employee i take that class and implement it. This is because client have a diferrent way of updating its properties and the same goes from employee</p>
<pre><code>public class Client : PersonInterface{
public override void Update(PersonModel person)
{
// implementing the way of how the client is going to be update it
}
public override void Delete(int id)
{
// implementing the way of how the client is going to be delete it
}
}
</code></pre>
<p>And employee implementation:</p>
<pre><code>public class Employee: PersonInterface{
public override void Update(PersonModel person)
{
// implementing the way of how the employee is going to be update it
}
public override void Delete(int id)
{
// implementing the way of how the employee ent is going to be delete it
}
}
</code></pre>
<p>And my question is: <strong>is this the correct way that solve my problem when handling cases that some classes have somethings in common but there are 2 or 3 this that may vary?</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T15:11:59.370",
"Id": "71916",
"Score": "0",
"body": "I'd recommend making the `Find` and `GetAll` methods in abstract base class `abstract` as well. They current implementations provide no useful shared functionality."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T15:13:26.453",
"Id": "71917",
"Score": "0",
"body": "If they *do* actually contained shared functionality, make sure the `List` they're working against is instantiated in the base class' constructor."
}
] |
[
{
"body": "<p>Yes. When some classes have things in common but common things different having a abstract base class is a good way to go.</p>\n\n<p>Having a common base class gives you a number of advantages:</p>\n\n<ul>\n<li><p>Reuse between the classes. Your <code>Find</code> and <code>GetAll</code> methods don't have to be rewritten for each type of person. So you avoid having to test this N times, and you avoid accidental (and subtle) differences in implementation (=> bugs!). (N = the number of classes extending from <code>Person</code>)</p></li>\n<li><p>A consistent interface. Other code using a <code>Person</code> doesn't (necessarily) need to know what kind of <code>Person</code> it's working with. For example you could write a script to get all people and update them without having to worry about the differences between clients/employees.</p></li>\n</ul>\n\n<p>But you need to make sure of a few things:</p>\n\n<ul>\n<li><p>The implementations in your base class must work for all children, now and in the future. So if you want to add an <code>Employer</code> class you don't want to have to change the base class methods. If you do so you have to test your other class implementations to make sure they still work. That being said, minor modifications often aren't too much of a big deal.</p></li>\n<li><p>If your classes have a small amount in common but large differences you could end up only partially being able to rely on a consistent interface. So you lose the flexibility of just operating on <code>Person</code> objects. If your language supports it traits might be a better way to go here. Also if you find yourself in this situation your classes might be getting too big. Try breaking them down. (Nobody likes a god object!)</p></li>\n</ul>\n\n<p>But broadly speaking; Yes, go for it!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T13:15:21.403",
"Id": "41798",
"ParentId": "41794",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "41798",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T12:30:26.340",
"Id": "41794",
"Score": "4",
"Tags": [
"c#"
],
"Title": "Abstract Person with Employees and Clients"
}
|
41794
|
<p>In my first iterative algorithm, I do this</p>
<pre><code>for (auto &widget : controls.getWidgets())
{
if (!widget->visible) continue;
widget->draw();
for (auto &widget_component : widget->components)
{
if (!widget_component->visible) continue;
widget_component->draw();
for (auto &ww : widget_component->components)
{
if (!ww->visible) continue;
ww->draw();
}
}
}
</code></pre>
<p>Now, I see the flaw in this algorithm because of the repetition of code.</p>
<p>I try to write a recursive function call to handle this thing.</p>
<pre><code>void swcApplication::recursiveDisplay(swcWidget *next)
{
if (next == nullptr) return;
if ((next->parent != nullptr) &&
!next->parent->visible) return;
if (next->visible)
next->draw();
for (auto &i : next->components)
{
recursiveDisplay(i);
}
}
void display()
{
for (auto &widget : controls.getWidgets())
{
recursiveDisplay(widget);
}
}
</code></pre>
<p><strong>Display first the parent before all other children, if parent is not visible, then don't draw its children</strong></p>
<p>Is the above phrase satisfy by this algorithm (As far as I can see, it is)? Is this optimal? I don't know what drawbacks might occur here because I just write in a few seconds.</p>
<p>If you didn't find anything wrong here, now, how can I put it back in iterative way? I know iteration is better.</p>
<p><strong>Update</strong></p>
<p>I didn't use any <code>z</code> attribute here and instead I go for <a href="http://en.wikipedia.org/wiki/Painter%27s_algorithm" rel="nofollow">painter's algorithm</a>.</p>
<p>The <em>flaw</em> I am referring in my <code>iteration</code> version is that, <strong>it is limited to draw widgets</strong> depends on how deep I will code for iteration.</p>
|
[] |
[
{
"body": "<p>You can modify the recursive code to use an explicit stack:</p>\n\n<pre><code>#include <stack>\n\nvoid display_widgets(control& controls)\n{\n std::stack<widget*> widgets;\n for(auto &widget : controls.getWidgets()) {\n widgets.push(widget);\n }\n\n while(!widgets.empty()) {\n widget* w = widgets.top();\n widgets.pop();\n if(!widget->visible) {\n continue;\n }\n widget->draw();\n for(auto& component : widget->components) {\n widgets.push(component);\n }\n }\n}\n</code></pre>\n\n<blockquote>\n <p>I know iteration is better.</p>\n</blockquote>\n\n<p>This is highly dependent on language and usage. It is \"better\" in that recursion can use <code>O(n)</code> stack space (although not always - tail call optimization gets rid of this limitation), and won't blow your stack. However, in this case, assuming the recursive algorithm actually did what you wanted, it would be better and easier. </p>\n\n<p>You can always turn a recursive solution into an iterative one by replacing the call stack with an actual stack of your own, as above. For very deeply nested recursive calls, this may save you from stack overflows, however, it is more fiddly to code, and in this case, doesn't gain you anything. </p>\n\n<p>Having written the code above, my advice would be to stick with the recursive solution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T01:44:53.430",
"Id": "72212",
"Score": "1",
"body": "The original non-recursive version also doesn't paint all parents before painting any children; maybe that's not a requirement; maybe parent widgets are non-overlapping; or if they overlap, maybe get_widgets returns them in Z-order, and the overlapping parent and its children should be painted after the overlapped parent and its children."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T01:51:30.503",
"Id": "72213",
"Score": "0",
"body": "@ChrisW Yeah, I think I misread (or misinterpreted) the requirement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T01:56:48.870",
"Id": "72214",
"Score": "0",
"body": "@ChrisW I've modified my answer. Thanks for pointing that out."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T01:17:22.423",
"Id": "41922",
"ParentId": "41795",
"Score": "4"
}
},
{
"body": "<p>There are three ways in which your recursive version doesn't match your non-recursive version.</p>\n\n<ol>\n<li><p>The recursive version will go deeper: it will paint great-grandchild widgets (if there are any)</p></li>\n<li><p>The following tests exist in the recursive version but not in the non-recursive version:</p>\n\n<pre>\n if (next == nullptr) return;\n\n if ((next->parent != nullptr) &&\n !next->parent->visible) return;\n</pre></li>\n<li><p>Most importantly (this is probably a bug), your recursive version displays children even if the parent is not visible. The <code>if (!widget->visible) continue;</code> in your non-recursive version should be <code>if (!next->visible) return;</code> in your recursive version.</p></li>\n</ol>\n\n<p>I don't see why your parameter name is <code>next</code>: I think I'd call it <code>widget</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T04:48:31.013",
"Id": "72232",
"Score": "0",
"body": "`#1` That is what I wanted; `#3` I don't think its a bug. How could I know if the underlying parent is visible or not? If the parent is not visible, then don't draw its underlying children."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T04:49:33.907",
"Id": "72233",
"Score": "0",
"body": "Also I think checking for `if (next == nullptr)` isn't necessary anymore?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T04:55:04.883",
"Id": "72234",
"Score": "0",
"body": "Um sorry, yes you are right."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T10:39:24.637",
"Id": "72249",
"Score": "0",
"body": "No, I was wrong: your test of `next->parent->visible` prevents children being displayed. Still, removing that statement and not recursing into children of invisible parents would be clearer."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T01:56:58.780",
"Id": "41926",
"ParentId": "41795",
"Score": "4"
}
},
{
"body": "<p>You don't need quite so much checking and complexity in your recursive display function.</p>\n\n<pre><code>recursiveDisplay(swcWidget * widget)\n{\n // don't draw the widget or any of it's children if it is not visible\n if(widget != nullptr && widget->visible)\n {\n // draw the current widget first\n widget->draw();\n\n // then draw the children\n // we already know at this point the parent of these children is visible.\n for(auto & widgetComponent : widget->components)\n {\n recursiveDisplay(widgetComponent);\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T16:17:00.360",
"Id": "41974",
"ParentId": "41795",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T12:38:36.110",
"Id": "41795",
"Score": "6",
"Tags": [
"c++",
"optimization",
"c++11",
"recursion",
"iteration"
],
"Title": "Iteration to recursive function"
}
|
41795
|
<p>This is Part 1 of a question about performance and general best practices. Part 2 is located <a href="https://codereview.stackexchange.com/questions/41835/entity-framework-6-0-2-performance-of-auditable-change-tracking-part-2-of-2">here</a>. The body of the messages are the same to illustrate their similarity, the difference is the code provided. This one provides the data the text template utilizes, the other provides the logic to generate the code. The focus isn't so much on the template, but the pattern of managing a database that tracks changes across potentially multiple domains.</p>
<p>Another thing I decided I'll be adding: the templates will construct the basic outline of the dialogs through WPF for me. In the case of searching for items within the database, I've already used the data on the entities to generate query builders:</p>
<pre><code>var recipeQuery = new RecipeQueryData(user);
recipeQuery.CreateIngredientsQueryData();
recipeQuery.IngredientsData.CreateItemQueryData();
recipeQuery.IngredientsData.ItemData.NameCriteria = "t";
recipeQuery.IngredientsData.ItemData.SearchNameType = StringSearchType.Contains;
var recipesWithT2 = RecipeQueryData.ConstructQuery(recipeQuery, fcasCtx.Recipes);
</code></pre>
<p>Compared with:</p>
<pre><code>var recipesWithT =
(from recipe in fcasCtx.Recipes
from ingredient in recipe.Ingredients
where ingredient.Item.Name.Contains(criteria)
select recipe).Distinct();
Console.WriteLine(recipesWithT.ToString() == recipesWithT2.ToString());
</code></pre>
<p>Yields true. While by itself isn't much, it's interesting that I'll be able to enable a user to have a fairly powerful search tool by specifying nested conditions.</p>
<p>I've <a href="http://www.abstraction-project.com/zips/HFAEF.zip" rel="nofollow noreferrer">uploaded a small example</a> which demonstrates the template's use. It's changed quite a lot since the code posted and edited by lol.upvote. It automatically generates the files and folders based off of the context namespace provided in EntityConstants.tt. To preserve space I've removed all binaries, so you might have to fix it in the package manager console when you load the solution.</p>
<p>I'm kind of new to the realm of Database authoring, so I wanted to get some feedback on a system which generates auditable entities.</p>
<p>I'm using Visual Studio 2013 with the Entity Framework 6.0.2. Handling Migrations through the Package Manager Console. I'm rather unfamiliar with EF Performance, and what such a change tracking system would do. I know that I could enable the change tracking on the server, but this system will involve tracking who changed what, based off of their identity defined within the database (and honestly, I don't understand the SQL server change tracking one bit.) It's meant to focus on potentially multiple domains, so whoever would use the client would login using SQL Authentication. The end result is Active Directory supplies the authentication, and users are handled by storing their SID within the registry which links to the proper domain.</p>
<p>A portion of the logic from Part 2 was moved here for space reasons when it was updated to the most recent version of the code.</p>
<h2>Template</h2>
<h3>Header</h3>
<pre><code><#@ template debug="true" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>
using AllenCopeland.FCAS.Administration;
using AllenCopeland.FCAS.Instances;
<#
const long ER_NONE = 0x000,
ER_NOTTRACKED = 0x001,
ER_REQUIRED = 0x002,
ER_MAXLEN = 0x004,
ER_KEY = 0x008,
ER_FIXED = 0x010 | ER_NOTTRACKED,
ER_COLLECTION = 0x020 | ER_NOTTRACKED,
ER_COLLECTION_BIDIRECTIONAL = 0x040 | ER_COLLECTION,
ER_COLLECTION_UNIDIRECTIONAL_REQUIRED = 0x080 | ER_COLLECTION,
ER_COLLECTION_UNIDIRECTIONAL_OPTIONAL = 0x100 | ER_COLLECTION,
ER_IGNORE_ON_ADDMETHOD = 0x200,
ER_REQUIRED_NO_ATTRIBUTE = 0x400 | ER_REQUIRED;
var nullableTypes = new string[] { "bool", "byte", "short", "int", "long", "decimal", "double", "float" };
const string ContextName = "FCASDBContext";
const string ContextNamespace = "AllenCopeland.FCAS";
const string authorityEntity = "DomainUser";
const string authorityAuthIDFieldName = "AuthUserID";
const string authorityAuthIDFieldValue = "AuthorizerID";
var shortformLookup = new Dictionary<string, string>()
{
{ "string", "System.String" },
{ "bool", "System.Boolean" },
{ "byte", "System.Byte" },
{ "short", "System.Int16" },
{ "int", "System.Int32" },
{ "long", "System.Int64" },
{ "decimal", "System.Decimal" },
{ "double", "System.Double" },
{ "float", "System.Single" },
};
</code></pre>
<h3>Entities</h3>
<pre><code>var entities = new []
{
new {
Namespace = "AllenCopeland.FCAS.Stock",
EntityName = "DistributorInventoryItem",
PluralName = "DistributorInventoryItems",
PluralInstanceName = "DistributorInventoryItemInstances",
Properties = new []
{
new { Name = "Name", DataType = "string", Requirements = ER_REQUIRED, Description = "of the name of the <see cref=\"DistributorInventoryItem\" />"},
new { Name = "Price", DataType = "decimal", Requirements = ER_REQUIRED, Description = "of the price of the <see cref=\"DistributorInventoryItem\" />" },
new { Name = "PriceByWeight", DataType = "bool", Requirements = ER_REQUIRED, Description = "on whether the <see cref=\"DistributorInventoryItem.Price\" /> is charged by weight." },
new { Name = "Quantity", DataType = "int", Requirements = ER_REQUIRED, Description = "of the number of items received relative to each <see cref=\"DistributorInventoryItem.Pack\" />" },
new { Name = "QuantityMax", DataType = "int", Requirements = ER_NONE, Description = "of the maximum number of items received relative to each <see cref=\"DistributorInventoryItem.Pack\" />" },
new { Name = "Pack", DataType = "int", Requirements = ER_REQUIRED, Description = "of the number of packs for the <see cref=\"DistributorInventoryItem\" /> received per each unit on an order." },
new { Name = "Distributor", DataType = "Distributor", Requirements = ER_REQUIRED, Description = "the <see cref=\"DistributorInventoryItem\" /> belongs to." },
new { Name = "ProductID", DataType = "int", Requirements = ER_REQUIRED, Description = "that represents the unique identifier of the <see cref=\"DistributorInventoryItem\" /> relative to its <see cref=\"Distributor\" />." },
new { Name = "Brand", DataType = "Brand", Requirements = ER_REQUIRED, Description = "that represents the unique identifier of the <see cref=\"DistributorInventoryItem\" /> relative to its <see cref=\"Distributor\" />." },
}.ToDictionary(keySelector => keySelector.Name, valueSelector => valueSelector),
},
new {
Namespace = "AllenCopeland.FCAS.Stock",
EntityName = "Distributor",
PluralName = "Distributors",
PluralInstanceName = "DistributorInstances",
Properties = new []
{
new { Name = "Name", DataType = "string", Requirements = ER_REQUIRED, Description = "of the name of the <see cref=\"Distributor\" />." },
new { Name = "Logo", DataType = "DatabaseImage", Requirements = ER_NONE, Description = "which represents the logo for the <see cref=\"Distributor\" />." },
}.ToDictionary(keySelector => keySelector.Name, valueSelector => valueSelector),
},
new {
Namespace = "AllenCopeland.FCAS.Stock",
EntityName = "Brand",
PluralName = "Brands",
PluralInstanceName = "BrandInstances",
Properties = new []
{
new { Name = "Name", DataType = "string", Requirements = ER_REQUIRED, Description = "of the name of the <see cref=\"Brand\" />" },
}.ToDictionary(keySelector => keySelector.Name, valueSelector => valueSelector),
},
new {
Namespace = "AllenCopeland.FCAS",
EntityName = "DatabaseImage",
PluralName = "DatabaseImages",
PluralInstanceName = "DatabaseImageInstances",
Properties = new []
{
new { Name = "Name", DataType = "string", Requirements = ER_REQUIRED, Description = "of the name of the <see cref=\"DatabaseImage\" />." },
new { Name = "Description", DataType = "string", Requirements = ER_NONE, Description = "of the description of the <see cref=\"DatabaseImage\" />." },
new { Name = "Data", DataType = "Byte[]", Requirements = ER_NOTTRACKED | ER_REQUIRED,
Description = "which contains the binary data of the <see cref=\"DatabaseImage\" />." },
}.ToDictionary(keySelector => keySelector.Name, valueSelector => valueSelector),
},
new {
Namespace = "AllenCopeland.FCAS.Administration",
EntityName = "DomainUser",
PluralName = "DomainUsers",
PluralInstanceName = "DomainUserInstances",
Properties = new []
{
new { Name = "SecurityIdentifier", DataType = "string", Requirements = ER_KEY | ER_FIXED | ER_MAXLEN | (46L << 32) | ER_REQUIRED,
Description = "of the security identifier of the <see cref=\"DomainUser\" />" },
new { Name = "Disabled", DataType = "bool", Requirements = ER_NONE | ER_IGNORE_ON_ADDMETHOD,
Description = "of whether the <see cref=\"DomainUser\" /> is disabled." },
new { Name = "Domain", DataType = "Domain", Requirements = ER_REQUIRED_NO_ATTRIBUTE | ER_FIXED,
Description = "which denotes the domain from which the <see cref=\"DomainUser\" /> is derived." },
}.ToDictionary(keySelector => keySelector.Name, valueSelector => valueSelector),
},
new {
Namespace = "AllenCopeland.FCAS.Administration",
EntityName = "Domain",
PluralName = "Domains",
PluralInstanceName = "DomainInstances",
Properties = new []
{
new { Name = "Name", DataType = "string", Requirements = ER_REQUIRED, Description = "of the name of the <see cref=\"Domain\" />" },
new { Name = "Companies", DataType = "Company", Requirements = ER_COLLECTION_BIDIRECTIONAL,
Description = "set which denotes which companies have access to the <see cref=\"Domain\" />." }
}.ToDictionary(keySelector => keySelector.Name, valueSelector => valueSelector),
},
new {
Namespace = "AllenCopeland.FCAS.Administration",
EntityName = "Company",
PluralName = "Companies",
PluralInstanceName = "CompanyInstances",
Properties = new []
{
new { Name = "Name", DataType = "string", Requirements = ER_REQUIRED, Description = "of the name of the <see cref=\"Company\" />" },
new { Name = "Description", DataType = "string", Requirements = ER_NONE, Description = "of the descriptive text of the <see cref=\"Company\" />" },
new { Name = "Domains", DataType = "Domain", Requirements = ER_COLLECTION_BIDIRECTIONAL,
Description = "set which denotes which domains the <see cref=\"Company\" /> has access to the ." }
}.ToDictionary(keySelector => keySelector.Name, valueSelector => valueSelector),
},
new {
Namespace = "AllenCopeland.FCAS.Stock",
EntityName = "InventoryItem",
PluralName = "InventoryItems",
PluralInstanceName = "InventoryItemInstances",
Properties = new []
{
new { Name = "Name", DataType = "string", Requirements = ER_REQUIRED, Description = "of the name of the <see cref=\"InventoryItem\" />" },
new { Name = "Units", DataType = "InventoryUnit", Requirements = ER_COLLECTION_BIDIRECTIONAL,
Description = "set which denotes the inventory units associated to the <see cref=\"InventoryItem\" />" },
new { Name = "Categories", DataType = "InventoryItemCategory",
Requirements = ER_COLLECTION_BIDIRECTIONAL,
Description = "set which denotes the inventory categories associated to the <see cref=\"InventoryItem\" />" },
}.ToDictionary(keySelector => keySelector.Name, valueSelector => valueSelector),
},
new {
Namespace = "AllenCopeland.FCAS.Stock",
EntityName = "InventoryItemCategory",
PluralName = "InventoryItemCategories",
PluralInstanceName = "InventoryItemCategoryInstances",
Properties = new []
{
new { Name = "Name", DataType = "string", Requirements = ER_REQUIRED, Description = "of the name of the <see cref=\"InventoryItem\" />" },
new { Name = "Items", DataType = "InventoryItem", Requirements = ER_COLLECTION_BIDIRECTIONAL,
Description = "set which denotes the inventory items associated to the <see cref=\"InventoryItemCategory\" />" },
}.ToDictionary(keySelector => keySelector.Name, valueSelector => valueSelector),
},
new {
Namespace = "AllenCopeland.FCAS.Stock",
EntityName = "InventoryUnit",
PluralName = "InventoryUnits",
PluralInstanceName = "InventoryUnitInstances",
Properties = new []
{
new { Name = "Name", DataType = "string", Requirements = ER_REQUIRED, Description = "of the name of the <see cref=\"InventoryUnit\" />" },
new { Name = "PluralName", DataType = "string", Requirements = ER_REQUIRED, Description = "of the plural name of the <see cref=\"InventoryUnit\" />" },
new { Name = "ShortName", DataType = "string", Requirements = ER_NONE, Description = "of the shortened name of the <see cref=\"InventoryUnit\" />" },
new { Name = "Items", DataType = "InventoryItem", Requirements = ER_COLLECTION_BIDIRECTIONAL,
Description = "set which denotes the inventory items associated to the <see cref=\"InventoryUnit\" />" },
}.ToDictionary(keySelector => keySelector.Name, valueSelector => valueSelector),
},
};
</code></pre>
<p>Followed by:</p>
<pre><code>var orderedEntities = (from e in entities
orderby e.Namespace,
e.EntityName
group e by e.Namespace).ToDictionary(key=>key.Key, value=>value.ToArray());
int index = 0;
var indices = entities.ToDictionary(keySelector=>keySelector, valueSelector=>0);
foreach (var entity in from ns in orderedEntities.Keys
from entity in orderedEntities[ns]
select entity)
indices[entity] = index++;
var maxEL = index.ToString().Length;
</code></pre>
<h3>Enums</h3>
<pre><code>#>
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
<#
foreach (var entityNamespace in orderedEntities.Keys)
{
#>
namespace <# WriteLine(entityNamespace); #>
{
using <# Write(entityNamespace); #>.Instances;
<#
foreach (var entity in orderedEntities[entityNamespace])
{
var currentEntityIndex = indices[entity];
#>
/// <summary>
/// Denotes the potential elements within a <see cref="<# Write(entity.EntityName); #>" />
/// that can change.
/// </summary>
[Flags]
public enum <# Write(entity.EntityName); #>Changes :
<#
int pC = entity.Properties.Count - entity.Properties.Values.Where(k=>(k.Requirements & ER_NOTTRACKED) == ER_NOTTRACKED).Count();
if (pC <= 6)
WriteLine("byte");
else if (pC <= 13)
WriteLine("short");
else if (pC <= 29)
WriteLine("int");
else
WriteLine("long");
#>
{
/// <summary>
/// The <see cref="<# Write(entity.EntityName); #>" /> was created.
/// </summary>
Created = 1,<#
WriteLine("");
int offset = 0;
foreach (var property in entity.Properties)
{
if ((property.Value.Requirements & ER_NOTTRACKED) == ER_NOTTRACKED)
continue;#>
/// <summary>
/// The <see cref="<# Write(string.Format("{0}.{1}", entity.EntityName, property.Key)); #>"/>
/// was changed on the <see cref="<# Write(entity.EntityName); #>" />.
/// </summary>
<#WriteLine(string.Format("{0} = {1},", property.Key, Math.Pow(2, ++offset)));#><#}
#>
/// <summary>
/// The <see cref="<# Write(entity.EntityName); #>.Deleted"/>
/// was changed on the <see cref="<# Write(entity.EntityName); #>" />.
/// </summary>
Deleted = <# Write(Math.Pow(2, ++offset).ToString()); #>,
}
</code></pre>
<h3>Entity Classes</h3>
<pre><code> public class <# Write(entity.EntityName); #> :
GenericRootEntity<<# Write(entity.EntityName); #>, <# Write(entity.EntityName); #>Changes, <# Write(entity.EntityName); #>Instance>
{
<#if (entity.EntityName == authorityEntity) {#>internal const string <# Write(authorityAuthIDFieldName); #> = "<# Write(authorityAuthIDFieldValue); #>";<#}#>
internal const string TableName = "[" + FCASDBContext.TablePrefix + "<# Write(entity.PluralName); #>]";
<#
foreach (var property in entity.Properties.Values)
{
if ((property.Requirements & ER_COLLECTION) == ER_COLLECTION)
{#>
/// <summary>
/// Data member for <see cref="<# Write(property.Name); #>" />
/// </summary>
private ICollection<<# Write(property.DataType); #>> _<# Write(property.Name); #>;
<#}}#>
public bool Deleted { get; protected set; }
<#
foreach (var property in entity.Properties)
{#>
/// <summary>
/// Returns the <see cref="<#
string shortForm;
shortformLookup.TryGetValue(property.Value.DataType, out shortForm);
shortForm = shortForm ?? property.Value.DataType;
Write(shortForm);
#>"/> value <# WriteLine(property.Value.Description); #>
/// </summary>
<#
if ((property.Value.Requirements & ER_REQUIRED) == ER_REQUIRED && (property.Value.Requirements & ER_REQUIRED_NO_ATTRIBUTE) != ER_REQUIRED_NO_ATTRIBUTE){
#>
[Required()]
<#}
if ((property.Value.Requirements & ER_KEY) == ER_KEY){
#>
[Key()]
<#}
if ((property.Value.Requirements & ER_KEY) == ER_KEY){
#>
[MaxLength(<# Write(((property.Value.Requirements & 0x7FFFFFFF00000000L) >> 32).ToString()); #>)]
<#}
if ((property.Value.Requirements & ER_FIXED) == ER_FIXED){
#>
[Editable(false)]
<#}
if (((property.Value.Requirements & ER_COLLECTION) == ER_COLLECTION))
{#>
public virtual ICollection<<# Write(property.Value.DataType);#>> <# WriteLine(property.Key); #>
{
get
{
if (this._<# Write(property.Key); #> == null)
this._<# Write(property.Key); #> = new HashSet<<# Write(property.Value.DataType);#>>();
return this._<# Write(property.Key); #>;
}
protected set
{
this._<# Write(property.Key); #> = value;
}
}<#
}
else
{
var targetEnt = entities.FirstOrDefault(ent=>ent.EntityName == property.Value.DataType);
#>
public <# WriteLine(string.Format("{3}{0} {1} {{ get; {2}set; }}", string.Format("{0}{1}", property.Value.DataType, (nullableTypes.Contains(property.Value.DataType) && (property.Value.Requirements & ER_REQUIRED) != ER_REQUIRED) ? "?" : string.Empty), property.Key, ((property.Value.Requirements & ER_NOTTRACKED) == ER_NOTTRACKED) ? string.Empty : "protected ", targetEnt != null ? "virtual " : string.Empty));
}
}
foreach (var property in entity.Properties)
{
if ((property.Value.Requirements & ER_NOTTRACKED) == ER_NOTTRACKED)
continue;#>
internal void Set<# Write(property.Key); #>(<# Write(property.Value.DataType); #> value, <# Write(authorityEntity); #> authorizingUser)
{
if (this.<# Write(property.Key); #> == value)
return;
this.PropertyChange(<# Write(entity.EntityName); #>Changes.<# Write(property.Key); #>, this.<# Write(property.Key); #> = value, authorizingUser);
}
<#}#>
internal void Delete(<# Write(authorityEntity); #> authorizingUser)
{
if (this.Deleted)
return;
this.PropertyChange(<# Write(entity.EntityName); #>Changes.Deleted, this.Deleted = true, authorizingUser);
}
internal void Undelete(<# Write(authorityEntity); #> authorizingUser)
{
if (!this.Deleted)
return;
this.PropertyChange(<# Write(entity.EntityName); #>Changes.Deleted, this.Deleted = false, authorizingUser);
}
}
<#
}
#>
}
<#
}
</code></pre>
<p>The referenced GenericInstanceEntity is <a href="http://www.indiegamedevs.com/text/auditableChangeTracking/GenericInstanceEntity%603.txt" rel="nofollow noreferrer">here</a>.</p>
<p>The referenced GenericRootEntity is <a href="http://www.indiegamedevs.com/text/auditableChangeTracking/GenericRootEntity%603.txt" rel="nofollow noreferrer">here</a>.</p>
<p>The results of running the Text Template is <a href="http://www.indiegamedevs.com/text/auditableChangeTracking/TrackedEntityAndInstance.txt" rel="nofollow noreferrer">here</a>.</p>
<p>The referenced method and associated constant values are:</p>
<pre><code>internal const string TablePrefix = "FCAS.";
internal const string TableInstancesPrefix = "FCAS.INST.";
internal const string TableMappingPrefix = "FCAS.MAP.";
internal static bool ValuesEqual<TValue>(TValue left, TValue right)
{
var obj = (object)left;
if (obj != null)
if (typeof(IEquatable<TValue>).IsAssignableFrom(typeof(TValue)))
return ((IEquatable<TValue>)left).Equals(right);
else
return left.Equals(right);
else
return ((object)right) == null;
}
</code></pre>
<p>I'm posting this because I'm curious if this is a decent path to follow for such a project, or if I'm sorely mislead. Bidirectional collections of entities are supported; however, single 1:many relationships aren't present within the template's construction. The means to which change tracking is managed is a bit convoluted; however, its goal is to simplify construction of such a model. I'm pretty sure if there's overhead it will mostly be due to the entity framework itself.</p>
<p>I'd like to know if I'm on the right track.</p>
<p>Deletion of primary entities is not allowed, for data retention reasons. The appearance of deletion is handled through flags.</p>
<p>Changes are tracked by Column, and only the columns that you state are, by your own design, malleable. It seems to make more sense than trying to use the Standard T-SQL change tracking, unless there's something I missed about it.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T17:05:27.190",
"Id": "71926",
"Score": "0",
"body": "Please include the code you want reviewed, in your post - don't just link to it. Link to *on-the-side* stuff, not to the code you want reviewed. As it currently stands, this question could be put on hold until it's edited to include the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T20:11:02.610",
"Id": "71940",
"Score": "0",
"body": "It's 560 lines for the template, and over 2544 lines for the resulted code the template generates. Is that still okay?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T21:52:57.570",
"Id": "71948",
"Score": "1",
"body": "560 lines should be fine. If you feel it's too much to review, you can break it down into multiple questions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T03:48:12.773",
"Id": "72228",
"Score": "2",
"body": "I just noticed (as I edited your post to split up the code block parts) your edit says `The focus isn't so much on the template, but the pattern of managing a database that tracks changes across potentially multiple domains.` - this would normally be off-topic on this site, we... *review code* ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T03:59:02.833",
"Id": "72231",
"Score": "3",
"body": "Point. We'll focus on reviewing the code then. Nice clean edit, by the way, appreciate it. I'm putting together a more comprehensive example that focuses on the code exported by the template. I'll post back shortly to get it back on track."
}
] |
[
{
"body": "<p>I'm not familiar with template coding but I could follow this script all along, except this one-liner:</p>\n\n<pre><code>public <# WriteLine(string.Format(\"{3}{0} {1} {{ get; {2}set; }}\", string.Format(\"{0}{1}\", property.Value.DataType, (nullableTypes.Contains(property.Value.DataType) && (property.Value.Requirements & ER_REQUIRED) != ER_REQUIRED) ? \"?\" : string.Empty), property.Key, ((property.Value.Requirements & ER_NOTTRACKED) == ER_NOTTRACKED) ? string.Empty : \"protected \", targetEnt != null ? \"virtual \" : string.Empty)); \n</code></pre>\n\n<p>Doesn't parse in my poor little fried brain. I couldn't figure out where the <code>protected</code> was going to end up.</p>\n\n<p>I need to break it down to see what it does:</p>\n\n<pre><code>WriteLine(\n string.Format(\"{3}{0} {1} {{ get; {2}set; }}\", \n string.Format(\"{0}{1}\", \n property.Value.DataType, \n (nullableTypes.Contains(property.Value.DataType) \n && (property.Value.Requirements & ER_REQUIRED) != ER_REQUIRED) \n ? \"?\" \n : string.Empty), \n property.Key, \n ((property.Value.Requirements & ER_NOTTRACKED) == ER_NOTTRACKED) \n ? string.Empty \n : \"protected \", \n targetEnt != null \n ? \"virtual \" \n : string.Empty)); \n</code></pre>\n\n<p>How about at least putting the arguments in order?</p>\n\n<pre><code>WriteLine(\n string.Format(\"{0}{1} {2} {{ get; {3}set; }}\", \n targetEnt != null \n ? \"virtual \" \n : string.Empty\n string.Format(\"{0}{1}\", \n property.Value.DataType, \n (nullableTypes.Contains(property.Value.DataType) \n && (property.Value.Requirements & ER_REQUIRED) != ER_REQUIRED) \n ? \"?\" \n : string.Empty), \n property.Key, \n ((property.Value.Requirements & ER_NOTTRACKED) == ER_NOTTRACKED) \n ? string.Empty \n : \"protected \")); \n</code></pre>\n\n<p>If it's possible, I'd try to break this into something like 3 lines, be it only for readability.</p>\n\n<hr>\n\n<p>Minor annoyance, the resulting code seems to have mixed tabs and spaces:</p>\n\n<p><img src=\"https://i.stack.imgur.com/qsfmK.png\" alt=\"enter image description here\"></p>\n\n<p>I don't like the redundant <code>this</code> qualifier sprinkled everywhere, but the code is very consistent about it, so it's only down to personal preference here.</p>\n\n<hr>\n\n<p>I find this is a very interesting approach, however it's also a very intrusive one: if I understand your code correctly, your entities are being so much more than the regular average POCO out there.</p>\n\n<p>This breaks the <em>Single Responsibility Principle</em>. I believe a <em>decorator</em> would be less intrusive, and more focused - basically <em>compose</em> the functionality rather than <em>inheriting</em> it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T02:16:16.980",
"Id": "72216",
"Score": "0",
"body": "Could you clarify on the point of a 'decorator'? The goal behind this approach is to enable a high fidelity auditable set of entities. Shortly I will update with the most recent version. This was my first foray with the T4 templating engine, so the newest version cleans a lot of it up and generates a file per type. Also: the generic base types were initially introduced to simplify writing this code by hand, are you saying I should merge the code with the template and clean it up some?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T02:46:12.873",
"Id": "72222",
"Score": "0",
"body": "A decorator would *encapsulate* the functionality you're tucking into your base class. If you were to change your auditing strategy in the future, you've painted yourself in a corner with *inheritance*; with *composition*, a POCO remains *just a POCO* and the audit code and `DomainUser` dependencies can live in a `ActiveDirectoryAuditEntity` decorator; entities should have only 1 reason to change, and you've hard-wired them to AD - a decorator would shift this coupling to a class that explicitly says \"Pick me! I work with AD!\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T02:58:58.440",
"Id": "72223",
"Score": "0",
"body": "Perhaps I'm a bit confused because I'm unfamiliar with the idea of the decorator pattern...? The resulted instance that's constructed tracks each of the possible fields that could change and the entity handles detecting which exact fields have changed and persists only those changes. Which part of the overall design breaks this pattern? The reliance on the DomainUser, the use of a secondary class to handle change tracking, or something else?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T03:03:53.137",
"Id": "72224",
"Score": "0",
"body": "@AlexanderMorou Maybe I didn't completely grasp what you're doing. Are your POCO classes (the *entities* EF is using) inherited from `GenericRootEntity<TRoot, TRootProperties, TInstance>`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T03:06:21.433",
"Id": "72225",
"Score": "1",
"body": "There's three types generated for each defined Entity. The Changes enum which is more of a helpful design tool when you're debugging so you can look at it to see what change is represented by a given Instance. The Primary type which derives from the GenericRootEntity`3, and the Instance type which derives from GenericInstanceEntity`3 in which inheritors mirror the structure of the TRoot Entity, except with nullable types as nullable always. The template generates the code to handle high fidelity auditing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T03:15:06.933",
"Id": "72226",
"Score": "0",
"body": "I might add, I come from a highly regulated area, so: it's possible that through the use of a VPN, there might be multiple domains in play. The client code will utilize the active domains to do identity resolution when they login. The SID is stored instead of their name to avoid collision, and it also acts as a sort of password. When an admin possibly adds a domain and a user from that domain, the chances of someone replicating a domain to try go gain access is there; however, the likelihood of them getting the SID of the target user without having access to the real domain is very low."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T02:07:23.100",
"Id": "41929",
"ParentId": "41796",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T12:45:57.103",
"Id": "41796",
"Score": "3",
"Tags": [
"c#",
"performance",
"entity-framework"
],
"Title": "Entity Framework 6.0.2 - Performance of Auditable Change Tracking Part 1 of 2"
}
|
41796
|
<p>I have this code I am using in a private project. The following is a snippet of code I use to retrieve and load playlists from YouTube:</p>
<pre><code>for (feedEntry in a.feed.entry) {
if (a.feed.entry.hasOwnProperty(feedEntry)) {
feedTitle = a.feed.entry[feedEntry].title.$t.replace('] - ', ']').replace(' : ', '').replace(/\(.*?\)/g, "").replace(/\[.*?\]/g, "");
feedURL = a.feed.entry[feedEntry].link[1].href;
fragments = feedURL.split("/");
videoID = fragments[fragments.length - 2];
url = videoURL + videoID;
var c = feedTitle.split(' - ');
tracklist.push({
'title': c[1],
'artist': c[0],
'url': 'http://youtubeinmp3.com/fetch/?video=http://www.youtube.com/watch?v=' + videoID + '',
'album': 'YouTube'
})
}
</code></pre>
<p>This code, understandably, causes the browser to freeze a few seconds when loading larger playlists.</p>
<p>What ways could I go about optimizing this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T14:25:11.480",
"Id": "71905",
"Score": "0",
"body": "You could look at using better [regular expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) as they are _very_ fast."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T14:28:55.480",
"Id": "71906",
"Score": "1",
"body": "and you might want to do this on the server where you have more control - if you are reorganising data into an array all the time, I's vote to let the server do it ( you can cache it in a db )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T14:33:13.303",
"Id": "71907",
"Score": "1",
"body": "@Praveen Oh, thanks! And i was suspecting I should do something about my expressions, but I picked up regexp yesterday so I'm not very good with them."
}
] |
[
{
"body": "<p>The freezing comes primarily from the fact that JavaScript is single-threaded so when your loop is busy-looping everything else will wait until the scope has finished before the browser can continue to poll on the event queue.</p>\n\n<p>To solve this you can convert your code to <em>asynchronous</em> executing using <code>setTimeout()</code> to allow the browser to do other tasks in-between.</p>\n\n<p>Another thing is that <code>for in</code> loops are very slow so this can be replaced by using Object keys instead.</p>\n\n<p>Your parsing can be optimized by caching the current object as well as re-factor the parsing itself to a separate function method:</p>\n\n<pre><code>var keys = Object.keys(a.feed.entry), // retrieve all keys from the object\n count = keys.length, // number of keys to parse\n segment = 10, // number to parse each segment\n current; // counter for segment\n\n// start loop\n(function doSegment() {\n\n current = segment; // reset segment counter for each iteration\n\n while(current-- && count)\n parseFeedEntry(a.feed.entry[keys[--count]]);\n\n if (count)\n setTimeout(doSegment, 11); // delay 11ms to allow browser to breath\n})();\n\nfunction parseFeedEntry(entry) {\n // parse the entry here\n var feedTitle = entry.title.$t.replace('] - ', ']'). ...8X...\n // etc., notice entry is now cached\n}\n</code></pre>\n\n<h2><a href=\"http://jsfiddle.net/AbdiasSoftware/GDZ34/\">Online demo</a></h2>\n\n<p>Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T17:14:32.140",
"Id": "71928",
"Score": "0",
"body": "That's neat, but the freezing doesn't really affect this situation - I'm more looking to speed up the whole thing, thus I wanted to improve my expressions. Should I create a separate thread for that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T17:20:29.677",
"Id": "71929",
"Score": "0",
"body": "@JacobPedersen you can't make a separate thread unless you want to involve a web worker. In any case that would probably be slower than direct expression due to the memory copy between the two threads - and a bit overkill for something like this IMO. I'm not an ace at regex so I can't help there (and it wasn't tagged with expressions?). The gain is minimal though and the main issue with the code is the blocking code (for-in loop). The answer above shows a non-blocking approach which will solve that so the expressions themselves won't matter so much really. my 2 cents."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T17:28:19.297",
"Id": "71930",
"Score": "0",
"body": "Alright, will try it out. By \"Seperate thread\" I meant seperate question :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T17:33:15.273",
"Id": "71931",
"Score": "0",
"body": "@JacobPedersen aah! :D My head is a bit tired today"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T18:09:24.020",
"Id": "71935",
"Score": "0",
"body": "Happens to the best of us :p\n\nCould you point out where/how i should put this? Here's my full function: http://jsfiddle.net/hRP35/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T18:30:29.930",
"Id": "71937",
"Score": "0",
"body": "@JacobPedersen just place it inside the callback (convert callback to an actual function instead of var due to strict mode and scoped functions). I looked at the fiddle but there are many issues in the code and you most likely will run into recursion errors (stack overflow), the variables need to be declared and so forth. If I should implement it for you I would have to debug the whole project which is a bit outside the scope here am I afraid :-/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T09:17:08.417",
"Id": "72033",
"Score": "0",
"body": "Of course it is. This is part of a project I made to learn more about javascript anyways :P I wasn't able to fix any of my code, so I guess I'll leave it as it is until i learn some more about AJAX and XML."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T15:03:57.640",
"Id": "72091",
"Score": "0",
"body": "I found a better solution to the script that retrieves the playlist data, making this far easier (see my own answer). Thanks for the async script and all the help!"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T15:45:11.197",
"Id": "41809",
"ParentId": "41804",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T14:21:42.980",
"Id": "41804",
"Score": "4",
"Tags": [
"javascript",
"performance",
"youtube"
],
"Title": "Retrieve and load playlists from YouTube"
}
|
41804
|
<p>I am writing my own tooltip plugin for my portfolio website that I am currently working on. It works rather well, however, I feel that there is a lot I could improve. This is one of my bigger jQuery plugins that I have written.</p>
<pre><code>(function($) {
// Used as a template for addTooltip()
var tooltipDefaults = {
'class': null,
'showOn': 'mouseenter',
'hideOn': 'mouseleave',
'direction': 'top',
'offset': null
}
// Store generated IDs to avoid conflicting IDs
var tooltipIds = new Array();
// Keep track of displayed popups
var displayedTooltips = new Array();
function generateUniqueId()
{
var id;
do {
id = Math.floor(Math.random()*90000) + 10000;
} while ($.inArray(id, tooltipIds) !== -1);
tooltipIds.push(id);
return id;
}
function getUniqueId(id)
{
return parseInt(id.substr(0, 5));
}
function isUniqueId(id)
{
return !NaN(getUniqueId(id));
}
function removeUniqueId(id)
{
var id = getUniqueId(id);
var idIndex = $.inArray(id, tooltipIds);
if (idIndex !== -1) {
tooltipIds.splice(idIndex);
}
}
$.fn.displayTooltip = function()
{
var element = $(this);
var tooltip = $('#' + element.attr('data-tooltip-id'));
var config = element.data('config');
var offset = element.offset();
var left;
var top;
switch (config.direction) {
case 'left':
top = offset.top + "px";
left = offset.left - tooltip.outerWidth() - config.offset + "px";
break;
case 'top':
top = offset.top - element.outerHeight() - config.offset + "px";
left = offset.left + ((element.outerWidth() / 2) - (tooltip.outerWidth() / 2)) + "px";
break;
case 'right':
top = offset.top + "px";
left = offset.left + element.outerWidth() + config.offset + "px";
break;
case 'bottom':
top = offset.top + element.outerHeight() + config.offset + "px";
left = offset.left + ((element.outerWidth() / 2) - (tooltip.outerWidth() / 2)) + "px";
break;
}
tooltip.css({
'position': 'absolute',
'left': left,
'top': top,
'z-index': 5000
});
if (element.isTooltipDisplayed()) {
return;
}
tooltip.show();
displayedTooltips.push(element.attr('id'));
}
$.fn.hideTooltip = function()
{
var element = $(this);
var idIndex = $.inArray(element.attr('id'), displayedTooltips);
if (idIndex !== -1) {
displayedTooltips.splice(idIndex);
}
$('#' + element.attr('data-tooltip-id')).hide();
}
$.fn.addTooltip = function(content, params)
{
var config = $.extend(tooltipDefaults, params);
return this.each(function() {
var element = $(this);
// If the element already has a tooltip change the content inside of it
if (element.hasTooltip()) {
$('#' + element.attr('data-tooltip-id')).html(content);
return;
}
var tooltipId = (element.is('[id]') ? element.attr('id') : generateUniqueId()) + '-tooltip';
element.attr('data-tooltip-id', tooltipId);
var tooltip = $('<div>', {
id: tooltipId,
role: 'tooltip',
class: config.class
}).html(content);
$('body').append(tooltip);
/**
* If showOn and hideOn are the same events bind a toggle
* listener else bind the individual listeners
*/
if (config.showOn === config.hideOn) {
element.on(config.showOn, function() {
if (!element.isTooltipDisplayed()) {
element.displayTooltip();
} else {
element.hideTooltip();
}
});
} else {
element.on(config.showOn, function() {
element.displayTooltip();
}).on(config.hideOn, function() {
element.hideTooltip();
});
}
// Store config for other functions use
element.data('config', config);
// Saftey check incase the element recieved focus from the code running above
element.hideTooltip();
});
}
$.fn.hasTooltip = function()
{
return $(this).is('[data-tooltip-id]');
}
$.fn.isTooltipDisplayed = function()
{
var element = $(this);
if (!element.hasTooltip()) {
return false;
}
return ($.inArray(element.attr('id'), displayedTooltips) === -1) ? false : true;
}
$.fn.removeTooltip= function()
{
return this.each(function() {
var element = $(this);
var tooltipId = element.attr('data-tooltip-id');
var config = element.data('config');
$('#' + tooltipId).remove();
if (isUniqueId(tooltpId)) {
removeUniqueId(tooltipId);
}
element.removeAttr('data-tooltip-id');
if (config.showOn === config.hideOn) {
element.off(config.showOn);
} else {
element.off(config.showOn);
element.off(config.hideOn);
}
element.removeData('config');
});
}
// Reposition tooltip on window resize
$(window).on('resize', function() {
if (displayedTooltips.length < 1) {
return;
}
for (var i = 0; i < displayedTooltips.length; i++) {
$('#' + displayedTooltips[i]).displayTooltip();
console.log(displayedTooltips);
}
});
}(jQuery));
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T14:45:12.590",
"Id": "71911",
"Score": "0",
"body": "`new Array()` -> `[]`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T14:52:45.677",
"Id": "71912",
"Score": "0",
"body": "`if (element.isTooltipDisplayed()) { return; }` could probably called before all left & top calculations..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T01:49:41.747",
"Id": "71976",
"Score": "2",
"body": "1.this is not good jquery plugin api style conversion. your plugin should only has one namespace. 2. not use utility in jQuery(like $.inArray), the performance is too slow"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T02:01:46.127",
"Id": "71979",
"Score": "0",
"body": "check this performance table [jspref](http://jsperf.com/jquery-inarray-vs-underscore-indexof/24)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T08:35:53.790",
"Id": "72028",
"Score": "0",
"body": "@caoglish `indexOf()`"
}
] |
[
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li><p>There seems to be a ton of overkill with regards to <code>id</code>, since the user will never look at the id of a tooltip, you can simply use:<br></p>\n\n<pre><code>function generateUniqueId()\n{\n var id = generateUniqueId.id = ( generateUniqueId.id || 0) + 1;\n tooltipIds.push(id);\n return id;\n}\n</code></pre>\n\n<p>on the whole I would review the code and simplify how id's work.</p></li>\n<li>Namespaces; @caoglish is right, your approach is wrong. jQuery plugin style would be 1 function <code>tooltip</code> on which you can call then <code>create</code>, <code>show</code>, <code>hide</code> etc.</li>\n<li>In <code>removeUniqueId</code> you simply use <code>id = getUniqueId(id);</code> ( drop the <code>var</code> ), since you already have the <code>id</code> as a parameter</li>\n<li>As @Charlie mentioned; <code>var tooltipIds = new Array();</code> -> <code>var tooltipIds = [];</code></li>\n<li>In <code>removeTooltip</code> you have a bug in <code>(isUniqueId(tooltpId)) {</code> , you meant to use <code>tooltipId</code></li>\n<li>You would have caught this if you added <code>\"use strict\";</code> right after <code>(function($) {</code> (this activates strict mode)</li>\n<li>I really like the way you use <code>config</code> in <code>displayTooltip</code></li>\n<li><code>console.log()</code> does not belong in production code</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:47:35.973",
"Id": "72594",
"Score": "0",
"body": "Thank you a lot! I will be sure to make these changes. Can you possibly explain to me how that generateUniqueId method works?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:57:50.283",
"Id": "72599",
"Score": "0",
"body": "I am using the function to store the value of `id` and I just keep adding 1 so that the value is unique."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:59:07.813",
"Id": "72602",
"Score": "0",
"body": "Alright, also is it really ideal to only use one namespace. It just seems cluttered to toss everything into one namespace. Or is there a design pattern that could make something like that better?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T17:02:28.647",
"Id": "72605",
"Score": "0",
"body": "I will agree that it might be more cluttered for the author, but the convenience of the user comes first ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T18:05:44.010",
"Id": "72612",
"Score": "0",
"body": "I just rewrote the whole plugin to an OOP approach. I also made the changes you suggested and the whole ID system is now out. I dropped about 80 lines of code. How much better is this than the previous one and are there still areas to be improved? If you wouldn't mind taking a look that is."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T13:58:18.893",
"Id": "42149",
"ParentId": "41807",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T14:43:55.417",
"Id": "41807",
"Score": "5",
"Tags": [
"javascript",
"jquery",
"html",
"plugin"
],
"Title": "Tooltip plugin for portfolio website"
}
|
41807
|
<p>I would like to know whether I'm going in a correct way or not in building my Poker game. So far, I've implemented card and deck classes and I would like to see your feedback about my work. Feel free to criticize the code of any regard (organization, order, comments ... etc) </p>
<p><strong>card.h</strong> </p>
<pre><code>#ifndef CARD_H
#define CARD_H
#include <string>
const int SUIT_MAX(4);
const int RANK_MAX(13);
class Card
{
friend class Deck; // Deck Class needs to access to Card Class but not vice versa
public:
explicit Card();
explicit Card(const int &suit, const int &rank);
std::string Card2Str() const;
private:
int generate_suit();
int generate_rank();
int get_suit() const;
int get_rank() const;
int m_suit;
int m_rank;
};
#endif
</code></pre>
<p><strong>card.cpp</strong></p>
<pre><code>#include <stdlib.h> /* srand, rand */
#include "card.h"
#include <iostream>
const std::string SUIT[SUIT_MAX] = {"S", "H", "D", "C"};
const std::string RANK[RANK_MAX] = {"2","3","4","5","6","7","8","9","10","J","Q","K","A"};
Card::Card()
{
m_suit = generate_suit();
m_rank = generate_rank();
}
Card::Card(const int &suit, const int &rank) : m_suit(suit), m_rank(rank)
{
}
int Card::generate_suit()
{
return rand() % (SUIT_MAX-1) + 0;
}
int Card::generate_rank()
{
return rand() % (RANK_MAX-1) + 0;
}
std::string Card::Card2Str() const
{
return SUIT[get_suit()] + RANK[get_rank()];
}
int Card::get_suit() const
{
return m_suit;
}
int Card::get_rank() const
{
return m_rank;
}
</code></pre>
<p><strong>deck.h</strong></p>
<pre><code>#ifndef DECK_H
#define DECK_H
#include <vector>
#include <iostream>
#include <fstream>
#include "card.h"
using namespace std;
class Deck
{
public:
explicit Deck();
void print_Deck() const;
void getOneCard();
private:
std::vector<Card> m_deck;
};
#endif
</code></pre>
<p><strong>deck.cpp</strong></p>
<pre><code>#include <iostream>
#include "deck.h"
Deck::Deck()
{
for (unsigned int i(0); i < SUIT_MAX; ++i)
{
for (unsigned int j(0); j < RANK_MAX; ++j)
{
Card card(i, j);
m_deck.push_back(card);
}
}
}
void Deck::print_Deck() const
{
unsigned int count(1);
for (unsigned int i(0); i < m_deck.size(); ++i)
{
std::cout << m_deck[i].Card2Str() << " ";
if ( count == 13 )
{
std::cout << std::endl;
count = 0;
}
++count;
}
}
void Deck::getOneCard()
{
Card cd(m_deck.back().get_suit(), m_deck.back().get_rank());
m_deck.pop_back();
std::cout << cd.Card2Str() << std::endl;
}
</code></pre>
<p><strong>main.cpp</strong></p>
<pre><code>#include <iostream>
#include <vector>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <string>
#include "card.h"
#include "deck.h"
int main()
{
srand (time(NULL));
Deck _deck;
_deck.print_Deck();
_deck.getOneCard();
std::cout << std::endl;
_deck.print_Deck();
std::cout << std::endl;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T17:48:32.213",
"Id": "71932",
"Score": "0",
"body": "I happen to be personally interested in playing card representations in C++. You may take a look at my latest posted version [here](http://codereview.stackexchange.com/questions/36657/is-this-a-good-first-use-of-template-classes-with-my-deck-class) for some ideas."
}
] |
[
{
"body": "<p>I come from Java world, but here are just a few thoughts:</p>\n\n<ul>\n<li><code>generate_suit</code> and <code>generate_rank</code> methods should probably not subtract 1 from MAXes and also adding zero at the end is unnecessary. E.g. <code>rand() % (SUIT_MAX-1)</code> is <code>rand() % 3</code> and <a href=\"http://en.wikipedia.org/wiki/Modulo_operation\">this could never be 3</a>, so you will never have generated clubs ♣.</li>\n<li><p>Friending <code>Card</code> class by <code>Deck</code> class is not necessary. Just make <code>get_suit</code> and <code>get_rank</code> methods public and/or create a copy constructor of the <code>Card</code> class and/or rewrite <code>getOneCard</code> method like this:</p>\n\n<pre><code>void Deck::getOneCard()\n{ \n std::cout << m_deck.back().Card2Str() << std::endl;\n m_deck.pop_back(); \n}\n</code></pre></li>\n<li><code>Card::Card()</code> constructor doesn't seem used now, so consider deleting it along with both <code>generate*</code> methods.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T16:57:19.167",
"Id": "71925",
"Score": "0",
"body": "thanks for the feedback. For the rand(), it is a good point and I'll keep this in mind. About Card::Card(), basically I've implemented that because in case the user wants to see a mere card without considering Deck or any other class. It is just an extra info I guess, so I guess there is no harm of keeping it with full regard of your feedback. About friend Class, I'm not certain but it seems to me it should be there because Card should have its own data private, keeping everything tight and secure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T17:12:42.900",
"Id": "71927",
"Score": "1",
"body": "@CroCo I think friending is not necessary here, so it violates Card's encapsulation without a purpose. Even if it was necessary for some other case, why would you want to hide get_suit and get_rank methods of Card when it already indirectly exposes them via the Card2Str method (metaphorically speaking)? If public audience already knows what Card I am (through Card2Str method), why hide my suit or rank getters?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T16:44:53.417",
"Id": "41812",
"ParentId": "41810",
"Score": "8"
}
},
{
"body": "<ul>\n<li><p>Prefer <a href=\"https://stackoverflow.com/questions/1282295/what-exactly-is-nullptr\"><code>nullptr</code></a> to <code>NULL</code> if you're using C++11.</p></li>\n<li><p><code><stdlib.h></code> and <code>time.h</code> are both C libraries. Use the respective C++ libraries <code><cstdlib></code> and <code><ctime></code>. The rest are okay. You don't need to include <code><vector></code> in <strong>main.cpp</strong>.</p></li>\n<li><p>Since you use a storage container for your deck, you can display it using iterators:</p>\n\n<pre><code>for (auto iter = m_deck.begin(); iter != m_deck.cend(); ++iter)\n{\n std::cout << *iter << \"\\n\";\n}\n</code></pre>\n\n<p>If you're using C++11, use a <a href=\"http://www.cprogramming.com/c++11/c++11-ranged-for-loop.html\" rel=\"nofollow noreferrer\">range-based <code>for</code>-loop</a>:</p>\n\n<pre><code>for (auto& iter : m_deck)\n{\n std::cout << iter << \"\\n\";\n}\n</code></pre></li>\n<li><p>I don't know why you're using randomness to generate a card within the class. The constructor should be given input to determine its rank and suit. A card shouldn't create itself, and you wouldn't want this with an actual card game. Remove the generate functions entirely, and instead allow the constructor to receive arguments to determine the card's value.</p></li>\n<li><p>You also don't need to construct the deck within its constructor. A deck can still start out empty until cards are passed to it. That should be handled in client code, especially if someone <em>doesn't</em> want a 52-card deck (or a certain game uses something different).</p></li>\n<li><p>As an alternative to using <code>std::string</code>s, consider <code>enum</code>s for the ranks and suits:</p>\n\n<pre><code>// make sure the first rank is explicitly set at 1\n// this will make the last rank equal 13\nenum Rank { Ace=1, Two, /* ... */, Queen, King };\n</code></pre>\n\n<p></p>\n\n<pre><code>enum Suit { Spades, Hearts, Diamonds, Clubs };\n</code></pre>\n\n<p>With this, you'll no longer need the arrays nor the max constants. Your <code>m_rank</code> and <code>m_suit</code> members should also be one of these <code>enum</code> type (<code>Rank</code> and <code>Suit</code> respectively). The <code>enum</code>s and the <code>Card</code> class declaration should all then be contained in a <code>namespace</code>.</p>\n\n<p>Within your card class, you'll need functions to convert a given <code>enum</code> value to a <code>char</code> value for displaying. You could, for instance, do this with a <code>switch</code> statement, which will serve as a look-up table. This will also make it easier to maintain the ranks and suits.</p>\n\n<pre><code>std::string getRank(Rank rank)\n{\n switch (rank)\n {\n case Ace: return \"A\";\n // ...\n default: throw std::logic_error(\"invalid rank\");\n }\n}\n\n// same idea with suits\n</code></pre>\n\n<p>Also note the <code>default</code> statement. If an invalid rank is passed in, an <a href=\"http://en.cppreference.com/w/cpp/error/logic_error\" rel=\"nofollow noreferrer\"><code>std::log_error</code></a> exception will be thrown. Regardless of what works best for error-handling, there should be a <code>default</code> statement here to properly handle it.</p></li>\n<li><p>Rename <code>Card2Str()</code> to <code>CardToString()</code>. The former is just awkward wording. It should also be lowercase as it's a function and not a type.</p></li>\n<li><p><code>getOneCard()</code> doesn't specify <em>where</em> in the deck the one card is drawn. Since it takes a card from the top of the deck, just call it <code>draw()</code> or <code>deal()</code>. On the other hand, it's <code>void</code> and has no parameters, so it's not returning a card. If this is supposed to just display a top card, then it's ineffective as it's still destroying the top card.</p>\n\n<p>Better yet, consider having a <code>draw()</code> <em>and</em> a <code>top()</code> (perhaps you just need to peek at the top card). The functionality also looks a bit unclear. Since you're using <code>std::vector</code>, a storage container, make use of its member functions. In this case, use <code>back()</code>:</p>\n\n<p><strong><code>draw()</code>:</strong></p>\n\n<pre><code>Card Deck::draw()\n{ \n Card cd = m_deck.back();\n m_deck.pop_back();\n return cd;\n}\n</code></pre>\n\n<p><strong><code>top()</code>:</strong></p>\n\n<pre><code>// return by const& as this Card should only be read-only\n// also make the function const as no data members are modified\nCard const& Deck::top() const\n{ \n return m_deck.back();\n}\n</code></pre>\n\n<p>For both of these functions, be sure the caller is first checking for an empty deck.</p>\n\n<p><em>Side-note</em>: You <em>can</em> use a different storage container if you, say, need to be able to insert into or draw from somewhere else in the deck besides the top or bottom. For that, you can use an <a href=\"http://en.cppreference.com/w/cpp/container/list\" rel=\"nofollow noreferrer\"><code>std::list</code></a> (doubly linked list). If you instead want to insert into or draw from the top <em>and</em> bottom, you can use an <a href=\"http://en.cppreference.com/w/cpp/container/deque\" rel=\"nofollow noreferrer\"><code>std::deque</code></a> (double-ended queue). Otherwise, stay with what you have.</p></li>\n<li><p>Your deck is missing something: a shuffle function! You could utilize <a href=\"http://en.cppreference.com/w/cpp/algorithm/random_shuffle\" rel=\"nofollow noreferrer\"><code>std::random_shuffle</code></a> from the STL to do it nicely for you:</p>\n\n<pre><code>void Deck::shuffle()\n{\n std::random_shuffle(m_deck.begin(), m_deck.end());\n}\n</code></pre>\n\n<p>You should also check for an empty deck prior to shuffling.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T23:45:14.310",
"Id": "71964",
"Score": "0",
"body": "I think it would be very awkward to program if ranks/suits were enums; IMO giving up the arrays for switch statements everywhere would make most things *worse*, not better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T23:55:06.440",
"Id": "71966",
"Score": "0",
"body": "@Hurkyl: It was based on a suggestion given to me a number of times. Even without the `enum`s, it would make little sense for those members to be `int`s. With `enum`s, you have a more accurate type. Even with the arrays, you would have to make sure it doesn't go out of bounds."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T14:36:38.560",
"Id": "72080",
"Score": "0",
"body": "@Jamal, thank you so much for this invaluable info. About Card2Str, actually I'm chosen 2 over To because I use Matlab and this shortcut is common in some functions. Also, I totally agree with \"Hurkyl\" that using enum makes the code a little longer, so arrays would be a better choice with full regard of your opinion. About using iterators, I think it would be a good idea. About shuffling, I think Dealer Class is in charge of shuffling, correct me if I'm wrong. About top, it seems a good function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T14:43:57.037",
"Id": "72083",
"Score": "0",
"body": "About getOneCard(), I think I need to move this function to Dealer Class, since Deck Class does no action itself. I mean Deck Class should only store cards nothing else. This is my understanding."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T14:55:27.857",
"Id": "72086",
"Score": "0",
"body": "About top(), shouldn't be a function in Dealer Class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T15:01:36.850",
"Id": "72090",
"Score": "0",
"body": "@CroCo: Not exactly. A Deck class, like any other storage container, should be able to execute actions itself. For instance, just like `std::vector` has a `pop_back()` function, the Deck class has a `draw()` function. It just depends on the type of functions you use. As for a Dealer class, you're probably thinking of a *player* who deals the cards from the deck. That Dealer would need to call Deck's functions to add, draw, or shuffle cards. On that note, I should also add that you'll need a `reset()` function (also found in my link)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T00:30:59.067",
"Id": "72208",
"Score": "0",
"body": "Good idea to use an `enum` for the suit. If you use an `enum` for the rank, assign an explicit value to avoid off-by-one weirdness: `enum Rank { Ace=1, Two, Three, … };`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T00:49:23.150",
"Id": "72209",
"Score": "0",
"body": "@200_success, I'm still not see why using `enum` is better than using arrays."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T01:43:54.133",
"Id": "72211",
"Score": "0",
"body": "@CroCo: To be honest, I've had this doubt myself at first. After going through many iterations of my playing card classes, I've gone through different setups. If you'd like, a few of us can discuss this in chat."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T17:46:48.083",
"Id": "41816",
"ParentId": "41810",
"Score": "12"
}
},
{
"body": "<p>The <code>Card</code> constructor is unnecessarily complicated:</p>\n\n<pre><code>explicit Card(const int &suit, const int &rank)\n</code></pre>\n\n<p>Why not just take <code>int</code>s?</p>\n\n<pre><code>explicit Card(int suit, int rank)\n</code></pre>\n\n<hr>\n\n<p>There's not much that can be done with a <code>Card</code>, except to convert it into a string. What about comparing with another card for equality? How about comparing with another card by rank? That's impossible unless you stringify it and parse the string. The fact that <code>Deck</code> needs to be a <code>friend</code> is a red flag.</p>\n\n<hr>\n\n<p>The <code>Card</code> class has a <code>Card2Str()</code> method. That's awkward, since the \"Card\" part of the name is redundant. In contrast, <code>Deck</code> has a <code>print_Deck()</code> method. Why the inconsistency in capitalization and in functionality? Neither method is idiomatic C++, which would provide an <a href=\"https://stackoverflow.com/q/1549930/1157100\"><code>operator<<</code> for <code>std::ostream&</code></a>. The <code>ostream</code> approach is also more flexible, since it is not constrained to write its output to <code>std::cout</code>. (You could write to a <code>std::stringstream</code>, for example, to obtain a string.)</p>\n\n<hr>\n\n<p><code>Deck::getOneCard()</code> is not useful, since it returns <code>void</code> and prints its result to <code>std::cout</code> instead. You want to return a <code>Card</code>, or more properly, a <code>const Card&</code> — and let the caller decide what to do with the card. The name is inappropriate, since \"get…\" has a connotation of having no side effect; <code>drawCard()</code> would be better. And if you can draw a card from the deck, there had better be a way to put it back at the bottom of the deck.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T02:08:12.133",
"Id": "72215",
"Score": "0",
"body": "As for the very last point, I think it was you or someone else who told me that the user shouldn't have to worry about returning cards like that (although `std::deque` works with that). Other methods may include having two storage containers (what I have now) or having an iterator keeping track of the top of the deck."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:09:36.967",
"Id": "72401",
"Score": "0",
"body": "@200_success, what's wrong with passing by a constant reference? About overloading cout, it is a good idea. I will put this in mind. Even though I've implemented getOneCard() for only testing, I believe the Dealer Class is in charge of drawing cards. I'm picturing Deck Class as a bunch of cards nothing else which reflects the reality."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:28:06.777",
"Id": "72405",
"Score": "0",
"body": "Passing `const int&` will work too. It's just that `int` is more straightforward, so why not simplify?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:31:04.630",
"Id": "72407",
"Score": "1",
"body": "What's the point of a `Deck` that's just a `vector<Card>` with a print method? You might as well get rid of the `Deck` class and have the `Dealer` hold a `vector<Card>`. At that point, you've just renamed `Deck` to `Dealer`. At the end of the day, you're still missing some functionality to manipulate that collection of cards."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T04:08:53.990",
"Id": "72443",
"Score": "0",
"body": "@200_success: Precisely. There are some things that `Deck` should and shouldn't do. Drawing and shuffling, for instance, *should* be available so that a player can use them on the deck. A dealer is just someone who *uses* the deck, but is not *the* deck."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T04:10:21.293",
"Id": "72444",
"Score": "0",
"body": "@CroCo: It's relatively cheap to pass an `int`, so `const&` is unneeded. However, you can just make it `const` for the const-correctness alone."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T06:54:11.113",
"Id": "72451",
"Score": "0",
"body": "@Jamal `const int` would be correct, but a bit superfluous. It just prevents the function from mutating its local copy of the variable, at the expense of making its signature look weird."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T01:20:14.923",
"Id": "41923",
"ParentId": "41810",
"Score": "5"
}
},
{
"body": "<p>This is probably overkill for a poker program, but if you wanted to reuse your Deck class for card games other than poker you'll need to decouple it from your Card class.</p>\n\n<p>In general, a Deck of cards is similar for all card games regardless of what type of cards are being used. Decks can be shuffled, cards can be drawn, etc.</p>\n\n<p>Cards however can be poker cards, pinochle cards, memory game cards, UNO cards, or many more, not all have suits or ranks, though they all may have some way to print or display whatever values they do contain.</p>\n\n<p>With that in mind, if you plan on making other card games besides poker, consider making an ICard abstract interface with some type of pure virtual display or print method, and having your Deck class depend on the interface instead of the Card class directly. Then you'll be able to perform Deck actions on any type of card for any type of card game you can dream up in the future. It will also mean that Deck should not be friends with any concrete Card class.</p>\n\n<p>This added complexity though is not necessary if you only plan to make a poker game.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T17:25:00.227",
"Id": "72329",
"Score": "0",
"body": "Now that's my kind of approach! A big +1 for you!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:16:21.500",
"Id": "72402",
"Score": "1",
"body": "@YoungJohn, I don't want to make so complicated. What I'm trying to do is building only one type of Poker games. This allows me to see how the procedure flows, after that I'll update the game to be more flexible. I know this is not good approach, however I think it is good for beginners. Thanks for the advice though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:30:24.033",
"Id": "72406",
"Score": "0",
"body": "Don't even worry about it, it is a common trade-off to choose between making code less complex vs more generic. Your version is less complex and if that is enough for your application then it is absolutely the correct thing to do."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T15:46:17.723",
"Id": "41971",
"ParentId": "41810",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "41816",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T15:53:21.387",
"Id": "41810",
"Score": "15",
"Tags": [
"c++",
"classes",
"playing-cards"
],
"Title": "Card and Deck classes"
}
|
41810
|
<p>I've written a List monad as an example for a <a href="https://codereview.stackexchange.com/q/41783/21609">related question</a>. This is a rather frustrating experience as I wanted to use Java, which (as of Java 7) still lacks lambda expressions and lacks higher-order type parameters, which is one reason why this</p>
<pre><code>interface Monad<A, I<A> extends Monad<A, I<A>>> {
public static I<A> return(A x);
public I<B> bind(Function<A, I<B>> f);
}
</code></pre>
<p>is impossible. Also, return-type polymorphism would be great. But I digress.</p>
<p>I am looking for a review of the following:</p>
<ul>
<li>general style.</li>
<li>general correctness, considering that I wouldn't claim to actually understand monads.</li>
<li>ways to increase the type safety and generality, considering that an interface as above is impossible as of my knowledge.</li>
<li>ways to reduce verbosity without sacrificing conceptual elegance.</li>
</ul>
<p>I am not looking for a review of</p>
<ul>
<li>… the lack of JavaDoc-comments, as this is educational code.</li>
<li>… ease of use of the <code>List</code> class. E.g. an accessor <code>Option<A> get(int i)</code> would be contrary to the purpose of this code as a monad showcase.</li>
</ul>
<p>Here is the implementation itself:</p>
<pre><code>import java.lang.String;
import java.lang.StringBuilder;
import java.lang.Integer;
import java.lang.System;
interface Function<A, B> {
public B apply(A x);
}
class List<A> {
private final A head;
private final List<A> tail;
private final int size;
// unit :: A -> M[A]
// public List(A x) -- implied by "new List<>(A...)"
// "List" happens to be *additive*, so we also offer a "zero" instance
// and a "plus" operation
// "zero", a neutral element for the "plus" operation
// public List() -- implied by "new List<>(A...)"
// "plus" concatenates two Lists
// plus :: (M[A], M[A]) → M[A]
// important properties regarding the zero:
// zero.plus(x) == x
// x.plus(zero) == x
public List<A> plus(List<A> that) {
if (this.size == 0) return that;
return new List<A>(this.head, this.tail.plus(that));
}
// a convenience constructor that hides excessive "plus"sing
public List(A... xs) {
// technically, we have to do something like:
// List<A> result = new List<>();
// for (A x : xs)
// result = result.plus(new List<>(x));
// this = result
// let's take the equivalent shortcut:
if (xs.length == 0) {
this.head = null;
this.tail = null;
this.size = 0;
}
else {
List<A> result = new List<A>();
for (int i = xs.length - 1; i > 0; i--) {
result = new List<A>(xs[i], result);
}
this.head = xs[0];
this.tail = result;
this.size = result.size + 1;
}
}
// an internal constructor to create the linked lists
private List(A x, List<A> xs) {
this.head = x;
this.tail = xs;
this.size = xs.size + 1;
}
// "bind"
// bind :: (M[A], A → M[B]) → M[B]
// can be implemented in terms of our "plus"
public <B> List<B> bind(Function<A, List<B>> f) {
if (this.size == 0) return new List<B>();
List<B> partialResult = this.tail.bind(f);
return f.apply(this.head).plus(partialResult);
}
// how about a nice "toString"?
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
if (this.size > 0) {
sb.append(this.head);
for (List<A> ptr = this.tail; ptr.size > 0; ptr = ptr.tail) {
sb.append(",");
sb.append(ptr.head);
}
}
sb.append("]");
return sb.toString();
}
}
</code></pre>
<p>And here is some example usage:</p>
<pre><code>public class Main {
public static void main (String[] args)
{
// example: repeat each element
final Function<String, List<String>> repeatEachElement = new Function<String, List<String>>() {
@Override
public List<String> apply(String s) {
return new List<String>(s, s);
}
};
final List<String> strings = new List<String>("foo", "bar", "baz");
System.out.println(strings);
System.out.println(strings.bind(repeatEachElement));
// example: square each element
final Function<Integer, List<Integer>> square = new Function<Integer, List<Integer>>() {
@Override
public List<Integer> apply(Integer i) {
return new List<Integer>(i * i);
}
};
final List<Integer> numbers = new List<Integer>(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
System.out.println(numbers);
System.out.println(numbers.bind(square));
// --------------- //
// The Monad Laws: //
// --------------- //
// note: these aren't _proofs_ of correctnes,
// just some examples showing that they're probably correct.
// 1. "(unit x) >>= f ≡ f x" //
assert new List<Integer>(42).bind(square).toString() == square.apply(42).toString();
// 2. "m >>= unit ≡ m" //
final Function<Integer, List<Integer>> unit = new Function<Integer, List<Integer>>() {
@Override
public List<Integer> apply(Integer i) {
return new List<>(i);
}
};
assert numbers.bind(unit).toString() == numbers.toString();
// 3. "(m >>= f) >>= g ≡ m >>= ( \x -> (f x >>= g) )" //
// m = numbers
// f = square
// g = stringify
final Function<Integer, List<String>> stringify = new Function<Integer, List<String>>() {
@Override
public List<String> apply(Integer i) {
return new List<>(i.toString());
}
};
final Function<Integer, List<String>> nested = new Function<Integer, List<String>>() {
@Override
public List<String> apply(Integer i) {
return square.apply(i).bind(stringify);
}
};
assert numbers.bind(square).bind(stringify).toString()
== numbers.bind(nested).toString();
}
}
</code></pre>
<p>See it in action here: <a href="http://ideone.com/S3r7v6" rel="nofollow noreferrer">http://ideone.com/S3r7v6</a></p>
|
[] |
[
{
"body": "<p>This is pretty decent code. A few things seem noteworthy:</p>\n\n<ul>\n<li><p>The spacing is inconsistent. This could have happened if <code>size</code> was a boolean <code>isEmpty</code> in a previous incarnation…</p></li>\n<li><p>There are a lot more opportunities to declare variables to be <code>final</code> than were used.</p></li>\n<li><p>The documentation <em>inside</em> the methods is a bit sparse. For example, it would be helpful to explicitly point out that <code>for (int i = xs.length - 1; i > 0; i--)</code> goes through the array backwards, but will stop before the first element.</p></li>\n<li><p>The <code>toString</code> is missing an <code>@Override</code>.</p></li>\n<li><p>It might be cheaper to do an <code>sb.append(',')</code> than <code>sb.append(\",\")</code> (char vs. String).</p></li>\n<li><p>Testing with <code>assert</code> is a horrible idea, but admittedly good enough for educational code.</p></li>\n<li><p><a href=\"http://openjdk.java.net/projects/jdk8/\" rel=\"nofollow\">In March 2014, Java 8 will be released</a>, and the horribly verbose <code>Function</code> definitions can be shortened to lambdas. Yay!</p></li>\n<li><p>Actually, writing an <code>Option</code> implementation (aka. <code>Maybe</code>) alongside of the <code>List</code> would be fairly useful – it too is an additive monad, even simpler in its implementation, and would help to highlight which part of the code is for the monads, and which is for the linked list.</p></li>\n<li><p>In the test for the third monad law, <code>f</code> (here: <code>square</code>) has type <code>Integer → Integer</code>. Thus we only test this with two different types, although in general we should be able to test three different types. A <code>sqroot :: Integer -> Double</code> might have had more illustrative value. Also, <code>stringify</code> actually has the type <code>Object → String</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T16:57:09.487",
"Id": "72792",
"Score": "0",
"body": "I mostly agree. But could you elaborate why using assertions is \"a horrible idea\"? I disagree and like the clear intent that is delivered by using assert. Of course -ea has to be active..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T17:15:27.747",
"Id": "72797",
"Score": "1",
"body": "@CarstenHoffmann `assert` is meant to check invariants and contracts, e.g. that the argument to a method isn't `null`. If an assertion fails, an `AssertionError` is thrown which isn't meant to be caught. Thus, an assertion-based test suite will have at most one failing test. A framework like JUnit has a more nuanced approach. It provides abstractions over common tests, and can output a summary, making a statement like “*we now pass 97% of the test suite*” possible. It's also easier to explain *why* a test failed when using such a framework."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T18:24:33.667",
"Id": "72821",
"Score": "0",
"body": "Totally get your point. Thanks for clearing that up. I somehow understood your objection against assert as a general statement."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T15:55:44.067",
"Id": "42315",
"ParentId": "41811",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T16:21:18.563",
"Id": "41811",
"Score": "8",
"Tags": [
"java",
"functional-programming",
"linked-list",
"generics",
"monads"
],
"Title": "Monadic Immutable Linked List in the Least Functional Language Evar"
}
|
41811
|
<p>I have some JavaScript code that allows users to select a plan which triggers the second select box to populate with options. The code works, however, it seems to be very inefficient. Any advice on improving the efficiency? </p>
<p>JavaScript: </p>
<pre><code>var term = 0;
var price = 0;
var additional = 0;
var fix = 0;
var plan = document.getElementById('billing-plan');
plan.addEventListener('change', enableBilling, false);
var select = document.getElementById('billing-price');
select.addEventListener('change', updatePrice, false);
var basic = {
"Option" : ["$200/month for 1-yr", "$250/month"],
"Value" : [300, 350]
}
var prime = {
"Option" : ["$300/month for 1-yr", "$350/month"],
"Value" : [400, 450]
}
var gold = {
"Option" : ["$400/month for 1-yr", "$450/month"],
"Value" : [500, 550]
}
function populateBilling(planName) {
//RESET BILLING PERIOD OPTIONS AND TOTALS
select.options.length = 1;
document.getElementById('payment-total').innerText = 0 + additional;
document.getElementById('payment-rebill').innerText = 0 + additional;
//FILL BILLING PERIOD WITH PLAN OPTIONS AND VALUES
if (planName == "basic") {
for (i = 0; i < basic.Option.length; i++){
var temp = document.createElement('option');
temp.value = basic.Value[i];
temp.text = basic.Option[i];
select.appendChild(temp);
}
} else if (planName == "prime") {
for (i = 0; i < basic.Option.length; i++){
var temp = document.createElement('option');
temp.value = prime.Value[i];
temp.text = prime.Option[i];
select.appendChild(temp);
}
} else {
for (i = 0; i < basic.Option.length; i++){
var temp = document.createElement('option');
temp.value = gold.Value[i];
temp.text = gold.Option[i];
select.appendChild(temp);
}
}
}
function enableBilling(e) {
document.getElementById('billing-price').disabled=false;
var planName = plan.options[plan.selectedIndex].text.toLowerCase();
populateBilling(planName);
}
function updatePrice(e) {
price = parseFloat(select.value);
fix = 100;
if (price == select.options[2].value){
term = 1;
}
document.getElementById('payment-total').innerText = price + additional;
if (price == select.options[2].value){
document.getElementById('payment-rebill').innerText = 0 + additional;
} else {
document.getElementById('payment-rebill').innerText = price + additional - fix;
}
}
</code></pre>
<p>Here it is in a jsfiddle: <a href="http://jsfiddle.net/aGq9q/13/" rel="nofollow">http://jsfiddle.net/aGq9q/13/</a></p>
|
[] |
[
{
"body": "<p>For starters, you can remove a lot of duplicate code from the <code>populateBilling()</code> function like this:</p>\n\n<pre><code>function populateBilling(planName) {\n var options = {\n basic: { \n \"Option\" : [\"$200/month for 1-yr\", \"$250/month\"],\n \"Value\" : [300, 350]\n },\n prime: { \n \"Option\" : [\"$300/month for 1-yr\", \"$350/month\"],\n \"Value\" : [400, 450]\n },\n gold: { \n \"Option\" : [\"$400/month for 1-yr\", \"$450/month\"],\n \"Value\" : [500, 550]\n }\n }\n\n //RESET BILLING PERIOD OPTIONS\n select.options.length = 1;\n document.getElementById('payment-total').innerText = 0 + additional;\n document.getElementById('payment-rebill').innerText = 0 + additional;\n var data = options[planName];\n if (data) {\n for (var i = 0; i < data.Option.length; i++){\n var temp = document.createElement('option');\n temp.value = data.Value[i];\n temp.text = data.Option[i];\n select.appendChild(temp);\n }\n }\n}\n</code></pre>\n\n<p>Working demo: <a href=\"http://jsfiddle.net/jfriend00/e8629/\" rel=\"nofollow\">http://jsfiddle.net/jfriend00/e8629/</a></p>\n\n<p>Here are a couple ideas when looking to simplify code:</p>\n\n<ol>\n<li><p>Any time you see the same pattern of code repeated over and over, figure that you should eliminate that repeated code, either with a common function, a loop or some other technique that makes only one copy of common code.</p></li>\n<li><p>Any time you see an if/else comparing to a bunch of values and then selecting different data based on what matches, consider using the keys of an object to do all the lookup work for you.</p></li>\n<li><p>Any time you don't really need data to persist across function calls, consider moving variables inside a function rather than using globals.</p></li>\n<li><p>Make absolutely sure that all loop variables are declared as local variables. Implicit global variables, particular loop variables are a bad source of hard to find bugs.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T18:04:35.440",
"Id": "71934",
"Score": "0",
"body": "Thanks for the response! I was told that is bad habit to do DOM manipulation inside of a loop. Having said that, any recommendations for appending the drop-downs outside the loop?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T18:10:38.580",
"Id": "71936",
"Score": "0",
"body": "@RyanSalmons - it depends upon what you're doing in the loop. There's no issue with adding two option values inside a loop here. In this case it's the more efficient way of doing it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T17:54:59.390",
"Id": "41817",
"ParentId": "41814",
"Score": "4"
}
},
{
"body": "<p>Same advice as @jfriend00, with an addition: if the user selects the \"Choose Plan\" placeholder, disable the billing period selector.</p>\n\n<pre><code>function populateBilling(planName) {\n //RESET BILLING PERIOD OPTIONS\n select.options.length = 1;\n document.getElementById('payment-total').innerText = 0 + additional;\n document.getElementById('payment-rebill').innerText = 0 + additional;\n //FILL BILLING PERIOD WITH PLAN OPTIONS AND VALUES\n var selectedPlan = plans[planName];\n if (selectedPlan) {\n for (var i = 0; i < selectedPlan.Option.length; i++) {\n var temp = document.createElement('option');\n temp.value = selectedPlan.Value[i];\n temp.text = selectedPlan.Option[i];\n select.appendChild(temp);\n }\n } else {\n document.getElementById('billing-price').disabled = true; // ← This\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Parsing the selection text to get a JavaScript identifier is sketchy. I'd make the value of each option explicit.</p>\n\n<pre><code><option value=\"basic\">Basic</option>\n</code></pre>\n\n<p>etc.</p>\n\n<pre><code>function enableBilling(e) {\n document.getElementById('billing-price').disabled=false;\n var planName = plan.options[plan.selectedIndex].value; // ← This\n populateBilling(planName);\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T06:11:07.733",
"Id": "41854",
"ParentId": "41814",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "41817",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T17:38:57.217",
"Id": "41814",
"Score": "5",
"Tags": [
"javascript"
],
"Title": "Varying a second drop-down's options based on a first selection"
}
|
41814
|
<p>I'm new to programming and also to Java and working on problems in <em>Intro to Java</em> by Robert Sedgewick. Here is my question:</p>
<blockquote>
<p>Connect Four: Given an N-by-N grid with each cell either occupied by
an 'X', an 'O', or empty, write a program to find the longest sequence
of consecutive 'X's either horizontal, vertically, or diagonally. To
test your program, you can create a random grid where each cell
contains an 'X' or 'O' with probability 1/3.</p>
</blockquote>
<p>With many modifications, I came up with some code, which I feel is not efficient. Can someone help make my code more efficient?</p>
<pre><code>public class connectfour {
public static void main(String[] args) {
int N=Integer.parseInt(args[0]),t=0;
String[][] a=new String[N][N];
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
double r=Math.random();
if(r<0.33){a[i][j]="X";t=1;}
else if(r<0.66)a[i][j]="O";
else a[i][j]=".";
System.out.print(a[i][j]+" ");
}
System.out.println();
}
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
if(a[i][j]=="X"){
//to check horizontally
for(int y=j,length=1;y<N-1;y++){
if(a[i][y]!=a[i][y+1])break;
length++;
if(t<length) t=length;}
//to check vertically
for(int x=i,length=1;x<N-1;x++)
{if(a[x][j]!=a[x+1][j])
break;
length++;
if(t<length) t=length;}
//to check diagonally ,right and down
for(int x=i,y=j,length=1;x<N-1&&y<N-1;x++,y++)
{ if(a[x][y]!=a[x+1][y+1])
break;
length++;
if(t<length) t=length; }
}
}
}
for(int i=N-1;i>=0;i--){
for(int j=0;j<N-1;j++){
if(a[i][j]=="X"){
//to check diagonally ,right and up
for(int x=i,y=j,length=1;x>0&&y<N-1;x--,y++)
{if(a[x][y]!=a[x-1][y+1])
break;
length++;
if(t<length) t=length;
}
}
}
}
System.out.println("the length of longest sequence of X in the above array: "+t);
}
}
</code></pre>
<hr>
<p>I want to post my improved code according to instructions given above. I implemented the algorithm suggested by Simon André Forsberg. It is working for all cases.</p>
<pre><code> public class connectfour2 {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]), highestconsecutive = 0;
String string1, string2 = "X", string3;
String[][] board = new String[N][N];
for(int i = 0; i < N; i++ )
{
for(int j = 0; j < N; j++ )
{
double r = Math.random();
if( r < 0.33 ) board[i][j] = "X";
else if( r < 0.66 ) board[i][j] = "O";
else board[i][j] = ".";
System.out.print( board[i][j] + " " );
}
System.out.println();
}
// loopingfor checking horizontally / vertically/diagonally down and right,down and left
for(int i = 0; i < N; i++ )
{ int consecutive1 = 0, consecutive = 0 ;
for(int j = 0; j < N; j++ )
{
// for horizontal check
string1 = board[i][j];
if( string1.equals(string2))
consecutive++;
else
consecutive=0;
if( highestconsecutive < consecutive)
highestconsecutive = consecutive;
// for vertical check
string1=board[j][i];
if(string1.equals(string2))
consecutive1++;
else
consecutive1=0;
if( highestconsecutive < consecutive1)
highestconsecutive = consecutive1;
// looping for diagonal check ,down and right
for( int x = i, y = j, length = 0; x < N && y < N ; x++, y++ )
{
string1 = board[x][y];
if(string1.equals(string2))
length++;
else
length=0;
if(highestconsecutive < length)
highestconsecutive = length;
}
// looping for diagonal check ,down and left
for( int x = i, y = N - j - 1, length = 0; x < N && y >= 0 ; x++, y-- )
{
string1 = board[x][y];
if(string1.equals(string2))
length++;
else
length=0;
if(highestconsecutive < length)
highestconsecutive = length;
}
}
}
System.out.println("the length of longest sequence of X in the above array: "+highestconsecutive);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I'm not a Java programmer, so I won't attempt to mislead you with any specific information. However, I'd really like to address the issues with indentation and whitespace, as a basic thing to writing code. I'll address this using example code.</p>\n\n<hr>\n\n<p><em>Please</em> keep your indentation consistent throughout the code. Although you're a beginner, this is something you should be able to do. It helps your code stay clean for yourself and others. It's most common to indent by four spaces.</p>\n\n<p>For instance, when you open curly braces, the following lines (until the closing brace) should be indented so that it looks like the code \"belongs\" there.</p>\n\n<pre><code>public static void func {\n // first line...\n // second line...\n // n lines...\n}\n</code></pre>\n\n<p>Also, put whitespace between your keywords, operators, operands, and curly braces. It'll help separate them, making it much easier to read them.</p>\n\n<p>Before:</p>\n\n<pre><code>for(i=0;i<10;++i){}\n</code></pre>\n\n<p>After:</p>\n\n<pre><code>for (i = 0; i < 10; ++i) {}\n</code></pre>\n\n<p>Combining the points about indentation and whitespace:</p>\n\n<pre><code>public static void func {\n for (i = 0; i < 10; ++i) {\n for (i = 0; i < 10; ++i) {\n int i = 0;\n i++;\n }\n }\n}\n</code></pre>\n\n<p>Also note from this example that the closing braces are on their own lines. This is preferred for any multi-line placement type, although still done for single-line statements. Opening braces, on the other hand, can still be on the same line as the statement.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T18:18:57.503",
"Id": "41818",
"ParentId": "41815",
"Score": "10"
}
},
{
"body": "<p>Oh dear. Where do we start?</p>\n\n<h2>Formatting</h2>\n\n<p>Formatting is important, because it makes code easier to read. That in turn makes it easier to understand and debug your code. What kind of formatting is recommended? Java has it's own <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html\">Coding Conventions</a> which you can follow. Here is a short summary of a sensible style which I use:</p>\n\n<ul>\n<li>Binary operators like <code>+</code> or <code>=</code> are surrounded by a space.</li>\n<li>The opening braces of a block begin on the same line.</li>\n<li>Closing braces always go on a line of their own, and are vertically aligned under the opening keyword.</li>\n<li>Statements inside a block are indented by one level (4 spaces), and for no other reasons.</li>\n<li>Inside a <code>for</code> loop, the semicolons separating the three statements are followed by a space.</li>\n<li>A keyword that takes a condition in parens has a space before and after the parens.</li>\n<li>Corresponding phrases on different lines are vertically aligned to emphasize their connection.</li>\n</ul>\n\n<p>Using these guidelines, a piece of code like</p>\n\n<pre><code>//to check diagonally ,right and down\n\n for(int x=i,y=j,length=1;x<N-1&&y<N-1;x++,y++)\n { if(a[x][y]!=a[x+1][y+1])\n break;\n length++;\n if(t<length) t=length; }\n</code></pre>\n\n<p>would become</p>\n\n<pre><code>// to check diagonally, right and down\nfor (int x = i, y = j, length = 1; x < N - 1 && y < N - 1; x++, y++) {\n if (a[x][y] != a[x + 1][y + 1]) {\n break;\n }\n length++;\n if (t < length) {\n t = length;\n }\n}\n</code></pre>\n\n<p>This is already much easier to read. If you take care of the “small things” like formatting, it's much more believable that you are also careful with the “big things” like design or algorithms.</p>\n\n<h1>Variable Names</h1>\n\n<p>Good variable names are another way to make code easier to understand. While mathematics have the convention that single-letter variable names should be used, this is <em>not</em> the case in modern programming. A variable should convey the <em>meaning</em> of the data. For example, it would be better to call your <code>a</code> what it is: the <code>board</code>. The <code>r</code> could be <code>random</code>, or a <code>roll</code> (as in dice roll). The <code>t</code> is probably meant to be the <code>longestLength</code>.</p>\n\n<p>I will stop right here, because your code isn't otherwise reviewable in it's current state. If you could make that code work, you can surely also make it <em>beautiful</em>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T02:59:51.613",
"Id": "71988",
"Score": "0",
"body": "thank you amon for your time and suggestions ,surely change my style"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T18:19:04.340",
"Id": "41819",
"ParentId": "41815",
"Score": "12"
}
},
{
"body": "<h3>Introduction</h3>\n<p>Hi and Welcome to Code Review! There are number of things that you can learn today.</p>\n<p>First I would like to say that it is nice that your algorithm works. Thanks for providing a compilable example, that helps a lot.</p>\n<p>Now, secondly, I have to disappoint you: <strong>I will not simply "give you the better code"</strong>. I don't really think you would learn so much from that. However, I can help you in figuring out what things needs to be improved in your current code.</p>\n<h3>List of improvements</h3>\n<h1>YOUR CODE IS NOT READABLE!</h1>\n<p>Sorry for shouting but I am very serious. The importance of code readability cannot be emphasized enough. The readability of your code is severely off.</p>\n<ul>\n<li><p>Indentation: Your indentation is not consistent. Each <code>{</code> should be followed by one extra indentation step, and each <code>}</code> should remove one indentation step.</p>\n</li>\n<li><p>Spacing: It seems like you are always using as few spaces as possible. If you are having serious storage problems and are running out of bytes, then... no, I wouldn't understand it even then...</p>\n<p>Compare</p>\n<pre><code> else if(r<0.66)a[i][j]="O";\n</code></pre>\n<p>with</p>\n<pre><code> else if(r < 0.66) a[i][j] = "O";\n</code></pre>\n<p>And compare</p>\n<pre><code> for(int x=i,y=j,length=1;x<N-1&&y<N-1;x++,y++)\n</code></pre>\n<p>with</p>\n<pre><code> for (int x = i, y = j, length = 1; x < N - 1 && y < N - 1; x++, y++)\n</code></pre>\n<p>Spacing is good for you. One space after each comma, one after semicolon, one before & after <code>=</code> and <code>&&</code>. Makes things so much readable. OrhowwouldyoulikeitifIwrotemyreviewlikethis,withoutusingspacesatall? (I hope that example made things clear why spacing is good).</p>\n</li>\n</ul>\n<p>Please read up on the <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html\" rel=\"noreferrer\">Java coding conventions</a>, all these things are mentioned there.</p>\n<p>Once you have learned how to improved those, if you are using an IDE such as <a href=\"http://www.eclipse.org\" rel=\"noreferrer\">Eclipse</a>, which I hope that you do - if you are not I really suggest that you download Eclipse now. Press Ctrl + Shift + F in Eclipse to make it format for you. If you are using NetBeans, press Alt + Shift + F.</p>\n<ul>\n<li>Variable names: <strong>All</strong> (except one) of your variable names is only one character. Try to have self-documenting variable names. What is the variable used for? <code>row</code> and <code>col</code> could be better names than <code>i</code> and <code>j</code>. <code>t</code> could be called <code>maximumFoundLength</code>.</li>\n</ul>\n<h3>String comparison</h3>\n<p>It is more or less pure luck that your code works at all. Thanks to Java only creating one String instance for <code>"X"</code> and such, it works with comparing your Strings with <code>==</code>. However, if you would have any user input, this wouldn't work. <code>==</code> compares <strong>object references</strong>, to compare Strings correctly in Java you should use the <code>.equals</code> method. Please see the Stack Overflow question <a href=\"https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java\">"How do I compare Strings in Java?"</a></p>\n<h3>Limited number of possible values --> Enum</h3>\n<p>Since the possible values of your board is very limited, you can use an <code>enum</code> instead of a String to store the value of the positions.</p>\n<pre><code>public enum BoardValue {\n X, O, EMPTY; // _ for empty positions\n @Override\n public String toString() {\n return this == EMPTY ? "." : this.name();\n }\n}\n</code></pre>\n<p>Now make your <code>String[][] a</code> into <code>BoardValue[][] board</code>, which will make it much better to use in the long run.</p>\n<h3>Classes, Methods and Objects</h3>\n<p>Java is an object-oriented programming language. I think you can learn a lot by reading Oracle's Java <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/\" rel=\"noreferrer\">Lesson: Classes and Objects</a>. I would suggest that you make your game board into a <strong>class</strong>. Your current <code>String[][] a=new String[N][N];</code> should be a <strong>field</strong> in the class.</p>\n<p>This class could then have several <strong>methods</strong>:</p>\n<ul>\n<li><code>void randomize()</code>: Randomizes new data in to the board.</li>\n<li><code>void output()</code>: Print the information to System.out.</li>\n<li><code>int findConsecutive(String lookingFor)</code>: Scan the board for the largest consecutive of the specified String.</li>\n</ul>\n<h3>Your algorithm</h3>\n<p>Your current algorithm works by looping through the entire two-dimensional board and for each position it does the following:</p>\n<ul>\n<li>Remember the value of the current position, we can call this "current"</li>\n<li>Loop through the rest of this row/column/diagonal</li>\n<li>When you encounter a position that is not equal to "current", you break this loop.</li>\n</ul>\n<p>This is highly inefficient because you are checking each tile way too many times than you need. Instead, you should treat each row/column/diagonal like an individual line of positions. Consider this algorithm:</p>\n<ul>\n<li><code>searchingFor</code> is the value you want to search for (<code>"X"</code> or <code>"O"</code>)</li>\n<li>Initialize the value <code>consecutive</code> to 0.</li>\n<li>Initialize the value <code>highestConsecutive</code> to 0.</li>\n<li>For each row/column/diagonal, loop through the positions in the line and check for <code>searchingFor</code>\n<ul>\n<li>When you encounter this value, you do the following:\n<ul>\n<li>increase <code>consecutive</code> by 1.</li>\n<li>If <code>consecutive</code> is more than <code>highestConsecutive</code>, set <code>highestConsecutive</code> to the value of <code>consecutive</code>.</li>\n</ul>\n</li>\n<li>If the value did not match, reset <code>consecutive</code> to 0.</li>\n</ul>\n</li>\n<li>Once the loop is finished, <code>highestConsecutive</code> is the highest consecutive number for this current row/column/diagonal.</li>\n</ul>\n<p>Regarding diagonals, you can loop through those by starting at a position on <strong>the edge</strong> of the board and do the loop once in a straight diagonal line, like the following.</p>\n<p><img src=\"https://i.stack.imgur.com/Q3st5.png\" alt=\"enter image description here\" /></p>\n<p>Start at all positions where x=0 or y=0 and loop on each square in a bottom-right manner.</p>\n<p>Then to the same for the other direction, you will have to start at x=MAX and y=0 and loop on each square in the bottom-left direction.</p>\n<p><strong>One final thing:</strong></p>\n<p>When you have improved your code, please come back here and post your improved version (also pointing us to this question).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T16:04:35.127",
"Id": "72111",
"Score": "0",
"body": "thank you sir, i understood my fault ,i was checking each individual many times and able to change for horizontal and vertical checks but finding difficult in checking diagonally. can you be more specific about looping for diagonals? thank you once again sir"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:27:07.070",
"Id": "72123",
"Score": "1",
"body": "@user3300600 Added a little description and a picture on how you could do the diagonal looping."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T23:45:32.893",
"Id": "72205",
"Score": "1",
"body": "Insteadofcodinglikethis whyNotTryThis?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T18:19:18.580",
"Id": "41820",
"ParentId": "41815",
"Score": "22"
}
}
] |
{
"AcceptedAnswerId": "41820",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T17:39:50.360",
"Id": "41815",
"Score": "11",
"Tags": [
"java",
"beginner",
"connect-four"
],
"Title": "Find longest sequence horizontally, vertically or diagonally in Connect Four game"
}
|
41815
|
<p>I have a population (<code>Pop</code>) which has an attribute which is a list of individuals (<code>Ind</code>) where each individual has an attribute which is a list of chromosomes (<code>Chromo</code>). Each chromosome is a list of numbers which tells about the fitness (=reproductive success, the fitness is obtain by multiplying all numbers of a all chromosomes) of the individuals. Within one position on the chromosome, there are different values for the different individuals. I'd like to set the greatest value to 1 and the others to keep their relative value in comparison to the biggest value.</p>
<p>For example, if on one position on the n-th chromosome, the individuals in the population have the values [3,4,0.4,12,5,6] (that would be a case of a population of 6 individuals).</p>
<p>I'd like to set these value to:</p>
<pre><code>a = [3,4,0.4,12,5,6]
[i/float(max(a)) for i in a]
</code></pre>
<p>I tried to create this function but I got lost and can hardly find out a solution in all these lists!</p>
<p>You can reach the 14th of the 4th chromosome in the 25th individual by writing:</p>
<pre><code>population.inds[24].chromosomes[3].alleles[13]
</code></pre>
<p>To make sure my aim is understood. I'd like to create a function which take an instance of <code>Pop</code> as argument and return the same or another <code>Pop</code> where all positions on the chromosomes are replaced by numbers in the range [0,1] respecting the relative values of all numbers at the same position on the same chromosome in the population.</p>
<p>Below is my code (it is long but reading the constructor of the classes <code>Chromo</code>, <code>Ind</code> and <code>Pop</code> (which are all impressively basic) should, I hope, be enough. The class <code>WalkerRandomSampling</code> serve only the purpose of performing a random weighted sampling).</p>
<p>One might have a look to what I tried, the method is called <code>set_best_fitness_to_one</code> and is within the <code>Pop</code> class.</p>
<pre><code>from random import uniform, gauss, choice, expovariate, shuffle
from numpy import arange, array, bincount, ndarray, ones, where
from numpy.random import seed, random, randint, binomial
from operator import mul, methodcaller
class WalkerRandomSampling(object):
"""Walker's alias method for random objects with different probablities.
Based on the implementation of Denis Bzowy at the following URL:
http://code.activestate.com/recipes/576564-walkers-alias-method-for-random-objects-with-diffe/
"""
def __init__(self, weights, keys=None):
"""Builds the Walker tables ``prob`` and ``inx`` for calls to `random()`.
The weights (a list or tuple or iterable) can be in any order and they
do not even have to sum to 1."""
n = self.n = len(weights)
if keys is None:
self.keys = keys
else:
self.keys = array(keys)
if isinstance(weights, (list, tuple)):
weights = array(weights, dtype=float)
elif isinstance(weights, ndarray):
if weights.dtype != float:
weights = weights.astype(float)
else:
weights = array(list(weights), dtype=float)
if weights.ndim != 1:
raise ValueError("weights must be a vector")
weights = weights * n / weights.sum()
inx = -ones(n, dtype=int)
short = where(weights < 1)[0].tolist()
long = where(weights > 1)[0].tolist()
while short and long:
j = short.pop()
k = long[-1]
inx[j] = k
weights[k] -= (1 - weights[j])
if weights[k] < 1:
short.append( k )
long.pop()
self.prob = weights
self.inx = inx
def random(self, count=None):
"""Returns a given number of random integers or keys, with probabilities
being proportional to the weights supplied in the constructor.
When `count` is ``None``, returns a single integer or key, otherwise
returns a NumPy array with a length given in `count`.
"""
if count is None:
u = random()
j = randint(self.n)
k = j if u <= self.prob[j] else self.inx[j]
return self.keys[k] if self.keys is not None else k
u = random(count)
j = randint(self.n, size=count)
k = where(u <= self.prob[j], j, self.inx[j])
return self.keys[k] if self.keys is not None else k
def test(self):
weights = [12,3,2,0,5]
test = WalkerRandomSampling(weights=weights)
a = []
for i in xrange(10000):
a.append(test.random())
b = []
for value in range(4):
b.append(len([i for i in a if i == value])/float(len(a)))
print b
print weights
class Chromo(object):
def __init__(self, alleles):
self.alleles=alleles
def mutations(self):
nb_mut = binomial(chromo_size, mut_rate)
for one_mut in xrange(nb_mut):
self.alleles[choice(range(chromo_size))] *= pdf_mutation(pdf_mut_scale)
return self
class Ind(object):
def __init__(self, chromosomes):
self.chromosomes = chromosomes
def fitness(self):
if nb_chromosomes == 1:
return reduce(mul, self.chromosomes[0].alleles)
fit = 1
for gene_pos in xrange(chromo_size):
alleles = []
for chromo_pos in range(len(self.chromosomes)):
alleles.append(self.chromosomes[chromo.pos].alleles[gene_pos])
fit *= sum(alleles)/len(alleles) # + dominance effect. Epistasis?!
return fit
def reprod(self,other):
off = Ind(chromosomes = [])
for one_chromo in xrange(nb_chromosomes):
# recombination. Because the population has been shuffled, it is not necessary to create two recombined chromosomes and that select one (segragation). I construct only one recombined chromosome where self construct the first part of the chromosome.
nb_cross = binomial(chromo_size, recombination)
cross_pos = WalkerRandomSampling([1]*(chromo_size-1)).random(count=nb_cross).sort()
recombined_chromo = Chromo([])
previous_cross = 0
for sex, one_cross in enumerate(cross_pos):
if sex%2 == 0:
recombined_cromo.alleles.append(self.chromosomes.alleles[previous_cross:(one_cross+1)])
else:
recombined_cromo.alleles.append(other.chromosomes.alleles[previous_cross:(one_cross+1)])
previous_cross = one_cross
off.chromosomes.append(recombined_chromo)
return off
class Pop(object):
def __init__(self, inds):
self.inds = inds
def reproduction(self):
"First chose those that reproduce and then simulate mutations in offsprings"
# chosing those who reproduce - Creating the offspring population
new_pop = Pop(inds=[])
fitness = []
for one_ind in self.inds:
fitness.append(one_ind.fitness())
min_fitness = min(fitness)
if min_fitness < 0:
fitness = [one_ind - min_fitness for one_ind in fitness]
pick = WalkerRandomSampling(weights = fitness)
if nb_chromosomes == 1 and recombination == 0:
for i in xrange(pop_size):
new_pop.inds.append(self.inds[pick.random()])
else:
for i in xrange(pop_size):
father = self.inds[pick.random()]
mother = self.inds[pick.random()]
off = father.reprod(mother)
new_pop.inds.append(off)
nb_off += 1
# Mutations
for one_ind in new_pop.inds:
for chromo_number in xrange(nb_chromosomes):
one_ind.chromosomes[chromo_number].mutations()
return new_pop
def create_population(self):
one_chromo = Chromo(alleles = [1]*chromo_size)
one_ind = Ind(chromosomes = [one_chromo for i in range(nb_chromosomes)])
return Pop(inds=[one_ind for i in xrange(pop_size)])
def stats(self, generation):
line_to_write = str(generation) + '\t' + str(replicat) + '\t' + str(mut_rate) + '\t' + str(pdf_mut_scale) + '\t' + str(pdf_mutation.__name__)\
+ '\t' + str(pop_size) + '\t' + str(nb_chromosomes) + '\t' + str(chromo_size) + '\t' + str(recombination) + '\t' + str(dominance) + '\t'
if output_type == 'mean fitness':
add = sum([ind.fitness() for ind in self.inds])/pop_size
output_file.write(line_to_write + str(add) + '\n')
def set_best_fitness_to_one(self):
list_chromo = zip(*[map(fun_for_set_fitness,[ind.chromosomes[chromo_number] for ind in self.inds]) for chromo_number in xrange(nb_chromosomes)])
new_pop = Pop([])
for one_ind in xrange(0,pop_size,nb_chromosomes):
new_pop.inds.append(list_chromo[one_ind:(ond_ind+nb_chromosomes)])
return new_pop
def fun_for_set_fitness(list_one_chromo_number):
l = zip(*list_one_chromo_number)
for locus_pos, one_locus in enumerate(l):
max_one_locus = max(one_locus)
one_locus = [i/float(max_one_locus) for i in one_locus]
l[locus_pos] = one_locus
return zip(*l)
######### Main #############
def main_run():
population = Pop([]).create_population()
for generation in xrange(Nb_generations):
population.stats(generation)
population = population.reproduction()
shuffle(population.inds)
population = population.set_best_fitness_to_one()
####### PARAMETERS ##########
# Parameters
Nb_generations = 120
# output_type = 'all individuals fitness'
output_type = 'mean fitness'
max_pop_size = 100 # this is only used to create the first (title, header) line!
# Output file
file_name = 'stats3.txt'
path = '/Users/remimatthey-doret/Documents/Biologie/programmation/Python/Fitness distribution in the population/' + file_name
output_file = open(path,'w')
first_line = 'Generation\treplicat\tmut_rate\tpdf_mut_scale\tpdf_mutation\tpop_size\tnb_chromosomes\tchromo_size\trecombination\tdominance\t'
if output_type == 'mean fitness':
first_line += 'mean_fitness'
if output_type == 'all individuals fitness':
for ind in xrange(max_pop_size):
first_line += 'fit_ind_' + str(ind) + '\t'
output_file.write(first_line + '\n')
# Parameters that iterate
total_nb_runs = 3 * 10 # just enter the total number of iteration of the main_run function
nb_runs_performed = 0
for mut_rate in [0.0001]:
for pdf_mut_scale in [0.01,0.1,0.3]: # Note: with an negative exponential distribution (expovariate) the expected value is 1/lambda
for pdf_mutation in [expovariate]:
for pop_size in [1000]:
for nb_chromosomes in [1]:
for chromo_size in [1000]:
for recombination in [0]:
for dominance in [0]:
for replicat in xrange(10):
main_run()
nb_runs_performed += 1
print str(float(nb_runs_performed)/total_nb_runs * 100) + '%'
</code></pre>
|
[] |
[
{
"body": "<p>Some advice here:</p>\n\n<ul>\n<li>You should try to follow the PEP 8 guidelines whenever it's possible. In your case, the naming convention is not followed.</li>\n<li>You should try to keep things simple. For instance, in <code>WalkerRandomSampling.__init__()</code>, it seems like you are doing a bit of logic to handle cases when <code>keys</code> is None and cases when it's not but at the end, you never init a <code>WalkerRandomSampling</code> with keys so it's quite hard to tell whether this is useful at all.</li>\n<li>Don't repeat yourself. It seems like the beginning of <code>WalkerRandomSampling.random()</code> is roughly the same no matter if <code>count is None</code> or not. The common code could be factorised out.</li>\n<li><p>Don't repeat yourself. The branches in:</p>\n\n<pre><code> previous_cross = 0\n for sex, one_cross in enumerate(cross_pos):\n if sex%2 == 0:\n recombined_cromo.alleles.append(self.chromosomes.alleles[previous_cross:(one_cross+1)])\n else:\n recombined_cromo.alleles.append(other.chromosomes.alleles[previous_cross:(one_cross+1)])\n previous_cross = one_cross\n</code></pre>\n\n<p>look way too similar. It probably would be better to write :</p>\n\n<pre><code> previous_cross = 0\n for sex, one_cross in enumerate(cross_pos):\n relevant_ind = other if sex%2 else self\n recombined_cromo.alleles.append(relevant_ind.chromosomes.alleles[previous_cross:(one_cross+1)])\n previous_cross = one_cross\n</code></pre></li>\n<li><p>Use list (or set or dict) comprehension whenever you can.</p>\n\n<pre><code>a = []\nfor i in xrange(10000):\n a.append(test.random())\nb = []\nfor value in range(4):\n b.append(len([i for i in a if i == value])/float(len(a)))\n</code></pre>\n\n<p>could be written :</p>\n\n<pre><code>a = [test.random() for i in xrange(10000)]\nb = [len([value for i in a if i == value])/float(len(a)) for value in range(4)]\n</code></pre>\n\n<p>and the second line can actually be written differently so that we have :</p>\n\n<pre><code>a = [test.random() for i in xrange(10000)]\nb = [a.count(value)/float(len(a)) for value in range(4)]\n</code></pre>\n\n<p>Similarly :</p>\n\n<pre><code> alleles = []\n for chromo_pos in range(len(self.chromosomes)):\n alleles.append(self.chromosomes[chromo.pos].alleles[gene_pos])\n</code></pre>\n\n<p>can be written :</p>\n\n<pre><code> alleles = [self.chromosomes[chromo.pos].alleles[gene_pos] for chromo_pos in range(len(self.chromosomes)]\n</code></pre>\n\n<p>and you could simplify the way you iterate :</p>\n\n<pre><code> alleles = [c.alleles[gene_pos] for c in self.chromosomes]\n</code></pre>\n\n<p>And :</p>\n\n<pre><code>fitness = []\nfor one_ind in self.inds:\n fitness.append(one_ind.fitness())\n</code></pre>\n\n<p>could become :</p>\n\n<pre><code>fitness = [one_ind.fitness() for one_ind in self.inds]\n</code></pre></li>\n<li><p>Do not build strings using concatenations multiple times. The recommended way is to use <code>join</code>:</p>\n\n<pre><code>for ind in xrange(max_pop_size):\n first_line += 'fit_ind_' + str(ind) + '\\t'\n</code></pre>\n\n<p>could be written as:</p>\n\n<pre><code>first_line += '\\t'.join('fit_ind_' + str(ind) for ind in xrange(max_pop_size))\n</code></pre>\n\n<p>(Also, that will not add the useless <code>\\t</code> at the end)</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T09:35:55.920",
"Id": "41865",
"ParentId": "41821",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41865",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T18:28:14.923",
"Id": "41821",
"Score": "5",
"Tags": [
"python",
"object-oriented",
"bioinformatics"
],
"Title": "Case study with a biological populations: a list of lists of lists"
}
|
41821
|
<pre><code>types = [
{ name: "Feature"}
{ name: "Enhancement"}
{ name: "Bug"}
{ name: "Spike"}
]
buildIndex = (source, property) ->
array = []
array[prop[property]] = prop for prop in source
array
buildIndex types, 'name'
</code></pre>
<p>Result:</p>
<pre><code>[Feature: Object, Enhancement: Object, Bug: Object, Spike: Object]
Bug: Object
Enhancement: Object
Feature: Object
name: "Feature"
Spike: Object
</code></pre>
<p>This is my ugly code. How to refactor this? My problem is the <code>buildIndex</code> function. Iyt works, but it isn't elegant.</p>
|
[] |
[
{
"body": "<p>There's something fishy here. You're creating an array, but you're not using it as one. You're simply adding named properties to it, like you can with any object. In the end, you're left with an array that still has a length of zero. So I'm betting you don't actually want an array at all.</p>\n\n<p>And in that case, I'd rewrite it to this</p>\n\n<pre><code>buildIndex = (source, property) ->\n obj = {}\n obj[prop[property]] = prop for prop in source\n obj\n</code></pre>\n\n<p>No more array-nonsense. However, if this is indeed what you're going for, then that's pretty much it. I agree it doesn't look particularly elegant, but it's about as good as it gets with basic CoffeeScript.</p>\n\n<p>However, you could use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce\" rel=\"nofollow\"><code>reduce</code></a>, if you're targeting browsers that support it (or Node.js):</p>\n\n<pre><code>buildIndex = (source, property) ->\n source.reduce (obj, item) ->\n obj[item[property]] = item\n obj\n , {}\n</code></pre>\n\n<p>but as you can see, the callback-first style of <code>reduce</code> means you end up with a dangling comma and argument instead, which isn't terribly neat either.</p>\n\n<p>Alternatively, if you're using something like <a href=\"http://underscorejs.org\" rel=\"nofollow\">underscore.js</a>, you can use a <code>groupBy</code> function to do this for you</p>\n\n<pre><code>buildIndex = (source, property) ->\n _.groupBy source, (item) -> item[property]\n</code></pre>\n\n<p>Looks better, although it's merely hiding the same code as above.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T08:17:19.740",
"Id": "72021",
"Score": "0",
"body": "Many thanks Flambino. underscore version is very elegant, but prefere use only coffescript ... replace array with object it's correct."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T01:24:41.140",
"Id": "41839",
"ParentId": "41822",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41839",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T18:44:35.413",
"Id": "41822",
"Score": "4",
"Tags": [
"coffeescript"
],
"Title": "Refactor array for loop result"
}
|
41822
|
<p>I'm currently creating a ASP.NET MVC page in C#.</p>
<p>I want to hide everything regarding the creation of our "models" and "viewmodels". </p>
<p>I have seen much of the fancy stuff regarding Dependency Injection as well as Action Filters, Custom Controllers and so on! But the people I work with are pretty new to this so I want it to keep it dead simple, but I still want to avoid all the new statement and keep the controller really lightweight. </p>
<p>Please advise me if I'm doing this the wrong way, and be constructive.</p>
<p><strong>Factory Class</strong></p>
<pre><code> public class Factory
{
public T BuildViewModel<T>() where T : class, new()
{
IViewModel<T> iVmInterf = (IViewModel<T>)Activator.CreateInstance<T>();
return iVmInterf.getViewModel();
}
}
</code></pre>
<p><strong>IViewModel InterFace</strong></p>
<pre><code> interface IViewModel<T>
{
T getViewModel();
}
</code></pre>
<p><strong>interface IProductViewModel</strong></p>
<pre><code>interface IProductViewModel
{
int ProductCost { get; }
string ProductName { get; }
}
</code></pre>
<p><strong>class ProductViewModel</strong></p>
<pre><code>class ProductViewModel : IViewModel<ProductViewModel>, IProductViewModel
{
private int _productCost;
private string _productName;
private IProductViewModel interf;
int IProductViewModel.ProductCost
{
get { return _productCost; }
}
string IProductViewModel.ProductName
{
get { return _productName; }
}
ProductViewModel IViewModel<ProductViewModel>.getViewModel()
{
return this;
}
}
</code></pre>
<p><strong>Usage in controller</strong></p>
<pre><code>Factory fact = new Factory();
IProductViewModel vmdl = fact.BuildViewModel<ProductViewModel>();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T21:11:57.237",
"Id": "71944",
"Score": "1",
"body": "How complex is the ViewModel -> Model mapping? Mapping tools such as AutoMapper can typically do most of what you are after."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T21:25:56.233",
"Id": "71945",
"Score": "0",
"body": "@dreza no that complex, but I want everybody to everything.. I like Automapper, but I want do do it myself ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-18T09:47:58.313",
"Id": "134565",
"Score": "0",
"body": "What's the motivation for avoiding `new` in this case?"
}
] |
[
{
"body": "<p><strong>Var</strong></p>\n\n<p>Use <code>var</code> for method-scope declarations when the right-hand side of the declaration makes the type obvious. This gives you the convenience during refactoring of being able to change the type in just one place.</p>\n\n<p>e.g.</p>\n\n<pre><code>IViewModel<T> iVmInterf = (IViewModel<T>)Activator.CreateInstance<T>();\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>var iVmInterf = (IViewModel<T>)Activator.CreateInstance<T>();\n</code></pre>\n\n<p><strong>Naming</strong></p>\n\n<p>You should not include hints about the type of a variable in its name, unless the variable only makes sense with that name. Additionally you should not abbreviate names, abbreviating names makes your code harder to read for no positive benefit.</p>\n\n<p>e.g.</p>\n\n<pre><code>IViewModel<T> iVmInterf\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>IViewModel<T> viewModel\n</code></pre>\n\n<p>and</p>\n\n<pre><code>private IProductViewModel interf;\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>private IProductViewModel viewModel;\n</code></pre>\n\n<p><strong>Design</strong></p>\n\n<p>Why does <code>ProductViewModel</code> contain an instance variable of type <code>IProductViewModel</code> when it itself implements <code>ProductViewModel</code>? It doesn't appear to be used anywhere and it doesn't make obvious sense why a view model would need a reference to another view model of the same type.</p>\n\n<p><code>IViewModel<T></code> takes an instance of itself for <code>T</code>, which I do not agree with from a design perspective. It doesn't make as much sense to say \"A view model for product view models\" than it does to say \"A view model for products\". As such I'd recommend making <code>T</code> refer to the model type the view model is for.</p>\n\n<p>Secondly, IViewModel's one method seems entirely useless. Imagine the scenario in which you want to call <code>GetViewModel</code>. Every time you call that method, you will be doing so with an instance of that viewmodel. It's a wasted call, you already have that data.</p>\n\n<p>With that in mind, your factory method becomes one line:</p>\n\n<pre><code>public T BuildViewModel<T>() where T : class, new()\n{\n return Activator.CreateInstance<T>();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-18T09:47:34.257",
"Id": "74035",
"ParentId": "41825",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "74035",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T20:29:18.323",
"Id": "41825",
"Score": "3",
"Tags": [
"c#",
"design-patterns",
"asp.net-mvc-4",
"controller"
],
"Title": "What can I do better in this ViewModel Creator?"
}
|
41825
|
<p><img src="https://i.stack.imgur.com/mckF3.png" alt="Banner"></p>
<p>Some time ago I started with a small Ruby project. I call it <code>social_aggregator</code>.
This software aggregates information from different networks to one xml-stream, which you can reuse. For instance on your personal website to show some of your activity to your audience or as your personal news feed.</p>
<p>I've a built in <code>Webrick</code> server, while I also want to support any other rack based server. So I have this two entry/start points:</p>
<p><code>config.ru</code>:</p>
<pre><code>$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'Aggregator'
require 'conf/router'
# Run aggregator
app = Thread.new{ Aggregator.new }
app.run
use ActiveRecord::ConnectionAdapters::ConnectionManagement
use ActiveRecord::QueryCache
run Router.map
</code></pre>
<p>And the <code>Aggregator.rb</code>:</p>
<pre><code>$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'conf/initializers/DatabaseInitializer'
require 'conf/initializers/ConsoleInitializer'
require 'app/plugins/PluginManager'
require 'app/utils/ArgumentParser'
require 'app/utils/Logging'
require 'app/utils/Setting'
# Main class
class Aggregator
include Logging
include Setting
# The version constant
AGGREGATOR_VERSION = '0.0.1' unless const_defined?(:AGGREGATOR_VERSION)
# Stores the environment
@@environment = :production
# Stores the run state
@@stop = false
# Initialize the whole system
def initialize(internal_server = false, arguments = [])
options = ArgumentParser.parse(arguments)
Logging::environment options.environment
# Set up logger
if options.quiet
Logging::quiet = true
end
logger.info 'Starting up aggregator now'
# Set environment to setting
logger.info "Using #{options.environment} environment"
@@environment = options.environment
# Connect database with orm
DatabaseInitializer.new(options.environment)
unless options.environment == :test || options.console
# Set up plugin manager
@@plugin_manager = PluginManager.new
if internal_server
require 'conf/initializers/ServerInitializer'
# Spawn new server
ServerInitializer.new
end
logger.info "Aggregator is up and running"
Signal.trap("SIGINT") do
Thread.current.exit
end
start
end
if options.console
ConsoleInitializer.new(options.environment)
end
end
# Returns the current environment
def self.environment
@@environment
end
# Returns the version number
def self.version
AGGREGATOR_VERSION
end
# Returns the plugin manager
def self.plugin_manager
@@plugin_manager
end
# Shutdown the system
def self.shutdown
@@stop = true
end
private
# Starts the aggregation
def start
@@plugin_manager.run
if @@stop
logger.info "Stopping aggregation now, due request to stop."
return
end
logger.debug "Aggregation done. Next aggregation in #{setting.aggregate_timer} seconds."
sleep setting.aggregate_timer
start
end
end
# Initialize aggregator
if __FILE__ == $PROGRAM_NAME
app = Aggregator.new(true, ARGV)
end
</code></pre>
<p>Is that a good way to realize a built in server as well as support for other app server?
If you're interested in the project, you can find it here: <a href="https://github.com/openscript/social_aggregator" rel="nofollow noreferrer">https://github.com/openscript/social_aggregator</a></p>
|
[] |
[
{
"body": "<p>You can see the answer to <a href=\"https://codereview.stackexchange.com/questions/41830/implementing-plugins-in-my-ruby-social-aggregator-app\">Implementing plugins in my Ruby social aggregator app</a> to see some general observations on your code style.</p>\n\n<p>The most important thing I have to point out on this code is that your run loop is not a loop, but a recursion. This is especially bad, since it will eventually kill your whole application on a <code>StackOverflow</code> exception (pun?)</p>\n\n<p>You should always use iteration over recursion when the loop is infinite:</p>\n\n<pre><code>def start\n until @@stop\n @@plugin_manager.run\n\n logger.debug \"Aggregation done. Next aggregation in #{setting.aggregate_timer} seconds.\"\n\n sleep setting.aggregate_timer\n end\nend\n</code></pre>\n\n<p>Also, you seem to mix instance scope and class scope. You allow for multiple <code>Aggregator</code>s, but there is only a single <code>shutdown</code>. Either design your class for multiple uses, in which case state and methods should be of the instance, or that it is a <code>Singleton</code>, for which there are <a href=\"http://dalibornasevic.com/posts/9-ruby-singleton-pattern-again\" rel=\"nofollow noreferrer\">patterns in ruby</a>.</p>\n\n<p>You seem to have a lot of comments in your code. Ruby encourages less comments, and more expressive method names. There is no point in a comment, if it does not add anything to the code itself. This code:</p>\n\n<pre><code># Initialize aggregator\napp = Aggregator.new(true, ARGV)\n</code></pre>\n\n<p>has no advantage to simply writing</p>\n\n<pre><code>app = Aggregator.new(true, ARGV)\n</code></pre>\n\n<p>Using static members (<code>@@stop</code>) is also not advisable. If you are writing inside the <code>self</code> scope (inside <code>def self.shutdown</code>) simple members (<code>@stop</code>) are actually in the class scope, being effectively static. To access them from outside this scope, add a getter:</p>\n\n<pre><code>def self.stop\n @stop\nend\n</code></pre>\n\n<p>Which will be accessible by calling <code>Aggregator.stop</code>.</p>\n\n<p>Refactored <code>Aggregator</code>:</p>\n\n<pre><code>class Aggregator\n include Logging\n include Setting\n\n AGGREGATOR_VERSION = '0.0.1'\n\n def self.version\n AGGREGATOR_VERSION\n end\n\n attr_reader :environment, :plugin_manager, :stop\n\n def initialize(internal_server = false, arguments = [])\n options = ArgumentParser.parse(arguments)\n\n Logging::environment options.environment\n Logging::quiet = true if options.quiet\n\n logger.info 'Starting up aggregator now'\n\n logger.info \"Using #{options.environment} environment\"\n @environment = options.environment\n\n DatabaseInitializer.new(options.environment)\n\n return if options.environment == :test\n\n if options.console\n ConsoleInitializer.new(options.environment)\n else\n @plugin_manager = PluginManager.new \n\n ServerInitializer.new if internal_server\n\n logger.info \"Aggregator is up and running\"\n\n Signal.trap(\"SIGINT\") do\n Thread.current.exit\n end\n\n start\n end\n end\n\n def shutdown\n @stop = true\n end\n\n private\n\n def start\n until stop\n @plugin_manager.run\n\n logger.debug \"Aggregation done. Next aggregation in #{setting.aggregate_timer} seconds.\"\n sleep setting.aggregate_timer\n end\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T18:07:08.473",
"Id": "72613",
"Score": "0",
"body": "Thank you for this great review. I've no clue, why I can't replace my static members with getters and setters. When I access them via a static getter method they are always `nil`.\nhttps://github.com/openscript/social_aggregator/blob/master/aggregator.rb"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T18:08:20.307",
"Id": "72614",
"Score": "0",
"body": "What I still wonder, if it's a good idea to have this built in Webrick server beside my `config.ru`. What do you think about it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T18:34:13.487",
"Id": "72619",
"Score": "0",
"body": "@Sam - read my answer carefully about using static members - you should not use the `@@` directive anywhere - to assign to the class variables call the setter (`Aggregator.stop='my_version'`), and it should work. Getters and setters in the class scope (`def self.stop=`) will set `@stop` to the class, not the instance, and vice versa."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T18:37:09.170",
"Id": "72620",
"Score": "0",
"body": "I would _not_ recommend using `Webrick` for anything but the development phase. Choose your webserver according to your application's sizing requirements. The simplest webserver I would advise you to look at is `thin`. See also http://stackoverflow.com/questions/10859671/webrick-as-production-server-vs-thin-or-unicorn"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T16:40:22.803",
"Id": "41895",
"ParentId": "41828",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "41895",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T22:11:34.983",
"Id": "41828",
"Score": "3",
"Tags": [
"ruby"
],
"Title": "Booting up my Ruby social aggregator app"
}
|
41828
|
<p><img src="https://i.stack.imgur.com/mckF3.png" alt="Banner"></p>
<p>Some time ago I started with a small Ruby project. I call it <code>social_aggregator</code>.
This software aggregates information from different networks to one xml-stream, which you can reuse. For instance on your personal website to show some of your activity to your audience or as your personal news feed.</p>
<p>I've written something like a plugin interface and a manager, which loads the plugin during the boot up process. A plugins aggregates data from a social network or another data source. One plugin per data source.</p>
<p>There is a <code>PluginFrame.rb</code>, which provides the interface and generalize some plugin functionality:</p>
<pre><code>require 'celluloid'
require 'digest/md5'
require 'app/models/Plugin'
require 'app/models/Action'
require 'app/models/Log'
require 'app/models/Message'
require 'app/models/MessageCategory'
require 'app/models/Follower'
require 'app/utils/Logging'
require 'app/utils/Setting'
class PluginFrame
include Setting
include Logging
include Celluloid
finalizer :unload
def initialize(plugin_model)
@plugin = plugin_model
settings_path @plugin.conf_path
logger.info "The plugin #{@plugin.name} has been initialized."
end
def run
logger.warn "The plugin #{@plugin.name} is not implemented!"
terminate
end
def unload
logger.warn "The plugin #{@plugin.name} is terminating!"
end
protected
# Returns a persisted action by given name
def get_action(name)
Action.find_or_create_by!(name: name, plugin: @plugin)
end
# Return whether last action occurance was before given time
def action_ready?(action, timer)
time_since_last_occurance = action.last_occurance
unless time_since_last_occurance.nil? || time_since_last_occurance > timer
logger.info "Possible aggregation in #{timer - time_since_last_occurance} seconds."
return false
end
return true
end
end
</code></pre>
<p>The <code>PluginManager.rb</code> checks if a plugin is valid and loads them:</p>
<pre><code>require 'celluloid'
require 'app/models/Plugin'
require 'app/utils/Logging'
require 'app/utils/Setting'
require 'app/plugins/PluginValidator'
require 'app/plugins/PluginWorker'
class PluginManager
include Logging
include Setting
include Celluloid
# Stores all valid plugin models
@plugin_definitions
# Stores all plugin instances (threads)
@plugin_instances
def initialize
logger.info 'Initializing plugin manager'
@plugin_definitions = []
@plugin_instances = []
initialize_plugins
end
def defined_plugins
@plugin_definitions
end
def loaded_plugins
@plugin_instances
end
def run
logger.debug 'Aggregating data from plugins.'
if loaded_plugins.count <= 0
logger.info 'No plugins loaded to aggregate data from.'
Aggregator::shutdown
return
elsif loaded_plugins.count > 2
pool_size = loaded_plugins.count
else
pool_size = 2
end
plugin_worker = PluginWorker.pool(size: pool_size)
loaded_plugins.map { |p| plugin_worker.future.run(p) }.map(&:value)
end
private
def initialize_plugins
plugins = []
logger.info 'Initializing plugins'
search.each do |p|
plugin = PluginValidator::validate p
unless plugin.nil?
plugins << plugin
end
end
logger.info "Found #{plugins.count} valid plugins."
plugins.each do |p|
plugin = Plugin.find_or_initialize_by(name: p.name)
plugin.update_attributes(
class_name: p.class_name,
conf_path: p.conf_path,
class_path: p.class_path
)
@plugin_definitions << plugin
end
logger.info 'Persisted plugin information.' if plugins.count > 0
@plugin_definitions.each do |p|
begin
require p.class_path
rescue => e
logger.warn "Couldn't parse file #{p.class_path}. Aggregator is not able to use the #{p.name} plugin."
logger.debug e
next
end
begin
if Object::const_get(p.class_name).ancestors.include? PluginFrame
instance = Object::const_get(p.class_name).spawn(p)
@plugin_instances << instance
logger.info "Plugin #{p.name} initialized"
else
raise
end
rescue => e
logger.warn "Couldn't instantiate class #{p.class_name} or class is not a plugin. Aggregator is not able to use the #{p.name} plugin."
logger.debug e
end
end
logger.warn 'Found no useable plugin!' if @plugin_instances.empty?
end
# Search for plugins
def search(directory = setting.plugin_folder)
plugins = Dir.glob("#{directory}/**")
if Aggregator::environment == :development
plugins.each do |p|
logger.debug "Found plugin folder #{p}. Validating plugin now."
end
end
plugins
end
end
</code></pre>
<p>My questions are:</p>
<ol>
<li>How would you modularize the functionality to pull the data from different sources?</li>
<li>What about to put the plugin into gems?</li>
</ol>
<p>If you're interested in the project, you can find it here: <a href="https://github.com/openscript/social_aggregator" rel="nofollow noreferrer">https://github.com/openscript/social_aggregator</a></p>
|
[] |
[
{
"body": "<p>Most of your code is not here, but some general points:</p>\n\n<ol>\n<li>File naming conventions: in ruby, file name convention is <a href=\"http://en.wikipedia.org/wiki/Snake_case\" rel=\"nofollow noreferrer\">snake case</a> - your files should be named as the name of your class, but as snake case - meaning <code>plugin_frame.rb</code>, <code>plugin_manager.rb</code>, <code>message_category.rb</code>. Remember to change you <code>require</code>s also.</li>\n<li>Finalizers are rarely if ever used in ruby, and I see no compelling reason to use them in your code.</li>\n<li>Ruby is a <a href=\"http://en.wikipedia.org/wiki/Duck_typing\" rel=\"nofollow noreferrer\"><code>duck typed</code></a> language - you don't have to declare methods just to say that they are not implemented - simply don't implement them.</li>\n<li>If you don't want to allow the initialization of the class <code>PluginFrame</code> you can refactor it to be a <code>module</code>. A <code>module</code> cannot be initialized by itself, but classes which include inherit its methods.</li>\n<li>You should abstract the use of members in your code - don't use <code>@plugin</code>, instead dd an <code>attribute_reader :plugin</code> and use <code>plugin</code>.</li>\n<li>If you are using <code>rails</code> you don't need to explicitly require the models, they should be automatically loaded when the server starts</li>\n<li>Refrain from using <code>unless</code> when there are action both for the positive and the negative results - <code>if</code> is much more readable</li>\n<li>Ruby is intended to more compact, so if the return value should be <code>true</code> or <code>false</code> due to some condition, simply return the result of the condition (no need for <code>return true</code>). Even the <code>return</code> keyword is not needed.</li>\n</ol>\n\n<p>Refactored <code>plugin_frame.rb</code>:</p>\n\n<pre><code>require 'celluloid'\nrequire 'digest/md5'\n\nrequire 'app/utils/logging'\nrequire 'app/utils/setting'\n\nclass PluginFrame\n include Setting\n include Logging\n include Celluloid\n\n protected\n\n attr_accessor :plugin\n\n # Returns a persisted action by given name\n def get_action(name)\n Action.find_or_create_by!(name: name, plugin: plugin)\n end\n\n # Return whether last action occurrence was before given time\n def action_ready?(action, timer)\n time_since_last_occurrence = action.last_occurrence\n\n time_since_last_occurrence && time_since_last_occurrence <= timer\n end\nend\n</code></pre>\n\n<p>This class is much more readable, succinct, and more easily shows its usage and responsibility. </p>\n\n<p>Unfortunately, this class seems to contain some partial responsibility - reading an action, checking if its ready, but it misses other actions which are assumed to be handled else-where - setting action's last occurrence and saving its state, for example. I assume this is written in some other class, but it breaks the Encapsulation guideline - put the logic for loading and saving an object in the same place, evaluating and maintaining state in the same place, etc...</p>\n\n<p>As for the <code>plugin_manager.rb</code>, some more points:</p>\n\n<ol>\n<li>You don't need to declare members in your class (<code>@plugin_definitions</code>, etc.). When they are initially assigned they 'magically' appear.</li>\n<li>You define getters, which are fine, although you can use <a href=\"https://stackoverflow.com/questions/4370960/what-is-attr-accessor-in-ruby\"><code>attr_accessor</code>s and <code>attr_reader</code>s</a> instead. Any way, you give your getters a different name than the members. This is not advisable - give them the same name.</li>\n<li>Instead of initializing an array, then using <code>each</code> on another array, and pushing the results to the first array, simply use <code>map</code> and <code>select</code>.</li>\n<li>Method naming - if you feel that a method needs a comment (namely <code>search</code>) to explain what it does, it might be better to rename it to be self-explanatory.</li>\n</ol>\n\n<p>Refactored:</p>\n\n<pre><code>class PluginManager\n include Logging\n include Setting\n include Celluloid \n\n def initialize\n initialize_plugins\n end\n\n attr_reader :plugin_definitions, :plugin_instances\n\n def run\n logger.debug 'Aggregating data from plugins.'\n\n if plugin_instances.count <= 0\n logger.info 'No plugins loaded to aggregate data from.'\n Aggregator::shutdown\n return\n end\n\n pool_size = [plugin_instances.count, 2].max \n plugin_worker = PluginWorker.pool(size: pool_size)\n plugin_instances.map { |p| plugin_worker.future.run(p) }.map(&:value)\n end\n\n private\n\n def initialize_plugins\n logger.info 'Initializing plugins' \n\n plugins = search_for_plugins.map { |p| PluginValidator::validate p }.compact \n logger.info \"Found #{plugins.count} valid plugins.\"\n\n @plugin_definitions = plugins.map do |p|\n Plugin.find_or_initialize_by(name: p.name).tap do |plugin|\n plugin.update_attributes(\n class_name: p.class_name,\n conf_path: p.conf_path,\n class_path: p.class_path\n )\n end\n end \n logger.info 'Persisted plugin information.' if plugins.count > 0\n\n @plugin_instances = plugin_definitions.map do |p|\n begin\n require p.class_path\n begin\n if Object::const_get(p.class_name).ancestors.include? PluginFrame\n Object::const_get(p.class_name).spawn(p)\n else\n raise\n end\n rescue => e\n logger.warn \"Couldn't instantiate class #{p.class_name} or class is not a plugin. Aggregator is not able to use the #{p.name} plugin.\"\n logger.debug e\n end\n rescue => e\n logger.warn \"Couldn't parse file #{p.class_path}. Aggregator is not able to use the #{p.name} plugin.\"\n logger.debug e\n end\n end\n\n logger.warn 'Found no useable plugin!' if plugin_instances.empty?\n end\n\n def search_for_plugins(directory = setting.plugin_folder)\n Dir.glob(\"#{directory}/**\").tap do |plugins|\n if Aggregator::environment == :development\n plugins.each do |p|\n logger.debug \"Found plugin folder #{p}. Validating plugin now.\"\n end\n end\n end\n end\nend\n</code></pre>\n\n<p>To package your code as a gem you can start by reading the <a href=\"http://guides.rubygems.org/make-your-own-gem/\" rel=\"nofollow noreferrer\">guide</a></p>\n\n<p>As for separating the plugins into separate gems - that is mostly a matter of opinion, I would advise against that - implement your plugins in the main gem, which then can be used as reference implementations for your gem users, which will be able to develop their own plugins in their applications, or within their own gems.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T18:10:25.317",
"Id": "72615",
"Score": "0",
"body": "Thank you very much for this great review. I've adapted almost everything and I learnt something from you.\nI've one more question and I believe you misunderstood my question with the gems. Would you put my plugins, which are managed by the `plugin_manager` you reviewed , into separate gems? Does this makes any sense?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T18:25:54.467",
"Id": "72617",
"Score": "1",
"body": "I've updated my answer"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T15:05:39.943",
"Id": "41886",
"ParentId": "41830",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41886",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T22:20:26.923",
"Id": "41830",
"Score": "1",
"Tags": [
"ruby",
"plugin"
],
"Title": "Implementing plugins in my Ruby social aggregator app"
}
|
41830
|
<p>I have made a method which takes two parameters: the value to convert and the base. Based upon those two parameters my method is adjusted (with several helper methods) to change the desired decimal number to a number with a different base.</p>
<p>Is this code practical and clean? If not, what should I change to make it better?</p>
<pre><code>public String baseConversion(int base, int value){
String finalResult = "";
String tempResult = "";
int countLength = 0, countFit = 0; // countLength counts the length of the tempResult string in order to know how many '0' to add. countFit counts how many times the tempValue fits into the current parameter 'value'
int placeValue; // Records the place value. ex 245: '2' is in the hundreds place value
int tempValue = 0;
while (value > 0){
placeValue = 1;
// calculates the highest power that fits in the value (takes desired base into account)
while (value > placeValue){
placeValue*=base;
countLength++;
}
if (value!=placeValue){
countLength--; // subtract to account for the value in the tempResult that is not '0'
placeValue/=base; // divide back as the previous while loop went one placeValue higher than needed in order to break out
}
//figures out how many times the placeValue can fit into the value
while (tempValue+placeValue <= value){
tempValue+=placeValue;
countFit++;
}
if (base==16){
tempResult += numConverter(countFit);
}
if (base==8 || base == 2 || base == 10){
tempResult += String.valueOf(countFit);
}
// adds zeros to the rest of the string
while (countLength > 0){
tempResult+="0";
countLength--;
}
// takes the current tempResult and combines with previous. ex combine 10000 with 100 = 10100
finalResult = combineResults(finalResult, tempResult);
value -= tempValue;
countFit=0;
tempValue=0;
tempResult="";
}
return finalResult;
}
</code></pre>
<p>Helper methods: </p>
<pre><code>private String numConverter(int number){
// only for hexadecimal
if(number == 10){
return "A";
}else if (number == 11){
return "B";
}else if (number == 12){
return "C";
}else if (number == 13){
return "D";
}else if(number == 14){
return "E";
}else if (number == 15){
return "F";
}else {
return String.valueOf(number);
}
}
private String combineResults(String a, String b){
String result = "";
int indexA = 0, indexB = 0;
int aTempLength = a.length(), bTempLength = b.length();
if (a.length() > b.length()){
while (aTempLength > bTempLength){
result+=a.charAt(indexA);
indexA++;
aTempLength--;
}
}else {
while (bTempLength > aTempLength){
result+=b.charAt(indexB);
indexB++;
bTempLength--;
}
}
while (aTempLength > 0){
if (String.valueOf(a.charAt(indexA)).equals("0")){
result+=b.charAt(indexB);
indexA++;
indexB++;
}else {
result+=a.charAt(indexA);
indexA++;
indexB++;
}
aTempLength--;
}
return result;
}
</code></pre>
|
[] |
[
{
"body": "<p>A few random notes:</p>\n\n<ol>\n<li><p>It returns an empty string with <code>0</code> as input <code>value</code>. I guess it's a bug.</p></li>\n<li>\n\n<pre><code>int countLength = 0, countFit = 0;\n</code></pre>\n\n<p>I'd put the variable declarations to separate lines. From Code Complete, 2nd Edition, p759:</p>\n\n<blockquote>\n <p>With statements on their own lines, the code reads from top to bottom, instead\n of top to bottom and left to right. When you’re looking for a specific line of code,\n your eye should be able to follow the left margin of the code. It shouldn’t have to\n dip into each and every line just because a single line might contain two statements.</p>\n</blockquote></li>\n<li><p>Horizontal scrolling doesn't make reading easier. You could put the comments in the line before the variables:</p>\n\n<pre><code>// countLength counts the length of the tempResult string in order to know how many '0' to add. \nint countLength = 0; \n//countFit counts how many times the tempValue fits into the current parameter 'value'\nint countFit = 0; \n</code></pre>\n\n<p>Anyway, commenting is a smell. <em>Clean Code</em> by <em>Robert C. Martin</em>, p54:</p>\n\n<blockquote>\n <p>The proper use of comments is to compensate for our failure to express ourself in\n code. Note that I used the word failure. I meant it. Comments are always failures. We must\n have them because we cannot always figure out how to express ourselves without them,\n but their use is not a cause for celebration.</p>\n</blockquote>\n\n<p>The book has lots of hints which help to avoid this smell.</p></li>\n<li><p>Try to minimize the scope of local variables. It's not necessary to declare them at the beginning of the method, declare them where they are first used. (<em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>)</p>\n\n<p>For example, <code>tempResult</code> could be declared inside the while loop:</p>\n\n<pre><code>while (value > 0) {\n String tempResult = \"\";\n ...\n\n}\n</code></pre>\n\n<p>It would make the <code>tempResult = \"\";</code> statement unnecessary at the end of the loop.</p></li>\n<li><p>If you don't know the already existing methods for these conversions in the JDK check them. <code>Integer</code> class has <code>toOctalString(int i)</code>, <code>toHexString(int i)</code> and <code>toBinaryString(int i)</code>. You can look into <a href=\"http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Integer.java#Integer.toUnsignedString%28int%2Cint%29\">their source</a> too.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T02:11:11.483",
"Id": "71980",
"Score": "1",
"body": "Thanks! Really good point about comments. Also this was for hw so I couldn't have used the already provided methods. But thanks anyways."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T23:57:37.770",
"Id": "41836",
"ParentId": "41831",
"Score": "5"
}
},
{
"body": "<p>Disclaimer: I'm new here, so this might not be the type of review people give, but I'm trying to match it as best as I can.</p>\n\n<h1>Formatting</h1>\n\n<p>A comment explaining the purpose of <code>combineResults(String a, String b)</code> next to the method would be helpful. (Yes, there's one in the main method, but documentation next to the helpers is good, too.) </p>\n\n<p>The same could be said for <code>numConverter(int number)</code>...</p>\n\n<p>Other than that, indentation looks good, braces look fine, etc. <code>:)</code></p>\n\n<h1>Algorithm</h1>\n\n<p>In general: You should be passing around <code>StringBuilder</code>s or <code>StringBuffer</code>s (or <code>char</code>s) instead of <code>String</code>s. The former are mutable, while the latter isn't mutable. This will save some performance. (e.g. appending is better on memory with the builders and buffers, rather than with raw <code>String</code>s.)</p>\n\n<h2>Main Algorithm</h2>\n\n<p>Ok... You took kinda an odd approach to converting bases. Rather than using all those while loops, you should focus on determining the next <em>least significant digit</em> by using the modulus operator followed by division.</p>\n\n<p>For example, in pseudocode:</p>\n\n<pre><code>while(number > 0) {\n nextDigit = number % base; //Get the next digit using modulo\n number /= base; \n // prepend nextDigit to result String Buffer\n}\n</code></pre>\n\n<p>This makes the <code>combineResults()</code> method unneeded, as prepend is built-in to the StringBuilder.</p>\n\n<h2>NumConverter</h2>\n\n<p>In the spirit of <code>StringBuilder</code>s vs. <code>String</code>, this should return a <code>char</code> rather than a <code>String</code>.</p>\n\n<p>Your current code assumes that the only <code>number</code> ever fed to this method will be less than 16. This could be a problem if it's a larger library, or if you want to expand the bases to more than hexadecimal.</p>\n\n<p>You could use a <code>switch</code>/<code>case</code> construct instead of the <code>else if</code>'s... </p>\n\n<p>Or, if you really want to shorten the code, you could do something like (note: this also implements the <code>char</code> return instead of <code>String</code>):</p>\n\n<pre><code>char numConverter(int digit) {\n if (num >= 16 || num < 0) //If we're not given a valid digit\n return 0; //Let the output know somehow... could throw an exception instead.\n else if (digit <= 10) //If we're dealing with a \"normal\" digit\n return ((char)num + '0'); //... return the numeric equivalent\n else //We're in extended digit range: we need letters!\n return ((char)digit + 'A' - 10); //Return hex equivalent of 10-15 (A-F)\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T02:12:51.770",
"Id": "71981",
"Score": "0",
"body": "Very good point about the modulus! I totally missed that option. Ill do that next time. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:41:20.260",
"Id": "72131",
"Score": "0",
"body": "Given the number of up-votes on your answer, it is pretty much the kind of review we do here :) Well done. Hope to see more posts from you. Welcome to Code Review!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T00:52:20.623",
"Id": "41838",
"ParentId": "41831",
"Score": "8"
}
},
{
"body": "<p>If you are deliberately <a href=\"/questions/tagged/reinventing-the-wheel\" class=\"post-tag\" title=\"show questions tagged 'reinventing-the-wheel'\" rel=\"tag\">reinventing-the-wheel</a>, please tag your question as such. Since you didn't tag it, I'm obligated to mention that you could just write</p>\n\n<pre><code>Integer.toString(value, base).toUpperCase();\n</code></pre>\n\n<hr>\n\n<p>I'll start with the helper methods. I believe that <strong>neither helper should be necessary</strong>.</p>\n\n<p><code>private String numConverter(int number)</code> is basically equivalent to <code>Character.toUpperCase(</code><a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#forDigit%28int,%20int%29\" rel=\"nofollow\"><code>Character.forDigit(digit, 16)</code></a><code>)</code>. That would be <code>static</code>, and returns a <code>char</code>; both would be a good idea for your <code>numConverter()</code>. Also, you only use <code>numConverter()</code> for hexadecimal, but it could actually work just as well for any base up to and including 16.</p>\n\n<p><code>combineResults()</code> looks like an adder that operates on strings, without needing to support carrying. That's an odd approach to base conversion. You should be able to build the result by appending a digit at a time without needing this function at all.</p>\n\n<p>Now, on to <code>baseConversion()</code> itself.</p>\n\n<p>The function is a pure function that does not rely on any object state. Therefore, it should be declared <strong><code>static</code></strong>.</p>\n\n<p>Personally, I feel that the parameters would be more natural in the reverse order <code>(value, base)</code>.</p>\n\n<p>You don't support negative inputs. That could be reasonable, but returning an empty string for such inputs is not. Throw an exception. Not supporting 0 as a value is a bit more surprising. You should be able to tweak your code to handle 0. Another surprise is that if <code>base</code> is not 2, 8, 10, or 16, the function returns an empty string. Again, either <strong>add support or add validation</strong>.</p>\n\n<p>The big block of variable declarations at the top is a bad sign. You should declare your variables in the <strong>tightest scope possible</strong>. The \"temp\" variables certainly don't belong there.</p>\n\n<p>This if-block, which conditionally undoes one iteration of the preceding while-loop, is a sign that the <strong>while-loop's termination condition is wrong</strong>.</p>\n\n<pre><code>if (value!=placeValue){\n countLength--; // subtract to account for the value in the tempResult that is not '0'\n placeValue/=base; // divide back as the previous while loop went one placeValue higher than needed in order to break out\n}\n</code></pre>\n\n<hr>\n\n<p>If asked to keep to the spirit of the original code, here's how I would rewrite it:</p>\n\n<pre><code>public static String baseConversion(int base, int value) {\n if (base <= 0 || value < 0) {\n throw new IllegalArgumentException(\"Negative bases and values are not supported\");\n }\n if (base < Character.MIN_RADIX) {\n throw new IllegalArgumentException(\"Base too small\");\n }\n if (base > Character.MAX_RADIX) {\n throw new IllegalArgumentException(\"Base too large\");\n }\n\n StringBuilder result = new StringBuilder();\n int placeValue;\n for (placeValue = 1; placeValue * base <= value; placeValue *= base) {}\n for (; placeValue > 0; placeValue /= base) {\n int digit = value / placeValue;\n value -= digit * placeValue;\n result.append(Character.forDigit(digit, base));\n }\n return result.toString().toUpperCase();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T15:34:07.083",
"Id": "72096",
"Score": "0",
"body": "I've read that sometimes it is better to declare all variables at the top as it simplifies debugging by not introducing new variables as you go through the process. However I might be wrong with this as I've never debugged a big project myself so I can't say too much about it. Anyways I'm not sure how I could improve the while loop termination. The only reason I have that if statement is because I need to update the variables that caused the loop boundary to turn false."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T10:13:28.753",
"Id": "41869",
"ParentId": "41831",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "41838",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T22:23:23.993",
"Id": "41831",
"Score": "10",
"Tags": [
"java",
"converting",
"reinventing-the-wheel"
],
"Title": "Is decimal, hexadecimal, octadecimal, binary converter efficient?"
}
|
41831
|
<p>I had a small technical C# task using SOLID principle and TDD. But I failed to prove my coding skill through the test.</p>
<p>Can anyone offer any small advice for me? I am really eager to learn what my faults are and how I can improve.</p>
<p>The interview question is <a href="https://github.com/JustGiving/Recruitment-Test" rel="noreferrer">here</a>, and my answer is <a href="https://github.com/hoonsbara/Recruitment-Test-master-Joel" rel="noreferrer">here</a>.</p>
<p>I just reference here some pieces of my source code.</p>
<p><strong>Program.cs</strong></p>
<pre><code>class Program
{
static void Main(string[] args)
{
////////////////////////////////////////////////////////////////////////////////
// Story 1. As a donor
Console.WriteLine("-------------------------------------- Story1\r\n");
//1.1. Craete Tax Calculator
decimal taxRate = 20;
ITaxCalculator taxCalculator = new TaxCalculator(taxRate);
//1.2. Display GiftAid
Console.WriteLine("Please enter donation amount:");
decimal Amount = decimal.Parse(Console.ReadLine());
Console.WriteLine("=> Your Gift Aid is: {0} \r\n\r\n", taxCalculator.GetGiftAid(Amount));
////////////////////////////////////////////////////////////////////////////////
// Story 2. As a site administrator
Console.WriteLine("-------------------------------------- Story2\r\n");
//2.1. Create using factory pattern
taxCalculator = new TaxCalculatorFactory().GetObject(new TaxRepository());
Console.WriteLine("Please enter donation amount:");
Amount = decimal.Parse(Console.ReadLine());
//2.2. Display GiftAid
Console.WriteLine("=> Your Gift Aid is: {0} \r\n\r\n", taxCalculator.GetGiftAid(Amount));
Console.WriteLine("Press any key to exit.");
Console.ReadLine();
}
}
</code></pre>
<p><strong>Calculator Classes</strong></p>
<pre><code>interface ITaxCalculatorFactory
{
ITaxCalculator GetObject(decimal taxRate);
ITaxCalculator GetObject(ITaxRepository taxRepo);
}
public class TaxCalculatorFactory
{
public TaxCalculatorFactory()
{
}
public ITaxCalculator GetObject(decimal dAmount)
{
return new TaxCalculator(dAmount);
}
public ITaxCalculator GetObject(ITaxRepository taxRepo)
{
return new TaxCalculatorByData(taxRepo);
}
}
public interface ITaxCalculator
{
decimal GetGiftAid(decimal dAmount);
}
public class TaxCalculator : ITaxCalculator
{
private readonly decimal _taxRate;
public TaxCalculator(decimal taxRate)
{
_taxRate = taxRate;
}
public decimal GetGiftAid(decimal dAmount)
{
var gaRatio = _taxRate / (100 - _taxRate);
return dAmount * gaRatio;
}
}
public class TaxCalculatorByData : ITaxCalculator
{
private readonly ITaxRepository _taxRepo;
public TaxCalculatorByData(ITaxRepository taxRepo)
{
_taxRepo = taxRepo;
}
public decimal GetGiftAid(decimal dAmount)
{
var gaRatio = _taxRepo.GetTaxRate() / (100 - _taxRepo.GetTaxRate());
return dAmount * gaRatio;
}
}
</code></pre>
<p><strong>Test Codes</strong></p>
<pre><code>[TestFixture]
public class GetAidTest
{
////////////////////////////////////////////////////////////////////////////////
// Story 1. As a donor
[Test]
public void Story1_Should_Return_TwentyFive_From_GiftAid()
{
/////////////////////////////////////////////////////////////
// Setup
decimal taxRate = 20;
decimal donationAmount = 100;
decimal valueExpected = 25;
var taxCalculator = new TaxCalculator(taxRate);
/////////////////////////////////////////////////////////////
// Action
var result = taxCalculator.GetGiftAid(donationAmount);
/////////////////////////////////////////////////////////////
// Verify the result
Assert.AreEqual(valueExpected, result, "Should return 25");
}
////////////////////////////////////////////////////////////////////////////////
// Story 2. As a administrator
[Test]
public void Story2_Should_Store_TaxRate_Fourty_And_Return_GiftAid()
{
/////////////////////////////////////////////////////////////
// Setup
decimal taxRate = 40;
decimal donationAmount = 100;
decimal valueExpected = 66.67m;
var repository = new Mock<ITaxRepository>();
repository.Setup(r => r.GetTaxRate()).Returns(taxRate);
repository.Setup(r => r.Save(It.IsAny<decimal>())).Verifiable();
ITaxCalculator taxCalculator = new TaxCalculatorFactory().GetObject(repository.Object);
/////////////////////////////////////////////////////////////
// Action
var result = decimal.Round(taxCalculator.GetGiftAid(donationAmount), 2, MidpointRounding.AwayFromZero);
/////////////////////////////////////////////////////////////
// Verify the result
Assert.AreEqual(valueExpected, result, "Should return 25");
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T13:39:39.287",
"Id": "72070",
"Score": "1",
"body": "Did you submit a pull request from your public repo? \"If you have a paid GitHub account, feel free to create a **private repo** . . . and send us a pull request.\" [their emphasis]"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T07:28:30.467",
"Id": "72241",
"Score": "1",
"body": "\"This assignment takes an average of about 30 minutes.\" 4 user stories in 30 mins. They must have really good programmers."
}
] |
[
{
"body": "<ol>\n<li><p><code>TaxCalculator</code> and <code>TaxCalculatorByDB</code> contains the same logic:</p>\n\n<pre><code>var gaRatio = _taxRepo.GetTaxRate() / (100 - _taxRepo.GetTaxRate());\nreturn dAmount * gaRatio;\n</code></pre>\n\n<p>Furthermore, it seems that <code>TaxCalculator</code> and the <code>GetObject(decimal taxRate)</code> method in the factory \nonly used for test. It's a test smell: <a href=\"http://xunitpatterns.com/Test%20Logic%20in%20Production.html\">Test Logic in Production</a>.\nI would use a mock instead of it.</p></li>\n<li><p>The assertion message does not say anything more than which is already obvious from the code itself:</p>\n\n<pre><code>Assert.AreEqual(valueExpected, result, \"Should return 25\"); \n</code></pre>\n\n<p>Try to explain the whys if it's possible. Why should it return 25? Otherwise it's just noise.</p></li>\n<li><p>You could write more than one test per story. What happens or what should happen on invalid inputs, for example?</p></li>\n<li><p>I think the <code>Program.cs</code> should contain only one thing: get donation amount and print the answer. Requirements of Story 1-4 should be combined.</p></li>\n<li><p>I think implementing Story 4 means that the program </p>\n\n<ol>\n<li>should ask for the event type, or</li>\n<li>print the result for every event type.</li>\n</ol></li>\n<li><p>I can't find any test for Story 3 and Story 4.</p></li>\n<li><p>I can't test now (I don't have a C# compiler) but I think values of Story 4 should also be printed with rounding.</p></li>\n<li><p>The <code>ITaxRepository.Save(decimal taxRate)</code> method seems unnecessary. Story 2 isn't crystal clear about that but since there isn't any detail about how an admin can change the tax rate I guess they meant it with SQL commands (for example) and not through the program.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T01:48:08.117",
"Id": "41841",
"ParentId": "41834",
"Score": "14"
}
},
{
"body": "<ol>\n<li><p>The interview defines 4 user stories but you have only really implemented 2 as far as I can see.</p></li>\n<li><p>Story 3 says that the amount should be rounded to 2 decimal places. You have done that by applying the rounding to the result as part of a unit test which misses the point of the story (imho). The story says something about \"should be displayed rounded to two decimal places\" so it might need a tax calculator view which displays the results as per requirements.</p></li>\n<li><p>You should avoid having two ways of creating your <code>TaxCalculator</code> objects. If you have a factory then you usually don't want the user to instantiate new objects by <code>new</code>. If I were to use your class I would not know which way to use and if there is a difference or not.</p></li>\n<li><p><code>dAmount</code> smells like <a href=\"http://en.wikipedia.org/wiki/Hungarian_notation\">hungarian notation</a> of which I'm not a fan of and which is generally frowned upon.</p></li>\n<li><p>I would prefer <code>Create</code> over <code>GetObject</code> as method name in the factory. </p></li>\n<li><p>Remove the <code>GetObject(decimal amount)</code> factory method - you can pass a mock repository in unit tests which always returns a fixed amount.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T02:24:03.057",
"Id": "41843",
"ParentId": "41834",
"Score": "16"
}
},
{
"body": "<p>In addition to the excellent previous posts and could be nit picking, but why the huge comment blocks?</p>\n\n<pre><code>////////////////////////////////////////////////////////////////////////////////\n</code></pre>\n\n<p>Seems unnecessary and it would certainly put me off if I was reviewing it!</p>\n\n<p>There is a typo in the comments, and again, typo's could be nitpicking, but I'd certainly be thinking \"has care and attention been paid whilst the code is being written\" (I accept that an interview situation is not a normal working environment, so this may be a bit harsh!).</p>\n\n<p>I'd also second the suggestion to avoid having two ways of creating your calculators. The factory doesn't seem like it's needed for this example. </p>\n\n<p>I'd be thinking it's possibly disobeying the YAGNI principle by putting in a factory when you only have a single tax calculator to handle.</p>\n\n<p>EDIT: </p>\n\n<p>Further nitpicking!</p>\n\n<p>You have a block level variable 'Amount' with a capital A, which I wouldn't expect, this is inconsistent with the rest of your variables.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T13:35:56.663",
"Id": "72068",
"Score": "3",
"body": "+1 In a do-at-home test, there's no excuse for formatting inconsistencies or typos. Polish it up when they give you the time. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-01-14T09:03:53.130",
"Id": "288220",
"Score": "0",
"body": "Yeah it's actually fairly common in commerical settings when people push something out as soon as it's functionally operational, rather than taking a few more minutes to re-read it and make sure it's cleaned up. \nI personally find your knowledge of the code is near enough at its maximum after you've got it functionally working which is the best time to refactor and cleanse."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T10:19:12.880",
"Id": "41870",
"ParentId": "41834",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T23:45:33.157",
"Id": "41834",
"Score": "23",
"Tags": [
"c#",
"object-oriented",
"interview-questions",
"tdd"
],
"Title": "Interview task - SOLID Principle and TDD"
}
|
41834
|
<p>This is Part 2 of a question about performance and general best practices. Part 1 is located <a href="https://codereview.stackexchange.com/questions/41796/entity-framework-6-0-2-performance-of-auditable-change-tracking-part-1-of-2">here</a>. The body of the messages are the same to illustrate their similarity, the difference is the code provided. One provides the logic the to generate the code the other provides the data to utilized by the template. The focus isn't so much on the template, but the pattern of managing a database that tracks changes across potentially multiple domains.</p>
<p>I'm kind of new to the realm of Database authoring, so I wanted to get some feedback on a system which generates auditable entities.</p>
<p>I'm using Visual Studio 2013 with the Entity Framework 6.0.2. Handling Migrations through the Package Manager Console. I'm rather unfamiliar with EF Performance, and what such a change tracking system would do. I know that I could enable the change tracking on the server, but this system will involve tracking who changed what, based off of their identity defined within the database (and honestly, I don't understand the SQL server change tracking one bit.) It's meant to focus on potentially multiple domains, so whoever would use the client would login using SQL Authentication. The end result is Active Directory supplies the authentication, and users are handled by storing their SID within the registry which links to the proper domain.</p>
<p>Here's the Text Template that contains the logic (the header portion was moved to Part 1):</p>
<pre><code>foreach (var entityNamespace in orderedEntities.Keys)
{
#>
namespace <# Write(entityNamespace); #>.Instances
{<#
foreach (var entity in orderedEntities[entityNamespace])
{
var currentEntityIndex = indices[entity];#>
public class <# Write(entity.EntityName); #>Instance :
GenericInstanceEntity<<# Write(entity.EntityName); #>, <# Write(entity.EntityName); #>Changes, <# Write(entity.EntityName); #>Instance>
{
internal const string TableName = "[" + <# Write(ContextName); #>.TableInstancesPrefix + "<# Write(entity.PluralName); #>]";
/// <summary>
/// Whether the <see cref="<# Write(entity.EntityName); #>" />
/// has been deleted.
/// </summary>
/// <remarks>
/// If the deletion state hasn't changed on the current instance,
/// this will be null. Refer to <see cref="<# Write(entity.EntityName); #>.Deleted" />
/// to determine its current deletion state.
/// </remarks>
public bool? Deleted { get; set; }
<#
foreach (var property in entity.Properties)
{
if ((property.Value.Requirements & ER_NOTTRACKED) == ER_NOTTRACKED)
continue;#>
/// <summary>
/// Returns/sets the <see cref="<#
string shortForm;
shortformLookup.TryGetValue(property.Value.DataType, out shortForm);
shortForm = shortForm ?? property.Value.DataType;
Write(shortForm);
#>"/> value the <see cref="<# Write(string.Format("{0}.{1}", entity.EntityName, property.Key)); #>"/>
/// was changed to.
/// </summary>
/// <remarks>
/// Returns null if it was not changed on the current
/// <see cref="<# Write(entity.EntityName); #>Instance" />.
/// </remarks>
public <# WriteLine(string.Format("{0} {1} {{ get; set; }}", nullableTypes.Contains(property.Value.DataType) ? string.Format("{0}?", property.Value.DataType) : property.Value.DataType, property.Key));
}#>
protected internal override void SetCreatedState()
{
this.Changes |= <# Write(entity.EntityName); #>Changes.Created;
}
protected override <# Write(entity.EntityName); #>Changes MergeChanges(<# Write(entity.EntityName); #>Changes first, <# Write(entity.EntityName); #>Changes second)
{
return first | second;
}
protected internal override bool IsPropertySet(<# Write(entity.EntityName); #>Changes property)
{
switch (property)
{
case <# Write(entity.EntityName); #>Changes.Created:
return (this.Changes & <# Write(entity.EntityName); #>Changes.Created) != <# Write(entity.EntityName); #>Changes.Created;<#
foreach (var property in entity.Properties)
{
if ((property.Value.Requirements & ER_NOTTRACKED) == ER_NOTTRACKED)
continue;#>
case <# Write(entity.EntityName); #>Changes.<# Write(property.Key); #>:
return this.<# Write(property.Key); #> != null;<#
}
#>
case <# Write(entity.EntityName); #>Changes.Deleted:
return this.Deleted != null;
}
return false;
}
protected override TValue GetProperty<TValue>(<# Write(entity.EntityName); #>Changes property)
{
switch (property)
{
case <# Write(entity.EntityName); #>Changes.Created:
return (TValue)(object)((this.Changes & <# Write(entity.EntityName); #>Changes.Created) != <# Write(entity.EntityName); #>Changes.Created);<#
foreach (var property in entity.Properties)
{
if ((property.Value.Requirements & ER_NOTTRACKED) == ER_NOTTRACKED)
continue;#>
case <# Write(entity.EntityName); #>Changes.<# Write(property.Key); #>:
return (TValue)(object)(this.<# Write(property.Key); #>);<#
}
#>
case <# Write(entity.EntityName); #>Changes.Deleted:
return ((TValue)(object)this.Deleted);
}
return default(TValue);
}
protected override void OnPropertyChanged<TValue>(<# Write(entity.EntityName); #>Changes property, TValue value)
{
switch (property)
{
case <# Write(entity.EntityName); #>Changes.Created:
bool bValue = (bool)(object)value;
if (bValue)
this.Changes |= <# Write(entity.EntityName); #>Changes.Created;
else
this.Changes &= ~<# Write(entity.EntityName); #>Changes.Created;
break;<#
foreach (var property in entity.Properties)
{
if ((property.Value.Requirements & ER_NOTTRACKED) == ER_NOTTRACKED)
continue;#>
case <# Write(entity.EntityName); #>Changes.<# Write(property.Key); #>:
this.<# Write(property.Key); #> = (<# Write(property.Value.DataType); #>)(object)(value);
break;<#
}
#>
case <# Write(entity.EntityName); #>Changes.Deleted:
this.Deleted = (bool?)(object)value;
break;
}
}
public override <# Write(entity.EntityName); #> Root { get { return base.Root; } protected internal set { base.Root = value; } }
public override <# Write(authorityEntity); #> AuthorizingUser { get { return base.AuthorizingUser; } protected internal set { base.AuthorizingUser = value; } }
}
<#
}
#>
}
<#
}
#>
namespace <# WriteLine(ContextNamespace); #>
{
using System.Data.Entity;
<#
foreach (var entityNamespace in orderedEntities.Keys)
{
#>
using <# Write(entityNamespace); #>;
using <# Write(entityNamespace); #>.Instances;
<#
}
#>
partial class <# WriteLine(ContextName); #>
{
<#
foreach (var entityNamespace in orderedEntities.Keys)
{
foreach (var entity in orderedEntities[entityNamespace])
{
#>
/// <summary>
/// Returns/sets the <see cref="DbSet{TEntity}" /> of <see cref="<# Write(entity.EntityName); #>" />
/// instances associated to the <see cref="<# Write(ContextName); #>" />.
/// </summary>
public DbSet<<# Write(entity.EntityName); #>> <# Write(entity.PluralName); #> { get; set; }
<#
}
}#>
<#foreach (var entityNamespace in orderedEntities.Keys)
{
foreach (var entity in orderedEntities[entityNamespace])
{
#>
/// <summary>
/// Returns/sets the <see cref="DbSet{TEntity}" /> of <see cref="<# Write(entity.EntityName); #>Instance" />
/// instances associated to the <see cref="<# Write(ContextName); #>" /> which represent the changes
/// applied to <see cref="<# Write(entity.EntityName); #>" /> entities.
/// </summary>
public DbSet<<# Write(entity.EntityName); #>Instance> <# Write(entity.PluralInstanceName); #> { get; set; }
<#
}
}
foreach (var entityNamespace in orderedEntities.Keys)
{
foreach (var entity in orderedEntities[entityNamespace])
{
var currentEntityIndex = indices[entity];
#>
/// <summary>
/// Describes the relationships on the <see cref="<# Write(entity.EntityName); #>" /> entity
/// with the <paramref name="modelBuilder" /> provided.
/// </summary>
/// <param name="modelBuilder">The <see cref="DbModelBuilder" /> instance
/// which maintains the schema of the data model.</param>
private void EntitySetup<# {
var numZeroes = maxEL - (currentEntityIndex+1).ToString().Length;
for (int i = 0; i < numZeroes; i++)
Write("0");
Write((currentEntityIndex + 1).ToString());
}#>(DbModelBuilder modelBuilder)
{<#string lowerName = String.Format("{0}{1}", entity.EntityName[0].ToString().ToLower(), entity.EntityName.Substring(1));#>
var <# Write(lowerName); #>Configuration = modelBuilder.Entity<<# Write(entity.EntityName); #>>();
<# Write(lowerName); #>Configuration.ToTable(<# Write(entity.EntityName); #>.TableName);
<# Write(lowerName); #>Configuration.Property(<# Write(lowerName); #>Prop => <# Write(lowerName); #>Prop.Identifier).HasColumnName(<# Write(entity.EntityName); #>.IDName);
<#
if (entity.EntityName == authorityEntity)
{
#>/* *
* Denote the actual key of this entity.
* This is required on <# Write(entity.EntityName); #> due to its
* relationships confusing the model builder?
* */
<#
Write(lowerName); #>Configuration.HasKey(<# Write(lowerName); #>Prop => <# Write(lowerName); #>Prop.Identifier);
<#
}
#>
#region Change Tracking for <# WriteLine(entity.EntityName); #>
<# Write(lowerName); #>Configuration.HasMany(<# Write(lowerName); #>Navigation => <# Write(lowerName); #>Navigation.Instances).WithRequired(<# Write(lowerName); #>InstNavigation => <# Write(lowerName); #>InstNavigation.Root)
.Map(<# Write(lowerName); #>InstMapping =>
<# Write(lowerName); #>InstMapping.MapKey(<# Write(entity.EntityName); #>.IDName));
#endregion
<#
foreach (var property in entity.Properties.Values)
{
var targetEnt = entities.FirstOrDefault(ent=>ent.EntityName == property.DataType);
if (targetEnt != null)
{
var targetEntID = indices[targetEnt];
if ((property.Requirements & ER_COLLECTION_BIDIRECTIONAL) == ER_COLLECTION_BIDIRECTIONAL)
{
string targetLowerName = String.Format("{0}{1}", targetEnt.EntityName[0].ToString().ToLower(), targetEnt.EntityName.Substring(1));
var targetEntityProperty = targetEnt.Properties.Values.FirstOrDefault(prop=>prop.DataType == entity.EntityName);
if (targetEntityProperty != null && targetEntID > currentEntityIndex)
{#>
<#
Write(lowerName); #>Configuration.HasMany(<# Write(lowerName); #>Navigation => <# Write(lowerName); #>Navigation.<# Write(property.Name); #>).WithMany(<# Write(targetLowerName); #>Navigation => <# Write(targetLowerName); #>Navigation.<# Write(targetEntityProperty.Name); #>)
.Map(<# Write(lowerName); #>To<# Write(targetEnt.EntityName); #>Mapping =>
{
<# Write(lowerName); #>To<# Write(targetEnt.EntityName); #>Mapping.MapLeftKey(<# Write(entity.EntityName); #>.IDName);
<# Write(lowerName); #>To<# Write(targetEnt.EntityName); #>Mapping.MapRightKey(<# Write(targetEnt.EntityName); #>.IDName);
<# Write(lowerName); #>To<# Write(targetEnt.EntityName); #>Mapping.ToTable(GenerateMappingTableName<<# Write(entity.EntityName); #>, <# Write(targetEnt.EntityName); #>>());
});
<#
}
}
else
{
var targetEntityProperty = targetEnt.Properties.Values.FirstOrDefault(prop=>prop.DataType == entity.EntityName);
if (targetEntID > currentEntityIndex || targetEntityProperty == null)
{
bool oneToMany = ((property.Requirements & ER_KEY) != ER_KEY) ||
targetEntityProperty != null &&
(targetEntityProperty.Requirements & ER_COLLECTION) == ER_COLLECTION;
bool altIsRequired =
targetEntityProperty != null &&
(targetEntityProperty.Requirements & ER_REQUIRED) == ER_REQUIRED;
if ((property.Requirements & ER_REQUIRED) == ER_REQUIRED)
{#>
<# Write(lowerName); #>Configuration.HasRequired(<# Write(lowerName); #>Navigation => <# Write(lowerName); #>Navigation.<# Write(property.Name); #>).<# Write(oneToMany ? "WithMany" : altIsRequired ? "WithRequiredDependent" : "WithOptional"); #>()
.Map(<# Write(lowerName); #>InstAuthUserMap =>
<# Write(lowerName); #>InstAuthUserMap.MapKey(<# Write(targetEnt.EntityName); #>.IDName));
<#
}
else
{#>
<# Write(lowerName); #>Configuration.HasOptional(<# Write(lowerName); #>Navigation => <# Write(lowerName); #>Navigation.<# Write(property.Name); #>).<# Write(oneToMany ? "WithMany" : altIsRequired ? "WithRequired" : "WithOptionalDependent"); #>()
.Map(<# Write(lowerName); #>InstAuthUserMap =>
<# Write(lowerName); #>InstAuthUserMap.MapKey(<# Write(targetEnt.EntityName); #>.IDName));
<#
}
}
}
}
}#>
var <# Write(lowerName); #>InstanceConfiguration = modelBuilder.Entity<<# Write(entity.EntityName); #>Instance>();
<# Write(lowerName); #>InstanceConfiguration.ToTable(<# Write(entity.EntityName); #>Instance.TableName);
<# Write(lowerName); #>InstanceConfiguration.Property(<# Write(lowerName); #>InstProp => <# Write(lowerName); #>InstProp.InstanceIdentifier).HasColumnName(<# Write(entity.EntityName); #>Instance.IDName);
#region Change Tracking for <# Write(entity.EntityName); #>Instance<#if (entity.EntityName == authorityEntity) {#>
/* *
* Denote the self relationship between the <# Write(entity.EntityName); #>,
* optional in this case to avoid model issues with two required 1:1
* relationships which isn't allowed.
* */
<# Write(lowerName); #>InstanceConfiguration.HasOptional(<# Write(lowerName); #>InstNavigation => <# Write(lowerName); #>InstNavigation.AuthorizingUser).WithMany()
.Map(<# Write(lowerName); #>InstAuthUserMap =>
<# Write(lowerName); #>InstAuthUserMap.MapKey(<# Write(authorityEntity); #>.<# Write(authorityAuthIDFieldName); #>));
<#}else{#>
/* *
* Denote the relationship between the <# Write(entity.EntityName); #>Instance and
* the <# Write(authorityEntity); #>.
* */
<# Write(lowerName); #>InstanceConfiguration.HasRequired(<# Write(lowerName); #>InstNavigation => <# Write(lowerName); #>InstNavigation.AuthorizingUser).WithMany()
.Map(<# Write(lowerName); #>InstAuthUserMap =>
<# Write(lowerName); #>InstAuthUserMap.MapKey(<# Write(authorityEntity); #>.<# Write(authorityAuthIDFieldName); #>));
<#}#>
<# Write(lowerName); #>InstanceConfiguration.HasOptional(<# Write(lowerName); #>InstNavigation => <# Write(lowerName); #>InstNavigation.Previous).WithOptionalDependent()
.Map(<# Write(lowerName); #>InstPrevMapping =>
<# Write(lowerName); #>InstPrevMapping.MapKey(<# Write(entity.EntityName); #>Instance.PreviousIDName));
#endregion<#if (currentEntityIndex + 2 <= entities.Length)
{
#>
EntitySetup<# {
var numZeroes = maxEL - (currentEntityIndex+2).ToString().Length;
for (int i = 0; i < numZeroes; i++)
Write("0");
Write((currentEntityIndex + 2).ToString());
}#>(modelBuilder);<#}#>
}
<#
}
}
foreach (var entityNamespace in orderedEntities.Keys)
{
foreach (var entity in orderedEntities[entityNamespace])
{
var requiredProperties = (from property in entity.Properties.Values
where (property.Requirements & ER_REQUIRED) == ER_REQUIRED
let UseSet = (property.Requirements & ER_NOTTRACKED) != ER_NOTTRACKED
orderby UseSet descending
select new { Property = property, UseSet }).ToArray();
var optionalProperties = (from property in entity.Properties.Values
where (property.Requirements & ER_REQUIRED) != ER_REQUIRED &&
(property.Requirements & ER_COLLECTION) != ER_COLLECTION &&
(property.Requirements & ER_IGNORE_ON_ADDMETHOD) != ER_IGNORE_ON_ADDMETHOD
let UseSet = (property.Requirements & ER_NOTTRACKED) != ER_NOTTRACKED
orderby UseSet descending
select new { Property = property, UseSet }).ToArray();
var noPropertiesUseSet =
((from rp in requiredProperties
where rp.UseSet
select rp).FirstOrDefault() ??
(from op in optionalProperties
where op.UseSet
select op).FirstOrDefault()) == null;
#>
/// <summary>
/// Adds a <see cref="<# Write(entity.EntityName); #>" /> to the <see cref="<# Write(ContextName); #>" />
/// with the <paramref name="authorizingUser" /><#
bool last = false;
var lastProp = optionalProperties.LastOrDefault() ?? requiredProperties.LastOrDefault();
foreach (var property in requiredProperties)
{
string lowerPropertyName = property.Property.Name[0].ToString().ToLower() + property.Property.Name.Substring(1);
Write(", ");
bool isLast = lastProp == property;
if (isLast)
Write("and ");
Write(string.Format("<paramref name=\"{0}\" />", lowerPropertyName));
}
foreach (var property in optionalProperties)
{
string lowerPropertyName = property.Property.Name[0].ToString().ToLower() + property.Property.Name.Substring(1);
Write(", ");
bool isLast = lastProp == property;
if (isLast)
Write("and ");
Write(string.Format("<paramref name=\"{0}\" />", lowerPropertyName));
}
#> provided.
/// </summary>
/// <param name="authorizingUser">
/// The <see cref="<# Write(authorityEntity); #>"/> which is responsible
/// for the insertion request.
/// </param>
<#
foreach (var property in requiredProperties)
{
string lowerPropertyName = property.Property.Name[0].ToString().ToLower() + property.Property.Name.Substring(1);
#>
/// <param name="<# Write(lowerPropertyName); #>">
/// The required <see cref="<#
string shortForm;
shortformLookup.TryGetValue(property.Property.DataType, out shortForm);
shortForm = shortForm ?? property.Property.DataType;
Write(shortForm);
#>"/> which denotes the <see cref="<# Write(entity.EntityName); #>.<# Write(property.Property.Name); #>" />
/// of the <see cref="<# Write(entity.EntityName); #>" /> to add.
/// </param>
<#
}
foreach (var property in optionalProperties)
{
string lowerPropertyName = property.Property.Name[0].ToString().ToLower() + property.Property.Name.Substring(1);
#>
/// <param name="<# Write(lowerPropertyName); #>">
/// The optional <see cref="<#
string shortForm;
shortformLookup.TryGetValue(property.Property.DataType, out shortForm);
shortForm = shortForm ?? property.Property.DataType;
Write(shortForm);
#>"/> which denotes the <see cref="<# Write(entity.EntityName); #>.<# Write(property.Property.Name); #>" />
/// of the <see cref="<# Write(entity.EntityName); #>" /> to add.
/// </param>
<#
}
#>
internal <# Write(entity.EntityName); #> Add<# Write(entity.EntityName); #>(<# Write(authorityEntity); #> authorizingUser<#
foreach (var property in requiredProperties)
{
string lowerPropertyName = property.Property.Name[0].ToString().ToLower() + property.Property.Name.Substring(1);
Write(", ");
Write(property.Property.DataType);
Write(" ");
Write(lowerPropertyName);
}
foreach (var property in optionalProperties)
{
Write(", ");
string lowerPropertyName = property.Property.Name[0].ToString().ToLower() + property.Property.Name.Substring(1);
Write(property.Property.DataType);
if (nullableTypes.Contains(property.Property.DataType))
Write("?");
Write(" ");
Write(lowerPropertyName);
Write(" = null");
}
#>)
{
var result = new <# Write(entity.EntityName); #>();<#
if (noPropertiesUseSet)
{
#>
result.CheckInstance(authorizingUser);
<#
}#>
<#
foreach (var property in requiredProperties)
{
string lowerPropertyName = property.Property.Name[0].ToString().ToLower() + property.Property.Name.Substring(1);#>
<#Write("result.");
if (property.UseSet)
{
WriteLine(string.Format("Set{0}({1}, authorizingUser);", property.Property.Name, lowerPropertyName));
}
else
{
WriteLine(string.Format("{0} = {1};", property.Property.Name, lowerPropertyName));
}
}
foreach (var property in optionalProperties)
{
string lowerPropertyName = property.Property.Name[0].ToString().ToLower() + property.Property.Name.Substring(1);#>
if (<# Write(lowerPropertyName); #> != null)
<#Write("result.");
if (property.UseSet)
{
WriteLine(string.Format("Set{0}({1}{2}, authorizingUser);", property.Property.Name, lowerPropertyName, (nullableTypes.Contains(property.Property.DataType)) ? ".Value" : string.Empty));
}
else
{
WriteLine(string.Format("{0} = {1}{2};", property.Property.Name, lowerPropertyName, (nullableTypes.Contains(property.Property.DataType)) ? ".Value" : string.Empty));
}
}
#>
this.<# Write(entity.PluralName); #>.Add(result);
this.<# Write(entity.PluralInstanceName); #>.Add(result.CurrentInstance);
return result;
}
<#
}
}
#>
}
}
</code></pre>
<ul>
<li>The referenced GenericInstanceEntity is <a href="http://www.indiegamedevs.com/text/auditableChangeTracking/GenericInstanceEntity%603.txt" rel="nofollow noreferrer">here</a>.</li>
<li>The referenced GenericRootEntity is <a href="http://www.indiegamedevs.com/text/auditableChangeTracking/GenericRootEntity%603.txt" rel="nofollow noreferrer">here</a>.</li>
<li>The results of running the Text Template is <a href="http://www.indiegamedevs.com/text/auditableChangeTracking/TrackedEntityAndInstance.txt" rel="nofollow noreferrer">here</a>.</li>
</ul>
<p>The referenced method and associated constant values are:</p>
<pre><code>internal const string TablePrefix = "FCAS.";
internal const string TableInstancesPrefix = "FCAS.INST.";
internal const string TableMappingPrefix = "FCAS.MAP.";
internal static bool ValuesEqual<TValue>(TValue left, TValue right)
{
var obj = (object)left;
if (obj != null)
if (typeof(IEquatable<TValue>).IsAssignableFrom(typeof(TValue)))
return ((IEquatable<TValue>)left).Equals(right);
else
return left.Equals(right);
else
return ((object)right) == null;
}
</code></pre>
<p>I'm posting this because I'm curious if this is a decent path to follow for such a project, or if I'm sorely mislead. Bidirectional collections of entities are supported; however, single 1:many relationships aren't present within the template's construction. The means to which change tracking is managed is a bit convoluted; however, its goal is to simplify construction of such a model. I'm pretty sure if there's overhead it will mostly be due to the entity framework itself.</p>
<p>I'd like to know if I'm on the right track.</p>
<p>Deletion of primary entities is not allowed, for data retention reasons. The appearance of deletion is handled through flags.</p>
<p>Changes are tracked by Column, and only the columns that you state are, by your own design, malleable. It seems to make more sense than trying to use the Standard T-SQL change tracking, unless there's something I missed about it.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T06:19:17.127",
"Id": "72235",
"Score": "0",
"body": "You should probably narrow down your question. I can hardly imagine someone scrolling through this unreadable wall of code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T06:35:14.830",
"Id": "72236",
"Score": "0",
"body": "Is it that unreadable? I find it easier than comprehending language-centric projects. I had a pattern I wanted structured for a project and instead of trudging through redundant boiler plate code, I chose the solution which constructs the code for me. I do it once, and it replicates automatically, benefits abound since fixes propagate through everything."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T23:53:17.853",
"Id": "41835",
"Score": "1",
"Tags": [
"c#",
"performance",
"entity-framework"
],
"Title": "Entity Framework 6.0.2 - Performance of Auditable Change Tracking Part 2 of 2"
}
|
41835
|
<ol>
<li>An N-Drome is a string that is the same forwards and backwards when split into n-character units. </li>
<li>For example, a string would be a 1-drome if and only if it were a standard palindrome. </li>
<li>An example of a 2-drome would be <code>abcdab</code> since its 2-character units are <code>ab</code>, <code>cd</code>, and <code>ab</code>, and its first and last 2-character units are identical.</li>
</ol>
<hr>
<pre><code>package ndrome;
import java.util.Scanner;
public class NDrome {
public static void main(String[] args) {
System.out.print("enter a string: ");
Scanner in = new Scanner(System.in);
String original = in.nextLine();
System.out.print("enter the n value: ");
int n = in.nextInt();
if(n-1>=original.length()){
System.out.println("Error:N value is greater than string length! exiting...");
System.exit(0);
}
int y = 2;
here: for (int i = 0, j = original.length() - 1;;) {
int x = n - 1;
String a = "", b = "";
while (x >= 0) {
if (i >= original.length()) {
break here;
} else {
a = a + original.charAt(i);
i++;
b = b + original.charAt(j - x);
x--;
}
}
j=j-n;
if (a.equals(b)) {
y = 1;
} else {
y = 0;
break;
}
}
if (y == 1) {
System.out.print("this is a " + n + "-drome");
} else if (y == 0) {
System.out.print("this is not a " + n + "-drome");
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I'm not a Java programmer, but I'll point out some familiar syntactical things I see:</p>\n\n<ul>\n<li><p>You should separate the logic by putting the checking code into a separate function, leaving <code>main()</code> to call the function, handle the input/output, and terminate when needed.</p></li>\n<li><p>What is the purpose of <code>y</code>? From the looks of it, it's used to hold an \"error condition\" for indicating whether or not the inputted string is an N-drome. If so, I think this should be a <code>boolean</code> type and given a relevant name. Either way, <code>y</code> should be renamed to reflect its purpose.</p>\n\n<p>What about strings <code>a</code> and <code>b</code>? Are they the leftmost one and the rightmost one for the original string? You should write out the purpose of these single-char variables to give them more meaning.</p></li>\n<li><p>The lack of an increment value in the <code>for</code>-loop doesn't look too clear. If someone wanted to see what the loop should do after each iteration, they would have to fish through the loop body. If the loop won't be incremented in each control path, then it may not be the best loop type to use.</p></li>\n<li><p>I'm not familiar with <code>break here</code>, but it looks like a <code>goto</code> in C++. I don't think something like that should be done with a loop (or probably anything practical). Again, you may need to rethink how you approach this loop type and execution.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T02:48:30.377",
"Id": "71983",
"Score": "0",
"body": "Y is a flag for my program. True I could have used a boolean type for better understanding. \"a\" and \"b\" are not single character variables, they hold a string and are for temporary use, so that the original string is not affected. Also I could not include the increment and condition statement in the loop as they have to incremented depending on the condition. Break is used to get out of the loop and prevent the program from doing unnecessary computations. Is there any way I can simplify the program with a simpler logic?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T02:55:04.493",
"Id": "71984",
"Score": "0",
"body": "I've never seen an N-drome before (though I was still able to answer), so I'll have to think about that. Again, I'm not fluent in Java, so there's not too much I can say. Please do wait around for others to provide an answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T01:54:35.387",
"Id": "41842",
"ParentId": "41840",
"Score": "5"
}
},
{
"body": "<p>The good news is that your code appears to be correct. The bad news is that it is very hard to follow.</p>\n\n<p>As @Jamal says, it is good practice to <strong>define a function</strong> rather than stuffing everything into <code>main()</code>. There are several reasons for that, including several reasons specific to your code:</p>\n\n<ul>\n<li>Separation of concerns. Each function should do one thing; the function's name should describe its purpose. It seems obvious to have a <code>main()</code> that reads the input and prints the result. The check should be done in an <code>isNDrome()</code> function.</li>\n<li>Code reuse. If everything is in <code>main()</code>, the only way to call your code is by running your program on the command line and writing to its standard input. Forget about ever putting a graphical or web interface on it. Your only reasonable code reuse mechanism is cut-and-paste.</li>\n<li>Unit testing. As it stands, it's barely possible.</li>\n<li>Simpler flow of control. You used a named <code>break</code> statement (with a label poorly named <code>here</code>, I might add). You also used a cryptically named variable (<code>y</code>) to store the result. When you discover that the string is not an N-drome, you have to set the flag (<code>y = 0</code>) <em>then</em> execute a jump (<code>break</code>). All of that would be cleaner with if your code were in an <code>isNDrome()</code> function: just <code>return false</code> as soon as you discover a mismatch.</li>\n</ul>\n\n<p>As I mentioned, your code is hard to read. A significant contributor to the problem is the <strong>proliferation of cryptically named variables</strong>: <code>y</code>, <code>i</code>, <code>j</code>, <code>x</code>, <code>a</code>, <code>b</code>. Only <code>n</code> is self-explanatory due to the nature of the problem. You need to reduce the number of variables <em>and</em> name them better.</p>\n\n<p>Performance-wise, <strong>string concatenation is considered to be a bad idea</strong> in Java. Since strings are immutable, each concatenation creates a new string. The innocuous-looking <code>a = a + original.charAt(i)</code> actually results in the following bytecode (which you can see by running <code>javap -c NDrome</code>):</p>\n\n<blockquote>\n<pre><code> 103: new #16 // class java/lang/StringBuilder\n 106: dup \n 107: invokespecial #17 // Method java/lang/StringBuilder.\"<init>\":()V\n 110: aload 8\n 112: invokevirtual #18 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n 115: aload_2 \n 116: iload 5\n 118: invokevirtual #19 // Method java/lang/String.charAt:(I)C\n 121: invokevirtual #20 // Method java/lang/StringBuilder.append:(C)Ljava/lang/StringBuilder;\n 124: invokevirtual #21 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;\n 127: astore 8\n</code></pre>\n</blockquote>\n\n<p>In other words, it's equivalent to</p>\n\n<pre><code>a = (new StringBuilder(a)).append(original.charAt(i)).toString();\n</code></pre>\n\n<p>Your code probably isn't performance-critical, but it would still be a good habit to avoid concatenating strings carelessly.</p>\n\n<h3>Proposed solution</h3>\n\n<p>The loop can be simplified to just half a dozen lines.</p>\n\n<pre><code>public static boolean isNDrome(CharSequence cs, int n) {\n int len = cs.length();\n\n if (n > len) {\n // Controversial, in my opinion. Arguably, the function should\n // just return false (which it would do naturally if you just\n // remove this check altogether.).\n throw new IllegalArgumentException(\"N exceeds input length\");\n }\n\n if (len % n != 0) {\n return false;\n }\n int chunks = len / n;\n for (int a = 0, z = chunks - 1; a < z; a++, z--) {\n // Compare chunk a, containing n characters from the first half\n // of the string, with chunk z, its counterpart from the second\n // half.\n CharSequence aChars = cs.subSequence(a * n, (a + 1) * n),\n zChars = cs.subSequence(z * n, (z + 1) * n);\n if (!aChars.equals(zChars)) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n\n<p>The code to call it can also look cleaner as a result.</p>\n\n<pre><code>public static void main(String[] args) {\n try (Scanner in = new Scanner(System.in)) {\n System.out.print(\"enter a string: \");\n String original = in.nextLine();\n System.out.print(\"enter the n value: \");\n int n = in.nextInt();\n\n try {\n System.out.printf(\"%s %s a %d-Drome\\n\",\n original,\n isNDrome(original, n) ? \"is\" : \"is not\",\n n);\n } catch (IllegalArgumentException nExceedsLength) {\n System.out.printf(\"Error: %s! Exiting.\\n\",\n nExceedsLength.getMessage());\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T18:12:09.363",
"Id": "72154",
"Score": "0",
"body": "Thank you for your insights. I will remember these points for the next time I code. You mentioned \"javap -c NDrome\". I reckon that is possible in command line. I am new to eclipse IDE. Can you please guide me how to do this in eclipse?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T19:14:09.807",
"Id": "72159",
"Score": "1",
"body": "I don't use Eclipse myself, but [this](http://stackoverflow.com/a/3393114/1157100) may help."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T08:47:25.173",
"Id": "41860",
"ParentId": "41840",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "41860",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T01:37:33.313",
"Id": "41840",
"Score": "5",
"Tags": [
"java",
"optimization",
"palindrome"
],
"Title": "Is my N-drome (variation of palindrome) checking program efficient?"
}
|
41840
|
<p>Implemented iterator for a binary tree and "pre" "in" and "post" order flavors. I'm looking for code review, best practices, optimizations etc.</p>
<pre><code>public class IterateBinaryTree<E> {
private TreeNode<E> root;
/**
* Takes in a BFS representation of a tree, and converts it into a tree.
* here the left and right children of nodes are the (2*i + 1) and (2*i + 2)nd
* positions respectively.
*
* @param items The items to be node values.
*/
public IterateBinaryTree(List<? extends E> items) {
create(items);
}
private static class TreeNode<E> {
TreeNode<E> left;
E item;
TreeNode<E> right;
TreeNode(TreeNode<E> left, E item, TreeNode<E> right) {
this.left = left;
this.item = item;
this.right = right;
}
}
private void create (List<? extends E> items) {
root = new TreeNode<E>(null, items.get(0), null);
final Queue<TreeNode<E>> queue = new LinkedList<TreeNode<E>>();
queue.add(root);
final int half = items.size() / 2;
for (int i = 0; i < half; i++) {
if (items.get(i) != null) {
final TreeNode<E> current = queue.poll();
final int left = 2 * i + 1;
final int right = 2 * i + 2;
if (items.get(left) != null) {
current.left = new TreeNode<E>(null, items.get(left), null);
queue.add(current.left);
}
if (right < items.size() && items.get(right) != null) {
current.right = new TreeNode<E>(null, items.get(right), null);
queue.add(current.right);
}
}
}
}
/**
* Returns the preorder representation for the given tree.
*
* @return the iterator for preorder traversal
*/
public Iterator<E> preOrderIterator () {
return new PreOrderItr();
}
private class PreOrderItr implements Iterator<E> {
private final Stack<TreeNode<E>> stack;
public PreOrderItr() {
stack = new Stack<TreeNode<E>>();
stack.add(root);
}
@Override
public boolean hasNext() {
return !stack.isEmpty();
}
@Override
public E next() {
if (!hasNext()) throw new NoSuchElementException("No more nodes remain to iterate");
final TreeNode<E> node = stack.pop();
if (node.right != null) stack.push(node.right);
if (node.left != null) stack.push(node.left);
return node.item;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Invalid operation for pre-order iterator.");
}
}
/**
* Returns the in-order representation for the given tree.
*
* @return the iterator for preorder traversal
*/
public Iterator<E> inorderIterator() {
return new InOrderItr();
}
private class TreeNodeDataInOrder {
TreeNode<E> treeNode;
boolean visitedLeftBranch;
TreeNodeDataInOrder(TreeNode<E> treeNode, Boolean foo) {
this.treeNode = treeNode;
this.visitedLeftBranch = foo;
}
}
private class InOrderItr implements Iterator<E> {
private final Stack<TreeNodeDataInOrder> stack;
public InOrderItr() {
stack = new Stack<TreeNodeDataInOrder>();
stack.add(new TreeNodeDataInOrder(root, false));
}
@Override
public boolean hasNext() {
return !stack.isEmpty();
}
@Override
public E next() {
if (!hasNext()) throw new NoSuchElementException("No more nodes remain to iterate");
while (hasNext()) {
final TreeNodeDataInOrder treeNodeData = stack.peek();
final TreeNode<E> treeNode = treeNodeData.treeNode;
if (!treeNodeData.visitedLeftBranch) {
if (treeNode.left != null) {
stack.add(new TreeNodeDataInOrder(treeNode.left, false));
}
treeNodeData.visitedLeftBranch = true;
} else {
stack.pop();
if (treeNode.right != null) {
stack.add(new TreeNodeDataInOrder(treeNode.right, false));
}
return treeNode.item;
}
}
throw new AssertionError("A node has not been returned when it should have been.");
}
@Override
public void remove() {
throw new UnsupportedOperationException("Invalid operation for in-order iterator.");
}
}
/**
* Returns the post-order representation for the given tree.
*
* @return the iterator for preorder traversal
*/
public Iterator<E> postOrderIterator() {
return new PostOrderItr();
}
private class TreeNodeDataPostOrder {
TreeNode<E> treeNode;
boolean visitedLeftAndRightBranches;
TreeNodeDataPostOrder(TreeNode<E> treeNode, Boolean visitedLeftAndRightBranches) {
this.treeNode = treeNode;
this.visitedLeftAndRightBranches = visitedLeftAndRightBranches;
}
}
private class PostOrderItr implements Iterator<E> {
private final Stack<TreeNodeDataPostOrder> stack;
private PostOrderItr() {
stack = new Stack<TreeNodeDataPostOrder>();
stack.add(new TreeNodeDataPostOrder(root, false));
}
@Override
public boolean hasNext() {
return !stack.isEmpty();
}
@Override
public E next() {
if (!hasNext()) throw new NoSuchElementException("No more nodes remain to iterate");
while (hasNext()) {
final TreeNodeDataPostOrder treeNodeData = stack.peek();
final TreeNode<E> treeNode = treeNodeData.treeNode;
if (!treeNodeData.visitedLeftAndRightBranches) {
if (treeNode.right != null) {
stack.add(new TreeNodeDataPostOrder(treeNode.right, false));
}
if (treeNode.left != null) {
stack.add(new TreeNodeDataPostOrder(treeNode.left, false));
}
treeNodeData.visitedLeftAndRightBranches = true;
} else {
stack.pop();
return treeNode.item;
}
}
throw new AssertionError("A node has not been returned when it should have been.");
}
@Override
public void remove() {
throw new UnsupportedOperationException("Invalid operation for post-order iterator.");
}
}
public static void main(String[] args) {
Iterator<Integer> itr = null;
Integer[] arr = {1, 2, 3, 4, null, 6, 7};
Integer[] arr1 = {1, 2, 3, 4, 5, 6, 7}; // full
Integer[] arr2 = {1, 2, null, 3, null, null, null}; // left skew
Integer[] arr3 = {1, null, 3, null, null, null, 7}; // right skew
Integer[] arr4 = {1}; // single element
System.out.println("---- TESTING FOR PREORDER -----------");
IterateBinaryTree<Integer> iteratePreOrder = new IterateBinaryTree<Integer>(Arrays.asList(arr));
System.out.print("Expected: 1 2 4 3 6 7, Actual: ");
itr = iteratePreOrder.preOrderIterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
System.out.println();
IterateBinaryTree<Integer> iteratePreOrder1 = new IterateBinaryTree<Integer>(Arrays.asList(arr1));
System.out.print("Expected: 1 2 4 5 3 6 7, Actual: ");
itr = iteratePreOrder1.preOrderIterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
System.out.println();
IterateBinaryTree<Integer> iteratePreOrder2 = new IterateBinaryTree<Integer>(Arrays.asList(arr2));
System.out.print("Expected: 1 2 3, Actual: ");
itr = iteratePreOrder2.preOrderIterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
System.out.println();
IterateBinaryTree<Integer> iteratePreOrder3 = new IterateBinaryTree<Integer>(Arrays.asList(arr3));
System.out.print("Expected: 1 3 7, Actual: ");
itr = iteratePreOrder3.preOrderIterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
System.out.println();
IterateBinaryTree<Integer> iteratePreOrder4 = new IterateBinaryTree<Integer>(Arrays.asList(arr4));
System.out.print("Expected: 1, Actual: ");
itr = iteratePreOrder4.preOrderIterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
System.out.println();
System.out.println("---- TESTING FOR INORDER -----------");
IterateBinaryTree<Integer> iterateInOrder = new IterateBinaryTree<Integer>(Arrays.asList(arr));
System.out.print("Expected: 4 2 1 6 3 7, Actual: ");
itr = iterateInOrder.inorderIterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
System.out.println();
IterateBinaryTree<Integer> iterateInOrder1 = new IterateBinaryTree<Integer>(Arrays.asList(arr1));
System.out.print("Expected: 4 2 5 1 6 3 7, Actual: ");
itr = iterateInOrder1.inorderIterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
System.out.println();
IterateBinaryTree<Integer> iterateInOrder2 = new IterateBinaryTree<Integer>(Arrays.asList(arr2));
System.out.print("Expected: 3 2 1, Actual: ");
itr = iterateInOrder2.inorderIterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
System.out.println();
IterateBinaryTree<Integer> iterateInOrder3 = new IterateBinaryTree<Integer>(Arrays.asList(arr3));
System.out.print("Expected: 1 3 7, Actual: ");
itr = iterateInOrder3.inorderIterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
System.out.println();
IterateBinaryTree<Integer> iterateInOrder4 = new IterateBinaryTree<Integer>(Arrays.asList(arr4));
System.out.print("Expected: 1, Actual: ");
itr = iterateInOrder4.inorderIterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
System.out.println();
System.out.println("---- TESTING FOR POSTORDER -----------");
IterateBinaryTree<Integer> iteratePostOrder = new IterateBinaryTree<Integer>(Arrays.asList(arr));
System.out.print("Expected: 4 2 6 7 3 1, Actual: ");
itr = iteratePostOrder.postOrderIterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
System.out.println();
IterateBinaryTree<Integer> iteratePostOrder1 = new IterateBinaryTree<Integer>(Arrays.asList(arr1));
System.out.print("Expected: 4 5 2 6 7 3 1, Actual: ");
itr = iteratePostOrder1.postOrderIterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
System.out.println();
IterateBinaryTree<Integer> iteratePostOrder2 = new IterateBinaryTree<Integer>(Arrays.asList(arr2));
System.out.print("Expected: 3 2 1, Actual: ");
itr = iteratePostOrder2.postOrderIterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
System.out.println();
IterateBinaryTree<Integer> iteratePostOrder3 = new IterateBinaryTree<Integer>(Arrays.asList(arr3));
System.out.print("Expected: 7 3 1, Actual: ");
itr = iteratePostOrder3.postOrderIterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
System.out.println();
IterateBinaryTree<Integer> iteratePostOrder4 = new IterateBinaryTree<Integer>(Arrays.asList(arr4));
System.out.print("Expected: 1, Actual: ");
itr = iteratePostOrder4.postOrderIterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-11T05:45:46.343",
"Id": "169628",
"Score": "0",
"body": "you might be interested in this post http://techieme.in/postorder-node-iterator-of-binary-tree/"
}
] |
[
{
"body": "<p>I haven't checked the correctness of the implementation, just some notes about the code:</p>\n\n<ol>\n<li><p><code>Stack</code> seems more or less deprecated. <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Stack.html\" rel=\"nofollow\">Javadoc says the following</a>:</p>\n\n<blockquote>\n <p>A more complete and consistent set of LIFO stack \n operations is provided by the Deque interface and its\n implementations, which should be used in preference to this class.</p>\n</blockquote></li>\n<li><blockquote>\n<pre><code>public class IterateBinaryTree<E> {\n</code></pre>\n</blockquote>\n\n<p><a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367\" rel=\"nofollow\">Class names should be nouns</a>, not verbs. I'd call it <code>IterableBinaryTree</code> instead.</p></li>\n<li><blockquote>\n<pre><code>TreeNode(TreeNode<E> left, E item, TreeNode<E> right) {\n</code></pre>\n</blockquote>\n\n<p>The first and last parameters are unnecessary, the code always call the constructor with <code>null</code> values for <code>left</code> and <code>right</code>.</p></li>\n<li><p><code>Boolean</code> (in the parameters) could the primitive <code>boolean</code> here:</p>\n\n<blockquote>\n<pre><code>TreeNodeDataPostOrder(TreeNode<E> treeNode, Boolean visitedLeftAndRightBranches) {\n this.treeNode = treeNode;\n this.visitedLeftAndRightBranches = visitedLeftAndRightBranches;\n}\n</code></pre>\n</blockquote>\n\n<p>It will throw an NPE when it's called with <code>null</code> so prevent it with a compile time check</p>\n\n<p>Anyway, in every existing callee calls it with <code>false</code>, it can be simply removed:</p>\n\n<pre><code>TreeNodeDataPostOrder(TreeNode<E> treeNode) {\n this.treeNode = treeNode;\n}\n</code></pre></li>\n<li><p><code>foo</code> could have a descriptive name:</p>\n\n<blockquote>\n<pre><code> TreeNodeDataInOrder(TreeNode<E> treeNode, Boolean foo) {\n this.treeNode = treeNode;\n this.visitedLeftBranch = foo;\n }\n</code></pre>\n</blockquote>\n\n<p>The issue is the same here, the code always pass it a <code>false</code>, so it can be removed too:</p>\n\n<pre><code>TreeNodeDataInOrder(TreeNode<E> treeNode) {\n this.treeNode = treeNode;\n}\n</code></pre></li>\n<li><blockquote>\n<pre><code>for (int i = 0; i < half; i++) {\n if (items.get(i) != null) {\n final TreeNode<E> current = queue.poll(); \n final int left = 2 * i + 1;\n final int right = 2 * i + 2;\n\n if (items.get(left) != null) {\n current.left = new TreeNode<E>(items.get(left));\n queue.add(current.left);\n }\n if (right < items.size() && items.get(right) != null) {\n current.right = new TreeNode<E>(items.get(right));\n queue.add(current.right);\n }\n }\n}\n</code></pre>\n</blockquote>\n\n<p>You can use a <a href=\"http://blog.codinghorror.com/flattening-arrow-code/\" rel=\"nofollow\">guard clause here to make the code flatten</a>.</p>\n\n<pre><code>for (int i = 0; i < half; i++) {\n if (items.get(i) == null) {\n continue;\n }\n final TreeNode<E> current = queue.poll();\n final int left = 2 * i + 1;\n ...\n}\n</code></pre></li>\n<li><p>I'd avoid abbreviations like <code>Itr</code> (in <code>PreOrderItr</code> and in others). I've found that they undermine autocomplete. (When you type <code>PreOrderIte</code> and press Ctrl+Space in Eclipse it founds nothing.)</p></li>\n<li><blockquote>\n<pre><code>private final Stack<TreeNode<E>> stack;\n\npublic PreOrderItr() {\n stack = new Stack<TreeNode<E>>();\n stack.add(root);\n}\n</code></pre>\n</blockquote>\n\n<p>You could put the object creation to the same line as the field declaration:</p>\n\n<pre><code>private class PreOrderItr implements Iterator<E> {\n private final Stack<TreeNode<E>> stack = new Stack<TreeNode<E>>();;\n\n public PreOrderItr() {\n stack.add(root);\n }\n</code></pre>\n\n<p>I think it's easier to read and a line shorter.</p></li>\n<li><blockquote>\n<pre><code>if (!treeNodeData.visitedLeftBranch) {\n addStackIfNotNull(treeNode.left);\n if (treeNode.left != null) {\n stack.add(new TreeNodeDataInOrder(treeNode.left));\n }\n treeNodeData.visitedLeftBranch = true;\n} else {\n stack.pop();\n addStackIfNotNull(treeNode.right);\n if (treeNode.right != null) {\n stack.add(new TreeNodeDataInOrder(treeNode.right));\n }\n return treeNode.item;\n}\n</code></pre>\n</blockquote>\n\n<p>You could extract out a method here:</p>\n\n<pre><code>private void addStackIfNotNull(final TreeNode<E> node) {\n if (node != null) {\n stack.add(new TreeNodeDataInOrder(node));\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>if (!treeNodeData.visitedLeftBranch) {\n addStackIfNotNull(treeNode.left);\n treeNodeData.visitedLeftBranch = true;\n} else {\n stack.pop();\n addStackIfNotNull(treeNode.right);\n return treeNode.item;\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T00:53:30.843",
"Id": "43471",
"ParentId": "41844",
"Score": "3"
}
},
{
"body": "<p>A minor bug: You get an <code>IndexOutOfBoundsException</code> for an empty list in <code>IterateBinaryTree.create(List<? extends E> items)</code>. You don't have a comment stating you need to input a list containing at least something. Consider returning <code>IllegalArgumentException</code> and adding a comment.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-17T11:07:44.440",
"Id": "63140",
"ParentId": "41844",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T02:29:18.747",
"Id": "41844",
"Score": "2",
"Tags": [
"java",
"tree",
"iterator"
],
"Title": "Iterator for binary tree - pre, in, and post order iterators"
}
|
41844
|
<p>This is a programming practice that our teacher gave us, and I would appreciate if someone can look over my program and tell me if I did a good job.</p>
<p>Basically, the context is I joined a company and am supposed to write a program in C that takes three inputs (ft of steel, number of ball bearings, and lbs of bronze), and returns how many bells and whistles can be made the next day. </p>
<p>Making a whistle requires 0.5 ft of steel and 1 ball bearing. Making a bell requires 1.10 lbs of bronze (.75 lbs of bronze and 1 clapper (.35 lbs of bronze)).</p>
<p>This is the program I have written. I apologize if it seems messy.</p>
<pre><code>#include <stdio.h>
#include <stdbool.h>
void PrintLine();
int CalculateWhistles(int steel, int bearings);
int CalculateBells(int bronze);
int main() {
bool runProgram = true;
int runAgain = 0;
while (runProgram == true) {
int ftSteelIn = 0;
int numBallBearingIn = 0;
int ibsBronzeIn = 0;
printf("\n\n"); // Formatting...
PrintLine();
printf(" How many feet of steel was received today: "); // Steel received
scanf("%d", &ftSteelIn);
printf(" How many ball bearings were received today: "); // Ball bearings received
scanf("%d", &numBallBearingIn);
printf(" How many pounds of bronze was received today: "); // Bronze received
scanf("%d", &ibsBronzeIn);
PrintLine(); // Print line
PrintLine(); // Print line
// Print company logo and program title
printf(" Acme Corporation\n");
printf(" Product Report\n");
PrintLine();// Print line
// Print number of bells and whistles
printf(" Number of Bells %d\n", CalculateBells(ibsBronzeIn));
printf(" Number of Whistles %d\n", CalculateWhistles(ftSteelIn, numBallBearingIn));
PrintLine(); // Print line
PrintLine();
printf("\n\n");
PrintLine();
// Ask the user if they would like to run the program again
printf(" Would you like to run the program again? ('1' for yes, '2' for no): ");
scanf("%d", &runAgain);
PrintLine();
// If user does not say 'yes', end the program and say goodbye
if (runAgain != 1) {
printf("\n Exitting the program. Have a good day.\n\n");
PrintLine();
runProgram = false;
}
}
return 0;
}
void PrintLine() {
int i = 0;
printf(" ");
while (i <= 70) {
printf("-");
i++;
}
printf("\n");
}
int CalculateWhistles(int steel, int bearings) {
steel = steel / 0.5;
if (steel < bearings) {
return steel;
}
else if (bearings < steel) {
return bearings;
}
}
int CalculateBells(int bronze) {
int bells = bronze / 1.1;
return bells;
}
</code></pre>
<p>It runs fine with no errors. There is a second part where I calculate the remainder, but I want some feedback before I go on to that part.</p>
<p>Any advice would be appreciated, how to make it more efficient or anything like that (I'm just learning C).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T04:07:01.170",
"Id": "71994",
"Score": "1",
"body": "Forgot to add, the instructor wants the PrintLine() functions for the output."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T12:17:16.207",
"Id": "72056",
"Score": "0",
"body": "Since you mentioned you are a beginner, and you seem eager to learn, [check out this article](http://drupal.technicat.com/writing/programming.html). It's full of good programming habits and if you get into them now, you will have a much easier time learning more about programming."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:43:18.377",
"Id": "72132",
"Score": "0",
"body": "Thanks, I definitely want to get better and will read it when I have the time! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T14:47:48.197",
"Id": "72292",
"Score": "0",
"body": "\"PrintLine(); // Print line\" \n\nThis may be the best code comment I have ever seen :o)"
}
] |
[
{
"body": "<p>Roughly 50% of all programming is about dealing with errors. You say your code works, but it doesn't handle errors and therefore doesn't work.</p>\n\n<p><strong>Example 1</strong>:</p>\n\n<pre><code>How many feet of steel was received today: four\n</code></pre>\n\n<p>Program doesn't say \"Error, try again\". Instead it displays all prompts without waiting for any user input and exits.</p>\n\n<p><strong>Example 2</strong>:</p>\n\n<pre><code>How many feet of steel was received today: 3.7\n</code></pre>\n\n<p>Program doesn't say \"Error, try again\". Instead it displays all prompts without waiting for any user input and exits.</p>\n\n<p><strong>Example 3</strong>:</p>\n\n<pre><code>How many feet of steel was received today: 3 4\n</code></pre>\n\n<p>Program doesn't say \"Error, try again\". Instead it assumes 3 feet of steel; displays \"How many ball bearings\" and doesn't wait for user input and assumes 4 ball bearings.</p>\n\n<p><strong>Example 4</strong>:</p>\n\n<pre><code>Would you like to run the program again? ('1' for yes, '2' for no): yes\n</code></pre>\n\n<p>Program doesn't say \"Error, try again\". Instead it exits.</p>\n\n<p><strong>Example 5</strong>:</p>\n\n<pre><code>How many feet of steel was received today: -99\nHow many ball bearings were received today: -99\nHow many pounds of bronze was received today: -99\n</code></pre>\n\n<p>Program decides you can make <code>-89</code> bells and <code>-198</code> whistles.</p>\n\n<p><strong>Example 6</strong>:</p>\n\n<pre><code>How many feet of steel was received today: 999999999999999999\nHow many ball bearings were received today: 999999999999999999\nHow many pounds of bronze was received today: 999999999999999999\n</code></pre>\n\n<p>Program decides you can make <code>-1351471477</code> bells and <code>-2147483648</code> whistles.</p>\n\n<p><strong>Example 7</strong>:</p>\n\n<pre><code>How many feet of steel was received today: 200\nHow many ball bearings were received today: 100\n</code></pre>\n\n<p>Program decides you can make <code>0</code> whistles. <em>Note: unlike the previous examples, this is not a \"failed to check for invalid input\" problem.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T04:03:32.607",
"Id": "71993",
"Score": "0",
"body": "Thanks for the advice, I'll change up the program. Some of these I will add if I have time, but I don't think they want too complex a program (this is literally a beginners course). I'm a bit of an overachiever ;), so I'll add to it but I don't want the grader getting frustrated at having to check my code for all the extra 'junk'."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T04:07:35.557",
"Id": "71995",
"Score": "0",
"body": "@Qwurticus: You can always keep a personal copy with all the changes. It's unfortunate that schools have to hold students to such constraints, but that's just how it is. What matters is that you're *improving* overall."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T06:20:12.803",
"Id": "72008",
"Score": "7",
"body": "@Brendan The other 50% is documentation!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T09:59:02.067",
"Id": "72037",
"Score": "0",
"body": "@Qwurticus my teached did actually bother me with all of these, getting a full score was beyond most of the students (I think I only did it once or twice) Viewing back on all I had to do, I created [smarti](https://github.com/theraot/smarti/blob/master/smarti.c) (for smart input) you can try readInt to read your numbers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T11:52:37.647",
"Id": "72052",
"Score": "1",
"body": "I'd upvote you if you changed that overly exaggerated 50% up there. If you plan your application properly, adding error messages and warnings should not take more more than 10% of total development time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T12:03:06.510",
"Id": "72053",
"Score": "1",
"body": "@Kevin to try to give any general number of percentage on debugging in a project is impossible. It depends on a number of factors: skill, methodology, code base, programming language and personality to mention some."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T12:04:13.703",
"Id": "72054",
"Score": "2",
"body": "@daramarak It's about adding error handling, not about debugging."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T12:16:30.827",
"Id": "72055",
"Score": "0",
"body": "@Kevin, the wording is \"dealing with errors\" that definitely includes debugging. So debugging is perhaps a subset of dealing with errors, but that doesn't making a general about time usage statement any easier."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T11:47:13.910",
"Id": "72261",
"Score": "0",
"body": "For your last error, I think you have your numbers switched; `200 / .5 = 400` **not** `100`. I've never done any real C programming, but the compiler doesn't look for branches that don't explicitly return?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T14:50:24.520",
"Id": "72296",
"Score": "0",
"body": "@Kevin ITIL tends to take the documentation up to 50%"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T03:29:47.930",
"Id": "41849",
"ParentId": "41845",
"Score": "30"
}
},
{
"body": "<ul>\n<li><p>Although it is common to have functions start with a lowercase letter, it depends on what is preferred in your programming environment. You can choose either case, preferably the one mentioned, unless your instructor has you use a certain one.</p></li>\n<li><p>I'd consider removing all these <code>PrintLine()</code> calls, as well as the function itself, if they're not that necessary. It just clutters the code, especially with most of the work being done in <code>main()</code>. Since the instructor requires this, you'll just have to keep them. But if you're keeping or want to keep personal copies of your assigned programs, you may make this change.</p></li>\n<li><p>You don't need the <code>else if</code> statement in <code>CalculateBells()</code>. As that statement is only the opposite of the first one, a plain <code>else</code> will work. You may still keep it that way in case you may need to make additions at some point.</p></li>\n<li><p>This:</p>\n\n<pre><code>steel = steel / 0.5;\n</code></pre>\n\n<p>can be shortened to this:</p>\n\n<pre><code>steel /= 0.5;\n</code></pre>\n\n<p>This works for all mathematical operators and similar situations.</p></li>\n<li><p>For conditional statements like this, you don't need to include the <code>true</code>:</p>\n\n<pre><code>while (runProgram == true)\n</code></pre>\n\n<p>This does the same thing:</p>\n\n<pre><code>while (runProgram)\n</code></pre>\n\n<p>If you were to use something with <code>false</code>, you would have this:</p>\n\n<pre><code>while (!someCondition)\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T03:58:34.973",
"Id": "71991",
"Score": "0",
"body": "Unfortunately, the $printLine()$ functions are necessary, the teacher wants the output to have those long lines. :/ I'll change the if/else to an else statement, that was stupid on my part, but the function is supposed to return an integer and it gives back the number I want, but I'll change it to a float or double and see how that works. Thanks for the advice!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T04:00:20.247",
"Id": "71992",
"Score": "0",
"body": "@Qwurticus: That's fine in this case. Just wanted to make sure this wasn't something you wanted to do. :-) Just make sure to *not* edit the original code, otherwise answers will be invalidated. You may still add a note about the printing functions so that others are aware."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T06:19:07.800",
"Id": "72007",
"Score": "3",
"body": "@Jamal Just to pick nits, there isn't really a \"C naming convention\", at least, not in the sense that it's some \"official\" C way. More importantly, a programmer should use a style convention consistent with the other programmers he is working with, or if he is alone, at least consistently throughout all of his code so he doesn't confuse himself later. There's a zillion popular naming conventions for programs written in C, the *real* problems occur when different ones collide."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T06:27:13.370",
"Id": "72009",
"Score": "0",
"body": "@JasonC: That's a good point. It is just something I'm used to seeing. Thanks! I'll make some changes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T06:40:10.683",
"Id": "72011",
"Score": "5",
"body": "Actually, `CalculateBells()` and `CalculateWhistles()` _should_ return `int`s. What kind of factory would produce half a whistle? And what kind of sound would half a whistle make?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T06:43:11.137",
"Id": "72014",
"Score": "0",
"body": "@200_success: Fair enough. I wasn't quite sure what was supposed to happen there, and I assumed it was an error."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T11:41:59.747",
"Id": "72051",
"Score": "1",
"body": "@200_success: half as good sound :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T23:23:57.473",
"Id": "72201",
"Score": "0",
"body": "@200_success: that's an amazing koan."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T03:51:38.650",
"Id": "41850",
"ParentId": "41845",
"Score": "11"
}
},
{
"body": "<p>I'm not sure how far you are in your class, but here are a few notes I didn't see in other answers:</p>\n\n<ul>\n<li><p>It is possible your <code>CalculateWhistles()</code> method could fail the <code>if</code> condition tests and reach the end of the non-<code>void</code> method. Your methods should <strong>ALWAYS</strong> have a return statement for <em>every</em> case, even if you have to return nothing. For example, what will your code do if <code>steel</code> is equal to <code>bearings</code>?</p>\n\n<blockquote>\n<pre><code>int CalculateWhistles(int steel, int bearings) {\n steel = steel / 0.5;\n if (steel < bearings) {\n return steel;\n }\n else if (bearings < steel) {\n return bearings;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>Because this method fails to return a value if the test conditions fail, it wouldn't compile on my system. I have a more strict compiler than most, so that tells me that you aren't compiling with warnings enabled, which you should have turned on. I rewrote the method so that it would compile on my system properly.</p>\n\n<pre><code>int calculateWhistles(int steel, int bearings)\n{\n steel /= 0.5;\n if (steel <= bearings) return steel;\n else return bearings;\n}\n</code></pre></li>\n<li><p>Use a <code>for</code> loop in your <code>PrintLine()</code> method.</p>\n\n<blockquote>\n<pre><code>void PrintLine() {\n int i = 0;\n printf(\" \");\n while (i <= 70) {\n printf(\"-\");\n i++;\n }\n printf(\"\\n\");\n}\n</code></pre>\n</blockquote>\n\n<p>However, when examining the <code>for</code> loop, all it does is print out some space and a bunch of dashes. <code>printf()</code> statements can be expensive on a system, so to maximize efficiency, you should use as few of them as possible.</p>\n\n<pre><code>void printLine()\n{\n printf(\" ------------------------------------------\\n\");\n}\n</code></pre>\n\n<p>But here is where we can really boost the efficiency, since your teacher is requiring the use of this method: use the <code>inline</code> keyword on the function. The point of making a function <code>inline</code> is to hint to the compiler that it is worth making some form of extra effort to call the function faster than it would otherwise - generally by substituting the code of the function into its caller. As well as eliminating the need for a call and return sequence, it might allow the compiler to perform certain optimizations between the bodies of both functions.</p>\n\n<p>This <strong>does not mean</strong> that you should <code>inline</code> everything.</p>\n\n<p>Use <code>inline</code>:</p>\n\n<ul>\n<li>instead of <code>#define</code></li>\n<li>with <strong>very small</strong> functions are good candidates for <code>inline</code>: faster code and smaller executables (more chances to stay in the code cache)</li>\n<li>when the function is small <strong>and</strong> called very often</li>\n</ul>\n\n<p>Don't use <code>inline</code>:</p>\n\n<ul>\n<li>with large functions: leads to larger executables, which significantly impairs performance regardless of the faster execution that results from the calling overhead</li>\n<li>when the function is seldom used</li>\n</ul>\n\n<p>For your functions it is alright to use them though.</p>\n\n<pre><code>inline void printLine()\n{\n puts(\"------------------------------------------\");\n}\n</code></pre></li>\n<li><p>You don't need the <code>bells</code> variable in the method <code>CalculateBells()</code>.</p>\n\n<blockquote>\n<pre><code>int CalculateBells(int bronze) {\n int bells = bronze / 1.1;\n return bells;\n}\n</code></pre>\n</blockquote>\n\n<p>You can just return the math you do to the parameter alone, surrounded by parenthesis.</p>\n\n<pre><code>int calculateBells(int bronze)\n{\n return (bronze / 1.1);\n}\n</code></pre></li>\n<li><p>Some of your comments I don't find necessary.</p>\n\n<blockquote>\n<pre><code> printLine(); // Print line\n</code></pre>\n</blockquote></li>\n<li><p>You can initialize all of your variables of one type on one line. This will help later with organization of larger programs.</p>\n\n<blockquote>\n<pre><code>int ftSteelIn = 0;\nint numBallBearingIn = 0;\nint ibsBronzeIn = 0;\n</code></pre>\n</blockquote>\n\n<p>This will also cut down on your lines of code a bit.</p>\n\n<pre><code>int ftSteelIn = 0, numBallBearingIn = 0, ibsBronzeIn = 0;\n</code></pre></li>\n<li><p>If you put all of your methods before <code>main()</code>, you don't have to prototype them beforehand. However, since we are using <code>__inline__</code>, we will have to use prototypes.e</p></li>\n<li><p>I would have the user input a <code>char</code> of either \"y\" or \"n\" to indicated if they want to run the program again, perhaps in a <code>do-while</code> loop. </p></li>\n<li><p>You could use the function <a href=\"http://www.cplusplus.com/reference/cstdio/puts/\" rel=\"nofollow\"><code>puts()</code></a> instead of <code>printf()</code> in some places.</p></li>\n<li><p>Personally I feel like your \"report\" has too much space in it.</p>\n\n<blockquote>\n<pre><code> printf(\" Acme Corporation\\n\");\n</code></pre>\n</blockquote>\n\n<p>But that is to your discretion.</p></li>\n</ul>\n\n<hr>\n\n<h2>Final code (with my changed implemented):</h2>\n\n<pre><code>#include <stdio.h>\n#include <stdbool.h>\n#include <ctype.h>\n\nvoid printLine();\nint calculateWhistles(int steel, int bearings);\nint calculateBells(int bronze);\n\ninline void printLine()\n{\n puts(\"----------------------------------------------------\");\n}\n\ninline int calculateWhistles(int steel, int bearings)\n{\n steel /= 0.5;\n if (steel <= bearings) return steel;\n else return bearings;\n}\n\ninline int calculateBells(int bronze)\n{\n return (bronze / 1.1);\n}\n\nint main()\n{\n bool isRunning = true;\n char runAgain = 'n'; // default to no\n\n do\n {\n int ftSteelIn = 0, numBallBearingIn = 0, ibsBronzeIn = 0;\n\n printf(\"How many feet of steel was received today? \");\n scanf(\"%d\", &ftSteelIn);\n printf(\"How many ball bearings were received today? \");\n scanf(\"%d\", &numBallBearingIn);\n printf(\"How many pounds of bronze was received today? \");\n scanf(\"%d\", &ibsBronzeIn);\n for(; getchar() != '\\n'; getchar())\n {\n } // eat superfluous input, including the newline\n\n // Print company logo and program title\n puts(\"\\nAcme Corporation: Product Report\");\n printLine();\n\n // Print number of bells and whistles\n printf(\"Number of Bells: %d\\n\", calculateBells(ibsBronzeIn));\n printf(\"Number of Whistles: %d\\n\", calculateWhistles(ftSteelIn, numBallBearingIn));\n\n // Ask the user if they would like to run the program again\n printf(\"Would you like to run the program again? (y/N) \"); // capital 'N' to suggest it is default\n scanf(\"%c\", &runAgain);\n\n if (tolower(runAgain) != 'y') isRunning = false;\n } while (isRunning);\n\n puts(\"Exitting the program. Have a good day.\");\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T05:43:41.637",
"Id": "72001",
"Score": "0",
"body": "Thanks! I didn't think the if/else statements through too much. The printLine() statements are redundant, I'll remove them (I should have wrote the program and then added formatting). Is there a real difference between using a for loop instead of a while loop for the printLine()? We haven't learned too much about C yet (I'm pretty good with Python and C++ and usually use for loops). I used prototypes because our instructor wants us to use them to show we know \"how functions work\" *Rolls eyes*."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T05:56:08.620",
"Id": "72004",
"Score": "0",
"body": "@Qwurticus Ahh, \"prototypes\" was the word I was looking for! :) In the case where I used the `for` loop, there isn't much difference between that and a `while` loop besides looking cleaner. It should perform in the exact same way (though with the `for` loop I am seeing fewer instructions when I look at the Assembly output, so there may be a negligible efficiency increase)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T06:05:01.760",
"Id": "72005",
"Score": "1",
"body": "Ah, okay. I like efficiency (and I agree that for loops look cleaner ;) )."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T06:42:55.337",
"Id": "72012",
"Score": "0",
"body": "Apparently I have to declare that I am using C99 or later, and my instructor hasn't talked about that. I'd declare i outside but I think the while loop is probably cleaner in this case (maybe..)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T06:43:08.057",
"Id": "72013",
"Score": "0",
"body": "For `PrintLine()`, I'd just hard-code one long string literal: `printf(\" ---------------------\\n\");` — the code does exactly what it looks like, and it's slightly more efficient."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T06:45:01.220",
"Id": "72015",
"Score": "4",
"body": "The compiler should alert you to the first point (reaching the end of a non-void function) if you turn on warnings. For that reason, always compile with warnings turned on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:27:58.797",
"Id": "72365",
"Score": "1",
"body": "@syb0rg I upvoted, but I think you should consider adding a warning about inlining functions. `inline` does make sense for this example, but you have to be careful with noobies since they may decide to inline everything, regardless of the size of the project."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:32:04.723",
"Id": "72367",
"Score": "0",
"body": "@DavidSchwartz I'll make an edit as soon as possible, thanks."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T04:35:59.360",
"Id": "41851",
"ParentId": "41845",
"Score": "16"
}
},
{
"body": "<p>The other answers here are very good, especially the accepted one by Brendan. I would like to add one additional comment. You wrote:</p>\n\n<blockquote>\n <p>Any advice would be appreciated, <em>how to make it more efficient</em> ...</p>\n</blockquote>\n\n<p>I want to touch on your comment about making it \"more efficient\" with just a simple comment: Don't. Write your code, get it working. Code cleanly and do what makes sense to keep your design straightforward. Document your code, think about others who might view or work with it, and think about yourself in the future coming back to it and not remembering what you were thinking when you wrote it.</p>\n\n<p>Once your program is written, <em>then</em> ask yourself: Is it not meeting the hard performance requirements I have set? Is the UI too slow? Is some algorithm here or there taking too long and actually affecting usage of my program in a noticeable and negative way? Am I running out of memory somewhere? If so, then first concentrate on improving any algorithms or logic on a higher level; perhaps, for example, you are sorting a large amount of data and it is definitively too slow or resource intensive -- first consider a different sorting algorithm. After you are satisfied with that, then if necessary you can proceed to add further micro-optimizations but only after you have clearly identified where the actual bottlenecks are (e.g. profiling, or measuring function times, not just blind guessing). </p>\n\n<p>Do not worry about wasting a few CPU cycles here or there if it leads to clean, maintainable, clear code, especially during initial development where you may be changing things unexpectedly. You want to avoid premature optimizations that both distract you from your real goal and lock you in to a certain implementation that cannot be easily changed if and when it is necessary.</p>\n\n<p>It is very common for new programmers to start wanting to make unnecessary micro-optimizations right off the bat; especially in areas that don't really matter (e.g. writing a program that say, generates image files, but trying to optimize the code that checks if an output filename string is valid.) Don't go down that path! Design -> Implement -> Test -> Profile -> Optimize -> Test, and only do the last 3 if your performance requirements aren't met.</p>\n\n<p>I know this is may be general advice and a bit premature, but if you keep this in mind (as well as all the information in the other great answers here) you will be setting yourself up for a smooth and productive experience.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T06:28:26.573",
"Id": "72010",
"Score": "1",
"body": "Thanks! I definitely get impatient and will focus more on actually getting the code working. I've heard horror stories about programs that work just fine but are impossible to read, and what good is that to someone who wants to improve it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T18:55:22.707",
"Id": "72349",
"Score": "0",
"body": "@Qwurticus It's great for a contractor being paid by the hour, actually. There's nothing contractors love more than big, messy programs that rack up the billable hours. Plus, they don't have to do any clean up because once the contract is up, they're off to the next gig."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:18:47.537",
"Id": "72404",
"Score": "0",
"body": "@corsiKa I hope you are being facetious, because that is terrible advice, especially for a new programmer. If a contractor wants a \"next gig\", that's not the best work ethic. It works for me, though, when I eventually get hired to clean up your mess. I make far more money from repeat clients (and the references they bring) than from maintenance -- plus good work leads to longer term lead/consulting jobs (and happier end-users, there's some karma point opportunities there -- next time you get frustrated with a piece of software, perhaps the developers behind it had that same bad attitude)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T06:15:40.440",
"Id": "41855",
"ParentId": "41845",
"Score": "13"
}
},
{
"body": "<p>You have some 'magic numbers' embedded in the code which are a really bad idea as they make it difficult to maintain or change. You should separate out the fixed ratios and give them meaningful names. Using #define for a numerical constant isn't too bad in C as it doesn't have a const modifier. So add #define CLAPPER_BRONZE 0.35 etc.</p>\n\n<p>A final subtle point is that you've stated a whistle needs an X and a Y and you've added X's and Y's weights (0.75 + 0.35) and implemented a function to divide by 1.1.</p>\n\n<p>It would actually be much better to capture the knowledge you have about the domain more directly and transparently in the code. If you're told making a widget needs an X and a Y then code that. Then worry about coding what an X needs. This may seem like overkill but it will be much easier to change the code to adapt to changing circumstances. (E.g. we switch to making X's out of something else.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:37:14.283",
"Id": "72128",
"Score": "0",
"body": "I couldn't recall if my instructor went over #define so I didn't want to throw that in there yet (This is a freshman course in C), but I'll keep it in mind for the next programming practice. Could you possibly explain your final point about making the \"domain more transparent\"? If it takes 1.1 lbs of bronze to create a bell, is not simple just to divide by that number to get the optimum number of bells that can be produced? :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T18:05:15.133",
"Id": "72149",
"Score": "0",
"body": "That seems like massive overkill when X is \"0.75lb of bronze\" and \"Y is 0.35lb of bronze\", unless all you're suggesting is to replace `bronze / 1.1` with `bronze / (BELL_BRONZE + CLAPPER_BRONZE)`. How else would you sensibly code the requirement that making a bell requires 0.75lb of bronze, and then another 0.35lb of bronze?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T12:21:00.027",
"Id": "72268",
"Score": "0",
"body": "Of course it's overkill for this little example. Just trying to stimulate the braincells for a real case."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T09:22:18.543",
"Id": "41862",
"ParentId": "41845",
"Score": "5"
}
},
{
"body": "<p>Minor thing: Don't write</p>\n\n<pre><code>steel = steel / 0.5;\n</code></pre>\n\n<p>The result of dividing steel by 0.5 isn't an amount of steel. It's an upper limit for the number of whistles you can make. So write</p>\n\n<pre><code>int whistles = steel / 0.5;\n</code></pre>\n\n<p>Now the big thing: You don't have \"steel\". You have \"feet of steel\". What if the spec changes and the amount of steel is entered in meters? Or in pound, and you have to calculate the length? Better to write</p>\n\n<pre><code>steelInFeet\n</code></pre>\n\n<p>so if the spec changes it is much more obvious where in your code you have to make changes. For example: </p>\n\n<pre><code>double steelInFeet = steelInMeters / 0.3048;\nint whistles = steelInFeet / 0.5; \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:40:49.020",
"Id": "72129",
"Score": "0",
"body": "Okay, I'll change the name and keep that in mind for later programs. :) They don't expect us to think about those things just yet, so while I doubt I'll be hurt by not changing it, it can't hurt to do so either."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T15:09:42.743",
"Id": "72303",
"Score": "0",
"body": "Also, `x / 0.5` is the same as `x * 2`, just harder to read and more prone to rounding/truncation errors. (No error in this case, but there could be.) I always choose multiplication over division if given the option."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T18:57:58.933",
"Id": "72351",
"Score": "0",
"body": "As a matter of taste, I typically omit the `In`. So I personally would use `steelFeet` or `steelMeters`. I do this a lot with my training application. You get `trainingMinutes` and `defaultCourseDurationHours`. Although 100% I'd take `steelInFeet` over `steel` any day!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T11:21:24.100",
"Id": "41872",
"ParentId": "41845",
"Score": "5"
}
},
{
"body": "<p>Do you really want to make these calculations with integers? Shouldn't you be using floating point variables?</p>\n\n<p>I'm impressed on how every other answer focused on esthetics but didn't comment on the most critical problem of your code: it doesn't work even with correct input.</p>\n\n<p>edit: Actually, other answers touched the issue, it was I that failed to notice that this is not exactly a bug, since using <code>int</code>s do achieve the desirable answer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T12:46:46.430",
"Id": "72062",
"Score": "3",
"body": "I would have commented if it didn't work. Assigning to an int automatically rounds a floating point value towards zero to the next integer. If you use 1.1 pounds of bronze for a bell then \"int bells = bronze / 1.1;\" will indeed give the correct result since you can't build 3 1/2 bells."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T12:54:24.337",
"Id": "72063",
"Score": "4",
"body": "It does work, since rounding the results down to the nearest `int` is the reasonable behaviour. Furthermore, @Brendan's accepted answer points out that the program fails to accept floating-point inputs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T14:18:54.697",
"Id": "72077",
"Score": "0",
"body": "I stand corrected. I was reading this on my phone and didn't realized @Brendan's answer already touched on the floating point issue. The integer truncation is also really desirable, my bad."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:40:51.447",
"Id": "72130",
"Score": "0",
"body": "@200_success: Yeah, that's also what confused me with my answer. Sufficient documentation would've helped, but the OP was not expected to excel in that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:45:22.340",
"Id": "72133",
"Score": "0",
"body": "It is my bad, in the future I will post the original document/question to make it clearer. There is a second \"extra-credit\" part to this problem that calculates the remainder and adds it to next day's materials. That would use floats/doubles."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T12:20:50.727",
"Id": "41874",
"ParentId": "41845",
"Score": "-1"
}
},
{
"body": "<p>People have said plenty about the code so I'll just make one point.</p>\n\n<p>Your commenting is poor. Commenting is difficult for beginners because it's hard for you to tell which parts of your code are obvious and need no more explanation, and which parts would benefit from having comments added. As you gain more experience, you'll get better at this.</p>\n\n<p>Most of your comments are completely redundant because they don't add any explanation. For example, you have several instances of</p>\n\n<pre><code>PrintLine(); // Print line\n</code></pre>\n\n<p>Use comments to document the PrintLine function, not the places where it's called. It's pretty obvious that it prints a line, so you don't need to keep saying it.</p>\n\n<p>In a similar vein, your comments on the lines that read user input don't help the reader understand the code: it's obvious that those lines read in the amount of steel, brass and ball bearings.</p>\n\n<p>On the other hand, you don't document the two <code>Calculate</code> functions at all. That's the only part of the program that really needs explaining, since it's the only part that uses facts specific to the problem that you're trying to solve (e.g., what materials you need to make a bell or a whistle.) You could say something like</p>\n\n<pre><code>int CalculateBells (int bronze)\n// Calculate the number of bells that can be made from a given amount\n// of bronze. Each bell requires 1.1lb.\n{\n [...]\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:31:55.803",
"Id": "72126",
"Score": "0",
"body": "Thanks for the advice, I did realize how stupid my comments were and have since gone back through and cleaned it up."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:34:06.383",
"Id": "72127",
"Score": "0",
"body": "Welcome to CR. Great first answer. +1"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:04:57.970",
"Id": "41897",
"ParentId": "41845",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "41849",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T02:58:15.560",
"Id": "41845",
"Score": "24",
"Tags": [
"c",
"beginner",
"homework"
],
"Title": "Feedback on a programming practice problem in C"
}
|
41845
|
<p>This program connects all nodes of the binary tree at the same level. A node of a tree contains a left, right and a sibling pointer which would connect it to the next node at the same level. This connection is from left to to right. Example: consider a binary tree with parent as node A and left and right child as node B and C. then this program joins B.sibling to C. If the immediate sibling is null, then it is skipped. More details if needed can be found <a href="http://www.geeksforgeeks.org/connect-nodes-at-same-level-with-o1-extra-space/" rel="nofollow">here</a>. I'm looking for code review, best practices, optimizations etc.</p>
<pre><code>public class JoinLevelsWithoutAuxStore<E> {
private TreeNode<E> root;
public JoinLevelsWithoutAuxStore(List<? extends E> items) {
create(items);
}
private static class TreeNode<E> {
TreeNode<E> left;
E item;
TreeNode<E> right;
TreeNode<E> sibling;
TreeNode(TreeNode<E> left, E item, TreeNode<E> right, TreeNode<E> sibling) {
this.left = left;
this.item = item;
this.right = right;
}
}
/**
* Takes in a BFS representation of a tree, and converts it into a tree.
* here the left and right children of nodes are the (2*i + 1) and (2*i + 2)nd
* positions respectively.
*
* @param items The items to be node values.
*/
private void create (List<? extends E> items) {
root = new TreeNode<E>(null, items.get(0), null, null);
final Queue<TreeNode<E>> queue = new LinkedList<TreeNode<E>>();
queue.add(root);
final int half = items.size() / 2;
for (int i = 0; i < half; i++) {
if (items.get(i) != null) {
final TreeNode<E> current = queue.poll();
final int left = 2 * i + 1;
final int right = 2 * i + 2;
if (items.get(left) != null) {
current.left = new TreeNode<E>(null, items.get(left), null, null);
queue.add(current.left);
}
if (right < items.size() && items.get(right) != null) {
current.right = new TreeNode<E>(null, items.get(right), null, null);
queue.add(current.right);
}
}
}
}
/**
* Joins the level of the binary tree.
* If any node is null, it is skipped in the process.
*/
public void join() {
if (root == null) throw new IllegalStateException("the root cannot be null");
TreeNode<E> firstNode = root;
while (firstNode != null) {
TreeNode<E> firstNodeAtNextLevel = null;
TreeNode<E> prevNodeAtNextLevel = null;
for (TreeNode<E> currentNode = firstNode; currentNode != null; currentNode = currentNode.sibling) {
List<TreeNode<E>> nodeList= new ArrayList<TreeNode<E>>();
nodeList.add(currentNode.left);
nodeList.add(currentNode.right);
for (TreeNode<E> node : nodeList) {
if (node == null) continue;
if (firstNodeAtNextLevel == null) {
firstNodeAtNextLevel = node;
} else {
prevNodeAtNextLevel.sibling = node;
}
prevNodeAtNextLevel = node;
}
}
firstNode = firstNodeAtNextLevel;
}
}
/**
* Returns the levelorder representation for the given tree.
* Each granular item of this iterator is a set of items,
* where first element of set is the leftmost non-null item at that level
* and the last one would be the rightmost non-null item at same level.
*
* A next, advances to next level, and returns the level as a set.
*
* @return the iterator for levelorder traversal
*/
public Iterator<List<E>> levelOrderIterator() {
return new LevelOrderItr();
}
private class LevelOrderItr implements Iterator<List<E>> {
private final Stack<TreeNode<E>> stack;
public LevelOrderItr() {
stack = new Stack<TreeNode<E>>();
stack.add(root);
}
@Override
public boolean hasNext() {
return !stack.isEmpty();
}
@Override
public List<E> next() {
if (!hasNext()) throw new NoSuchElementException("No more nodes remain to iterate");
TreeNode<E> node = stack.pop();
if (node.left != null) stack.push(node.left);
final List<E> levelList = new ArrayList<E>();
for (TreeNode<E> temp = node; temp != null; temp = temp.sibling) {
levelList.add(temp.item);
}
return levelList;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Invalid operation for pre-order iterator.");
}
}
public static void main(String[] args) {
Integer[] arr1 = {1, 2, 3, 4, null, null, 7};
List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(arr1));
JoinLevelsWithoutAuxStore<Integer> joinLevels = new JoinLevelsWithoutAuxStore<Integer>(list1);
joinLevels.join();
int ctr = 0;
Iterator<List<Integer>> itr = joinLevels.levelOrderIterator();
while (itr.hasNext()) {
List<Integer> list = itr.next();
System.out.println("Level: " + ctr);
for (Integer i : list) {
System.out.print(i + " - ");
}
ctr++;
System.out.println("");
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>My observations:</p>\n\n<p><strong>Use properties - do not expose raw members</strong> - your <code>TreeNode</code> implementation exposes raw members. You should use getters and setters instead.</p>\n\n<p><strong>Unused parameters</strong> - in your <code>TreeNode</code> constructor you declare 4 parameters, but you always pass only one which is not <code>null</code> (the <code>item</code>), the other parameters are unnecessary.</p>\n\n<pre><code>private static class TreeNode<E> {\n TreeNode<E> left;\n E item;\n TreeNode<E> right;\n TreeNode<E> sibling;\n\n TreeNode(E item) {\n this.item = item;\n }\n\n public E getItem() { return item; }\n\n public TreeNode<E> getLeft() { return left; }\n public void setLeft(TreeNode<E> left) { this.left = left; }\n\n // ... other getters and setters\n}\n</code></pre>\n\n<p><strong>Unclear algorithm</strong> - in your <code>create</code> method you create a <code>half</code> variable, which is half the length of the item list. This suggests you might do something binary (recurse the first half of the list, then the other half, or something like that). Actually, you are going over the list item by item linearly. This creates a very unreadable code, and it took me quite a while to understand what it actually does. If you are iterating over the list - use an <code>Iterator</code>:</p>\n\n<pre><code>private void create (List<? extends E> items) {\n var itemIterator = items.iterator();\n\n if (!itemIterator.hasNext()) {\n return;\n }\n root = new TreeNode<E>(itemIterator.next());\n\n final Queue<TreeNode<E>> queue = new LinkedList<TreeNode<E>>();\n queue.add(root);\n\n while (itemIterator.hasNext()) {\n var current = queue.poll();\n var left = itemIterator.next();\n\n current.setLeft(left);\n queue.add(left);\n\n if (itemIterator.hasNext()) {\n var right = itemIterator.next();\n\n current.setRight(right);\n queue.add(right);\n }\n }\n}\n</code></pre>\n\n<p>Your <code>join</code> algorithm is also unclear - you create a list on each iteration, which always contains exactly two elements - <code>left</code> and <code>right</code> - is it a bug?</p>\n\n<p><strong>Meaningful naming</strong> - use names which convey the correct meaning - <code>nodeList</code> does not convey what the list is used for, <code>prevNodeAtNextLevel</code> is confusing - since it is used in the current level, not the next...</p>\n\n<pre><code>public void join() {\n if (root == null) throw new IllegalStateException(\"the root cannot be null\");\n\n TreeNode<E> firstNodeAtNextLevel = root; \n\n while (firstNodeAtNextLevel != null) {\n var currentNode = firstNodeAtNextLevel;\n\n firstNodeAtNextLevel = currentNode.getLeft();\n\n TreeNode<E> right = null;\n while (currentNode != null) {\n var left = currentNode.getLeft();\n if (right != null) {\n right.setSibling(left);\n }\n right = currentNode.getRight();\n if (left != null) {\n left.setSibling(right);\n }\n currentNode = currentNode.getSibling();\n }\n }\n}\n</code></pre>\n\n<p><strong>Use correct data structures</strong> - in <code>LevelOrderItr</code> you manage a <code>Stack</code>, but it never has more than one element! You <code>pop()</code> the current node and <code>push()</code> the next... Simply using <code>TreeNode<E> current;</code> would be sufficient - and more readable</p>\n\n<pre><code>private class LevelOrderItr implements Iterator<List<E>> {\n private final TreeNode<E> current;\n\n public LevelOrderItr() {\n current = root;\n }\n\n @Override\n public boolean hasNext() {\n return current != null;\n }\n\n @Override\n public List<E> next() {\n if (!hasNext()) throw new NoSuchElementException(\"No more nodes remain to iterate\");\n\n final List<E> levelList = new ArrayList<E>();\n for (TreeNode<E> temp = current; temp != null; temp = temp.sibling) {\n levelList.add(temp.item);\n }\n current = current.getLeft();\n\n return levelList;\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException(\"Invalid operation for pre-order iterator.\");\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:28:51.300",
"Id": "72366",
"Score": "0",
"body": "Overall a very meaningful feedback, except first point \"Use properties - do not expose raw members\" the class is a private nested class, and its OK to not do the getter / setter stuff as these classes are confined to the outer class. Its similar to Entry/Node of linkedlist."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:41:34.060",
"Id": "72371",
"Score": "1",
"body": "I can see your point (although there is no harm in encapsulating private classes), you might consider though, to make `E item` `final`, since it is not supposed to change after instanciation, and that cannot be conveyed otherwise when the member is exposed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:43:42.963",
"Id": "72373",
"Score": "0",
"body": "Agree on this here."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T18:36:46.683",
"Id": "41994",
"ParentId": "41848",
"Score": "4"
}
},
{
"body": "<p>A minor bug: You get an <code>IndexOutOfBoundsException</code> for an empty list in <code>JoinLevelsWithoutAuxStore.create(List<? extends E> items)</code>. You don't have a comment stating you need to input a list containing at least something. Consider returning <code>IllegalArgumentException</code> and adding a comment.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-17T11:19:27.010",
"Id": "63147",
"ParentId": "41848",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T03:25:17.937",
"Id": "41848",
"Score": "3",
"Tags": [
"java",
"algorithm",
"tree"
],
"Title": "Join/ connect all levels of Binary tree without any aux storage"
}
|
41848
|
<p>Are these classes properly guarded for thread safety? Do you see any issues with any of the classes?</p>
<pre><code>@ThreadSafe
public class RetirementAccount {
public static final int TYPE1 = 0;
public static final int TYPE2 = 1;
@GuardedBy("this")
private final int accountType;
@GuardedBy("buySell")
public final List<BuySell> buySell;
public RetirementAccount(int accountType) {
this.accountType = accountType;
this.buySell = Collections.synchronizedList(new ArrayList<BuySell>());
}
public void addToAccount(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException();
} else {
synchronized (buySell) {
buySell.add(new BuySell(amount));
}
}
public double interestGained() {
synchronized (this) {
switch (accountType) {
…..
}
}
</code></pre>
<p><code>BuySell</code>:</p>
<pre><code>@Immutable
public class BySell {
public final double depositAmount;
public BuySell(double depositAmount) {
this.depositAmount = depositAmount;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Not a guru in the Concurrency yet, but I'll try to be helpful.</p>\n\n<p>First thing I notice is that in the <code>addToAccount</code> method you synchronize the access to the <code>buySell</code> list, which is redundant because it's already synchronized in the constructor. The only time you would do that is when iterating through that list, because iterators are not synchronized. You can see that from the source code, compared with the collection's <code>add</code> method</p>\n\n<pre><code>public boolean add(E e) {\n synchronized (mutex) { return c.add(e); } // Synchronized\n}\n\npublic Iterator<E> iterator() {\n return c.iterator(); // Must be manually synched by user!\n}\n\npublic ListIterator<E> listIterator() {\n return list.listIterator(); // Must be manually synched by user\n}\n\npublic ListIterator<E> listIterator(int index) {\n return list.listIterator(index); // Must be manually synched by user\n}\n</code></pre>\n\n<p>Moreover, I would get rid of the <code>else</code> statement</p>\n\n<pre><code>public void addToAccount(double amount) {\n if (amount <= 0) {\n throw new IllegalArgumentException();\n }\n buySell.add(new BuySell(amount));\n}\n</code></pre>\n\n<p>The second thing is the <code>interestGained</code> method. You omitted that part but I suspect that you do use the <code>buySell</code> list in that <code>switch</code> statement. With the current implementation there could be a situation when the list is updated while the gained interest being calculated. If you want to avoid such situations you would probably synchronize on the <code>buySell</code> list instead of <code>this</code>, especially with the <code>accountType</code> being <code>final</code>.</p>\n\n<p>The <code>BuySell</code> class is immutable, so it's thread-safe by definition.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T09:22:20.437",
"Id": "41863",
"ParentId": "41852",
"Score": "3"
}
},
{
"body": "<p>About the name of <code>BuySell</code>, from <em>Clean Code</em> by <em>Robert C. Martin</em>, page 25: </p>\n\n<blockquote>\n <p>Classes and objects should have noun or noun phrase names like <code>Customer</code>, <code>WikiPage</code>,\n <code>Account</code>, and <code>AddressParser</code>. [...] A class name should not be a verb.</p>\n</blockquote>\n\n<p>Actually, what it contains is usually called <code>Transaction</code>. I'd rename the <code>buySell</code> field too to <code>transactions</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T12:47:38.807",
"Id": "41876",
"ParentId": "41852",
"Score": "2"
}
},
{
"body": "<p>In your example code you have the following synchronization-related statements:</p>\n\n<ul>\n<li><code>this.buySell = Collections.synchronizedList(new ArrayList<BuySell>());</code></li>\n<li><code>synchronized (buySell) {</code></li>\n<li><code>synchronized (this) {</code></li>\n</ul>\n\n<p>As a consequence, you are synchronizing on three different things in one class.</p>\n\n<p>This is very confusing, and is buggy.</p>\n\n<p>You are onlu showing us part of your class, but, there is no point in making buySell a synchronizedCollection if you are going to also gate access to it using <code>synchronized(buySell)</code>.... it is redundant, and introduces 2 levels of synchronization.</p>\n\n<p>Presumably when you calculate interest you also access the <code>buySell</code> class, and, as a consequence you have two levels of synchronization there too.</p>\n\n<p>A deadlock is a situation where two threads each have a lock, and they each attempt to get another lock where that other lock is being held by the other thread. If you have multiple lock points in your class it becomes much easier to code things where you introduce deadlock possibilities. I cannot see any in your code at the moment, but your code is incomplete, and these are bugs that can creep in as the class is maintained.</p>\n\n<p>The safest way to do things is to have just a single object which you use to cate access to your class. It is often tempting to use the actual instance itself as the gate, make every method <code>synchronized</code>, and, if you did, your class would become:</p>\n\n<pre><code>public class RetirementAccount {\n\n public static final int TYPE1 = 0;\n public static final int TYPE2 = 1;\n\n private final int accountType; \n public final List<BuySell> buySell;\n\n public RetirementAccount(int accountType) {\n this.accountType = accountType;\n this.buySell = new ArrayList<BuySell>();\n }\n\n public synchronized void addToAccount(double amount) {\n if (amount <= 0) {\n throw new IllegalArgumentException();\n } else {\n buySell.add(new BuySell(amount));\n }\n }\n\n public synchronized double interestGained() {\n\n switch (accountType) {\n …..\n }\n</code></pre>\n\n<p>This would be a thread-safe class, and it has just one synchronization lock point (the class instance itself). There is no internal possibility of any deadlock, and it would be much better than what you have.</p>\n\n<p>There is a better solution though....</p>\n\n<p>The problem with the above solution is that you expose the locking system in the instance and make it public. Anyone can do:</p>\n\n<pre><code>synchronized(myaccount) {\n ....\n}\n</code></pre>\n\n<p>and they essentially become a prt of your locking system, and that can result in lock-conditions that are unexpected when you created your class.</p>\n\n<p>To make the class completely thread-safe, and have just a single lock point, and still keep isolated from the out-side, I recommend using a dedicated lock instance. It typically looks like this....</p>\n\n<pre><code>public class RetirementAccount {\n\n public static final int TYPE1 = 0;\n public static final int TYPE2 = 1;\n\n private final int accountType; \n public final List<BuySell> buySell;\n private final Object synclock = new Object();\n\n public RetirementAccount(int accountType) {\n this.accountType = accountType;\n this.buySell = new ArrayList<BuySell>();\n }\n\n public void addToAccount(double amount) {\n synchronized (synclock) {\n if (amount <= 0) {\n throw new IllegalArgumentException();\n } else {\n buySell.add(new BuySell(amount));\n }\n }\n }\n\n public double interestGained() {\n\n synchronized (synclock) {\n\n switch (accountType) {\n …..\n }\n }\n</code></pre>\n\n<p>Synchronization and other locking mechanisms are complicated concepts, and they are hard to write, and hard to read. There are rules which make it easier:</p>\n\n<ul>\n<li>discipline - you have to create a system, and you have to follow it diligently</li>\n<li>dependence - use prefabricated classes where you can (<code>java.util.concurrent.*</code> is your friend) .... <strong><em>but</em></strong> understand what those classes do. Just because one instance is safe, it does not mean your system is safe. They do not solve all problems.</li>\n<li>discipline - you have to create a system, and you have to follow it diigently</li>\n<li>use as few locks as possible - the fewer locks you have to mentally track, the better.</li>\n<li>discipline - you have to create a system, and you have to follow it diigently</li>\n<li>avoid places where you have double-locking - you synchonize against one class, then synchronize against another. These double-locking situations are a precursor to deadlocks (they add risk).</li>\n<li>discipline - you have to create a system, and you have to follow it diigently</li>\n<li>avoid synchronizing classes with synchronized methods because that leads to conditions where outside influences can affect the internal locking of your instance.</li>\n<li>discipline - you have to create a system, and you have to follow it diigently</li>\n</ul>\n\n<p>Did I mention that successful thread-safe implementations require discipline? You have to be diligent about implementing the synchronization correctly at each place it is needed.</p>\n\n<p>Finally, there are ways you can force thread-safe operation with light versions of locking. My general advice to people is \"don't try to be clever unless you really are that clever\". It takes a special kind of brain to understand all the nuances of Java's memory moela nd the way the threading affects it. If you have it clear in your mind, then sure, play some tricks.... but, even those who have i clear, mess up when they try to be clever.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T14:50:23.610",
"Id": "72084",
"Score": "0",
"body": "Thanks for your comments. I am inheriting this code definitely see improvements.Your response makes sense. One more thing this class isn't encapsulated properly with public final List<BuySell> buySell; which forces client class to synchronize on it.shouldn't I hide this field (make it private final) and probably provide getBuySells() method which returns CLONE of an original collection (List<BuySell> buySell)? Actually realizing BuySell is an Immutable class so I don't need to clone the collection in getBuySells() but simply return the collection?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T14:58:55.513",
"Id": "72089",
"Score": "0",
"body": "Also I just observed that there are no equals() and hashCode() in those classes. I'll have to add them as well.."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T12:58:19.747",
"Id": "41877",
"ParentId": "41852",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T04:49:05.143",
"Id": "41852",
"Score": "6",
"Tags": [
"java",
"thread-safety",
"concurrency",
"finance",
"locking"
],
"Title": "Thread-safe retirement account class"
}
|
41852
|
<p>I haven't been able to find an existing tool that does this, so I'm attempting to create one. If anyone knows of one that already exists, I'd appreciate a pointer to it. I plan on using this primarily for cleaning up old backup copies and was hoping for a review of its correctness or suggestions for improvement. Part of my concern is whether or not filecmp.cmp(), as I've used it here with the third argument set to False, does a full byte by byte comparison. I'm also providing it here in the hope that someone else might find it useful. I have run it on Ubuntu 12.04 LTS with Python 2.7.3.</p>
<pre><code># Prints a list of paths to files that exist in dir_l but not dir_r. File name
# differences are ignored. Recursively scans subdirectories. Skips hidden files
# and folders by default. Files of the same size are compared byte by byte (?).
# Differences in folder structures are ignored. For example, if
# dir_l/subdir1/file1 and dir_r/subdir2/subdir3/file2 match byte for byte,
# then dir_l/subdir1/file1 exists in dir_r.
# Two primary data structures are used:
# (1) A list of all the paths to files in dir_l (recursively including
# subdirectories of dir_l and excluding hidden files and folders by default).
# (2) A hash mapping each unique file size in dir_r to a list of all the paths
# to files in dir_r of that size (recursively including subdirectories of dir_r
# and excluding hidden files and folders by default).
# For each file pointed to in (1), its size is checked for existence in (2).
# If its size does not exist in (2), the file path to it is stored as
# unmatched. If its size does exist in (2), a byte by byte comparison (?) is
# done between it and each file matching its size in (2) until a match is
# found, if any. If a match is not found, the file path to it is stored as
# unmatched. The stored list of unmatched file paths, if any, is then printed.
# Requires the progress bar library (2.2)
# https://pypi.python.org/pypi/progressbar/2.2
# http://code.google.com/p/python-progressbar/
import sys
import os
import filecmp
import argparse
from progressbar import *
def main():
help_description = \
'Prints a list of paths to files that exist in dir_l but not dir_r. File \
name differences are ignored. Recursively scans subdirectories. Skips hidden \
files and folders by default. Files of the same size are compared \
byte by byte (?). Differences in folder structures are ignored. For example, \
if dir_l/subdir1/file1 and dir_r/subdir2/subdir3/file2 match byte for byte, \
then dir_l/subdir1/file1 exists in dir_r.'
parser = argparse.ArgumentParser(description = help_description)
parser.add_argument('-a', '--all', action='store_true', help='do not skip \
hidden files and folders')
parser.add_argument('dir_l')
parser.add_argument('dir_r')
args = vars(parser.parse_args())
include_hidden = args['all']
dir_l = args['dir_l']
dir_r = args['dir_r']
if not os.path.isdir(dir_l):
print "Invalid directory path: " + dir_l
sys.exit(2)
if not os.path.isdir(dir_r):
print "Invalid directory path: " + dir_r
sys.exit(2)
print "Preprocessing..."
# creates (1)
# (1)
filepaths_l = get_dir_file_paths(dir_l, include_hidden);
# creates (2)
filepaths_r = get_dir_file_paths(dir_r, include_hidden);
# (2)
size_to_filepaths_r = dict()
for filepath in filepaths_r:
size = os.path.getsize(filepath)
if size in size_to_filepaths_r:
# adds this path to the existing list of paths to files in dir_r of this
# size
size_to_filepaths_r[size].append(filepath)
else:
# starts a new list of paths to files in dir_r of this size
size_to_filepaths_r[size] = [filepath]
del filepaths_r
# compares the files
print "Comparing files..."
# will hold a list of all the paths to files in dir_l that do not exist in
# dir_r
unmatched = []
# creates a progress bar
pbar = ProgressBar(widgets=[Percentage(), Bar()], maxval=len(filepaths_l))
pbar.start()
# counter for the progress bar
i = 0
for filepath_l in filepaths_l:
match = False
# gets the size of the file pointed to by filepath_l
size = os.path.getsize(filepath_l)
if size in size_to_filepaths_r:
# each of the files pointed to in the list of file paths stored in
# size_to_filepaths_r[size] is the same size as the file pointed to by
# filepath_l
for filepath_r in size_to_filepaths_r[size]:
# compares the files byte by byte (?)
if filecmp.cmp(filepath_l, filepath_r, False):
match = True
# found a match, no need to check the rest of the files in the list,
# if any
break
if match == False:
# either no files in dir_r exist that are the same size as the file
# pointed to by filepath_l, or none of those that do are a
# byte by byte (?) match
unmatched.append(filepath_l)
i = i + 1
pbar.update(i)
pbar.finish()
# prints the paths to any unmatched files
if not unmatched:
print "No unmatched files"
else:
print "Unmatched files:"
for filepath in unmatched:
print filepath
# Returns a list of all the paths to files in the directory pointed to by 'top',
# recursively including subdirectories. Hidden files and folders are ignored
# unless 'include_hidden' is set to True.
def get_dir_file_paths(top, include_hidden):
filepaths = []
for dirpath, dirnames, filenames in os.walk(top):
if not include_hidden:
# ignore hidden files and folders
# http://stackoverflow.com/questions/13454164/os-walk-without-hidden-folders
# Answer by Martijn Pieters
filenames = [f for f in filenames if not f[0] == '.']
dirnames[:] = [d for d in dirnames if not d[0] == '.']
for filename in filenames:
filepath = os.path.join(dirpath, filename)
filepaths.append(filepath)
return filepaths
main()
</code></pre>
<p>Code updated to use suggestions by Janne Karila:</p>
<pre><code># Two primary data structures are created:
# (1) A list of tuples. Each tuple contains a pair of items: a file size and a
# file path. The file size is the size of the file pointed to by the file path.
# The list is sorted on the file sizes. The set of file paths consists of all
# the paths to the files in directory_l (recursively including subdirectories
# of directory_l and excluding hidden files and folders by default).
# For example:
# [(file_size_1, file_path_1), (file_size_2, file_path_2), ...,
# (file_size_n, file_path_n)]
# file_size_1 = size of the file pointed to by file_path_1,
# file_size_2 = size of the file pointed to by file_path_2, ...,
# file_size_n = size of the file pointed to by file_path_n
# file_size_1 <= file_size_2 <= ... <= file_size_n
# file_path_1, file_path_2, ..., file_path_n = all the paths to the files in
# directory_l (recursively including subdirectories of directory_l and
# excluding hidden files and folders by default)
# (2) A dictionary mapping each unique file size in directory_r to a list of
# all the paths to files of that size in directory_r (recursively including
# subdirectories of directory_r and excluding hidden files and folders by
# default).
# For each file pointed to in (1), its size is checked for existence in (2).
# If its size does not exist in (2), the file path to it is stored as
# unmatched. If its size does exist in (2), a byte by byte comparison is done
# between it and each file matching its size in (2) until a match is found, if
# any. If a match is not found, the file path to it is stored as unmatched. The
# stored list of unmatched file paths, if any, is then printed.
# Uses suggestions by msvalkon and Janne Karila in Stack Exchange Code Review:
# http://codereview.stackexchange.com/questions/41853/byte-by-byte-directory-comparison-ignoring-folder-structures-and-file-name-diffe
# Requires the progress bar library (2.2)
# https://pypi.python.org/pypi/progressbar/2.2
# http://code.google.com/p/python-progressbar/
import argparse
import collections
import filecmp
import os
import sys
from operator import itemgetter
from progressbar import Bar, Percentage, ProgressBar
def main():
help_description = \
'Prints a list of the paths to the files that exist in the directory pointed \
to by directory_l, but that do not exist in the directory pointed to by \
directory_r. File name differences are ignored. Recursively scans \
subdirectories of directory_l and directory_r. Skips hidden files and folders \
by default. Files of the same size are compared byte by byte. Differences in \
directory structures are ignored. For example, if \
directory_l/subdirectory_1/file_name_1 and \
directory_r/subdirectory_2/subdirectory_3/file_name_2 match byte for byte, \
then directory_l/subdirectory_1/file_name_1 exists in directory_r.'
parser = argparse.ArgumentParser(description = help_description)
parser.add_argument('-a', '--all', action='store_true', help='include hidden \
files and folders')
parser.add_argument('directory_l', help='path to a directory of files to \
search for')
parser.add_argument('directory_r', help='path to a directory of files to \
search in')
args = vars(parser.parse_args())
include_hidden = args['all']
directory_l = args['directory_l']
directory_r = args['directory_r']
if not os.path.isdir(directory_l):
print "Invalid directory path: " + directory_l
sys.exit(2)
if not os.path.isdir(directory_r):
print "Invalid directory path: " + directory_r
sys.exit(2)
unmatched = find_unmatched(directory_l, directory_r, include_hidden)
# Prints the paths to any unmatched files.
if not unmatched:
print "No unmatched files."
else:
print "Unmatched files:"
for file_path in unmatched:
print file_path
def find_unmatched(directory_l, directory_r, include_hidden):
print "Preprocessing..."
# Creates (1)
size_file_path_tuple_list_l = sizes_paths(directory_l, include_hidden)
# Sorts the list by the first item in each tuple pair (size).
size_file_path_tuple_list_l_sorted = sorted(size_file_path_tuple_list_l, \
key=itemgetter(1)) # (1)
# Creates (2)
size_file_path_tuple_list_r = sizes_paths(directory_r, include_hidden)
size_to_file_path_list_dict_r = \
dict_of_lists(size_file_path_tuple_list_r) # (2)
# Compares the files
print "Comparing files..."
unmatched = []
# Creates a progress bar
pbar = ProgressBar(widgets=[Percentage(), Bar()], \
maxval=len(size_file_path_tuple_list_l_sorted))
pbar.start()
for i, (size_l, file_path_l) in enumerate(size_file_path_tuple_list_l_sorted):
# size_to_file_path_list_dict_r[size_l] is a list of the paths to the files
# in directory_r (recursively including subdirectories of directory_r and
# excluding hidden files and folders by default) that are the same size as
# the file pointed to by file_path_1.
# Note that in the statement 'size_to_file_path_list_dict_r[size_l]', if
# size_l does not exist as a key in size_to_file_path_list_dict_r, then
# size_l is added as a key that maps to an empty list.
if not file_match(file_path_l, size_to_file_path_list_dict_r[size_l]):
# Either no files in directory_r (recursively including subdirectories of
# directory_r and excluding hidden files and folders by default) exist
# that are the same size as the file pointed to by file_path_l, or none
# of those that do are a byte by byte match.
unmatched.append(file_path_l)
pbar.update(i)
pbar.finish()
return unmatched
# Returns as tuple pairs the size of and path to each of the files in the
# directory pointed to by 'top', recursively including subdirectories of 'top'.
# Hidden files and folders are not returned unless 'include_hidden' is True.
def sizes_paths(top, include_hidden):
for file_path in get_directory_file_paths(top, include_hidden):
size = os.path.getsize(file_path)
yield size, file_path
# Returns each of the paths to the files in the directory pointed to by 'top',
# recursively including subdirectories of 'top'. Hidden files and folders are
# not returned unless 'include_hidden' is True.
def get_directory_file_paths(top, include_hidden):
for directory_path, folder_name_list, file_name_list in os.walk(top):
# directory_path is the path to the current directory
# folder_name_list is the list of all the folder names in the
# current directory
# file_name_list is the list of the file names in the current directory
if not include_hidden:
# Ignore hidden files and folders
# http://stackoverflow.com/questions/13454164/os-walk-without-hidden-folders
# Answer by Martijn Pieters
# Removes the file names that begin with '.' from the list of file names
# in the current directory.
file_name_list = [f for f in file_name_list if not f[0] == '.']
# Removes the folder names that begin with '.' from the list of folder
# names in the current directory.
folder_name_list[:] = [f for f in folder_name_list if not f[0] == '.']
for file_name in file_name_list:
yield os.path.join(directory_path, file_name)
# Creates and returns a dictionary of lists from a list of tuple pairs.
# The keys in the dictionary are the set of the unique first items from the
# tuple pairs. Each of these keys is mapped to a list of all the second items
# from the tuple pairs whose first item matches that key.
# Example:
# {'a': [1, 1], 'c': [1], 'b': [2, 3]} =
# dict_of_lists([('a', 1), ('a', 1), ('b', 2), ('b', 3), ('c', 1)])
def dict_of_lists(item_list):
# http://docs.python.org/2/library/collections.html#collections.defaultdict
d = collections.defaultdict(list)
for key, value in item_list:
# If d[key] does not exist, an empty list is created and value is attached
# to it. Otherwise, if d[key] does exist, value is appended to it.
d[key].append(value)
return d
# Returns True if and only if any of the files pointed to by the file paths in
# file_path_list_r are a byte by byte match for the file pointed to by
# file_path_l.
# Note that file_path_list_r may be an empty list.
def file_match(file_path_l, file_path_list_r):
return any(filecmp.cmp(file_path_l, file_path_r, False) \
for file_path_r in file_path_list_r)
main()
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>Yes, <code>filecmp.cmp</code> compares the contents of the files with <code>shallow=False</code></li>\n<li>Breaking <code>main</code> into more functions still gives better structure</li>\n<li>Making <code>get_dir_file_paths</code> a generator reduces memory use when building <code>size_to_filepaths_r</code>, and simplifies the function itself slightly.</li>\n<li>Use <code>collections.defaultdict(list)</code> to avoid <code>if size in size_to_filepaths_r</code> checks.</li>\n<li>Use <code>enumerate</code> to keep a loop counter</li>\n<li>Get the file sizes while walking the directories to benefit from disk caching.</li>\n<li>Compare all files of the same size consecutively for the same reason. (the code below sorts <code>filepaths_l</code> for that)</li>\n</ul>\n\n<p>I propose to rearrange the bulk of the work into these functions:</p>\n\n<pre><code>import collections\n\ndef dict_of_lists(items):\n d = collections.defaultdict(list)\n for key, value in items:\n d[key].append(value)\n return d\n\ndef get_dir_file_paths(top, include_hidden):\n for dirpath, dirnames, filenames in os.walk(top):\n if not include_hidden:\n # ignore hidden files and folders\n # http://stackoverflow.com/questions/13454164/os-walk-without-hidden-folders\n # Answer by Martijn Pieters\n filenames = [f for f in filenames if not f[0] == '.']\n dirnames[:] = [d for d in dirnames if not d[0] == '.']\n\n for filename in filenames:\n yield os.path.join(dirpath, filename)\n\ndef sizes_paths(top, include_hidden):\n for filepath in get_dir_file_paths(top, include_hidden):\n size = os.path.getsize(filepath)\n yield size, filepath\n\ndef file_match(filepath_l, filepaths_r):\n return any(filecmp.cmp(filepath_l, filepath_r, False) \n for filepath_r in filepaths_r)\n\ndef find_unmatched(dir_l, dir_r, include_hidden):\n\n filepaths_l = sorted(sizes_paths(dir_l, include_hidden))\n size_to_filepaths_r = dict_of_lists(sizes_paths(dir_r, include_hidden))\n\n # creates a progress bar\n pbar = ProgressBar(widgets=[Percentage(), Bar()], maxval=len(filepaths_l))\n pbar.start()\n\n unmatched = []\n\n for i, (size, filepath_l) in enumerate(filepaths_l):\n if not file_match(filepath_l, size_to_filepaths_r[size]):\n # either no files in dir_r exist that are the same size as the file \n # pointed to by filepath_l, or none of those that do are a \n # byte by byte match\n unmatched.append(filepath_l)\n pbar.update(i)\n pbar.finish()\n\n return unmatched\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T07:23:00.837",
"Id": "72710",
"Score": "0",
"body": "Thank you for your feedback! I'll look these over. It might take me a while."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T06:50:36.237",
"Id": "73833",
"Score": "0",
"body": "I've updated the code to use your suggestions. Thank you again!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:42:40.127",
"Id": "42188",
"ParentId": "41853",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "42188",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T05:59:51.160",
"Id": "41853",
"Score": "6",
"Tags": [
"python",
"file-system"
],
"Title": "Byte by byte directory comparison ignoring folder structures and file name differences"
}
|
41853
|
<p>I have a method that returns a list from a HTML page:</p>
<pre><code>private List<HtmlNodes> GetRelevantNodes(HtmlDocument aHtmlDoc, string aID)
{
List<HtmlNode> nodes = new List<HtmlNode>();
HtmlNode currentDiv = aHtmlDoc.GetElementbyId(aID);
if (currentDiv == null)
return null;
else
//Do stuff - fill the nodes list...
return nodes;
}
</code></pre>
<p><strong>I'm not sure what to do with the return value in case the <code>currentDiv</code> variable is <code>null</code></strong>. Obviously I can't continue the method regularly and I need to return from this method with <strong>some indication</strong> that there's no such <code>div</code>. </p>
<p>If I return <code>null</code> and handle it up the stack it'll work fine but it's less readable code (at list in my opinion... don't you think?). Another thing I can add is an <code>out string</code> with the error message and maybe use it later for the end user output but that still doesn't solve my readable problem. </p>
<p>I'd be happy to hear your ideas and advice.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T11:24:15.287",
"Id": "72049",
"Score": "0",
"body": "No, you don't want to expand your question. We're here to do code reviews, not answer questions. Your question is already borderline because of the wording (hence you already have 3 close-votes on it)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T12:34:39.287",
"Id": "72060",
"Score": "0",
"body": "The question I added was in the context of this code review, if you wanted me to change the format so it would be a code review and not a question you could have just comment me... I still would be happy to hear suggestions of how to handle a case of return type can't be initialized, like @Knagis exception suggestion."
}
] |
[
{
"body": "<p>You're right, this is not the best thing to do. The correct way would be to return an empty list.</p>\n\n<pre><code>private List<HtmlNodes> GetNodes(HtmlDocument aHtmlDoc, string aID)\n{\n List<HtmlNode> nodes = new List<HtmlNode>();\n\n HtmlNode currentDiv = aHtmlDoc.GetElementbyId(aID);\n if (currentDiv != null)\n {\n //Do stuff - fill the nodes list...\n }\n\n return nodes;\n}\n</code></pre>\n\n<p>Now why is that better than returning <code>null</code>? Simple, it allows to remove checking from the client code. Imagine your function would return <code>null</code> if there are no nodes, clients always need to write the following code when interacting with it:</p>\n\n<pre><code>List<HtmlNode> nodes = GetNodes(htmlDoc, id);\nif (nodes != null)\n{\n foreach (HtmlNode node in nodes)\n {\n // Super secret business code\n }\n}\n</code></pre>\n\n<p><em>Always</em>. Now if you'd return an empty list, the checking becomes <em>optional</em> on the client side:</p>\n\n<pre><code>foreach (HtmlNode node in GetNodes(htmlDoc, id))\n{\n // Still secret...\n}\n</code></pre>\n\n<p>Or with checking:</p>\n\n<pre><code>List<HtmlNode> nodes = GetNodes(htmlDoc, id);\nif (nodes.Length > 0)\n{\n foreach (HtmlNode node in nodes)\n {\n // Super secret business code\n }\n}\n</code></pre>\n\n<hr>\n\n<p>You should always write <a href=\"http://msdn.microsoft.com/en-us/library/b2s063f7.aspx\">XML Documentation</a>.</p>\n\n<hr>\n\n<pre><code>private List<HtmlNodes> GetNodes(HtmlDocument aHtmlDoc, string aID)\n</code></pre>\n\n<p>There's a typo, it should be <code>HtmlNode</code>.</p>\n\n<p>Also your variables are named not optimal. Drop that <code>a</code> prefix, nobody cares if it is an argument or not, it's a variable you have to work with.</p>\n\n<p>The name of the function is also not good, it's called <code>GetNodes</code> yet from what I see (and interpret into it) it does not fetch the nodes with the given ID, it fetches <em>the children of the first node with the given ID</em>. So it should actually be called <code>GetChildren</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T10:15:41.527",
"Id": "72042",
"Score": "0",
"body": "Thanks for the answer, right after I posted the question I thought of the same solution and now I'm embarrassed in my question... but your answer has given me the certificate it's the correct way to go.\nAbout the 'a' prefix I have to disagree since to me it's really readable that it's 'a' general var and not THE var or the 'current' var. And for the documentation - I would start implementing right away!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T10:29:50.760",
"Id": "72043",
"Score": "0",
"body": "I agree with this advice for handling a non-existent `aID`. Another justification: that's how [jQuery](http://api.jquery.com) would behave, and jQuery is awesome."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T10:45:19.810",
"Id": "72048",
"Score": "0",
"body": "@200_success: [jQuery is *always* the answer.](http://meta.stackexchange.com/questions/45176/when-is-use-jquery-not-a-valid-answer-to-a-javascript-question)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T10:05:49.453",
"Id": "41868",
"ParentId": "41867",
"Score": "8"
}
},
{
"body": "<p>You have to decide if the caller of your method needs to know if the parent was not found or if there is no difference when the parent was not found or when the parent element is simply empty.</p>\n\n<p>If the second holds true, then the other answer already describes the correct approach - return an empty list.</p>\n\n<p>However, if the caller needs to be informed that the parent element (<code>currentDiv</code>) does not exist:</p>\n\n<ol>\n<li>The best and most common one would be to throw an exception saying <em>The HTML node with ID {id} does not exist.</em>.</li>\n<li>If the exception should only be thrown in certain cases, your method could have a signature like <code>GetChildren(HtmlDocument doc, string id, bool throwIfNotExists = false)</code>. Now the caller can decide himself if the exception should be thrown. If not, then return an empty list (however, not null).</li>\n</ol>\n\n<p>Please note that the following two options are there just so that the answer is more complete, I personally would recommend option #2 from above.</p>\n\n<ul>\n<li>This option is more suitable for things like web services where exceptions might not be welcome - create a new type that your method returns: <code>class GetChildrenResult { public bool ParentFound; public List<HtmlNode> Children; }</code> (though use properties).</li>\n<li><strong>(Not recommended)</strong> You could use an <code>out</code> parameter. This is generally not a good idea but if you decide to do so, you should provide two overloads - one with the argument and second one without.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T12:21:34.310",
"Id": "41875",
"ParentId": "41867",
"Score": "7"
}
},
{
"body": "<p>I agree with Knais that the key question is whether you really need to indicate failure. If you do, then either a tuple or an out param in the form of a TryGetChildren function would be appropriate. I disagree with him in that I don't think that using an out param is a bad idea, at least not if done in the TryXxx pattern.</p>\n\n<p>I would NOT suggest using an out param for error message, as that is a bad idea - if you need more than the bool returned by the TryXxx pattern, then you should be using an object that is acted on, not a variable that is changed. It's just as easy to do the simple stuff, and it makes it possible to do more complex scenarios if you need to. And you should be doing it as a separate validation check, not an exception.</p>\n\n<p>But in 9 out of 10 cases returning a valid but empty collection, is the right thing to do, as you don't really care why you're not finding what you are looking for, you just want something to use in a for each loop.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T06:29:26.963",
"Id": "49120",
"ParentId": "41867",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41875",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T09:46:08.347",
"Id": "41867",
"Score": "4",
"Tags": [
"c#",
"null"
],
"Title": "Return value when the requested variable returns null"
}
|
41867
|
<p>I have a concept based polymorphism example listed below. I allow the user to provide any type that implements the draw method and then I add it into a vector of <code>unique_ptr</code> to concept base. If I have a pointer or reference I want to be able to deal with that even though the solution has value semantics in mind. I thus created a wrapper type which forwards to the correct implementation. I am hoping to get some feedback on if this is the best way to deal with the issue at hand.</p>
<pre><code>#include <iostream>
#include <vector>
#include <memory>
#include <algorithm>
class drawable_concept{
public:
drawable_concept() = default;
virtual ~drawable_concept() = default;
drawable_concept(drawable_concept const&) = delete;
drawable_concept& operator = (drawable_concept const& ) = delete;
virtual void draw() = 0;
};
template<class T>
class drawable_model : public drawable_concept{
public:
typedef T model_type;
drawable_model(T const& model) : model_(model){}
void draw(){
model_.draw();
}
~drawable_model() = default;
private:
T model_;
};
template<class T>
class drawable_forwarder{
public:
drawable_forwarder(T const& item) : item_(item){}
inline void draw(){
item_->draw();
}
private:
T item_;
};
class graphics_surface{
public:
void render(){
std::for_each(std::begin(controls_), std::end(controls_), [] (std::unique_ptr<drawable_concept> const& control){
control->draw();
});
}
template<class T>
void push_back(T control){
auto t = new drawable_model<T>(std::move(control));
controls_.push_back(std::unique_ptr<drawable_concept>(t));
}
private:
std::vector<std::unique_ptr<drawable_concept>> controls_;
};
struct triangle{
void draw(){
std::cout << "Triangle" << std::endl;
}
};
struct square{
void draw(){
std::cout << "Square" << std::endl;
}
};
int main(int argc, const char * argv[])
{
graphics_surface surface;
surface.push_back(triangle());
surface.push_back(square());
std::shared_ptr<triangle> ptr(new triangle);
drawable_forwarder<std::shared_ptr<triangle>> fwd(ptr);
surface.push_back(fwd);
surface.render();
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T13:37:28.847",
"Id": "72069",
"Score": "3",
"body": "Be careful with the wording. Your `drawable_concept` is an interface. Concepts relate to a template mechanism that might come in C++14."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T13:46:58.200",
"Id": "72071",
"Score": "0",
"body": "Just to complete the previous comment I am talking about [concepts light](http://isocpp.org/blog/2013/02/concepts-lite-constraining-templates-with-predicates-andrew-sutton-bjarne-s)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T15:41:13.477",
"Id": "72098",
"Score": "1",
"body": "@Nobody Sean Parent gave a talk at Boost Con entitle \"Value Semantics and Concepts Based Polymorphism\" which uses exactly this pattern. A similar pattern is used by boost::any, std::function and std::shared_ptr to achieve type erasure. But this extends the idea further by allowing operations on the stored object and retains value semantics on the objects being managed (i.e. you don't have to use traditional inheritance based OO) You can see the talk here: http://www.youtube.com/watch?v=_BpMYeUFXv8. It's very interesting."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T10:34:10.527",
"Id": "77331",
"Score": "0",
"body": "It seems this has been cross posted: http://stackoverflow.com/questions/21821948/concept-based-polymorphism"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-23T18:15:39.280",
"Id": "78631",
"Score": "0",
"body": "It's a bit late, but thank you very much. I didn't know about concept-based polymorphism until there, and I already found a project of mine where it solved some problems quite elegantly :)"
}
] |
[
{
"body": "<p>There is not much to be said actually, the concept-based polymorphism seems to be well implemented. You can slightly improve your <code>push_back</code> method by having it <code>emplace_back</code> the <code>std::unique_ptr</code>. It will be a little bit less verbose:</p>\n\n<pre><code>template<class T>\nvoid push_back(T control){\n auto t = new drawable_model<T>(std::move(control));\n controls_.emplace_back(t);\n}\n</code></pre>\n\n<p>Also, I suppose that a <code>draw</code> shouldn't alter the object being drawn. Therefore, you better <code>const-qualify</code> all of your <code>draw</code> methods.</p>\n\n<p>You could also be more consistent with the way you use <code>inline</code>: you inlined <code>drawable_forwarder</code>'s <code>draw</code> method but not <code>drawable_model</code> while it basically does the same thing.</p>\n\n<hr>\n\n<p>One fun addition would be to write a method that would create the <code>drawable_model</code> object in-place. That would require to add the following constructor to <code>drawable_model</code>:</p>\n\n<pre><code>template<typename... Args>\ndrawable_model(Args&&... args):\n model_(std::forward<Args>(args)...)\n{}\n</code></pre>\n\n<p>And the following method to <code>graphics_surface</code> (not sure about the name):</p>\n\n<pre><code>template<typename T, typename... Args>\nvoid emplace_back(Args&&... args)\n{\n auto t = new drawable_model<T>(std::forward<Args>(args)...);\n controls_.emplace_back(t);\n}\n</code></pre>\n\n<p>Then, you could use it this way:</p>\n\n<pre><code>int main()\n{\n graphics_surface surface;\n\n // Assume triangle and rectangle have complete constructors\n surface.emplace_back<triangle>(3.5, 6.8, 4.8, 3.2);\n surface.emplace_back<square>(/* whatever */);\n\n surface.render();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T20:43:17.303",
"Id": "44101",
"ParentId": "41879",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "44101",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T13:34:36.720",
"Id": "41879",
"Score": "11",
"Tags": [
"c++",
"c++11",
"polymorphism"
],
"Title": "Concept based polymorphism"
}
|
41879
|
<p>After watching <a href="https://twitter.com/raymondh" rel="nofollow">Raymond Hettinger</a>s talk <a href="http://www.youtube.com/watch?v=OSGv2VnC0go" rel="nofollow">Transforming Code into Beautiful, Idiomatic Python</a> I got back to a function I wrote.</p>
<p>I'm not quite sure how to make it more pythonic but I think this might be a use-case to use the <a href="http://docs.python.org/3.4/library/functions.html#map" rel="nofollow">map function</a>.</p>
<pre><code>import logging
import string
import os
def _mounted_drives(possible_device_letters=string.ascii_uppercase):
"""Returns a set of mounted drive letters on a Windows machine."""
result = set()
for letter in possible_device_letters:
mounted = os.path.exists(letter + ':')
if mounted:
logging.info('Found device ' + letter)
result.add(letter)
return result
if __name__ == '__main__':
print(_mounted_drives())
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T19:43:17.317",
"Id": "72171",
"Score": "0",
"body": "There shouldn't be a leading underscore in the function name. By convention, a leading underscore would indicate that it is a private member of a class."
}
] |
[
{
"body": "<p>Removing the logging and using <a href=\"http://docs.python.org/2/tutorial/datastructures.html#sets\" rel=\"noreferrer\">set comprehension</a> :</p>\n\n<pre><code>def _mounted_drives(possible_device_letters=string.ascii_uppercase):\n return {l for l in possible_device_letters if os.path.exists(l + ':')}\n</code></pre>\n\n<p>If you do want the logging but you do not care about it being done once every device is found :</p>\n\n<pre><code>def _mounted_drives(possible_device_letters=string.ascii_uppercase):\n s = {l for l in possible_device_letters if os.path.exists(l + ':')}\n for l in s:\n logging.info('Found device ' + l)\n return s\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:41:43.817",
"Id": "41900",
"ParentId": "41885",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T15:03:30.327",
"Id": "41885",
"Score": "2",
"Tags": [
"python",
"functional-programming",
"file-system",
"windows",
"logging"
],
"Title": "Loop filling a set with logging"
}
|
41885
|
S.O.L.I.D is a set of principles used for designing object oriented solutions:
S - Single Responsibility principle
O - Open Closed principle
L - Liskov Substitution principle
I - Interface Segregation principle
D - Dependency Inversion principle
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T16:14:34.130",
"Id": "41892",
"Score": "0",
"Tags": null,
"Title": null
}
|
41892
|
<p>A bowling score calculator is my go-to exercise for learning the basics of a language. I recently had to pick up Perl so I did this.</p>
<p>I'm concerned that I'm doing subroutines wrong. I had a hard time figuring out the syntax for dealing with arguments and what <em>exactly</em> <code>@_</code> is.</p>
<p>I'm just looking for feedback on any egregious mistakes or instances where I go against convention.</p>
<pre><code>use strict;
use warnings;
use List::Util qw(sum);
sub is_strike { #is this frame a strike?
$_[0] == 10;
}
sub is_spare { #is this frame a spare?
($_[0] + $_[1]) == 10;
}
sub throws_for_score { #how many extra throws contribute to this frame's score?
(is_strike(@_) || is_spare(@_)) ? 2 : 1;
}
sub frame_advance { #how many throws should we consume to move to the next frame?
is_strike(@_) ? 1 : 2;
}
sub score_frame { #sum the score for x throws, where x is the number of throws that count for this frame's score
my $frame_index = $_[1];
my $frame_end = $frame_index + 2;
my $score_end = $frame_index + throws_for_score(@{$_[0]}[$frame_index..$frame_end]);
sum @{$_[0]}[$frame_index..$score_end];
}
sub score_game {
(my $game = $_[0]) =~ s/-//gi; #remove hyphens
my @throws = split(//, $game); #create an array of throws
find_strikes(\@throws);
my $current = 0;
my $score = 0;
do {
my $frame_score = score_frame(\@throws, $current);
$score += $frame_score;
$current += frame_advance(@throws[$current..($current+2)]);
} while($current <= $#throws-2); #while the current index is not beyond the tenth frame
$score;
}
sub find_strikes { #replace strike marks with 10
foreach(@{$_[0]}) {
if($_ eq 'X') {
$_ = 10;
}
}
}
print score_game("X-X-X-X-X-X-X-X-X-X-XX") . "\n"; #300
print score_game("55-55-55-55-55-55-55-55-55-55-5") . "\n"; #150
print score_game("00-00-00-00-00-00-00-00-X-X-XX"); #60
</code></pre>
|
[] |
[
{
"body": "<p>It's nice that you're using <code>strict</code> and <code>warnings</code>.</p>\n\n<h1>Subroutine Arguments</h1>\n\n<p>A subroutine should first unpack the argument list, e.g. like <code>my ($foo, $bar) = @_;</code>, then do some processing, and explicitly <code>return</code> a value. While we can return implicitly and can access items in <code>@_</code> directly, both can be error-prone and should be avoided in most situations.</p>\n\n<p>For example, this would change the <code>is_strike</code> to</p>\n\n<pre><code>sub is_strike {\n my ($frame) = @_;\n return $frame == 10;\n}\n</code></pre>\n\n<p>The line <code>(is_strike(@_) || is_spare(@_)) ? 2 : 1;</code> is similar obfuscation. First, we'll get rid of the unnecessary ternary operator:</p>\n\n<pre><code>return 2 if is_strike(@_) || is_spare(@_);\nreturn 1;\n</code></pre>\n\n<p>Next, we make it clearer by unpacking the arguments here as well. Don't mind the implied copy, we are optimizing for readability not performance!</p>\n\n<pre><code>my ($frame_1, $frame_2) = @_;\nreturn 2 if is_strike($frame_1) || is_spare($frame_1, $frame_2);\nreturn 1;\n</code></pre>\n\n<p>Why is this better? We immediately see that this function only uses its first two parameters.</p>\n\n<p>We can do the same exercise with <code>score_frame</code>. You are using the <code>@_</code> argument array throughout the whole subroutine, instead of giving each argument a self-explaining name.</p>\n\n<pre><code># sum the score for x throws,\n# where x is the number of throws that count for this frame's score\nsub score_frame {\n my ($frame, $index) = @_;\n my $frame_end = $index + 2;\n my $score_end = $index + throws_for_score(@$frame[$index .. $frame_end]);\n return sum @$frame[$frame_index .. $score_end];\n}\n</code></pre>\n\n<p>Let's look at this excerpt:</p>\n\n<pre><code>(my $game = $_[0]) =~ s/-//gi; #remove hyphens\nmy @throws = split(//, $game); #create an array of throws\n</code></pre>\n\n<p>The <code>/i</code> flag (case insensitive) on the substitution makes no sense, as you aren't using any characters that have a case. Try to avoid <code>/i</code>, as it makes many optimizations in the regex engine impossible.</p>\n\n<p>If you are only deleting a set of characters, you can use the more efficient transliteration <code>tr/-//d</code>, where <code>d</code> is “delete”. Together with proper argument unpacking, we get:</p>\n\n<pre><code>my ($game) = @_;\n$game =~ tr/-//d;\nmy @throws = split //, $game;\n</code></pre>\n\n<p>Whether you use parens for the arguments to builtin functions is largely a matter of taste. I prefer to omit them as I find the resulting code cleaner (and faster to write). Others enjoy that parens make the argument list explicit, which is otherwise hard to understand (technically, <a href=\"http://www.perlmonks.org/?node_id=663393\">Perl parsing is not decidable</a>).</p>\n\n<p>This line is hard to understand:</p>\n\n<pre><code>while($current <= $#throws-2); #while the current index is not beyond the tenth frame\n</code></pre>\n\n<p>I don't know what the tenth frame is about, but wouldn't a condition like <code>$current <= 10</code> be better if this is about the tenth frame?. </p>\n\n<h1>The <code>map</code> Function</h1>\n\n<p>The <code>find_strikes</code> function has a number of problems. Here is it's current form:</p>\n\n<pre><code>sub find_strikes { #replace strike marks with 10\n foreach(@{$_[0]}) {\n if($_ eq 'X') {\n $_ = 10;\n }\n }\n}\n</code></pre>\n\n<ul>\n<li>Modifying data that has been passed in is generally frowned upon. If you do something like that, document it. Even better, return a new list.</li>\n<li>Whenever possible, name the iteration variable instead of using <code>$_</code>.</li>\n<li>Some people prefer the <code>statement if condition</code> form instead of the verbose <code>if (condition) { statement }</code>. Note that the braces are not optional in this case.</li>\n</ul>\n\n<p>For example, we could rewrite the code like this:</p>\n\n<pre><code>sub find_strikes {\n my ($frames) = @_;\n my @frames_with_strikes;\n\n for my $frame (@frames) {\n if($frame eq 'X') {\n push @frames_with_strikes, 10;\n }\n else {\n push @frames_with_strikes, $frame;\n }\n }\n\n return @frames_with_strikes;\n}\n</code></pre>\n\n<p>That is excessively verbose, and actually a good example where the <code>?:</code> operator can be set to good use:</p>\n\n<pre><code>sub find_strikes {\n my ($frames) = @_;\n my @frames_with_strikes;\n\n for my $frame (@frames) {\n push @frames_with_strikes, ($frame eq 'X') ? 10 : $frame;\n }\n\n return @frames_with_strikes;\n}\n</code></pre>\n\n<p>We can shorten this further by using a <code>map</code> list transformation instead of an explicit loop:</p>\n\n<pre><code>sub find_strikes {\n my ($frames) = @_;\n return map { $_ eq 'X' ? 10 : $_ } @$frames;\n}\n</code></pre>\n\n<p>It is more “perlish” to take a list of values rather than an array reference:</p>\n\n<pre><code>sub find_strikes {\n my (@frames) = @_;\n return map { $_ eq 'X' ? 10 : $_ } @frames;\n}\n</code></pre>\n\n<p>or without unnecessary copies:</p>\n\n<pre><code>sub find_strikes {\n return map { $_ eq 'X' ? 10 : $_ } @_;\n}\n</code></pre>\n\n<p>In either way, it could now be invoked as</p>\n\n<pre><code>my @frames = find_strikes(split //, $game);\n</code></pre>\n\n<p>Less action at a distance, and clearer code.</p>\n\n<h1><code>say</code> > <code>print</code></h1>\n\n<p>You have lines like <code>print score_game(\"X-X-X-X-X-X-X-X-X-X-XX\") . \"\\n\"</code>. This can be improved</p>\n\n<ul>\n<li><p>… by passing a list rather than a single string:</p>\n\n<pre><code>print score_game(\"X-X-X-X-X-X-X-X-X-X-XX\"), \"\\n\";\n</code></pre>\n\n<p>all arguments will be joined without a space (unless you change certain settings).</p></li>\n<li><p>… by using <code>say</code> instead of <code>print</code>. The <code>say</code> function behaves exactly the same, but automatically appends a newline. Prefer it for normal text output. Use <code>print</code> when you don't want to print out a <em>line</em>, e.g. when handling binary data, a protocol with specific requirements on line endings, or when printing half a line.</p>\n\n<pre><code>use feature qw/say/; # activate the \"say\" function, available since v5.10.0\n\nsay score_game(\"X-X-X-X-X-X-X-X-X-X-XX\");\n</code></pre></li>\n</ul>\n\n<h1>Testing</h1>\n\n<p>In comments to your <code>print</code> invocations, you have given the expected output. Let's make an automated test out of this!</p>\n\n<p>The <code>Test::More</code> module is Perl's most commonly used test framework. Here is how we can write a test:</p>\n\n<pre><code>use Test::More;\n\nis(score_game(\"X-X-X-X-X-X-X-X-X-X-XX\"), 300, '\"X\"es');\nis(score_game(\"55-55-55-55-55-55-55-55-55-55-5\"), 150, 'fives');\nis(score_game(\"00-00-00-00-00-00-00-00-X-X-XX\"), 60, 'zeroes and \"X\"es');\n\ndone_testing;\n</code></pre>\n\n<p>The <code>is</code> test compares for string equivality (which is also good enough for numbers). There is also the <code>ok</code> test which asserts that some condition is true. The last argument is an optional test description.</p>\n\n<p>When we now execute the script, we get the following output:</p>\n\n<pre><code>ok 1 - \"X\"es\nok 2 - fives\nok 3 - zeroes and \"X\"es\n1..3\n</code></pre>\n\n<p>everything passed, nice! If I'm sneaky and change the expected output of one of the functions, we get:</p>\n\n<pre><code>ok 1 - \"X\"es\nnot ok 2 - fives\n# Failed test 'fives'\n# at so1.pl line 54.\n# got: '150'\n# expected: '42'\nok 3 - zeroes and \"X\"es\n1..3\n# Looks like you failed 1 test of 3.\n</code></pre>\n\n<p>The <code>is</code> test outputs a reason for the test failure when the input doesn't match our expectations.</p>\n\n<p>The output format is called TAP (Test Anything Protocol), and rarely used manually. Test suites are usually executed with the <code>prove</code> tool, which ships with Perl:</p>\n\n<pre><code>$ prove some_test.pl\nsome_test.pl .. ok \nAll tests successful.\nFiles=1, Tests=3, 0 wallclock secs ( 0.04 usr 0.00 sys + 0.02 cusr 0.00 csys = 0.06 CPU)\nResult: PASS\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:18:45.300",
"Id": "72121",
"Score": "0",
"body": "Impressive answer! However, I do not quite agree with the way you removed the ternary operator in the first functions as I find OP's version easier to read. Pure matter of personal preference I guess."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T18:36:55.700",
"Id": "72158",
"Score": "0",
"body": "The ternary operator is just a personal style choice. I seek out using it whenever possible because it's my favorite operator :) This answer was extremely helpful and revealed to me some syntax that I was not aware existed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T19:44:00.663",
"Id": "72172",
"Score": "0",
"body": "Since function parameters are aliased within `@_` (and not copied anywhere before making the call?) is it safe to say that there is no real advantage to passing an array ref to function (as opposed to passing an array as list)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T20:04:37.607",
"Id": "72173",
"Score": "1",
"body": "@mpapec There are many subtle differences. Calling a function with a list of scalars means that this list of scalars has to be written onto the stack, whereas an arrayref is just a single item. This becomes noticeable for really large amounts of data. Using an arrayref also allows us to modify the array itself (e.g. to append an element), whereas using a list of aliased scalars only allows us to modify each element. When writing list transformations (as here), a flat list is preferable as it's easier to compose. In other cases, references are preferable because of performance. It depends."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T17:14:27.833",
"Id": "41898",
"ParentId": "41893",
"Score": "8"
}
},
{
"body": "<p>I have a number of problems with your program, and <a href=\"https://codereview.stackexchange.com/a/41898/31503\">amon has categorized most of them</a>.... but, the most significant issue is that the code does not work... at least when it comes to spares, and some un-tested input values....</p>\n\n<p>There are three places it fails:</p>\n\n<ul>\n<li><p>it does not specify a good way to declare a spare. I would have expected a token like <code>/</code> to indicate a spare, leading to input like:</p>\n\n<pre><code>print score_game(\"5/-5/-5/-5/-5/-5/-5/-5/-5/-5/-5\") . \"\\n\"; #150\n</code></pre>\n\n<p>But, in the absence of that token, it makes it impossible to input the 'wild' spare sequence that I would have represented as:</p>\n\n<pre><code>print score_game(\"0/-0/-0/-0/-0/-0/-0/-0/-0/-0/-0\") . \"\\n\"; #100\n</code></pre></li>\n<li><p>this leads to the second issue I have, which is invalid input..... you do not handle it very well. For example, should the spare sequence have been input as:</p>\n\n<pre><code>print score_game(\"010-010-010-010-010-010-010-010-010-010-0\") . \"\\n\"; #100\n</code></pre>\n\n<p>your code strips the frame-separating <code>-</code> hyphen before it is sure what the frame really is.....</p></li>\n<li><p>finally, your code accepts broken data as input:</p>\n\n<pre><code>print score_game(\"66-66-66-66-66-66-66-66-X-X-XX\") . \"\\n\"; #156\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T22:08:29.820",
"Id": "41914",
"ParentId": "41893",
"Score": "3"
}
},
{
"body": "<h3>Tests</h3>\n\n<p>Your test cases only involve zeros and tens. Surely you need to test more realistic, less exotic cases too.</p>\n\n<h3>Input format</h3>\n\n<p>I like that you disregard the <code>-</code> in the input and interpret the framing yourself — that enhances robustness. Common notation for a <a href=\"http://en.wikipedia.org/wiki/Spare_(bowling)\" rel=\"nofollow noreferrer\">spare</a> is a <code>/</code> on the second throw. <del>It would be nice if you supported that.</del> As <a href=\"https://codereview.stackexchange.com/a/41914/9357\">@rolfl points out</a>, you <em>need</em> to support that because each throw has to be represented in one character, and you have no other way to indicate a frame of 0, 10. Also, in accordance with the principle that you should be lenient in what you accept, it would be better to accept both uppercase and lowercase <code>x</code> as a strike.</p>\n\n<h3>Parameter passing</h3>\n\n<p>You split the tasks into small functions, each with a specific purpose. Normally, that is an excellent idea, but I feel that the parameter passing is very cumbersome when expressed in Perl. </p>\n\n<p>First, I recommend consistently unpacking the parameter list into named variables in the first line of each subroutine. That way, it's easy to see what parameters the subroutine expects. An exception could be made if the subroutine is trivial (e.g. <code>is_strike()</code> below). In contrast, your <code>score_frame()</code> has a <code>$_[0]</code> buried in the last line, which hurts readability.</p>\n\n<p>Second, Perl is a punctuation-heavy language, and you managed to get hit hard, both by dereferencing and by array access, whenever you use <code>@{$_[0]}[$foo..$bar]</code> — which is quite frequently. My previous suggestion to give names to all parameters helps a bit. An object-oriented interface for frames would help — you could write <code>$game->throws($foo..$bar)</code> instead.</p>\n\n<p>Another strategy is to pass the lists by value rather than by reference.</p>\n\n<p>You currently call <code>score_frame(\\@throws, $current)</code>.</p>\n\n<p>How about calling <code>score_frame(@throws, $current)</code> instead? Unfortunately, that would make it awkward for <code>score_frame()</code> to unpack its arguments:</p>\n\n<pre><code>sub score_frame {\n my (@throws) = @_;\n my $current = pop @throws;\n …\n}\n</code></pre>\n\n<p>It would be better to put the scalar parameter first: <code>score_frame($current, @throws)</code>. Then, the arguments could be unpacked more naturally:</p>\n\n<pre><code>sub score_frame {\n my ($current, @throws) = @_;\n …\n}\n</code></pre>\n\n<p>But we can make it even simpler. Instead of maintaining and passing the index of the first throw of the frame, just consume the throws, shrinking the list a frame at a time. The front of the list is always the first throw of the current frame. See my solution below — I think it feels really natural!</p>\n\n<h3>Decomposition</h3>\n\n<p>The functions <code>is_strike()</code>, <code>is_spare()</code>, and <code>score_frame()</code> are a good idea. However, I feel that <code>frame_advance()</code> and <code>throws_for_score()</code> actually hurt readability, since it's no longer apparent from looking at the main loop in <code>score_game()</code> what the three cases are.</p>\n\n<p>I prefer to interpret the input using this one-liner in <code>score_game()</code>. It gets the assignment right the first time, requiring no subsequent mutation.</p>\n\n<pre><code># Split the game history into an array of throws,\n# replacing X with 10.\n… = map { s/X/10/i; $_} split(/-?/, $game);\n</code></pre>\n\n<h3>Suggested solution</h3>\n\n<pre><code>use feature qw(say);\nuse strict;\nuse warnings;\nuse List::Util qw(sum);\n\n# Is this frame a strike?\nsub is_strike { \n shift == 10;\n}\n\n# Is this frame a spare? (Call this subroutine only if it's not a strike.)\nsub is_spare {\n my ($first_throw, $second_throw) = @_;\n $second_throw eq '/' || $first_throw + $second_throw == 10;\n}\n\nsub score_frame {\n my ($first_throw, $second_throw, @bonus) = @_;\n $second_throw = 10 - $first_throw if $second_throw eq '/';\n sum($first_throw, $second_throw, @bonus);\n}\n\nsub score_game {\n my ($game) = @_;\n\n # Split the game history into an array of throws,\n # replacing X with 10.\n @_ = map { s/X/10/i; $_} split(/-?/, $game);\n\n my $score = 0;\n for my $frame (1..10) {\n if (is_strike(@_)) {\n # Consume one throw in this frame.\n # Include the next two throws as a bonus for this frame.\n $score += score_frame(shift, $_[0], $_[1]);\n } elsif (is_spare(@_)) {\n # Consume two throws in this frame.\n # Include the next throw as a bonus for this frame.\n $score += score_frame(shift, shift, $_[0]);\n } else {\n # Consume two throws in this frame. No bonus.\n $score += score_frame(shift, shift);\n }\n }\n $score;\n}\n\nsay score_game(\"X-X-X-X-X-X-X-X-X-X-XX\"); #300\nsay score_game(\"55-55-55-55-55-55-55-55-55-55-5\"); #150\nsay score_game(\"00-00-00-00-00-00-00-00-X-X-XX\"); #60\nsay score_game(\"01-10-20-03-04-35-55-6/-X-24\"); #77\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T23:38:45.043",
"Id": "72204",
"Score": "2",
"body": "Nice review. Note that `{ s/foo/bar/; $_ }` is equivalent to `s/foo/bar/r` which is available since perl 5.14 (released 2011). Reassigning to `@_` is frowned upon (except when doing tail calls), because it doesn't buy you anything over creating a new variable: `my @frames = map ...` is more self-documenting."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T22:10:10.793",
"Id": "41915",
"ParentId": "41893",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41898",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T16:15:09.223",
"Id": "41893",
"Score": "10",
"Tags": [
"perl"
],
"Title": "Bowling calculator in Perl"
}
|
41893
|
<p>I have fairly simple collision checking and handling Python code which is currently bottlenecking my performance quite a bit. I haven't done too much coding in python and I'm quite sure there's something that could be done better:</p>
<p>Assuming I read this profiler correctly, <code>get_nearby_entities</code> is the biggest culprit.</p>
<p><a href="http://bpaste.net/show/oidB2Gz0xLLFkNxx6UOj/" rel="nofollow noreferrer">Profiler output</a></p>
<h3>Collision handling</h3>
<p>In collision handling I go through all (moving) entities and find nearby entities from the collision grid (default search range is 9 closest cells).</p>
<pre><code>def handle_collision():
for first in entities:
# Pair all possible combinations, but only once per pair
grid.remove_entity(first)
# all entities are readded to the grid at the start of next update
for second in grid.get_nearby_entities(first):
# Check and handle collision
</code></pre>
<h3>Grid implementation:</h3>
<p>In <code>get_nearby_entities()</code> I return list consisting entities from all cells within search radius. There's propably more efficient way to do this using Python.</p>
<pre><code>import math
class Cell(object):
def __init__(self):
self.entities = []
def add_entity(self, entity):
self.entities.append(entity)
def remove_entity(self, entity):
self.entities.remove(entity)
def clear(self):
del self.entities[:]
class CollisionGrid(object):
def __init__(self, width, height, cell_size):
self.width = width
self.height = height
self.cell_size = cell_size
self.cols = int(math.ceil((self.width / cell_size)))
self.rows = int(math.ceil((self.height / cell_size)))
self.cells = [Cell() for _ in range(self.rows*self.cols)]
def add_entity(self, entity):
self.get_cell(entity.position).add_entity(entity)
def remove_entity(self, entity):
self.get_cell(entity.position).remove_entity(entity)
def get_nearby_entities(self, entity, radius = None):
if(not radius):
radius = self.cell_size
entities = []
min_x = int((entity.position.x - radius) / self.cell_size)
min_y = int((entity.position.y - radius) / self.cell_size)
max_x = int(min_x + 2*radius/self.cell_size + 1)
max_y = int(min_y + 2*radius/self.cell_size + 1)
if (min_x < 0): min_x = 0
if (min_y < 0): min_y = 0
if (max_x >= self.cols): max_x = self.cols
if (max_y >= self.rows): max_y = self.rows
for y in range(min_y, max_y):
for x in range(min_x, max_x):
entities.extend(self.cells[self.cols*y + x].entities)
return entities
def get_cell(self, position):
return self.cells[int(position.x / self.cell_size) +
int(position.y / self.cell_size) * self.cols]
def clear(self):
for c in self.cells:
c.clear()
</code></pre>
<h3>Picture of few entities in collision grid:</h3>
<p><img src="https://i.stack.imgur.com/1Gx63.png" alt="few entities in collision grid"></p>
<h3>It is after 200 entities when simulation really starts to slow down:</h3>
<p><img src="https://i.imgur.com/Ev4nTri.png" alt="few more entities"></p>
<h3>Test main:</h3>
<pre><code>import sfml as sf
import math
from entity import Entity
from collision_grid import CollisionGrid
WIDTH = 1280
HEIGHT = 720
Entity.SIZE = 50
settings = sf.window.ContextSettings()
settings.antialiasing_level = 8
window = sf.RenderWindow(sf.VideoMode(WIDTH, HEIGHT), "Collision Test",
sf.Style.DEFAULT, settings)
entities = []
grid = CollisionGrid(WIDTH, HEIGHT, Entity.SIZE)
time_per_frame = sf.seconds(1/60)
class Statistics(object):
def __init__(self, font):
self.text = sf.Text()
self.update_time = sf.seconds(0)
self.num_frames = 0
self.text.font = font
self.text.position = (5, 5)
self.text.character_size = 18
self.num_entities = 0
self.collision_checks = 0
def update(self, dt):
statistics.num_frames += 1
statistics.update_time += dt
if (self.update_time >= sf.seconds(0.1)):
fps = int(self.num_frames / self.update_time.seconds)
tps = int(self.update_time.microseconds / self.num_frames)
text = "FPS: " + str(fps) + "\n"
text += "update: " + str(tps) + " us\n"
text += "entities: " + str(self.num_entities) + "\n"
text += "collision checks: " + str(self.collision_checks) + "\n"
self.text.string = text
self.update_time -= sf.seconds(0.1)
self.num_frames = 0
def draw(self, target):
target.draw(self.text)
font = sf.Font.from_file("Media/Fonts/Sansation.ttf")
statistics = Statistics(font)
def process_events():
for event in window.events:
if type(event) is sf.CloseEvent:
window.close()
elif type(event) is sf.KeyEvent and event.code is sf.Keyboard.ESCAPE:
window.close()
elif type(event) is sf.MouseButtonEvent and event.pressed:
entities.append(Entity(event.position, sf.Color.GREEN))
def update(dt):
for e in entities:
e.update(dt)
if (e.position.x < 0):
e.position.x += WIDTH
elif (e.position.x > WIDTH):
e.position.x -= WIDTH
if (e.position.y < 0):
e.position.y += HEIGHT
elif (e.position.y > HEIGHT):
e.position.y -= HEIGHT
def render():
window.clear()
for e in entities:
e.draw(window)
grid.draw(window)
statistics.draw(window)
window.display()
def update_grid():
for e in entities:
grid.add_entity(e)
def handle_collision():
statistics.num_entities = len(entities)
statistics.collision_checks = 0
for f in entities:
# Pair all possible combinations, but only once per pair
grid.remove_entity(f)
for s in grid.get_nearby_entities(f):
statistics.collision_checks += 1
d = s.position - f.position
if (not (d.x or d.y)):
d.x += 0.1
distance = math.sqrt(d.x**2 + d.y**2)
radii = f.shape.radius + s.shape.radius
if (distance < radii):
offset = d * (radii/distance - 1)
f.velocity -= offset/2
s.velocity += offset/2
if __name__ == "__main__":
clock = sf.Clock()
time_since_last_update = sf.seconds(0)
for i in range(200):
entities.append(Entity(sf.Vector2(75+int(i%23)*50, 75+int(i/23)*50), sf.Color.GREEN))
while window.is_open:
dt = clock.restart()
time_since_last_update += dt
while time_since_last_update > time_per_frame:
time_since_last_update -= time_per_frame
process_events()
update_grid()
handle_collision()
grid.clear()
update(time_per_frame)
statistics.update(dt)
render()
</code></pre>
<h3>Entity</h3>
<pre><code>import sfml as sf
import utility
class Entity(object):
SIZE = 50
def __init__(self, position, color):
self.shape = sf.CircleShape()
self.shape.radius = Entity.SIZE/2
self.shape.fill_color = sf.Color.TRANSPARENT
self.shape.outline_color = color
self.shape.outline_thickness = 1
self.position = position
self.velocity = sf.Vector2()
self.line = sf.VertexArray(sf.PrimitiveType.LINES, 2)
def update(self, dt):
self.position += self.velocity * dt.seconds
speed = utility.length(self.velocity)
if (speed > 0.1):
self.velocity -= utility.unit_vector(self.velocity) * 0.1
else:
self.velocity.x = 0
self.velocity.y = 0
def draw(self, target):
self.shape.position = self.position - self.shape.radius
self.line[0].position = self.position
self.line[1].position = self.position + self.velocity
target.draw(self.shape)
target.draw(self.line)
</code></pre>
<h3>Utility methods used by Entity</h3>
<pre><code>def length(vector):
return math.sqrt(vector.x * vector.x + vector.y * vector.y)
def unit_vector(vector):
return vector / length(vector)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T20:42:09.130",
"Id": "72176",
"Score": "0",
"body": "It is difficult to improve the performance of code without a runnable test case whose performance we can measure. You could help us out here by making a self-contained runnable test case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T21:26:05.583",
"Id": "72185",
"Score": "0",
"body": "@GarethRees I have little test case for this written with sfml. Should I upload that somewhere or try to create smaller test case. (I find it easier to test, when I actually get some visual feedback)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T21:31:54.597",
"Id": "72186",
"Score": "0",
"body": "[pySFML](http://www.python-sfml.org) is a bit inconvenient to install (there's no [PyPI](https://pypi.python.org/pypi) package), so it would best if you could simplify your test case so that it runs on plain Python, and add it to your question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T10:29:16.437",
"Id": "72248",
"Score": "0",
"body": "Thanks for posting some test code. But I can't run it: you haven't posted the code for the `Entity` class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T11:15:44.373",
"Id": "72254",
"Score": "0",
"body": "@GarethRees I added Entity class and 2 utility methods it uses during update-step"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T12:12:37.397",
"Id": "72267",
"Score": "0",
"body": "As a side note, I think your cells are too small meaning you spend too much time in your broad phase compared to narrow phase."
}
] |
[
{
"body": "<p>Looking at your profiling information you spend a total of 14.5s in handle_collision() out of which 3.8s is spent in get_nearby_entities. So your culprit may actually be somewhere else (I can't tell without the rest of your source).</p>\n\n<h2>Precalculate/Cache nearby status</h2>\n\n<p>You are calculating the nearby entities too many times. Consider this, you have a cluster of 100 entities that are in nearby cells. For each of those you will calculate roughly the same nearby entity list (1st list contains 100 entities, 2nd contains 100 - 1, 3rd contains 100-2 etc). This gives you O(n^2) behavior. If you'd instead cache which entities were nearby last call for this node (and properly reset this cache), you could reduce this down to amortized O(n).</p>\n\n<p><strong>Edit:</strong> Even if the number of entities per node is small you're still doing redundant work. In the picture below, consider that you're processing cell 5, which means that you're looking at entities in 0,1,2,4,5,6,8,9,10 and adding them to a list. Next iteration you're processing cell 6, now you're looking at entities in 1,2,3 5,6,7,9,10,11. Which means that you have 6 cells in common with the previous iteration. You can devise a scheme for reducing this redundancy.</p>\n\n<pre><code>+--+--+--+--+\n| 0| 1| 2| 3|\n+--+--+--+--+\n| 4| 5| 6| 7|\n+--+--+--+--+\n| 8| 9|10|11|\n+--+--+--+--+ \n</code></pre>\n\n<h2>Edit: Compare squared distances</h2>\n\n<p>As I stated in my comment, most likely there is something else in <code>handle_collision()</code> that takes up 10/24s of your execution time. Now that I can see the source, there is not much there except the square root operator. Determining the square root is typically slow and often times unnecessary as:</p>\n\n<pre><code>sqrt(d^2) < r0 + r1 <=> d^2 < (r0 + r1)^2\n</code></pre>\n\n<p>So I would change your <code>handle_collision()</code> to defer calculating the square root until it is absolutely necessary:</p>\n\n<pre><code>def handle_collision():\n\n statistics.num_entities = len(entities)\n statistics.collision_checks = 0\n for f in entities:\n # Pair all possible combinations, but only once per pair\n grid.remove_entity(f)\n for s in grid.get_nearby_entities(f):\n statistics.collision_checks += 1\n\n d = s.position - f.position\n if (not (d.x or d.y)):\n d.x += 0.1\n distance_sqr = d.x**2 + d.y**2\n radii = f.shape.radius + s.shape.radius\n if (distance_sqr < radii*radii):\n offset = d * (radii/math.sqrt(distance_sqr) - 1)\n f.velocity -= offset/2\n s.velocity += offset/2\n</code></pre>\n\n<p>As not all objects collide, this should save you some sqrts, and I can't see anything else in there that would take time to execute. </p>\n\n<h2>Pre-allocate memory(?)</h2>\n\n<p>I know too little of python to make a clear call on this but in <code>get_nearby_entities()</code> you appear to be growing a vector inside of a doubly nested for-loop, in many languages this could be slow and you could consider pre-allocating a properly sized buffer for entitites to avoid many resizes.</p>\n\n<p><em>Edit: As was pointed out in comments, python's implementation runs in amortized O(n) time so pre allocating while saving some resizes will probably not gain you a significant amount of speed.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T22:54:49.010",
"Id": "72193",
"Score": "0",
"body": "With regard to your second point, Python's `list.extend(x)` has amortized cost O(`len(x)`) so this is not a concern here. See the [TimeComplexity](https://wiki.python.org/moin/TimeComplexity) page on the Python wiki."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T23:04:21.237",
"Id": "72194",
"Score": "0",
"body": "As I said I'm no python coder :) I'll edit my post."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T23:04:45.297",
"Id": "72195",
"Score": "0",
"body": "@EmilyL Currently cell size is same as entity size, and entities won't overlap much -> in single cell there is usually only 1 or 2 entities at most"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T23:08:23.087",
"Id": "72196",
"Score": "0",
"body": "Okay then would you please clarify the original post with more information about what quantities of entities and cells we're talking about?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T23:16:17.243",
"Id": "72198",
"Score": "0",
"body": "I looked at your profiling results again only 15% of your execution time seems to be spent in get_nearby_entities(). I believe your bottleneck may be elsewhere."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T00:04:52.127",
"Id": "72206",
"Score": "0",
"body": "Ok I added the whole test main. Is it even feasible with just Python to expect hundreds of simulated objects moving around?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T07:27:49.510",
"Id": "72240",
"Score": "0",
"body": "It doesn't look like there is much there that can take time except the sqrt operator. Consider comparing squared distances in your narrow-phase and do the sqrt only after you've determined that you have a collision."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T13:22:05.977",
"Id": "72274",
"Score": "0",
"body": "The computation of the square root is not an issue here: on modern processors, the time to compute the square root is dominated by the Python interpreter overhead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T13:39:02.900",
"Id": "72277",
"Score": "0",
"body": "@Gareth Did you try?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T13:47:20.293",
"Id": "72278",
"Score": "0",
"body": "@EmilyL.: Yes, I tried! (`timeit(lambda:mul(5, 5))` → 0.25s; `timeit(lambda:sqrt(5))` → 0.26s)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T14:28:41.250",
"Id": "72287",
"Score": "0",
"body": "So you're saying the 10s spent in `handle_collision()` is mostly the python interpreter?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T11:37:57.757",
"Id": "72490",
"Score": "0",
"body": "@EmilyL.: Yes, that's right."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T10:09:38.527",
"Id": "72721",
"Score": "0",
"body": "Why not put that up as an answer then?"
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T22:48:11.817",
"Id": "41918",
"ParentId": "41907",
"Score": "8"
}
},
{
"body": "<p>Python isn't fabulous at handling large numbers of math operations, but hundreds should be feasible.</p>\n\n<p>I agree that this doesn't look like it's primarily the fault of the collision grid. That said, it should be possible to speed up the grid calculation. I'd switch the grid to a really crude modulus of the object's position so that you don't calculate distances accurately until you need them: instead, sort everything into buckets by just dividing the entity position X and position Y by a scale (maybe with an offset so you can 'center' your grid in the world) this is cheaper than calculating distances ( no square roots) so it makes a good crude first pass. </p>\n\n<p>In the interest of simplicity I'd stick with default python lists for the grid and cells too. Plus, updating incrementally instead of a clean wipe should mean less memory shuffling. Here's a sketch of how I'd do it, though I doubt I'm covering your whole spec:</p>\n\n<pre><code>def create_grid(cells_x = 50, cells_y = 50):\n '''grid is a list-of-list-of-lists in row-column-list order'''\n grid = [ [ [] for x in range(cells_x)] for y in range(cells_y)] \n return grid\n\n\ndef get_nearby_entities( x,y, grid, radius = 1):\n '''this only checks cells, leaving detailed checks for later. It return all the entities in around x,y to <radius> cells''' \n min_x = max (x - radius, 0)\n max_x = min (x + radius, len( grid[0] ))\n\n min_y = max (y - radius, 0)\n max_y = min (y + radius, len(grid))\n\n nearby_cells = itertools.product(range (min_x, max_x + 1), range(min_y, max_y + 1))\n return itertools.chain(nearby_cells)\n\ndef get_address(entity, scale, offset):\n '''get the grid address for a given position'''\n address_x = math.floor ((entity.position.x + offset.x) / scale)\n address_y = math.floor ((entity.position.x + offset.y) / scale)\n return address_x, address_y\n\ndef rebuild_grid(grid, scale, offset, *entities):\n ''' update the grid after every step'''\n delenda = {}\n addenda = {}\n for x, y in itertools.product(range (len(grid[0])), range(len(grid))):\n for each_entity in grid[x][y]:\n current_address = get_address(each_entity)\n if current_address[0] != x or current_address[1] != y:\n delenda[each_entity] = (x,y)\n addenda[each_entity] = current_address\n\n for item in delenda:\n oldx, oldy = delenda[item]\n grid[oldx][oldy].remove(item)\n\n for item in addenda:\n oldx, oldy = addenda[item]\n grid[oldx][oldy].append(item)\n</code></pre>\n\n<p>I think this will be faster than your current update routine (among other things, using itertools is usually faster than hand-written loops) -- though depending on the data the incremental update might end up <em>slower</em> for data that doesn't cohere in time.</p>\n\n<p>The other obvious optimization would be to cache the collision checks as has been suggested. You'd maintain a dictionary of entity-entity pairs (this assumes entities are hashable, but they probably are). Inbetween steps set all existing pairs to a neutral value like None or -1; then as you do the checks for a given pair, you check the dictionary to be sure you haven't done that particular check before. I'd also do a two stage check for collision to cut out the square roots:</p>\n\n<pre><code># pretend the collisions are stored in a dictionary called 'colliders'\ndef collision_check ( pair, colliders, tolerance):\n ''' pair is a tuple (entity1, entity2)'''\n if colliders[pair] != None: return\n\n def collide():\n colliders[pair] = 1\n colliders[ (pair[1], pair[0]) ] = 1\n\n def miss():\n colliders[pair] = 0\n colliders[ (pair[1], pair[0]) ] = 0\n\n\n deltax = abs(pair[1].x - pair[0].x)\n deltay = abs(pair[1].y - pair[0].y) \n squaredist = deltax + deltay\n if squaredist < tolerance:\n collide()\n return\n\n if math.sqrt(math.pow(deltax,2) + math.pow(deltay, 2)) < tolerance:\n collide()\n return\n miss()\n</code></pre>\n\n<p>If after all that you still can't get the perf you want, you might want to look into using <a href=\"http://docs.scipy.org/doc/numpy/index.html\" rel=\"nofollow\">numpy</a> for the heavy duty tasks.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T01:44:56.010",
"Id": "41924",
"ParentId": "41907",
"Score": "4"
}
},
{
"body": "<h3>Minor improvements</h3>\n\n<p>Just looking at <code>get_nearby_entities</code> I see several (probably minor) improvements possibilities:</p>\n\n<ul>\n<li>transform it to a generator (it should save some memory space)</li>\n<li>remove some branching (I had some experience, where the branching misprediction was really slowing down my program )</li>\n<li><p>you are doing an (larger) approximation with you <code>max</code> variables: maybe it will improve if you do a finer computation</p>\n\n<pre><code>def get_nearby_entities(self, entity, radius = None):\n if(not radius):\n radius = self.cell_size\n\n min_x = max(int((entity.position.x - radius) / self.cell_size), 0)\n min_y = max(int((entity.position.y - radius) / self.cell_size), 0)\n max_x = min(int((entity.position.x + radius) / self.cell_size), self.cols)\n max_y = min(int((entity.position.y + radius) / self.cell_size), self.rows)\n\n for y in range(min_y, max_y):\n for x in range(min_x, max_x):\n yield from self.cells[self.cols*y + x].entities\n</code></pre></li>\n</ul>\n\n<h3>Grid entity removal</h3>\n\n<p>Maybe instead of actually removing the entities, you could mark them as 'visited' (via a boolean property). It might prevent some heavy memory usage.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-15T08:28:25.733",
"Id": "211206",
"Score": "0",
"body": "(I just realized, that this question is more than a year old...sorry for that)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-09T02:35:54.090",
"Id": "222270",
"Score": "0",
"body": "Good points anyway :) I'll propably revisit this code at some point for some improvements."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-14T17:56:11.180",
"Id": "113936",
"ParentId": "41907",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T20:00:56.273",
"Id": "41907",
"Score": "8",
"Tags": [
"python",
"performance",
"collision",
"sfml"
],
"Title": "Performance of collision detection in a grid"
}
|
41907
|
<p>I'm doing a program for a course in school (intro software development) and I'm looking for some general feedback as well as any ways this bit of code could be cleaner. I'm also wondering if it is bad practice to use <code>%=</code> as I've talked with some people and have been told it's not good to use any operators like that, other than <code>+=</code> and <code>-=</code> to keep code readable, although maybe that is specific to this particular course.</p>
<pre><code>private int heightInInches;
private final int VALUE_OF_ONE_FOOT = 12;
public String getHeightInFeetAndInches() {
String includeInches = "";
int leftOver = (heightInInches %= VALUE_OF_ONE_FOOT);
int newHeight = (heightInInches % VALUE_OF_ONE_FOOT);
if(leftOver < 0) {
includeInches = "";
}else if(leftOver <= 1) {
includeInches = "Inch";
}else {
includeInches = "Inches";
}
return newHeight + " feet " + leftOver + " " + includeInches;
}
</code></pre>
<p>This method should return a person's height in the form of (for example): 6 feet 1 inch(es) (if the inch amount exceeds 1).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T20:58:24.607",
"Id": "72181",
"Score": "7",
"body": "You might not want to be so hasty to choose an accepted answer. Give people time to answer, and then make a selection. Selecting an answer so soon may also ward off some answers that you may have received had you not accepted an answer so early."
}
] |
[
{
"body": "<p>I have no problem with <code>+=</code>, <code>-=</code> and even <code>*=</code>. But for <code>/=</code> and <code>%=</code>... perhaps I am just not used to them enough to like seeing them. I would recommend not using <code>%=</code>, but that is mostly my personal preference.</p>\n\n<p>Other comments:</p>\n\n<ul>\n<li><p>Instead of using the <code>heightInInches</code> as a field of the class, I would recommend passing it as a parameter to the method. Your method is only dependent of this single variable so I don't really see a reason to having it dependent on your class, especially since your method actually <strong>modifies</strong> this variable. You'd be much safer in having your method as</p>\n\n<pre><code>public String getHeightInFeetAndInches(int heightInInches) {\n</code></pre>\n\n<p>You could even make your method static if you would like (which I personally would recommend)</p></li>\n<li><p>Your <code>VALUE_OF_ONE_FOOT</code> should be <strong>static</strong> as it is a constant value.</p></li>\n<li><p>It is totally impossible for your <code>leftOver</code> value to be less than zero unless your <code>heightInInches</code> is also less than zero. And so far I haven't seen a single person with a negative height. <em>Did you mean <code>if (leftOver <= 0)</code>?</em></p></li>\n<li><p>I would have the last space as a part of the <code>includeInches</code> variable, as if it would be empty right now your return would end with a trailing space.</p></li>\n<li><p>Please use more spaces and make this line <code>}else if(leftOver <= 1) {</code> into <code>} else if (leftOver <= 1) {</code></p></li>\n<li><p>As @palacsint has pointed out, your code has a <strong>serious bug</strong>. I believe you should use the following:</p>\n\n<pre><code>int leftOver = heightInInches % VALUE_OF_ONE_FOOT;\nint newHeight = heightInInches / VALUE_OF_ONE_FOOT;\n</code></pre>\n\n<p>This would also have the benefit of not modifying your <code>heightInInches</code> variable (although I still think you should pass it as a parameter to the method instead of using it as a field).</p></li>\n<li><p>As pointed out by P. Lalonde in the comments below, your <code>VALUE_OF_ONE_FOOT</code> should be renamed to something like <code>INCHES_PER_FOOT</code>. All constants are values of something.</p></li>\n<li><p>Feature Request: Add support for the metric system ;)</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T20:45:29.430",
"Id": "72177",
"Score": "0",
"body": "Yes, I did mean `(leftOver <= 0)` Thanks for the great answer, Cheers!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T20:45:57.770",
"Id": "72178",
"Score": "5",
"body": "I agree with all those mentioned, I would also add that VALUE_OF_ONE_FOOT is redundant, a constant is quite often a VALUE_OF something, I would try to get something more descriptive, like NB_INCH_PER_FOOT or INCHES_PER_FOOT"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T20:46:22.420",
"Id": "72179",
"Score": "1",
"body": "@Mud No problem, and Welcome to Code Review!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T01:01:52.953",
"Id": "72210",
"Score": "1",
"body": "You forgot to mention ’^=’ which I think is definitely used more than ’/=’"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T12:07:07.947",
"Id": "72266",
"Score": "0",
"body": "You're right about the bug, of course, but I think you've put the operators on the wrong variables - `newHeight` is supposed to be the \"feet\" variable, not `leftover`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T12:35:59.703",
"Id": "72269",
"Score": "0",
"body": "@Clockwork-Muse Thanks for pointing that out. I have fixed the answer."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T20:38:47.110",
"Id": "41911",
"ParentId": "41909",
"Score": "14"
}
},
{
"body": "<p>+1 to <em>@Simon</em> and some other notes:</p>\n\n<ol>\n<li><p>If <code>heightInInches = 14</code> it returns <code>2 feet 2 Inches</code>. I guess it should be <code>1 feet 2 Inches</code>.</p></li>\n<li><p>The method currently violates the <a href=\"https://en.wikipedia.org/wiki/Command%E2%80%93query_separation\">Command Query Separation principle</a> because it modifies the <code>heightInInches</code> field.</p>\n\n<blockquote>\n <p>Functions should either do something or answer something, but not both. Either your\n function should change the state of an object, or it should return some information about\n that object. Doing both often leads to confusion.</p>\n</blockquote>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>, p45)</p></li>\n<li><p>In the output <code>feet</code> starts with a lowercase letter, <code>Inch(es)</code> starts with uppercase letter. It could be consistent.</p></li>\n<li><p>About the identation of the fields: if you have a new variable with a longer name you don't want to modify two other lines too to keep it nice. This also could cause unnecessary patch/merge conflicts.</p>\n\n<p>From <em>Code Complete, 2nd Edition</em> by <em>Steve McConnell</em>, p758:</p>\n\n<blockquote>\n <p><strong>Do not align right sides of assignment statements</strong></p>\n \n <p>[...]</p>\n \n <p>With the benefit of 10 years’ hindsight, I have found that, \n while this indentation style might look attractive, it becomes\n a headache to maintain the alignment of the equals signs as variable \n names change and code is run through tools that substitute tabs\n for spaces and spaces for tabs. It is also hard to maintain as\n lines are moved among different parts of the program that have \n different levels of indentation.</p>\n</blockquote></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T20:52:26.173",
"Id": "72180",
"Score": "1",
"body": "I thought it was strange doing two modulo in a row, couldn't put my finger on it. Thanks for filling in!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T20:48:05.067",
"Id": "41912",
"ParentId": "41909",
"Score": "13"
}
}
] |
{
"AcceptedAnswerId": "41911",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T20:27:38.923",
"Id": "41909",
"Score": "15",
"Tags": [
"java"
],
"Title": "Java %= and general feedback"
}
|
41909
|
<p>I am making a simple counter in assembly. It counts to a billion and exits. However, the performance of this is really horrible. A Java application (that does the same) outperforms it by around 10x. How can I optimize this code?</p>
<pre><code>include 'include/win32ax.inc'
section '.data' Data readable writeable
outhandle DD ?
inhandle DD ?
incr DD 0
numwritten DD ?
inchar DB ?
numread DD ?
section '.text' code readable executable
start:
invoke AllocConsole
invoke GetStdHandle,STD_OUTPUT_HANDLE
mov [outhandle],eax
invoke GetStdHandle,STD_INPUT_HANDLE
mov [inhandle],eax
invoke WriteConsole,[outhandle],"Starting...",11,numwritten,0
jmp loopcount
loopcount:
inc [incr]
cmp [incr], 1000000000;1 billion. ;]
jne loopcount
invoke WriteConsole,[outhandle]," Done count",13,numwritten,0
invoke ReadConsole,[inhandle],inchar,2,numread,0
invoke ExitProcess,0
.end start
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T23:12:33.343",
"Id": "72197",
"Score": "0",
"body": "I edited my answer after you accepted it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:50:42.027",
"Id": "72375",
"Score": "0",
"body": "@ChrisW i know."
}
] |
[
{
"body": "<p>Load <code>[incr]</code> into a register instead, for example <code>eax</code>, and increment the register.</p>\n\n<p>Instead of <code>cmp [incr], 1000000000</code> and <code>jne</code>, try loading 1000000 into the <code>ecx</code> register and using the <a href=\"http://en.wikibooks.org/wiki/X86_Assembly/Control_Flow#Loop_Instructions\"><code>loop</code></a> opcode.</p>\n\n<p>The advice above to use <code>loop</code> is probably obsolete. Instead it may be faster to do load 1000000 into a register like <code>ebx</code>, and do a <code>dec ebx</code> and <code>jnz loop</code>.</p>\n\n<p>Intel's <a href=\"http://software.intel.com/en-us/articles/branch-and-loop-reorganization-to-prevent-mispredicts\">Branch and Loop Reorganization to Prevent Mispredicts</a> seems to recommend you code a loop like this ...</p>\n\n<pre><code>loop_top:\n... do work inside the loop here ...\ncmp ebx,1000000\njz loop_end ; happens rarely\ninc ebx\njmp loop_top ; happens often\nloop_end:\n</code></pre>\n\n<p>... in order to optimize the branch prediction.</p>\n\n<p>Unrolling the loop might make it faster. In fact given how dumb the algorithm is, the best optimization is to immediately 1000000 to [incr] without looping.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T23:03:06.660",
"Id": "41919",
"ParentId": "41916",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "41919",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T22:33:48.103",
"Id": "41916",
"Score": "4",
"Tags": [
"optimization",
"performance",
"assembly"
],
"Title": "Counter in FASM assembly"
}
|
41916
|
<p>I have a class that serves to carry data between my JavaScript evaluation class and the player, via the Bukkit Conversations API, available in full <a href="https://github.com/Saposhiente/EvalJS/blob/master/src/com/github/Saposhiente/EvalJS/CodePrompt.java">on GitHub</a> (you will need <a href="http://dl.bukkit.org/downloads/bukkit/">Bukkit</a> and <a href="https://developer.mozilla.org/en-US/docs/Rhino/Download_Rhino">Rhino</a> as libraries (you can just comment out the JNBT code, it's not important), and a <a href="http://wiki.bukkit.org/Setting_up_a_server">Craftbukkit</a> server to run it). I was wondering in particular if I used inner classes correctly here, but also whether I should restructure my methods in some way. </p>
<pre><code>public class CodePrompt extends StringPrompt {
public final JavascriptRunner bridge;
private boolean cmd = false;
private String result = "";
private String prevInput = "";
public final Conversable coder;
protected Conversation conversation;
public Conversation getConversation() {
return conversation;
}
public CodePrompt(final JavascriptRunner bridge, final Conversable coder) {
this.bridge = bridge;
this.coder = coder;
//[API stuff]
conversation = EvalJS.instance.convFactory.withFirstPrompt(this).buildConversation(coder);
}
@Override
public String getPromptText(ConversationContext cc) {
if (cmd) {
return "";
} else {
return result;
}
}
@Override
public Prompt acceptInput(ConversationContext convContext, String input) {
try {
return eval(input);
} catch (Resumable resumable) {
return new InputPrompt(resumable);
}
}
private Prompt eval(String input) throws Resumable {
bridge.input(input); //on-before-evaluation function, by default just prints and logs the input, can be arbitrarily redefined
if (input.length() == 0) {
return this;
}
if (input.endsWith("\\")) {
prevInput += input.substring(0, input.length() - 1);
cmd = true;
return this;
}
if (input.length() > 1 && input.endsWith("\\n")) {
prevInput += input.substring(0, input.length() - 2) + "\n";
cmd = true;
return this;
}
input = prevInput + input;
prevInput = "";
if (input.startsWith("/")) {
cmd = true;
return doCommand(substitueInput(input), this);
} else {
cmd = false;
try {
final String output = bridge.eval(input);
List<String> pages = paginate(output);
if (pages.size() == 1) {
result = output;
return this;
} else {
result = "";
return new Pager(pages);
}
} catch (ContinuationPending cc) {
throw new EvaluationPending(cc);
}
}
}
private Prompt doCommand(String input, Prompt callback) {
//[Run a built-in command. Due to how this works around API limitations, changing the return type to void and removing the callback argument would not work.]
//Do-nothing implementation for testing:
System.out.println("Running command " + input);
return callback; //Real implementation does not actually return callback, but end behavior is similar to if it did
}
private String substitueInput(String input) throws SubstitutionPending {
return substitueInput(input, new StringBuilder(), input.indexOf("$(") + 2, 0);
}
private String substitueInput(String input, StringBuilder substitutedInput, int from, int to) throws SubstitutionPending {
if (from > 1) {
substitutedInput.append(input.substring(to, from - 2));
to = input.indexOf(")$", from) + 2;
if (to < 2) {
substitutedInput.append(input.substring(to, input.length()));
return substitutedInput.toString();
}
try {
substitutedInput.append(bridge.eval(input.substring(from, to - 2)));
} catch (ContinuationPending cc) {
throw new SubstitutionPending(input, substitutedInput, to, cc);
}
return substitueInput(input, substitutedInput, input.indexOf("$(", to) + 2, to);
} else {
substitutedInput.append(input.substring(to, input.length()));
return substitutedInput.toString();
}
}
public class InputPrompt extends StringPrompt {
protected final Resumable resumable;
public InputPrompt(Resumable resumable) {
this.resumable = resumable;
}
@Override
public String getPromptText(ConversationContext cc) {
return "";
}
@Override
public Prompt acceptInput(ConversationContext cc, String input) {
try {
return resumable.resume(input);
} catch (Resumable subResumable) {
return new InputPrompt(subResumable);
}
}
}
public abstract class Resumable extends Exception {
public Resumable(Throwable cause) {
super(cause);
}
public abstract Prompt resume(String newInput) throws Resumable;
}
public class SubstitutionPending extends Resumable {
private final String input;
private final StringBuilder substitutedInput;
private final int to;
@Override
public Prompt resume(String newInput) throws SubstitutionPending {
substitutedInput.append(bridge.resume(getCause(), newInput));
return doCommand(substitueInput(input, substitutedInput, input.indexOf("$(", to) + 2, to), CodePrompt.this);
}
public SubstitutionPending(String input, StringBuilder substitutedInput, int to, ContinuationPending cause) {
super(cause);
this.input = input;
this.substitutedInput = substitutedInput;
this.to = to;
}
@Override
public synchronized ContinuationPending getCause() {
return (ContinuationPending)super.getCause();
}
}
public class EvaluationPending extends Resumable {
@Override
public Prompt resume(String newInput) throws EvaluationPending {
final String output = bridge.resume(getCause(), newInput);
List<String> pages = paginate(output);
if (pages.size() == 1) {
result = output;
return CodePrompt.this;
} else {
result = "";
return new Pager(pages);
}
}
public EvaluationPending(ContinuationPending cause) {
super(cause);
}
@Override
public synchronized ContinuationPending getCause() {
return (ContinuationPending)super.getCause();
}
}
public static final int LINECHARS = 44;//low estimate; font is not monospaced
public static final int TEXTLINES = 20;
public List<String> paginate(String result) {//Okay, maybe not the best name for a method.
//[Split the input into strings that each fit in at most one page of the output text area]
//Approximated for brevity:
return Arrays.asList(result.split("\n")); //Real implementation has good reason for using List<String> instead of String[]
}
public class Pager extends ValidatingPrompt {
private final List<String> pages;
private int pos = 0;
private boolean noDisplay = false;
public Pager(List<String> pages) {
this.pages = pages;
}
@Override
public String getPromptText(ConversationContext cc) {
//BUG: When Pager first becomes the active prompt, it doesn't display anything (works only once you provide 1 input). This method isn't called at all. I have no idea why.
if (noDisplay) return "";
return pages.get(pos) + "Page " + (pos + 1) + "/" + pages.size() + ". n:next p:prev §o#§r:page §o#§r q:quit";//§o = italics §r = end of italics
}
@Override
protected boolean isInputValid(ConversationContext cc, String string) {
if (string.startsWith("/") || string.equalsIgnoreCase("n") || string.equalsIgnoreCase("p") || string.equalsIgnoreCase("e") || string.equalsIgnoreCase("q")) {
return true;
}
try {
Integer.parseInt(string);
return true;
} catch (NumberFormatException ex) {
return false;
}
}
@Override
protected Prompt acceptValidatedInput(ConversationContext cc, String string) {
switch (string.toLowerCase()) {
case "n":
if (pos + 1 >= pages.size()) {
cc.getForWhom().sendRawMessage("Invalid page!");
noDisplay = true;
} else {
pos++;
noDisplay = false;
}
return this;
case "p":
if (pos - 1 <= 0) {
cc.getForWhom().sendRawMessage("Invalid page!");
noDisplay = true;
} else {
pos--;
noDisplay = false;
}
return this;
case "e":
case "q":
return CodePrompt.this;
default:
if (string.startsWith("/")) {
noDisplay = true;
return doCommand(string, this);
} else {
int next = Integer.parseInt(string);
if (pos < 1 || pos > pages.size()) {
cc.getForWhom().sendRawMessage("Invalid page!");
noDisplay = true;
} else {
pos = next - 1;
noDisplay = false;
}
return this;
}
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your code is actually pretty good overall. I have one very big question, though: <em>why</em> do you want all these to be inner classes? Normally, we use inner classes only for a very specific reason and only if the class in question is a <em>critical component</em> of the outer class and somehow inseparable. Usually, this is done with enums, for example:</p>\n\n<pre><code>public class Coin {\n\n public static enum Side {\n HEADS,\n TAILS;\n }\n\n // ...\n}\n</code></pre>\n\n<p>For an example intrinsic to the Java API, you can look at <a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.State.html\" rel=\"nofollow\">Thread.State</a>.</p>\n\n<p>Here, it doesn't make any sense to have a Side without a Coin, and it makes the code more understandable to always reference a coin's side as something like <code>Coin.Side.HEADS</code>. We don't get much added benefit from extracting it into another class (i.e., <code>CoinSide.HEADS</code>).</p>\n\n<p>Would you say this is the case for all of these inner classes? My personal opinion is \"No.\" You're even creating whole <em>hierarchies</em> of classes in here, with your <code>abstract class Resumable</code> and then having <em>other</em> inner classes <code>extend</code> it. All of this is a bit complicated and all over the place for the function of a single class.</p>\n\n<p>This is often quoted, but it's true: remember that a class, just like a method, should <a href=\"http://www.codinghorror.com/blog/2007/03/curlys-law-do-one-thing.html\" rel=\"nofollow\">do one thing, and do it well</a>. Consider extracting some of these classes into their own files, if you see fit and think it will clean up the code some.</p>\n\n<hr>\n\n<p>Other than that, below are just some various tid bits. Take them or leave them.</p>\n\n<pre><code>public final JavascriptRunner bridge;\n// ...\nconversation = EvalJS.instance.convFactory.withFirstPrompt(this).buildConversation(coder);\n</code></pre>\n\n<p>In general, I'd prefer to have these kinds of objects (<code>bridge</code>, <code>instance</code>, <code>convFactory</code>) be accessed via getters and setters rather than being exposed as <code>public</code>. This is <em>especially</em> important for the one named <code>instance</code>, which I assume is supposed to be a <a href=\"http://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"nofollow\">singleton</a>. A singleton's initialization should always be thread-safe, which means it needs its own <a href=\"http://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html\" rel=\"nofollow\">synchronized</a> accessor method, like so:</p>\n\n<pre><code>private Thingy instance = null;\n\npublic static synchronized Thingy getInstance() {\n if(instance == null) instance = new Thingy();\n return instance;\n}\n</code></pre>\n\n<p>... or ...</p>\n\n<pre><code>private Thingy instance = null;\nprivate Object INSTANCE_LOCK = new Object();\n\npublic static Thingy getInstance() {\n synchronized(INSTANCE_LOCK) {\n if(instance == null) {\n instance = new Thingy();\n }\n }\n return instance;\n}\n</code></pre>\n\n<hr>\n\n<pre><code>public String getPromptText(ConversationContext cc) {\n if (cmd) {\n return \"\";\n } else {\n return result;\n }\n}\n</code></pre>\n\n<p>This could be rewritten in one line with the ternary operator: <code>cmd ? \"\" : result;</code></p>\n\n<hr>\n\n<pre><code>private Prompt eval(String input) throws Resumable {\n</code></pre>\n\n<p>In general, you should try to have more descriptive method names. Following Java naming conventions, they should always be verbs or verb phrases. It just makes your code more readable and easier to follow. For example, this could be called <code>evaluateInput()</code> or something.</p>\n\n<hr>\n\n<pre><code>return (ContinuationPending)super.getCause();\n</code></pre>\n\n<p>I'm sure you're fine with this, but just be careful with unsafe casting! :) I like to check whether the cast is valid with either <code>instanceof</code> or, preferably, <code>ContinuationPending.class.isInstance(super.getCause())</code>.</p>\n\n<hr>\n\n<pre><code>public static final int LINECHARS = 44;//low estimate; font is not monospaced\npublic static final int TEXTLINES = 20;\n</code></pre>\n\n<p>Constants should almost always go at the <em>top</em> of your classes rather than being spread out through the file. Same with inner classes, as a matter of fact: group them all together either at the top or the bottom of the main class. In general, I tend to lay out my classes like this:</p>\n\n<pre><code>public class Whatever {\n\n //CONSTANTS\n\n //INNER ENUMS\n\n //CONSTRUCTORS\n\n //crtical methods\n //getters and setters\n //method overrides (e.g., `toString()`, `actionPerformed()`, ...)\n\n //STATIC METHODS\n\n //INNER CLASSES\n}\n</code></pre>\n\n<p>That's just my particular style, but even if you don't like mine, there should be a consistent structure you use throughout your code.</p>\n\n<hr>\n\n<pre><code>if (string.startsWith(\"/\") || string.equalsIgnoreCase(\"n\") || string.equalsIgnoreCase(\"p\") || string.equalsIgnoreCase(\"e\") || string.equalsIgnoreCase(\"q\"))\n</code></pre>\n\n<p>This is a bit of an ugly <code>if</code> statement. I'd clean it up with something like this:</p>\n\n<pre><code>private static final List<String> VALID_INPUT = Collections.unmodifiableList(Arrays.asList(\"n\", \"p\", \"e\", \"q\"));\n\nif(string.startsWith(\"/\") || VALID_INPUT.contains(string.toLowerCase())) {\n //....\n</code></pre>\n\n<hr>\n\n<p>Finally...</p>\n\n<pre><code>return CodePrompt.this;\n</code></pre>\n\n<p>I'm a bit confused why you're accessing <code>this</code> statically here rather than just as <code>this</code> like you do throughout the rest of the code. Is there some obscure reason that I'm not aware of? If not, try to remain consistent.</p>\n\n<p>Pretty high quality stuff overall!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T04:23:48.847",
"Id": "73167",
"Score": "0",
"body": "Okay, I split the classes, but one thing that I'm concerned about now is that suddenly I have to make the majority of my `private` methods package-private, because the formerly-inner classes required them. Perhaps if all the Prompts were in the same package it would be more sensical, but EvalJS.instance and EvalJS.instance.convFactory are package-private, so that would break the use of them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T04:46:16.377",
"Id": "73169",
"Score": "0",
"body": "Also, the reason that I used `return CodePrompt.this;` at that point is that it was in the middle of the Pager inner class, and I wanted to return the CodePrompt, not the Pager."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T04:57:14.057",
"Id": "73171",
"Score": "0",
"body": "@Saposhiente Ah, gotcha! Didn't see that. I was skimming the code at work. Makes perfect sense. :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T20:14:51.977",
"Id": "42457",
"ParentId": "41920",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "42457",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T00:14:37.670",
"Id": "41920",
"Score": "11",
"Tags": [
"java",
"console"
],
"Title": "Using Bukkit conversations for a coding console"
}
|
41920
|
<p>Any major security risks? And please don't get angry over my novice log system.</p>
<pre><code><?php
function makesalt($lg)
{
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-';
$sz = strlen( $chars );
$str = '';
for( $i = 0; $i < $lg; $i++ ) {
$str .= $chars[ rand( 0, $sz - 1 ) ];
}
return $str;
}
function duelsha($th)
{
$tem = hash('sha512', $th);
$tem2 = md5($tem);
return hash('sha256', $tem2);
}
function shasalt($ht)
{
$salt = makesalt(30);
return duelsha($ht . $salt) . '|' . $salt;
}
function mysqlsan($ss)
{
if (get_magic_quotes_gpc()) $ss = stripslashes($ss);
return mysql_real_escape_string($ss);
}
function htent($st)
{
return htmlentities($st);
}
function sqlhtml($sm)
{
return htent(mysqlsan($sm));
}
function logs($tl)
{
$fh = fopen("server.log", 'w') or die("File error");
fwrite($fh, $tl) or die("File error");
fclose($fh);
}
?>
</code></pre>
|
[] |
[
{
"body": "<p>You home brewed security hashes and such are a big <strong>NO</strong>. Please, <a href=\"https://security.stackexchange.com/questions/25585/is-my-developers-home-brew-password-security-right-or-wrong-and-why\">check here</a> and <a href=\"https://security.stackexchange.com/questions/211/how-to-securely-hash-passwords\">here</a> for a good read regarding that. Also, please do not hash a hash, that can lead to collisions and should be avoided! Using a method such as <code>password_hash()</code> creates a salt for you, therefore you shouldn't have to make one on your own.</p>\n\n<p>You're using <code>mysql_real_escape_string()</code> which is not the way to go. If possible, move away from that and onto mysqli or PDO.</p>\n\n<p>And then your function <code>htent()</code> is sort of redundant. You don't have anything else in the function, so it shouldn't be needed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T01:48:56.930",
"Id": "41925",
"ParentId": "41921",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41925",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T00:21:26.953",
"Id": "41921",
"Score": "4",
"Tags": [
"php",
"security",
"hashcode"
],
"Title": "A PHP Toolkit of some functions"
}
|
41921
|
<p>A (long) while ago I set up a file server in my basement running Linux. I am OCD when it comes to backups.</p>
<p>I set the server up with (remember, this was a while ago):</p>
<ul>
<li>disk for OS</li>
<li>disk for 'valuable' things</li>
<li>disk for backups</li>
</ul>
<p>The idea was that if any one disk failed, I could replace things with minimal loss. The OS was supposed to be stuff that was easy to reinstall. The 'valuable' things are data that is irreplaceable (e-mail, photos, documents, etc.). The backup disk contains a copy of the valuable data.</p>
<p>I also have learned (a long time ago) that keeping backups of your current data is not very useful if you corrupt (or delete) your current data, and then replace your backups with the corrupt version. As a result, I keep 'snapshots' of my valuable data at regular intervals, and I can go back to any snapshot to retrieve the data <em>as it was at the time of the snapshot</em>. If I delete a file now, I can go to a previous snapshot, and restore it.</p>
<p>I started using a script written in bash to do this for me.... <a href="http://www.mikerubel.org/computers/rsync_snapshots/">Mike's handy backup script!</a></p>
<p>This worked for a while, but I discovered it had problems:</p>
<ol>
<li>I wanted to make it configurable (specify the folders to back up <em>outside</em> the script)</li>
<li>sometimes the backup was long-running, and another backup could start before the previous one completed (these snapshots are taken at every hour).</li>
<li>My monthly backup routine copies the entire snapshot disk to an external drive, and this takes hours, and I want the data to be consistent</li>
<li><code>rm -rf</code> on deeply-hard-linked files is a slow process.... so I had to remove it from the script....</li>
</ol>
<p>I extended Mike's script, and then ended up rewriting it in <code>perl</code>.</p>
<p>Over time things have changed. I now have a RAID array mounted on <code>/valuable</code> which contains things that are supposedly 'valuable' to me. The regular filesystem is still mounted as <code>/</code>. The destination for these snapshots is the disk (also a RAID array) mounted at <code>/snapshotng</code>. There is about 2TB of valuable data (many large photographs from the whole family, e-mails from decades, and documents, etc.)</p>
<p>An example configuration file for the script is:</p>
<pre><code># Try to make things in revers alphabetic order...
# makes co-existence with the snashot2backup more friendly.
# but still put the smaller folders first
# smaller folders
versioncontrol /valuable/versioncontrol .versioncontrol_exclude
local /usr/local .local_exclude
mysql /valuable/mysqlbackups .mysql_exclude
www /valuable/www .www_exclude
etc /etc .etc_exclude # get the /etc folder
# medium folders
root /root .root_exclude
opt /opt .opt_exclude
# large folders
gallery_cache /valuable/gallery23_cache .gallery_cache_exclude
netshare /valuable/netshare .netshare_exclude
pictures /valuable/pictures .pictures_exclude
home /valuable/home .home_exclude
webdav /valuable/webdav .webdav_exclude
</code></pre>
<p>The key features of this script are:</p>
<ul>
<li>it runs every hour (cron job)</li>
<li>it creates a complete copy of the source directory in a specially named folder in <code>/snapshotng</code></li>
<li>the snapshot uses hard-linked copies of the files unless the files have been changed since the previous snapshot (the hard-link is to the previous snapshot, not to the source).</li>
<li>it marks 'old' copies as 'trash'. It keeps at least:
<ul>
<li>1 copy from every year for the past 10 years</li>
<li>1 copy from every month for the past 18 months</li>
<li>1 copy from every week for the past 16 weeks</li>
<li>1 copy from every day for the past 14 days</li>
<li>1 copy from every hour for the past 48 hours.</li>
</ul></li>
<li>anything that does not fit the above 'keep' list is marked as trash.</li>
<li>it creates a file-system lock on each (target) directory it is about to back up</li>
<li>it e-mails me if there is a problem (mostly by logging to the cron job output)</li>
</ul>
<p>This script has been in use now for close on 10 years.... it has been extended, modified, and 'fixed', but has never been reviewed. Because of its age, it does not use the latest perl goodies..... sorry.</p>
<p>The output from the program looks like the following:</p>
<blockquote>
<pre><code>==============================
Mon Feb 17 20:17:01 EST 2014
------------------------------
Attempting to obtain lock /snapshotng/.snap.lock
Running "lockfile" "-5" "-r12" "/snapshotng/.snap.lock"
Locked snapshot folder with /snapshotng/.snap.lock in 0 seconds
SNAPSHOT PROCESS BEGINNING. Using ID 2014.02.17.20.17 @ Mon Feb 17 20:17:01 2014
Processing 13 folders based on the configuration file
Snapshot versioncontrol: /valuable/versioncontrol @ Mon Feb 17 20:17:01 2014
Running "lockfile" "-5" "-r-1" "/snapshotng/versioncontrol/.snapshot.lock"
Locked snapshot folder with /snapshotng/versioncontrol/.snapshot.lock in 0 seconds
Rules:
^versioncontrol\.2005\..*$
^versioncontrol\.2006\..*$
^versioncontrol\.2007\..*$
^versioncontrol\.2008\..*$
^versioncontrol\.2009\..*$
....
^versioncontrol\.2014\.02\.17\.17\..*$
^versioncontrol\.2014\.02\.17\.18\..*$
^versioncontrol\.2014\.02\.17\.19\..*$
^versioncontrol\.2014\.02\.17\.20\..*$
Matched versioncontrol.2009.05.01.06.55 to rule ^versioncontrol\.2009\..*$
Matched versioncontrol.2010.01.01.00.05 to rule ^versioncontrol\.2010\..*$
Matched versioncontrol.2011.01.01.00.17 to rule ^versioncontrol\.2011\..*$
.....
Matched versioncontrol.2014.02.17.13.17 to rule ^versioncontrol\.2014\.02\.17\.13\..*$
Matched versioncontrol.2014.02.17.14.17 to rule ^versioncontrol\.2014\.02\.17\.14\..*$
Matched versioncontrol.2014.02.17.15.17 to rule ^versioncontrol\.2014\.02\.17\.15\..*$
Matched versioncontrol.2014.02.17.16.17 to rule ^versioncontrol\.2014\.02\.17\.16\..*$
Matched versioncontrol.2014.02.17.17.17 to rule ^versioncontrol\.2014\.02\.17\.17\..*$
Matched versioncontrol.2014.02.17.18.17 to rule ^versioncontrol\.2014\.02\.17\.18\..*$
Matched versioncontrol.2014.02.17.19.17 to rule ^versioncontrol\.2014\.02\.17\.19\..*$
Latest is versioncontrol.2014.02.17.19.17
Running "mv" "/snapshotng/versioncontrol/versioncontrol.2014.02.15.20.17" "/snapshotng/versioncontrol/trash.versioncontrol.2014.02.15.20.17"
Using previous snapshot /snapshotng/versioncontrol/versioncontrol.2014.02.17.19.17 as the baseline.
Running "cp" "-alH" "/snapshotng/versioncontrol/versioncontrol.2014.02.17.19.17" "/snapshotng/versioncontrol/tmpsnap"
**** Using Exclude file /snapshotng/versioncontrol/.versioncontrol_exclude ****
Running "rsync" "-v" "-a" "--delete" "--exclude-from=/snapshotng/versioncontrol/.versioncontrol_exclude" "--delete-excluded" "/valuable/versioncontrol/" "/snapshotng/versioncontrol/tmpsnap/"
sending incremental file list
sent 75376 bytes received 607 bytes 151966.00 bytes/sec
total size is 183823276 speedup is 2419.27
Running "mv" "/snapshotng/versioncontrol/tmpsnap" "/snapshotng/versioncontrol/versioncontrol.2014.02.17.20.17"
Running "rm" "-f" "/snapshotng/versioncontrol/.snapshot.lock"
Completed snapshot for /valuable/versioncontrol in to /snapshotng/versioncontrol/versioncontrol.2014.02.17.20.17 @ Mon Feb 17 20:17:02 2014
......
SNAPSHOT PROCESS COMPLETE. Using ID 2014.02.17.20.17 @ Mon Feb 17
20:19:23 2014Mon Feb 17 20:19:23 2014 in 2 minutes, 22 seconds
</code></pre>
</blockquote>
<p>The actual example folder for the 'versioncontrol' backup looks like:</p>
<pre><code>trash.versioncontrol.2014.02.15.08.17 versioncontrol.2009.05.01.06.55 versioncontrol.2013.05.01.00.17 versioncontrol.2013.12.08.00.18 versioncontrol.2014.02.05.00.17 versioncontrol.2014.02.15.22.17 versioncontrol.2014.02.16.11.17 versioncontrol.2014.02.17.00.17 versioncontrol.2014.02.17.13.17
trash.versioncontrol.2014.02.15.09.17 versioncontrol.2010.01.01.00.05 versioncontrol.2013.06.01.00.17 versioncontrol.2013.12.15.00.18 versioncontrol.2014.02.06.00.17 versioncontrol.2014.02.15.23.17 versioncontrol.2014.02.16.12.17 versioncontrol.2014.02.17.01.17 versioncontrol.2014.02.17.14.17
trash.versioncontrol.2014.02.15.10.17 versioncontrol.2011.01.01.00.17 versioncontrol.2013.07.01.00.17 versioncontrol.2013.12.22.00.18 versioncontrol.2014.02.07.00.17 versioncontrol.2014.02.16.00.17 versioncontrol.2014.02.16.13.17 versioncontrol.2014.02.17.02.17 versioncontrol.2014.02.17.15.17
trash.versioncontrol.2014.02.15.11.17 versioncontrol.2012.01.01.00.17 versioncontrol.2013.08.01.00.17 versioncontrol.2013.12.29.00.17 versioncontrol.2014.02.08.00.17 versioncontrol.2014.02.16.01.17 versioncontrol.2014.02.16.14.17 versioncontrol.2014.02.17.03.17 versioncontrol.2014.02.17.16.17
trash.versioncontrol.2014.02.15.12.17 versioncontrol.2012.09.01.00.17 versioncontrol.2013.09.01.00.17 versioncontrol.2014.01.01.00.17 versioncontrol.2014.02.09.00.17 versioncontrol.2014.02.16.02.17 versioncontrol.2014.02.16.15.17 versioncontrol.2014.02.17.04.17 versioncontrol.2014.02.17.17.17
trash.versioncontrol.2014.02.15.13.17 versioncontrol.2012.10.07.20.17 versioncontrol.2013.10.01.00.17 versioncontrol.2014.01.01.01.17 versioncontrol.2014.02.09.01.17 versioncontrol.2014.02.16.03.17 versioncontrol.2014.02.16.16.17 versioncontrol.2014.02.17.05.17 versioncontrol.2014.02.17.18.17
trash.versioncontrol.2014.02.15.14.17 versioncontrol.2012.11.01.00.17 versioncontrol.2013.11.01.00.17 versioncontrol.2014.01.05.00.17 versioncontrol.2014.02.10.00.17 versioncontrol.2014.02.16.04.17 versioncontrol.2014.02.16.17.17 versioncontrol.2014.02.17.06.17 versioncontrol.2014.02.17.19.17
trash.versioncontrol.2014.02.15.15.17 versioncontrol.2012.12.01.00.17 versioncontrol.2013.11.03.00.17 versioncontrol.2014.01.12.00.17 versioncontrol.2014.02.11.00.17 versioncontrol.2014.02.16.05.17 versioncontrol.2014.02.16.18.17 versioncontrol.2014.02.17.07.17 versioncontrol.2014.02.17.20.17
trash.versioncontrol.2014.02.15.16.17 versioncontrol.2013.01.01.00.17 versioncontrol.2013.11.10.00.18 versioncontrol.2014.01.19.00.17 versioncontrol.2014.02.12.00.17 versioncontrol.2014.02.16.06.17 versioncontrol.2014.02.16.19.17 versioncontrol.2014.02.17.08.17
trash.versioncontrol.2014.02.15.17.17 versioncontrol.2013.01.01.01.17 versioncontrol.2013.11.17.00.17 versioncontrol.2014.01.26.00.17 versioncontrol.2014.02.13.00.17 versioncontrol.2014.02.16.07.17 versioncontrol.2014.02.16.20.17 versioncontrol.2014.02.17.09.17
trash.versioncontrol.2014.02.15.18.17 versioncontrol.2013.02.01.00.17 versioncontrol.2013.11.24.00.18 versioncontrol.2014.02.01.00.17 versioncontrol.2014.02.14.00.17 versioncontrol.2014.02.16.08.17 versioncontrol.2014.02.16.21.17 versioncontrol.2014.02.17.10.17
trash.versioncontrol.2014.02.15.19.17 versioncontrol.2013.03.01.00.17 versioncontrol.2013.12.01.00.18 versioncontrol.2014.02.02.00.17 versioncontrol.2014.02.15.00.17 versioncontrol.2014.02.16.09.17 versioncontrol.2014.02.16.22.17 versioncontrol.2014.02.17.11.17
trash.versioncontrol.2014.02.15.20.17 versioncontrol.2013.04.01.00.17 versioncontrol.2013.12.01.01.18 versioncontrol.2014.02.04.00.17 versioncontrol.2014.02.15.21.17 versioncontrol.2014.02.16.10.17 versioncontrol.2014.02.16.23.17 versioncontrol.2014.02.17.12.17
</code></pre>
<p>And you can see that an example file has many hard-links (113 in this case):</p>
<blockquote>
<pre><code>ls -la versioncontrol.2014.02.17.20.17/cvs/Garage/tx.asm,v
-r--r--r-- 113 user users 31582 Jun 24 2008 versioncontrol.2014.02.17.20.17/cvs/Garage/tx.asm,v
</code></pre>
</blockquote>
<hr>
<p>Here's the perl code.... Any improvements, suggestions, criticisms are welcome.</p>
<pre><code>#!/usr/bin/perl -w
# ----------------------------------------------------------------------
# perl version of mikes handy rotating-filesystem-snapshot utility
# ----------------------------------------------------------------------
use strict;
# The following are all used in the 'END' code block... and need to have some value...
my $now = time();
my $id = "Not Yet Calculated";
my $snaplock = "";
my $proglock = "";
my $rmtmpdir = "";
my $exitcode = 1;
sub mysys(;@) {
my @cl;
push @cl, @_;
my $msg = '"' . join ('" "', @cl) . '"';
print "Running $msg\n";
system(@cl);
if ($? == -1) {
die "failed to execute: $!\n";
} elsif ($? & 127) {
die sprintf ("child died with signal %d, %s coredump\n", ($? & 127), ($? & 128) ? 'with' : 'without');
} elsif ($?) {
printf STDERR ("child exited with value %d: %s\n", $? >> 8, $msg);
return 0;
}
return 1;
}
my $snapdir = "/snapshotng";
my $lockfile = "$snapdir/.snap.lock";
my $keepyears = 10;
my $keepmonths = 18;
my $keepweeks = 16;
my $keepdays = 14;
my $keephours = 48;
my $configfile = shift @ARGV;
$configfile ||= "/etc/snapshot/snap.cfg";
-f $configfile or die "Unable to locate config file $configfile";
# Sort out locking... This creates/locks the file, clears it, writes out the process ID.
my $strt = time();
# try to lock the file for a full minute... then fail.
print "Attempting to obtain lock $lockfile\n";
mysys("lockfile", "-5", "-r12", "$lockfile");
$proglock = $lockfile;
print "Locked snapshot folder with $proglock in " . ( time() - $strt ) . " seconds\n";
$now = time();
$id = buildID($now);
print "SNAPSHOT PROCESS BEGINNING. Using ID $id \@ " . localtime() . "\n";
my (%sourcefolders, %excludes, @order);
open CONFIG, "< $configfile" or die "Could not open config file $configfile: $!";
while (<CONFIG>) {
chomp;
$_ =~ s/#.*$//; #trim comments
$_ =~ s/^\s+|\s+$//g; #trim line
$_ =~ s/\s+/ /g; #normalize whitespace
next unless m/\w/; #require at least some content
my @parts = split / /;
@parts >= 2 or die "Config lines need to be of the form 'name path [excludefile]'.";
$sourcefolders{$parts[0]} = $parts[1];
$excludes{$parts[0]} = "";
if (@parts == 3) {
$excludes{$parts[0]} = $parts[2];
}
push @order, $parts[0];
}
$exitcode = @order;
print "Processing $exitcode folders based on the configuration file\n\n";
foreach (@order) {
processSnapshot($_);
$exitcode--;
}
mysys ("rm", "-f", "$proglock");
$proglock = "";
END {
if ($proglock) {
print "\n\nWARNING - INTERRUPTED: Removing lock files and temporary files\n";
if ($rmtmpdir and -d $rmtmpdir) {
print "Removing Temporary folder $rmtmpdir (can take a long time). Please let this finish!\n";
system("rm -rf $rmtmpdir");
print "Done!\n";
}
if ($snaplock && -f $snaplock) {
print "Removing lock file $snaplock\n";
system("rm -f $snaplock");
}
print "Removing lock file $proglock\n";
system("rm -f $proglock");
}
# truncate(LOCK, 0) or die "Can't truncate lock file to indicate completion: $!";;
# close (LOCK) or die "Can't close lock file: $!";
my $secs = time() - $now;
printf ("SNAPSHOT PROCESS COMPLETE. Using ID %s \@ %s" . localtime() . " in %d minutes, %02d seconds\n", $id, scalar(localtime()), int($secs / 60.0), ($secs % 60));
if ($exitcode) {
print "Failed to process successfully... there is an exitcode of $exitcode\n";
exit $exitcode;
}
}
exit 0;
### END OF PROGRAM, The following are the implementing subroutines.
sub buildID {
my $now = shift;
$now ||= time();
my @date = localtime($now);
my $year = $date[5] + 1900;
my $month = $date[4] + 1;
my $day = $date[3];
my $hour = $date[2];
my $min = $date[1];
return sprintf ("%04d.%02d.%02d.%02d.%02d", $year, $month, $day, $hour, $min) ;
}
sub lastYears($) {
my $name = shift;
my $to = (localtime($now))[5] + 1900;
my $from = $to - $keepyears + 1;
my @ret;
for ($from .. $to) {
push @ret, sprintf('^%s\.%04d\..*$', $name, $_);
}
return @ret;
}
sub lastMonths($) {
my $name = shift;
my $yr = (localtime($now))[5] + 1900 - int($keepmonths / 12);
my $tom = (localtime($now))[4] + 1;
my $fom = $tom - ($keepmonths % 12) + 1;
if ($fom <= 0) {
$yr--;
$fom += 12;
}
my @ret;
for (1 .. $keepmonths) {
push @ret, sprintf('^%s\.%04d\.%02d\..*$', $name, $yr, $fom);
$fom++;
if ($fom > 12) {
$fom = 1;
$yr++;
}
}
return @ret;
}
sub lastWeeks($) {
my $name = shift;
my $tm = $now;
my $dy = 60 * 60 * 24;
my $week = $dy * 7;
# Hunt backwards for the previous sunday.
while ((localtime($tm))[6] > 0) {
$tm -= $dy;
}
$tm -= ($keepweeks - 1) * $week;
my @ret;
for (1 .. $keepweeks) {
my ($day, $mon, $yr) = (localtime($tm))[3..5];
push @ret, sprintf('^%s\.%04d\.%02d\.%02d\..*$', $name, $yr + 1900, $mon + 1, $day);
$tm += $week;
}
# print "Weeks:\n " . join("\n ", @ret) . "\n";
return @ret;
}
sub lastDays($) {
my $name = shift;
my $tm = $now;
my $dy = 60 * 60 * 24;
$tm -= ($keepdays - 1) * $dy;
my @ret;
for (1 .. $keepdays) {
my ($day, $mon, $yr) = (localtime($tm))[3..5];
push @ret, sprintf('^%s\.%04d\.%02d\.%02d\..*$', $name, $yr + 1900, $mon + 1, $day);
$tm += $dy;
}
return @ret;
}
sub lastHours($) {
my $name = shift;
my $tm = $now;
my $hr = 60 * 60;
$tm -= ($keephours - 1) * $hr;
my @ret;
for (1 .. $keephours) {
my ($hour, $day, $mon, $yr) = (localtime($tm))[2..5];
push @ret, sprintf('^%s\.%04d\.%02d\.%02d\.%02d\..*$', $name, $yr + 1900, $mon + 1, $day, $hour);
$tm += $hr;
}
return @ret;
}
sub cleanAndLatest($$) {
my $name = shift;
my $folder = shift;
opendir DIR, $folder or die "Unable to read folder $folder: $!";
my @files;
my $dir;
foreach $dir (readdir DIR) {
next unless -d "$folder/$dir";
next if $dir =~ m/^trash\..*/;
next if -l "$folder/$dir";
if ($dir =~ m/(yearly|monthly|weekly|daily|hourly|adhoc)\.\d+/) {
my $os = 0;
my $nname;
do {
my $cid = buildID((stat "$folder/$dir")[9] + $os);
$nname = "$name.$cid";
$os += 60;
} while (-x "$folder/$nname");
print "renaming $folder/$dir to $folder/$nname\n";
mysys("mv", "$folder/$dir", "$folder/$nname") or die "Unable to move file.";
$dir = $nname;
}
next unless $dir =~ m/$name\.\d\d\d\d\.\d\d\.\d\d\.\d\d.\d\d/;
push @files, $dir;
}
closedir DIR;
return undef unless @files;
# my @tokeep;
my @toremove;
my @rules;
# Add the year rules...
push @rules, lastYears $name;
push @rules, lastMonths $name;
push @rules, lastWeeks $name;
push @rules, lastDays $name;
push @rules, lastHours $name;
print "Rules:\n " .join ("\n ", @rules) . "\n";
@files = sort @files;
my $latest;
foreach $dir (@files) {
my $found = 0;
my $rn = 0;
while ($rn < @rules) {
if ($dir =~ m/$rules[$rn]/) {
$found = 1;
$latest = $dir;
print "Matched $dir to rule " . $rules[$rn] . "\n";
splice @rules, $rn, 1;
last;
} else {
$rn++;
}
}
# push @tokeep, $dir if $found;
push @toremove, $dir unless $found;
}
print "Latest is $latest\n";
# exit 1;
foreach (@toremove) {
mysys("mv", "$folder/$_", "$folder/trash.$_") or die "Unable to rename file to trash";
}
return $latest;
}
sub processSnapshot {
my $name = shift;
my $folder = $sourcefolders{$name};
my $exclude = $excludes{$name};
my $outdir = "$snapdir/$name";
if ($exclude) {
# Make the exclude relative to the output dir unless it is already absolute.
$exclude = "$outdir/$exclude" unless $exclude =~ m/^\/.*/;
} else {
$exclude = "";
}
if ($exclude and ! -r $exclude) {
# print "Exclude file $exclude does not exist! Ignoring it!\n";
$exclude = "";
}
print "\n\nSnapshot $name: $folder \@ " . localtime() ."\n";
-d $outdir or mysys("mkdir", "-p", "$outdir") or die "Unable to make folder $outdir";
my $mysnaplock = "$outdir/.snapshot.lock";
$strt = time();
mysys("lockfile", "-5", "-r-1", "$mysnaplock");
$snaplock = $mysnaplock;
print "Locked snapshot folder with $snaplock in " . ( time() - $strt ) . " seconds\n";
my $tmpdir = "$outdir/tmpsnap";
-d $tmpdir and die "There already is a folder $tmpdir. Perhaps a previous snapshot was aborted. Please clean this up before we can continue.\n";
my $latest = cleanAndLatest($name, $outdir);
$rmtmpdir = $tmpdir;
if ($latest) {
print "Using previous snapshot $outdir/$latest as the baseline.\n";
mysys("cp", "-alH", "$outdir/$latest", "$tmpdir") or die "Failed to create linked copy of latest snapshot $latest!";
} else {
print "No previous snapshot baseline.\n";
mysys("mkdir", "-p", "$tmpdir");
}
my @args;
push @args, "-v", "-a", "--delete";
if ($exclude){
print "**** Using Exclude file $exclude ****\n";
push @args, "--exclude-from=$exclude", "--delete-excluded";
}
mysys("rsync", @args, "$folder/", "$tmpdir/") or die "Unable to complete rSync!";
mysys("mv", "$tmpdir", "$outdir/$name.$id") or die "Unable to rename rSync!";
$rmtmpdir = "";
mysys("rm", "-f", "$snaplock");
$snaplock="";
print "Completed snapshot for $folder in to $outdir/$name.$id \@ " . localtime() . "\n\n\n";
}
</code></pre>
|
[] |
[
{
"body": "<p>Well, this is actually pretty decent code. There still is a lot of stuff that could be improved, I tried to focus on some more relevant ones.</p>\n\n<h2>Subroutine Prototypes</h2>\n\n<p>In a declaration like <code>sub foo ($@&*) { ... }</code>, we call the weird thing in parens a <em><a href=\"http://perldoc.perl.org/perlsub.html#Prototypes\">prototype</a></em>. The prototype primarily changes how a call to that sub is <em>parsed</em>, and can set properties like <em>context</em> for the arguments. Contrary to popular belief, prototypes are not required in order to call a subroutine without parens – predeclaration (e.g. via <code>sub foo;</code>) is sufficient.</p>\n\n<p>Prototypes do not generally verify the type of the arguments. Instead, <code>$</code> or <code>@</code> or <code>%</code> impose a certain context on that argument – <code>my @foo = (1, 2, 3); bar @foo</code> will pass <code>1, 2, 3</code> as arguments to <code>bar</code> if it has no prototype or some list prototype, or it will evaluate the expression <code>@foo</code> is scalar context with a <code>$</code> prototype, thus passing <code>3</code> – the length of the array.</p>\n\n<p>Prototypes are useless, as they can be disabled by invoking a function via the <code>&</code> sigil: <code>&foo(...)</code>. Prototypes are a hindrance, because it's often not obvious that they change the context of an expression. Prototypes should not be used, unless you're trying to write something like <code>push</code> or <code>map</code>, which actually need them.</p>\n\n<p>Your <code>mysys</code> has the <code>(;@)</code> prototype, which is especially funny. <code>;</code> starts optional arguments, and <code>@</code> allows a list of arbitrary length (including zero arguments). So it's equivalent to <code>(@)</code> which is equivalent to no prototype at all.</p>\n\n<p>Your <code>lastX</code> and <code>cleanAndLatest</code> subs use prototypes in a misguided attempt to limit the number of arguments. Instead, check the size of <code>@_</code> if you have to do this, e.g. <code>die \"The sub lastHour takes exactly one argument\" if @_ != 1</code>.</p>\n\n<h2><code>say</code> > <code>print</code></h2>\n\n<p>The <code>[say</code>]<a href=\"http://perldoc.perl.org/functions/say.html\">say</a> builtin function is available since perl 5.10.0 (released 2007). It behaves <em>exactly</em> like <code>print</code>, except that it will append <code>\"\\n\"</code> to the output instead of <code>$\\</code>. This makes it insanely handy for text output. You can activate this function with</p>\n\n<pre><code>use feature 'say';\n</code></pre>\n\n<h2>Shell commands vs. builtins</h2>\n\n<p>Perl's history as an Unix sysadmin language means that it has many builtin functions. Using these has the advantage that you can do better error handling, don't waste resources by starting an external process, and have a truly portable interface. The downside is that they are sometimes not quite as flexible, and might need a bit of boilerplate.</p>\n\n<p>Instead of <code>lockfile</code>, use the <a href=\"http://perldoc.perl.org/functions/flock.html\"><code>flock</code></a> builtin. E.g:</p>\n\n<pre><code>use POSIX qw/:flock/; # import constants\n\nopen my $lock_fh, \">\", $lockfile or die \"Can't open $lockfile: $!\";\nflock $lock_fh, LOCK_EX or die \"Can't obtain lock on $lockfile\";\n\n...\n\nflock $lock_fh, LOCK_UN or die \"Can't unlock $lockfile\";\nclose $lock_fh;\nunlink $lockfile or die \"Can't remove lockfile $lockfile\";\n</code></pre>\n\n<p>Oh, all those horrible <code>or die</code>s. Since perl 5.10.1 (released 2009), the <a href=\"https://metacpan.org/pod/autodie\"><code>autodie</code></a> module is available which replaces most built-in functions by versions that <code>die</code> on failure rather than relying on you to handle their return code. I highly recommend you use it.</p>\n\n<p>Back to <code>flock</code>: It places an advisory lock on the file, and is blocking by default – there is no way to wait for <em>x</em> seconds, then fail (unless you whish to set an <a href=\"http://perldoc.perl.org/functions/alarm.html\"><code>alarm</code></a>). You can however use the nonblocking version <code>flock $fh, LOCK_EX | LOCK_UN</code> which returns immediately, possibly failing.</p>\n\n<p>Instead of <code>rm</code>, you can use the <a href=\"http://perldoc.perl.org/functions/unlink.html\"><code>unlink</code></a> builtin.</p>\n\n<p>Instead of <code>mv</code>, you can sometimes use <code>rename</code>. However, there are annoying portability issues and it won't work across file system boundaries (which is the case here). The <a href=\"https://metacpan.org/pod/File%3a%3aCopy\"><code>File::Copy</code></a> module (in Core since perl 5.002 (released 1996)) comes to the rescue, and offers the <code>move</code> and <code>copy</code> functions:</p>\n\n<pre><code>use File::Copy;\n\n# move will either rename, or copy, then unlink\nmove $source => $destination or die \"Couldn't move $source to $destination: $!\";\ncopy $source => $destination or die \"Couldn't copy $source to $destination: $!\";\n</code></pre>\n\n<p>While the shell commands are certainly more handy, you should evaluate whether the alternative may be safer.</p>\n\n<h2>Assorted Spotlights</h2>\n\n<ul>\n<li><p>This snippet here is hilarious:</p>\n\n<pre><code>my @cl;\npush @cl, @_;\nmy $msg = '\"' . join ('\" \"', @cl) . '\"';\nprint \"Running $msg\\n\";\n</code></pre>\n\n<p>I would write it as:</p>\n\n<pre><code>my ($program, @arguments) = @_;\nsay \"Running \", join ' ' => $program, map qq(\"$_\"), @arguments;\n</code></pre>\n\n<p>While equally obfuscated, the argument unpacking clearly shows what the parameters mean – <code>@cl</code> isn't the best variable name ever. Using <code>map qq(\"$_\")</code> clearly shows the intent that you want to put quotes around each item, <code>join ' '</code> shows that you want a space in between. Your solution is equivalent, but harder to grok if you aren't aware of that specific pattern.</p>\n\n<p>The part where your solution is better than mine is using a variable for the combined command.</p></li>\n<li><p>In order to avoid accidentally global variables, I tend to put the main part of a script into a <code>main</code> subroutine, then invoke it as <code>exit main(@ARGV)</code> at the top, directly after initializing those variables that are actually intended to be global.</p></li>\n<li><p><code>open CONFIG, \"< $configfile\" or die ...</code> – no.</p>\n\n<ol>\n<li><p>We, writing <em>modern</em> Perl, only use lexical variables for filehandles. The bareword <code>CONFIG</code> is effectively a package variable, which has all kinds of unintended side effects. </p></li>\n<li><p>In order to process even the most exotic filenames, you should use the three-argument form of <code>open</code>. I.e. the second argument only contains the mode, not the filename.</p></li>\n</ol>\n\n<p>Together:</p>\n\n<pre><code>open my $config, \"<\", $configfile or die ...\n</code></pre></li>\n<li><p>Overly eager stringification like <code>\"$proglock\"</code> is useless in most cases. A value will be made to a string if needed, we don't have to manually facilitate this. Such an expression only makes yet another copy, which is generally useless. (Yes, it also protects you against an evil programmer using out-arguments in his subroutines. However, it's the norm that parameters are not modified, so this wouldn't be much of a threat).</p></li>\n<li><p>Two-space indentation? Really? 4-space is the bestest!!1 But I think we can agree that tabs are worse ;-)</p></li>\n<li><p>The <code>localtime</code> function has a horrible design and requires you to remember indices of all the fields. However, there's the <a href=\"https://metacpan.org/pod/Time%3a%3alocaltime\"><code>Time::localtime</code></a> module (in Core since perl 5.004 (released 1997)) which fixes this:</p>\n\n<pre><code>(localtime($now))[5]\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>localtime($now)->year\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T02:33:12.087",
"Id": "72891",
"Score": "0",
"body": "Couple of FYI notes. The `cp` has to be `cp` and not `File::Copy` in order to get the right hard-links for the files. I don't believe File::Copy will cut it. I tried Perl flock, and never got it working to my satisfaction. Thanks for a great answer. Worth the bounty (when it lets me)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T00:08:24.220",
"Id": "42357",
"ParentId": "41928",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "42357",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T02:00:18.627",
"Id": "41928",
"Score": "21",
"Tags": [
"perl",
"linux",
"file-system"
],
"Title": "Regular backup/snapshots"
}
|
41928
|
<p>How can I improve this code (elegance, best practices, etc)?</p>
<pre><code>""" Simple in-memory database as a response to the Thumbtack coding challenge. """
class SimpleDb(object):
""" Simple in-memory database as a response to the Thumbtack coding challenge. """
def __init__(self):
""" Initialize SimpleDb instance. """
self.__db = {}
self.__num_equal_to_cache = {}
self.__transactions = [] # Stores previous values to allow rollback
def assign(self, name, value):
""" Sets value of name to value. Inserts name into database if it doesn't already exist. """
current_value = self.get(name)
if current_value == value:
return
self.__update_num_equal_to(current_value, value)
self.__update_current_transaction(name, current_value)
self.__db[name] = value
def get(self, name):
""" Returns value of name if it exists in the database, otherwise returns None. """
return self.__db[name] if name in self.__db else None
def get_num_equal_to(self, value):
""" Returns number of entries in the database that have the specified value. """
return self.__num_equal_to_cache[value] if value in self.__num_equal_to_cache else 0
def unset(self, name):
""" Removes name from database if it's present. """
current_value = self.__db.pop(name, None)
if current_value is None:
return
self.__update_num_equal_to(current_value)
self.__update_current_transaction(name, current_value)
def begin(self):
""" Opens transaction block. """
self.__transactions += [{}]
def rollback(self):
"""
Reverts database to its state before most current transaction.
Returns True on success, returns False if there aren't any open transactions.
"""
if not self.__transactions:
return False
for name, value in self.__transactions.pop().iteritems():
current_value = self.get(name)
if current_value == value:
continue
self.__update_num_equal_to(current_value, value)
if value is None:
del self.__db[name]
else:
self.__db[name] = value
return True
def commit(self):
"""
Commits all transactions to database. Returns True on success,
returns False if there aren't any open transactions.
"""
if not self.__transactions:
return False
self.__transactions = []
return True
def __update_num_equal_to(self, current_value, new_value=None):
"""
Decrements by one the number items present with current_value (if current_value
is not equal to None) and increments by one the number present with new_value
(if new_value is not equal to None).
"""
for amount_to_add, value in [(-1, current_value), (1, new_value)]:
if value is not None:
self.__num_equal_to_cache.setdefault(value, 0)
self.__num_equal_to_cache[value] += amount_to_add
def __update_current_transaction(self, name, value):
"""
Stores current value of name if not already stored to most recent transaction
(if any transactions open) to enable restoration of previous state on rollback.
"""
if self.__transactions and name not in self.__transactions[-1]:
self.__transactions[-1][name] = value
def display(value, default=None):
"""
Prints value to stdout. If value is None and a default value is
specified (and not None), then the default value is printed instead. Otherwise
the None value is printed.
"""
if value is None and default is not None:
value = default
print value
OPS = {
'GET': (2, lambda db, name: display(db.get(name), "NULL")),
'NUMEQUALTO': (2, lambda db, value: display(db.get_num_equal_to(value))),
'UNSET': (2, lambda db, name: db.unset(name)),
'BEGIN': (1, lambda db: db.begin()),
'ROLLBACK': (1, lambda db: db.rollback() or display("NO TRANSACTION")),
'COMMIT': (1, lambda db: db.commit() or display("NO TRANSACTION")),
'END': (1, lambda db: False),
'SET': (3, lambda db, name, value: db.assign(name, value)),
}
def process_command(simpleDb, command):
"""
Parses string commands and applies them to the database.
Returning False indicates that no more commands should be passed in.
"""
command = command.split()
opcode = command.pop(0).upper() if len(command) > 0 else None
if opcode is None or opcode not in OPS or len(command) != (OPS[opcode][0] - 1):
print "INVALID COMMAND"
elif 'END' == opcode:
return False
else:
OPS[opcode][1](simpleDb, *command)
return True
def run():
""" Reads database command from the command line and passes it through for processing. """
# BEGIN \n SET a 30 \n BEGIN \n SET a 40 \n COMMIT \n GET a \n ROLLBACK \n END
simpleDb = SimpleDb()
while process_command(simpleDb, raw_input()):
pass
run()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T02:30:20.917",
"Id": "72220",
"Score": "3",
"body": "Do you want to add http://www.thumbtack.com/challenges/software-engineer#simple-db to the question as a definition of the program's specification?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T12:03:01.063",
"Id": "72265",
"Score": "1",
"body": "If you want to edit the code, put your edited code after (not replacing) the existing code; otherwise that invalidates existing answers: see [Can I edit my own question to include suggested changes from answers?](http://meta.codereview.stackexchange.com/questions/1482/can-i-edit-my-own-question-to-include-suggested-changes-from-answers) for further details."
}
] |
[
{
"body": "<p>I find your treatment of transactions odd. I would expect that when a transaction is in progress, data modifications commands get buffered; queries would consult the state stored in the current transaction for any relevant data, then any stacked transactions, then finally consulting the \"real\" database. Instead, you immediately \"auto-commit\" each command, and add an entry to the undo list; a commit simply discards the undo list. That's not a realistic model of a database: one would expect that a commit either succeeds atomically or has no effect at all on the database.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T06:49:32.210",
"Id": "72237",
"Score": "0",
"body": "I was thinking just that. I've re-written the code such that no changes are made until the user sends the commit command."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T06:55:28.307",
"Id": "72239",
"Score": "1",
"body": "You might want to post the revised code as a second question, referencing this one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-08T07:06:45.950",
"Id": "175674",
"Score": "0",
"body": "some databases do indeed work like this -- optimistically committing, and writing a transaction log at the same time. it makes rollback more expensive, but commit much cheaper as you don't need to re-read the destination data to check that it's changed while the the transaction was running, before finally committing (and writing the rows). (eg: microsoft sql server works this way, as does oracle)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-08T07:53:12.103",
"Id": "175682",
"Score": "0",
"body": "@AndrewHill No matter how the transaction is implemented, it should still be atomic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-08T23:47:46.913",
"Id": "175878",
"Score": "0",
"body": "yes, row/page locks in sql server and temp storage of old versions for rollback purposes in oracle both prevent partially complete transactions from becoming visible; these dbms's are atomic, they just rely on more sophisticated ; how should the database behave when when 2 transactions try to modify the same row / or read a row written but not commited?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T03:20:52.133",
"Id": "41934",
"ParentId": "41930",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T02:08:46.853",
"Id": "41930",
"Score": "3",
"Tags": [
"python",
"database",
"python-2.x"
],
"Title": "Simple in-memory database"
}
|
41930
|
<p>I have lots of external shell commands to run.</p>
<p>So I gave every command a name and then run it.</p>
<pre><code>tar_report_cmd = 'zip -r {0} {1} '%(report_file, _export_dir)
exec_proc(tar_report_cmd)
mv_report_cmd = "mv {0} {1}".format(report_file,report_dir)
exec_proc(mv_report_cmd)
</code></pre>
<p>But it looks sort of redundant and not beautiful.</p>
<p>Is there any better practice to replace my way?</p>
<pre><code>def exec_proc(cmd_str):
results = os.popen(cmd_str).read()
return results
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T13:20:47.550",
"Id": "72272",
"Score": "0",
"body": "For the examples given, I would suggest using the library support for zip files and moving files. It's more cross-platform and gives you better precision and error recovery options. Tend towards calling other commands only when library versions are unavailable and do exactly what you need."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T13:21:39.240",
"Id": "72273",
"Score": "5",
"body": "This question appears to be off-topic because it is primarily about how to write code, rather than really reviewing code that has been written."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:38:06.563",
"Id": "72408",
"Score": "0",
"body": "@MichaelUrman The code may be written at a novice level, but it's still reviewable code. We're all here to learn how to write better code, and this question is no different."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:38:59.643",
"Id": "72409",
"Score": "2",
"body": "@MichaelUrman Also, your comment that this should be done using a Python library rather than an external command [should be posted as an answer](http://meta.codereview.stackexchange.com/a/1479/9357), since it is a suggestion that would result in an improvement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T02:50:39.967",
"Id": "72439",
"Score": "1",
"body": "@200_success I agree that if it were an on-topic question, my comment should be posted as an answer. But I see this as asking if it's a good approach, rather than asking for a code review. Note that the code given doesn't even work (what's `report_file`, `_export_dir`, ...?)."
}
] |
[
{
"body": "<p><strong>No, it is a security risk</strong>, and furthermore, <code>os.popen()</code> has been <a href=\"http://docs.python.org/2/library/os.html#file-object-creation\">deprecated</a> since Python 2.6. The replacement is to use the <a href=\"http://docs.python.org/2/library/subprocess.html#replacing-os-popen-os-popen2-os-popen3\"><code>subprocess</code> module</a>.</p>\n\n<p>The security risk is that <code>os.popen()</code> expects its command as a string. That means that the command will be interpreted by a shell to split it up into the command and its arguments. If <code>report_file</code>, <code>report_dir</code>, or <code>_export_dir</code> contain any spaces or characters with a special meaning to the shell, horrible unexpected things can happen, including <strong>arbitrary command execution</strong>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T06:03:18.767",
"Id": "41937",
"ParentId": "41936",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T05:40:35.610",
"Id": "41936",
"Score": "3",
"Tags": [
"python",
"python-2.x"
],
"Title": "Is it a good style to run external commands in Python?"
}
|
41936
|
<pre><code>public static void streamReport(this Report report, Stream stream)
{
using (var streamWriter = new StreamWriter(stream))
{
//some logic that calls streamWrite.Write()
streamWriter.Flush();
}
//Should "return stream;" here ?
}
</code></pre>
<p>I am writing an extension method to an object in which I would like to transform to a CSV which is generated and returned to a client (web).</p>
<p>My questions are:</p>
<ol>
<li>Should I return <code>stream</code> (change <code>void</code> to <code>Stream</code>) ?</li>
<li>Should I use the <code>out</code> keyword in before the <code>Stream</code> parameter ? Is this a common way to let the caller know the parameter will be changed ?</li>
<li>Should I change the method to generate a new stream (and not accept one) and trust the user to <code>Dispose</code> it ?</li>
<li>Should I pass <code>StreamWriter</code> instead of <code>Stream</code> ?</li>
</ol>
|
[] |
[
{
"body": "<ol>\n<li>Do you <em>need</em> the <code>Stream</code> reference in outer scope? I doubt it. After all, you already pass this same reference as parameter, so you should <em>already have</em> it. Also pay attention to <code>StreamWriter</code>. When you dispose it in <code>using</code> block - you dispose the underlying stream as well. Accessing it later on will lead to exceptions.</li>\n<li>No, you should not, if all you do is writing to the given stream. <code>out</code> implies, that you will assign a new value to passed reference parameter (meaning you will call <code>stream = new FileStream()</code> at some point or something). Which is not the case apparently.</li>\n<li>It depends on use cases. I guess the best approach is to create multiple methods to cover them all. For example you can create another method, which would accept <code>string</code> (file path) instead of a <code>Stream</code>. And another, which would accept a <code>StreamWriter</code>.</li>\n</ol>\n\n<p>Also, you should use verbs as method names. <code>Write(...)</code> or <code>WriteCsv(...)</code> for example. Not <code>streamReport</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T08:19:47.753",
"Id": "72243",
"Score": "0",
"body": "Thanks, I added a question.. due to the point you mention in 1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T08:00:51.563",
"Id": "41940",
"ParentId": "41939",
"Score": "4"
}
},
{
"body": "<p>Your questions imply that you might not be quite aware of how streams or references work in C#. </p>\n\n<ul>\n<li>You pass in a reference to a <code>Stream</code></li>\n<li>You create a <code>StreamWriter</code> which writes to that <code>Stream</code></li>\n<li>This will automatically make changes visible to anyone holding a reference to the same <code>Stream</code>.</li>\n</ul>\n\n<p>Therefor there is no need to try and return the <code>Stream</code> in any way from the method to make the changes visible to the caller - you just need to write to it. This is at least how I interpret your questions.</p>\n\n<p>However there is a catch in your implementation: disposing the <code>StreamWriter</code> will automatically close the underlying <code>Stream</code> which I find hugely annoying at times. <a href=\"http://msdn.microsoft.com/en-us/library/gg712853%28v=vs.110%29.aspx\">Only since .NET 4.5 there is a constructor for <code>StreamWriter</code> which allows you to leave the <code>Stream</code> open</a>. So right now your extension method will close the <code>Stream</code> which I guess is not the intention. Your only option to avoid that is to use .NET 4.5 or do not wrap the <code>StreamWriter</code> in a <code>using</code> statement.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T08:26:31.293",
"Id": "72244",
"Score": "0",
"body": "Nice comment, I am using `4.5.1`, will switch for this constructor."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T08:23:14.460",
"Id": "41942",
"ParentId": "41939",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "41942",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T07:32:27.283",
"Id": "41939",
"Score": "6",
"Tags": [
"c#",
"asp.net",
"stream"
],
"Title": "Extension method that writes to a stream"
}
|
41939
|
<p>Can someone review my code which I put on exercism.io for the word-count exercise (found <a href="https://github.com/exercism/exercism.io/blob/master/assignments/python/word-count/word_count_test.py">here</a>)?</p>
<pre><code>class Phrase:
def __init__(self, phrase):
self.phrase = phrase.strip().lower().split()
def word_count(self):
word_dict = {}
for word in self.phrase:
word_input = ''.join(e for e in word if e.isalnum()).strip()
if word_input:
word_dict[word_input] = word_dict.get(word_input, 0) + 1
return word_dict
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T09:57:38.187",
"Id": "72247",
"Score": "0",
"body": "I understand this is a Python exercise, but note that in real text word counting is not that easy. 'fish/meat' should be two words but 'A/C' only one. 'Los Angeles' should possibly be one word, while 'The Angels' are two words. It gets worse when you want to split sentences. nltk is a Python library that can help you with this if you're interested in natural language processing."
}
] |
[
{
"body": "<p>My first advice is <a href=\"http://www.youtube.com/watch?v=o9pEzgHorH0\" rel=\"nofollow noreferrer\">stop writing classes</a> if you don't need to : your class has only two methods an <code>init</code> and a proper method. This could probably be written as a simple function.</p>\n\n<pre><code>def word_count(phrase):\n word_dict = {}\n for word in phrase.strip().lower().split():\n word_input = ''.join(e for e in word if e.isalnum()).strip()\n if word_input:\n word_dict[word_input] = word_dict.get(word_input, 0) + 1\n return word_dict\n</code></pre>\n\n<p>Also, a lot of string processing you are doing is not useful, complicated and/or potentially wrong :</p>\n\n<ul>\n<li>On <code>phrase</code>, as noticed by Gareth Rees, there's not point calling <code>strip()</code> since you call <code>split()</code>.</li>\n</ul>\n\n<p>As I wasn't aware that the result would be the same, here a proof of concept :</p>\n\n<pre><code>a=' this is a little test'\na.split() == a.strip().split()\n-> True\n</code></pre>\n\n<p>and here's a link to the documentation for <a href=\"http://docs.python.org/2/library/stdtypes.html#str.strip\" rel=\"nofollow noreferrer\">strip</a> and <a href=\"http://docs.python.org/2/library/stdtypes.html#str.split\" rel=\"nofollow noreferrer\">split</a>.</p>\n\n<ul>\n<li>On individual words : the way you get <code>word_input</code> from <code>word</code> looks a bit convoluted to me. Among other things, there's no point in calling <code>strip()</code> on a string that only contains alphanumerical characters. Also, just removing \"special\" characters does not sound like the best option : <code>it's</code> and <code>its</code> will be considered the same way, its annoying :-). Maybe some characters like <code>'</code> should be taken into account during the splitting. Maybe, depending on the language you are to handle, other characters like <code>-</code> should be kept (for instance in French, \"basketball\" is \"basket-ball\" but neither \"basket\" nor \"ball\" are French words so splitting would be quite awkward and so would be removing the dash).</li>\n</ul>\n\n<p>Except for that, your code looks go to me!</p>\n\n<p>However, if you wanted to make things even more pythonic, you could use <a href=\"http://docs.python.org/library/collections.html#defaultdict-objects\" rel=\"nofollow noreferrer\">defaultdict</a>. <a href=\"https://stackoverflow.com/questions/893417/item-frequency-count-in-python\">This example</a> will probably look familar to you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T11:06:43.307",
"Id": "72253",
"Score": "2",
"body": "There's no point calling `.strip()` at all, since you call `.split()` just afterwards."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T08:50:05.740",
"Id": "41943",
"ParentId": "41941",
"Score": "5"
}
},
{
"body": "<p>Some notes:</p>\n<ul>\n<li>As already pointed out, an object-oriented approach seems overkill, a simple function will do.</li>\n<li><code>self.phrase</code>. That's very confusing, <code>phrase</code> is a string but <code>self.phrase</code> is a list of strings. A better name would be <code>words</code>.</li>\n</ul>\n<p>I'd write it with a functional approach using <code>collections.Counter</code>:</p>\n<pre><code>from collections import Counter\n\ndef word_count(phrase):\n words = phrase.lower().split()\n return Counter("".join(c for c in word if c.isalnum()) for word in words)\n</code></pre>\n<p>Or even simpler:</p>\n<pre><code>from collections import Counter\nimport re\n\ndef word_count(phrase):\n return Counter(re.sub(r"[^\\w ]+", '', phrase.lower()).split())\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-29T19:25:40.847",
"Id": "261966",
"Score": "0",
"body": "This doesn't work on none ASCII characters such as: `досвидания!`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-02-18T13:35:47.670",
"Id": "41960",
"ParentId": "41941",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T08:12:01.600",
"Id": "41941",
"Score": "6",
"Tags": [
"python",
"exercism"
],
"Title": "Exercism assignment word-count in Python"
}
|
41941
|
<p>I have used <code>INotifyPropertyChanged</code> for both Model and ViewModel. Is it correct?
First of all I was trying to use <code>INotifyPropertyChanged</code> only with Model, but for that I had to use observable collections in UI class.</p>
<p>Please comment on my design.</p>
<p><strong>MainPage.xaml</strong></p>
<pre><code><phone:PhoneApplicationPage
x:Class="LocLog.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="100"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
<TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ScrollViewer>
<TextBlock Text="{Binding Path=logText}"></TextBlock>
</ScrollViewer>
</Grid>
<Button Name="btn" Height="70" Width="130" Grid.Row="2" Click="btn_Click">Refresh</Button>
</Grid>
</phone:PhoneApplicationPage>
</code></pre>
<p><strong>Model</strong></p>
<pre><code>using System.ComponentModel;
using System.Windows;
namespace LocLog
{
class Model : INotifyPropertyChanged
{
private string dispalyText="";
public string DispalyText
{
get
{
return dispalyText;
}
set
{
dispalyText = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("DispalyText"));
}
}
public Model()
{
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
</code></pre>
<p><strong>ViewModel</strong></p>
<pre><code>using Microsoft.Phone.Reactive;
using StorageMech;
using System.ComponentModel;
using System.Windows;
namespace LocLog
{
public class ViewModel:INotifyPropertyChanged
{
private Model model;
Store storage;
private string LogText;
public string logText
{
get
{
return LogText;
}
set
{
LogText = value;
if(PropertyChanged != null)
PropertyChanged(this,new PropertyChangedEventArgs("logText"));
}
}
//Get log files from storage to dispaly on UI
public void RefreshLog()
{
model.DispalyText = storage.ReadFromFile();
}
public ViewModel()
{
storage = new Store();
model = new Model();
model.PropertyChanged += model_PropertyChanged;
}
void model_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
this.logText = model.DispalyText;
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
</code></pre>
<p>Storage Class</p>
<pre><code>using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using System.Threading;
using System.Windows;
namespace StorageMech
{
public class Store
{
Mutex m = new Mutex(false, "LOCLOGIC");
string strFileName = "locLogFile";
IsolatedStorageFile file;
IsolatedStorageFileStream fileStream;
public Store()
{
file = IsolatedStorageFile.GetUserStoreForApplication();
}
public void SaveToLog(string str)
{
try
{
m.WaitOne();
if (file != null)
{
//open file in append mode
fileStream = new IsolatedStorageFileStream(strFileName, System.IO.FileMode.Append, file);
}
using (var streamWriter = new StreamWriter(fileStream))
{
streamWriter.WriteLine(str);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
finally
{
if (fileStream != null)
fileStream.Close();
m.ReleaseMutex();
}
}
public string ReadFromFile()
{
try
{
m.WaitOne();
string line="";
if (file != null)
{
fileStream = new IsolatedStorageFileStream(strFileName, System.IO.FileMode.Open, file);
}
using (var streamReader = new StreamReader(fileStream))
{
string temp;
//read line by line and finally return
while ((temp = streamReader.ReadLine()) != null)
{
line = line + temp+"\n";
}
}
return line;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return "";
}
finally
{
if(fileStream != null)
fileStream.Close();
m.ReleaseMutex();
}
}
}
</code></pre>
<p>}</p>
|
[] |
[
{
"body": "<p>Only your viewmodel should implement <code>InotifyPropertyChanged</code>. That's kind of the whole point of mvvm. Normally, your viewmodel properties wrap your model properties. Also, it is your model, that should contain all the business logic. Viewmodel should know nothing about <code>Storage</code> or any other details of implementation. Viewmodel should only manage interactions with UI. Being said, you should have something like:</p>\n\n<pre><code> class Model\n {\n private Storage storage = new Storage();\n public string DispalyText { get; set; }\n\n public void RefreshLog()\n {\n DispalyText = storage.ReadFromFile();\n }\n }\n\n public class ViewModel : INotifyPropertyChanged\n {\n private Model model;\n\n //you should use capital first letter for properties\n public string LogText \n { \n get \n {\n return model.DispalyText;\n }\n set\n {\n model.DispalyText = value;\n if(PropertyChanged != null)\n PropertyChanged(this,new PropertyChangedEventArgs(\"LogText\"));\n }\n }\n\n public void RefreshLog()\n {\n model.RefreshLog();\n //this call should be refactored to separate method\n if(PropertyChanged != null)\n PropertyChanged(this,new PropertyChangedEventArgs(\"LogText\")); \n }\n\n public ViewModel()\n {\n model = new Model();\n }\n\n public event PropertyChangedEventHandler PropertyChanged;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T10:47:29.127",
"Id": "72250",
"Score": "0",
"body": "Great answer, just one more thing, what exactly should I write in MainPage.xaml.cs to get VM's changes back?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T10:53:29.207",
"Id": "72251",
"Score": "0",
"body": "@pranitkothari, nothing. As long as you use data binding to a property in xaml, the changes will be automatically propagated to UI whenever you raise a `PropertyChanged` event for that property."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T10:40:27.267",
"Id": "41948",
"ParentId": "41945",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41948",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T10:02:48.547",
"Id": "41945",
"Score": "2",
"Tags": [
"c#",
".net",
"mvvm",
"event-handling",
"xaml"
],
"Title": "MVVM implementation using C# and XAML"
}
|
41945
|
<p>I have written a script that sits on the admin portion on my website. </p>
<p>Here I assume the user is valid as I have code that checks that already.</p>
<p>The below code is checks if the user is Admin. If they are Admin they will be flagged with a "Y" on the database (this will be a "1" for optimization later but for sanity's sake with testing Y was easier).</p>
<p><strong>App Code:</strong></p>
<pre><code>Public Function IsUserAdmin(ByVal iUserID As Long) As Boolean
Dim sConnString As String = System.Web.Configuration.WebConfigurationManager.ConnectionStrings("mySQL").ConnectionString
Dim dsNames As SqlDataSource
Dim bReturn As Boolean = False
dsNames = New SqlDataSource
dsNames.ConnectionString = sConnString
Dim sSQL As String
sSQL = "SELECT IsAdmin FROM [SystemUsers] WHERE ID=@UserID"
dsNames.SelectCommand = sSQL
dsNames.SelectParameters.Clear()
dsNames.SelectParameters.Add("UserID", iUserID)
For Each datarow As Data.DataRowView In dsNames.Select(DataSourceSelectArguments.Empty) ‘ do I need a loop?
If datarow("IsAdmin").ToString().ToUpper = "Y" Then
bReturn = True
End If
Next
Return bReturn
dsNames.dispose
End Function
</code></pre>
<p><strong>.Net Code</strong></p>
<pre><code>‘Assuming basic login was okay we have a UserObject/UserID
Dim vAdmin as string
vAdmin = IsUserAdmin(Session("UserObject"))
If vAdmin = True Then
'Valid User
Else
Response.Redirect("../Default.aspx")
End If
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T11:25:24.517",
"Id": "72255",
"Score": "0",
"body": "If you want to edit the code, put your edited code after (not replacing) the existing code; otherwise that invalidates existing answers: see [Can I edit my own question to include suggested changes from answers?](http://meta.codereview.stackexchange.com/a/1483/34757) for further details."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T11:26:58.883",
"Id": "72256",
"Score": "1",
"body": "Also it's not `sSQL` that should be disposed (strings don't have a Dispose method): it's `dsNames`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T11:29:11.180",
"Id": "72257",
"Score": "0",
"body": "@ChrisW That's me having a blonde moment! Thanks"
}
] |
[
{
"body": "<p>I see you're not using the <a href=\"http://msdn.microsoft.com/en-us/library/5k850zwb.ASPX\" rel=\"nofollow\">role manager</a> built into .NET (together with a built-in membership provider). If you were, then this could be codeless and configured in the <code>Web.config</code>.</p>\n\n<p>For example, the <code>Web.config</code> of my <code>Logs</code> directory (which contains log files) look like this:</p>\n\n\n\n<pre class=\"lang-xml prettyprint-override\"><code><?xml version=\"1.0\"?>\n<configuration>\n <system.web>\n <authorization>\n <allow roles=\"Supervisor\"/>\n <deny users=\"*\"/>\n </authorization>\n </system.web>\n <system.webServer>\n <directoryBrowse enabled=\"true\"/>\n </system.webServer>\n</configuration>\n</code></pre>\n\n<p>Second, ideally you should call the <code>Dispose</code> method of your <code>SqlDataSource</code> when you finish using it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T11:30:32.610",
"Id": "72258",
"Score": "0",
"body": "I'll have to have a good read up! Will this also work for hiding sections on a webpage. There are places we want to only show certain data to a user."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T11:44:14.883",
"Id": "72260",
"Score": "1",
"body": "For hiding data within a web page I would use the `System.Web.Security.Roles.Role` class in the code-behind, for example the `Role.IsUserInRole(string roleName)` method, to show/hide sections of the page."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T11:50:31.053",
"Id": "72262",
"Score": "0",
"body": "That link and guidance looks really good. I'll have to pen in a day and really get into the meat of it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T12:00:12.160",
"Id": "72263",
"Score": "1",
"body": "A (perhaps small) benefit of the Web.config is that it applies to all files, even for example text files which cannot include code to check the user's permissions and to redirect if the user is not permitted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T12:02:39.400",
"Id": "72264",
"Score": "0",
"body": "I suspect I will use Web.Config to control \"Front End Users\" against \"Admin\" and then once into those sections use the Security.Roles from different pages where I need to limit further. i.e. \"Admin\" login will be lowest level login to that part of the site."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T22:14:12.077",
"Id": "72395",
"Score": "0",
"body": "@indofraiser I have the same login page for all types of user. But some users are created with the Admin role, so after they login they have Admin privileges and can see things that are restricted to Admins."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T10:57:59.237",
"Id": "41950",
"ParentId": "41946",
"Score": "4"
}
},
{
"body": "<h1>Naming</h1>\n\n<p>Per Microsoft, <a href=\"http://msdn.microsoft.com/en-us/library/ms229045(v=vs.110).aspx\" rel=\"nofollow\">Hungarian notation is to be avoided</a>. It was developed for untyped and weakly typed languages. <a href=\"/questions/tagged/vb.net\" class=\"post-tag\" title=\"show questions tagged 'vb.net'\" rel=\"tag\">vb.net</a> is a strongly typed language. The IDE will tell you what type a variable is. Don't use Hungarian notation.</p>\n\n<h1>Bugs</h1>\n\n<blockquote>\n<pre><code> For Each datarow As Data.DataRowView In dsNames.Select(DataSourceSelectArguments.Empty) ‘ do I need a loop?\n If datarow(\"IsAdmin\").ToString().ToUpper = \"Y\" Then\n bReturn = True\n End If\n Next\n Return bReturn\n</code></pre>\n</blockquote>\n\n<p>What happens if (God forbid) there are two records for a single user id and one of them is an Admin and the other isn't? So long as the last record <code>IsAdmin</code> you're fine, but if it's not, you will say that this user is not an Admin. Confusion ensues. </p>\n\n<p>This can be fixed by returning as soon as you find a record that <code>IsAdmin</code>.</p>\n\n<pre><code> For Each datarow As Data.DataRowView In names.Select(DataSourceSelectArguments.Empty) ‘ do I need a loop?\n If datarow(\"IsAdmin\").ToString().ToUpper = \"Y\" Then\n Return True\n End If\n Next\n Return False\n</code></pre>\n\n<p>Note that the <code>bReturn</code> variable is no longer needed.</p>\n\n<p>Also note that this always stops execution prior to disposing of <code>names</code>. You should use a <a href=\"http://msdn.microsoft.com/en-us/library/fk6t46tz.aspx\" rel=\"nofollow\"><code>Try...Finally</code> block</a> and dispose of <code>names</code> in the Finally part. (This is true of both the code I just presented and your original.)</p>\n\n<h1>Inconsistencies</h1>\n\n<p>I like that you declare and set the connection string all at once.</p>\n\n<blockquote>\n<pre><code>Dim sConnString As String = System.Web.Configuration.WebConfigurationManager.ConnectionStrings(\"mySQL\").ConnectionString\n</code></pre>\n</blockquote>\n\n<p>But you don't do the same for <code>sSQL</code>.</p>\n\n<blockquote>\n<pre><code>Dim sSQL As String\nsSQL = \"SELECT IsAdmin FROM [SystemUsers] WHERE ID=@UserID\"\n</code></pre>\n</blockquote>\n\n<p>While we're at it, we should take note that <code>sSQL</code> does not (and should not) be changed at runtime. Thus, it should be declared as a constant.</p>\n\n<pre><code>Const sql As String = \"SELECT IsAdmin FROM [SystemUsers] WHERE ID=@UserID\"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-22T17:08:03.597",
"Id": "60813",
"ParentId": "41946",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41950",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T10:21:14.343",
"Id": "41946",
"Score": "4",
"Tags": [
".net",
"vb.net",
"authentication"
],
"Title": "Login script check"
}
|
41946
|
<p>I have spent the last 6 months as I am studying web development in college to build a website template that is responsive and accessible from as many devices and browsers as possible. </p>
<p>I would really appreciate it if someone reviewed my HTML structure, CSS and share their opinion with me, my aim is to make this site appear nicely on as many devices and browsers as could.</p>
<p><strong>HTML:</strong></p>
<pre><code><!DOCTYPE html>
<html>
<!--
Website by Loai Bassam (Loai Design Studio) | www.loaidesign.co.uk
Date: 16 2 2014 - Last updated after launch: NA
-->
<head>
<title><?php include ("assets/includes/website-name.inc"); ?></title>
<meta name="description" content="">
<meta name="keywords" content="">
<?php include ("assets/includes/head.inc"); ?>
</head>
<body>
<!--Main Header-->
<header id="header">
<?php include ("assets/includes/header.inc"); ?>
</header>
<!--Header For Small Screens Only-->
<?php include ("assets/includes/second-header.inc"); ?>
<div id="page"><!--Page Container-->
<div class="topSection">
<div class="content">
<h1>Welcome</h1>
</div>
</div>
<div class="wrapper">
<div class="content">
<h1>Header One</h1>
<h2>Header Two</h2>
<h3>Header Three</h3>
<h4>Header Four</h4><br>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry dummy text of the printing and typesetting industry Lorem Ipsum is simply dummy text of the printing and typesetting industry dummy text of the printing and typesetting industry.</p><br>
<p><strong>Paragraph Strong</strong></p>
<p><em>Paragraph Empaissaied</em></p>
<p><small>Paragraph Small</small></p><br>
<a class="button" href="#">I am a Button</a><br>
<br>
<p><strong>List</strong></p>
<ul>
<li>List Item</li>
<li>List Item
<ul>
<li>Sub List Item</li>
<li>Sub List Item</li>
</ul>
</li>
</ul><br>
<p><strong>List</strong></p>
<ol>
<li>List Item</li>
<li>List Item
<ol>
<li>Sub List Item</li>
<li>Sub List Item</li>
</ol>
</li>
</ol><br>
<p>Abber (<abbr title="Oh, you found me :)">Hover over me</abbr>).</p><br>
<p>Paragraph<sub>subscript.</sub></p><br>
<p>Paragraph<sup>subscript.</sup></p><br>
<p>Paragraph<mark>Marked Line</mark></p><br>
<img alt="image" src="assets/images/image.jpg"><br>
<div class="table">
<div class="header">
<div class="cell A">
<p>Header</p>
</div>
<div class="cell B">
<p>Header</p>
</div>
<div class="cell C">
<p>Header</p>
</div>
</div>
<div class="row">
<div class="cell A">
<p>Cell</p>
</div>
<div class="cell B">
<p>Cell</p>
</div>
<div class="cell C">
<p>Cell</p>
</div>
</div>
<div class="row">
<div class="cell A">
<p>Cell</p>
</div>
<div class="cell B">
<p>Cell</p>
</div>
<div class="cell C">
<p>Cell</p>
</div>
</div>
</div>
</div>
</div>
<!--Footer-->
<?php include ("assets/includes/footer.inc"); ?>
</div><!--/Page-->
<!--Scripts-->
<?php include ("assets/includes/scripts.inc"); ?>
</body>
</html>
</code></pre>
<p><strong>CSS:</strong></p>
<pre><code>body {
color: #6B6B6B;
background-color: #262626;
font-family: 'arial', arial, sans-serif;
font-size: 1em;
line-height: 132%;
text-align: center;
-webkit-text-size-adjust: none;
-webkit-font-smoothing: antialiased;
-webkit-overflow-scrolling: touch;
overflow-y: auto;
overflow-x: hidden;
}
h1 {
font-size: 2em;
line-height: 100%;
}
h2 {
font-size: 1.8em;
line-height: 100%;
}
h3 {
font-size: 1.5em;
}
/*Font Extras*/
strong {
font-weight: 700;
}
small {
font-size: 0.81em;
}
em {
font-style: italic;
}
mark {
color: #FFF;
background-color: #405F80;
padding: 1px 4px;
margin: 0 4px;
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
}
/*Commands*/
.hide {
display: none;
}
.center {
text-align: center;
}
/*GENERAL STYLINGS ===========================================================*/
/*Form Elements*/
form {
text-align: left;
}
form div {
width: 100%;
display: inline-block;
margin-bottom: 20px;
}
form div p {
display: inline-block;
margin-bottom: 5px;
}
input, input[type=checkbox], input[type=radio], textarea, select {
color: inherit;
border: 1px solid #CDCDCD;
width: 100%;
padding: 10px;
line-height: 20px;
cursor: text;
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
-webkit-transition: all .1s linear;
-moz-transition: all .1s linear;
-ms-transition: all .1s linear;
-o-transition: all .1s linear;
transition: all .1s linear;
}
input:hover, input:focus,
textarea:hover, textarea:focus,
select:hover, select:focus {
color: #405F80;
border: 1px solid #405F80;
}
input[type=checkbox], input[type=radio] {
width: auto;
cursor: pointer;
margin: 0 5px 0 0;
}
label {
margin-left: 15px;
display: inline-block;
cursor: pointer;
-webkit-transition: all .1s linear;
-moz-transition: all .1s linear;
-ms-transition: all .1s linear;
-o-transition: all .1s linear;
transition: all .1s linear;
}
label:hover {
color: #405F80;
}
textarea {
resize: none;
height: 140px;
min-height: 140px;
max-height: 140px;
}
select {
cursor: pointer;
line-height: 40px;
height: 40px;
}
select option {
color: #6B6B6B;
}
#ui-datepicker-div {
font-size: 0.90em;
}
button, button.disabled:hover {
color: #fff;
background: #CDCDCD;
width: 100%;
padding: 15px;
font-weight: 700;
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
}
button:hover {
background: #405F80;
}
/*Validation Errors*/
span.error {
color: #D14E4B;
display: block;
font-size: 0.90em;
}
span.error:before {
content: "*";
}
input.error, textarea.error, select.error {
color: #D14E4B;
border: 1px solid #D14E4B;
}
/*Disable form when submitted*/
input.disabled, input.disabled:hover,
textarea.disabled, textarea.disabled:hover,
select.disabled, select.disabled:hover {
color: #CDCDCD;
background-color: #F7F7F7;
border: 1px solid #CDCDCD;
}
label.disabled, label.disabled:hover {
color: #CDCDCD;
}
/*Tables*/
.table {
width: 100%;
display: table;
table-layout: fixed;
border-collapse: collapse;
word-wrap: break-word;
text-align: center;
}
.table .header {
color: #fff;
background-color: #405F80;
display: table-row;
font-weight: 700;
}
.table .row {
display: table-row;
}
.table .cell {
border: 1px solid #405F80;
display: table-cell;
vertical-align: middle;
padding: 10px;
}
/*Buttons*/
.button {
color: #405F80;
border: 1px solid #405F80;
padding: 5px 10px;
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
}
.button:hover {
color: #fff;
background-color: #405F80;
}
/*Grid System*/
#grid1,#grid2,#grid3 {
width: 33.333%;
float: left;
}
#grid1 {
padding-right: 20px;
}
#grid2 {
padding: 0 10px;
}
#grid3 {
padding-left: 20px;
}
/*Gird Elements*/
.gridElement {
margin-bottom: 30px;
overflow: hidden;
}
#grid1 .gridElement:last-of-type,
#grid2 .gridElement:last-of-type,
#grid3 .gridElement:last-of-type {
margin-bottom: 0;
}
#grid1 img,#grid2 img,#grid3 img {
width: 100%;
}
/*============================================================================*/
/*HEADER =====================================================================*/
/*Header Wrapper*/
#header {
background-color: #fff;
width: 100%;
position: fixed;
top: 0; left: 0;
z-index: 1000;
-webkit-box-shadow: 0 0 15px 0 rgba(0,0,0,0.1);
-moz-box-shadow: 0 0 15px 0 rgba(0,0,0,0.1);
box-shadow: 0 0 15px 0 rgba(0,0,0,0.1);
}
/*Header Content Container*/
#headerContent {
max-width: 1024px;
height: 80px;
padding: 10px 20px;
margin: auto;
overflow: hidden;
}
/*Header Logo*/
#headerLogo {
width: 200px;
margin-top: 15px;
float: left;
}
/*Main Menu*/
@media screen and (min-width: 1024px) {
#mainMenu {
margin-top: 10px;
float: right;
}
#mainMenu li {
float: left;
margin-left: 5px;
}
#mainMenu a {
padding: 10px 15px;
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
}
#mainMenu a:hover {
color: #405F80;
}
#mainMenu a.active,
#mainMenu a.active:hover {
color: #fff;
background-color: #405F80;
}
/*Dropdown Menus*/
#mainMenu .subMenu ul {
background-color: #fff;
display: none;
padding: 1px;
margin-top: 18px;
position: absolute;
text-align: left;
-webkit-box-shadow: 0 0 15px 0 rgba(0,0,0,0.1);
-moz-box-shadow: 0 0 15px 0 rgba(0,0,0,0.1);
box-shadow: 0 0 15px 0 rgba(0,0,0,0.1);
}
#mainMenu .subMenu ul:before {
background-color: #fff;
content: "";
width: 100%;
height: 18px;
position: absolute;
top: -18px; left: 0; right: 0;
}
#mainMenu .subMenu:hover > ul {
display: block;
}
/*Dropdown Menu > Navigation*/
#mainMenu .subMenu ul li {
float: none;
margin: 0;
}
#mainMenu .subMenu ul a {
width: 100%;
padding: 7px 15px;
border-radius: 0;
-moz-border-radius: 0;
-webkit-border-radius: 0;
}
#mainMenu .subMenu ul a:hover {
color: #405F80;
background-color: #F7F7F7;
}
#mainMenu .subMenu ul a.active,
#mainMenu .subMenu ul a.active:hover {
color: #fff;
background-color: #405F80;
}
#mainMenu .subMenu:hover > a {
color: #405F80;
}
#mainMenu .subMenu:hover > a.active {
color: #fff;
}
.divider {
border-top: 1px solid #fff;
}
}
/*Tablet & Phone Header*/
#secondHeader {
display: none;
}
/*FOOTER ======================================================================*/
#footer {
color: #B2B2B2;
background-color: #262626;
border-top: 1px solid #262626;
width: 100%;
font-size: 0.85em;
text-align: center;
}
#footer .content {
padding: 30px 20px;
}
#footer .content a:hover {
filter: alpha(opacity=50);
opacity: 0.5;
}
/*Copyright Section*/
#footer .content .copyright {
padding-top: 10px;
line-height: 230%;
}
#footer .content .copyright img {
display: inline-block;
vertical-align: middle;
margin: 0 0 2px 5px;
}
/*PAGE LAYOUT ==================================================================*/
/*Main Page Container*/
#page {
background-color: #405F80;
width: 100%;
padding-top: 80px;
text-align: left;
}
/*Wrappers*/
.wrapper {
background-color: #FFF;
}
.wrapperA {
background-color: #F5F5F5;
}
/*Content Container*/
.content {
width: 1024px;
padding: 50px 20px;
margin: auto;
overflow: hidden;
}
/*PAGES =======================================================================*/
/*Top Sections >---------------------------------------------------------------*/
.topSection {
color: #fff;
background-color: #405F80;
padding: 10px 0;
}
.topSection.gallery {
background: url(../images/image.jpg) no-repeat center center;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
padding-top: 100px;
padding-bottom: 100px;
}
/*Home Page >------------------------------------------------------------------*/
/*Contact Page >---------------------------------------------------------------*/
#contactDetails {
width: 40%;
display: inline-block;
vertical-align: middle;
padding-left: 100px;
text-align: left;
}
/*(Tab to call & send SMS)*/
#contactDetails div div {
display: none;
}
/*Contact Form*/
#contactForm {
width: 40%;
display: inline-block;
vertical-align: middle;
}
/*404 Error Page >------------------------------------------------------------*/
#error404 {
padding: 250px 20px;
text-align: center;
}
/*Social Media Icons >--------------------------------------------------------*/
.socialbar a {
background-color: #CDCDCD;
background-image: url(../elements/icons-spritesheet.png);
background-repeat: no-repeat;
display: inline-block;
margin-bottom: -6px;
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
}
.socialbar a:hover {
background-color: #405F80;
}
.icon-amazon {
width: 35px;
height: 35px;
background-position: 0 0;
}
.icon-android {
width: 35px;
height: 35px;
background-position: -35px 0;
}
.icon-apple {
width: 35px;
height: 35px;
background-position: -70px 0;
}
.icon-appstore {
width: 35px;
height: 35px;
background-position: -105px 0;
}
.icon-behance {
width: 35px;
height: 35px;
background-position: -140px 0;
}
.icon-blogger {
width: 35px;
height: 35px;
background-position: -175px 0;
}
.icon-css3 {
width: 35px;
height: 35px;
background-position: 0 -35px;
}
.icon-deviant {
width: 35px;
height: 35px;
background-position: -35px -35px;
}
.icon-digg {
width: 35px;
height: 35px;
background-position: -105px -35px;
}
.icon-dribble {
width: 35px;
height: 35px;
background-position: -175px -35px;
}
.icon-drive {
width: 35px;
height: 35px;
background-position: 0 -70px;
}
.icon-dropbox {
width: 35px;
height: 35px;
background-position: -35px -70px;
}
.icon-ebay {
width: 35px;
height: 35px;
background-position: -70px -70px;
}
.icon-etsy {
width: 35px;
height: 35px;
background-position: -105px -70px;
}
.icon-facebook {
width: 35px;
height: 35px;
background-position: -140px -70px;
}
.icon-flicker {
width: 35px;
height: 35px;
background-position: -175px -70px;
}
.icon-forrst {
width: 35px;
height: 35px;
background-position: 0 -106px;
}
.icon-github {
width: 35px;
height: 35px;
background-position: -35px -106px;
}
.icon-google {
width: 35px;
height: 35px;
background-position: -70px -106px;
}
.icon-html5 {
width: 35px;
height: 35px;
background-position: -105px -106px;
}
.icon-instagram {
width: 35px;
height: 35px;
background-position: -140px -106px;
}
.icon-kickstarter {
width: 35px;
height: 35px;
background-position: -175px -106px;
}
.icon-linkedin {
width: 35px;
height: 35px;
background-position: 0 -141px;
}
.icon-microsoft {
width: 35px;
height: 35px;
background-position: -35px -141px;
}
.icon-paintress {
width: 35px;
height: 35px;
background-position: -105px -141px;
}
.icon-paypal {
width: 35px;
height: 35px;
background-position: -140px -141px;
}
.icon-picasa {
width: 35px;
height: 35px;
background-position: -175px -141px;
}
.icon-rss {
width: 35px;
height: 35px;
background-position: 0 -176px;
}
.icon-skype {
width: 35px;
height: 35px;
background-position: -35px -176px;
}
.icon-soundcloud {
width: 35px;
height: 35px;
background-position: -70px -176px;
}
.icon-tumbler {
width: 35px;
height: 35px;
background-position: -140px -176px;
}
.icon-twitter {
width: 35px;
height: 35px;
background-position: -175px -176px;
}
.icon-vimeo {
width: 35px;
height: 35px;
background-position: -210px 0;
}
.icon-wordpress {
width: 35px;
height: 35px;
background-position: -210px -35px;
}
.icon-yahoo {
width: 35px;
height: 35px;
background-position: -210px -71px;
}
.icon-youtube {
width: 35px;
height: 35px;
background-position: -210px -106px;
}
.icon-youtube1 {
width: 35px;
height: 35px;
background-position: -210px -142px;
}
/*PRINTING STYLES >----------------------------------------------------------*/
@media print {
body {
font-family: arial, georgia, serif;
background: none;
color: #000;
}
#page {
width: 100%;
margin: 0;
padding: 0;
background: none;
}
#header,#secondHeader,#footer {
display: none;
}
a:after {
color: #fff;
content: " [" attr(href) "] ";
}
}
</code></pre>
<p><strong>.htaccess:</strong></p>
<pre><code># Date 5 2 2014
Options -Indexes
DirectoryIndex index.html index.php
ErrorDocument 404 /404
RewriteEngine On
RewriteBase /
# Redirect if it begins with www.
RewriteCond %{HTTP_HOST} ^www\.(.*)$
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
# Remove enter code here.php; use THE_REQUEST to prevent infinite loops
# By puting the L-flag here, the request gets redirected immediately
RewriteCond %{THE_REQUEST} ^GET\ (.*)\.php\ HTTP
RewriteRule (.*)\.php$ $1 [R=301,L]
# Remove /index
# By puting the L-flag here, the request gets redirected immediately
# The trailing slash is removed in a next request, so be efficient and dont put it on there at all
RewriteRule (.*)/index$ $1 [R=301,L]
# Remove slash if not directory
# By puting the L-flag here, the request gets redirected immediately
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /$
RewriteRule (.*)/ $1 [R=301,L]
# Add .php to access file, but don't redirect
# On some hosts RewriteCond %{REQUEST_FILENAME}.php -f will be true, even if
# no such file exists. Be safe and add an extra condition
# There is no point in escaping a dot in a string
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !(/|\.php)$
RewriteRule (.*) $1.php [L]
# Change the sitemap extension from .php to .xml
RewriteRule ^sitemap.xml(.*)$ /sitemap.php?$1
# Leverage Browser Caching
# 480 weeks
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
Header set Cache-Control "max-age=290304000, public"
</FilesMatch>
# 2 DAYS
<FilesMatch "\.(xml|txt)$">
Header set Cache-Control "max-age=172800, public, must-revalidate"
</FilesMatch>
# 2 HOURS
<FilesMatch "\.(html|htm)$">
Header set Cache-Control "max-age=7200, must-revalidate"
</FilesMatch>
<IfModule mod_deflate.c>
#The following line is enough for .js and .css
AddOutputFilter DEFLATE js css
AddOutputFilterByType DEFLATE text/plain text/xml application/xhtml+xml text/css application/xml application/rss+xml application/atom_xml application/x-javascript application/x-httpd-php application/x-httpd-fastphp text/html
#The following lines are to avoid bugs with some browsers
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T20:52:14.820",
"Id": "72654",
"Score": "1",
"body": "The .inc ext is not used anymore. Switch to .php as it can introduce some security issues."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-06T09:43:16.210",
"Id": "92206",
"Score": "0",
"body": "PHP guy here: NEVER use .inc, as this is not parsed and can be downloaded directly from an attacker, seeing all your code. From a PHP perspective, your code is so 2005. Sorry. For a static website it's okay, but for a mod_rewrite driven PHP project: NEVER!"
}
] |
[
{
"body": "<p><strong>HTML:</strong></p>\n\n<ol>\n<li><p>Depending on the language on your website, you should add the <code>lang</code> attribute to your <code>html</code> tag:</p>\n\n<pre><code><html lang=\"en\">\n</code></pre></li>\n<li><p>You're missing the important viewport and charset meta tags in your head area. Add them before the <code>title</code> tag.</p>\n\n<pre><code><meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n</code></pre></li>\n<li><p>Watch your ID and class names! You have a pretty loose naming going on in your HTML. A <code>header</code> could appear everywhere on the page. You probably want to be more specific and do something like <code>site-header</code>. Same goes for things like <code>content</code>, <code>page</code>, etc.</p>\n\n<p>This way you will find your self switching between your HTML and CSS files to find out where you actually using the class you currently edit in your styles.</p></li>\n<li><p>I'm not sure if you were just testing the font sizes of your heading elements, but currently you have two <code>h1</code> elements on your page. There should only be one <strong>in the same outline</strong></p>\n\n<p>You can use multiple <code>h1</code> headings on your page if you create new outlines. This is possible by using HTML5 sectioning elements like <code>article</code>, <code>section</code>, etc. A good resource for this topic is <a href=\"http://html5doctor.com/\">HTML5 Doctor</a>.</p></li>\n<li><p>You're sometimes using <code>br</code> tags after natural block-level elements like <code>h4</code>, <code>ul</code> and <code>p</code>. This is unnecessary.</p></li>\n<li><p>You using <code>div</code>'s to create tables. Why? Use <code>table</code>, <code>tr</code>, <code>td</code>, etc. for tabular data. You can use the structure in your html if you actually want to use it for layout. Don't call it a <em>table</em> then.</p></li>\n</ol>\n\n<p><strong>CSS:</strong></p>\n\n<ol>\n<li><p>I don't know why you're using Arial in your font stack two times, but it's unnecessary. The following is enough:</p>\n\n<pre><code>font-family: Arial, sans-serif;\n</code></pre></li>\n<li><p><code>line-height</code> is one of the view properties, where you don't actually need a unit. I had problems with <code>em</code> and <code>%</code> there before, so I use the unit-less value:</p>\n\n<pre><code>line-height: 1.32;\n</code></pre></li>\n<li><p>Why are you hiding horizontal scrollbars? Unless you have a very good reason doing this, don't.</p></li>\n<li><p>Unless you use a font with <em>special</em> font-weights, you can just use <code>font-weight: bold;</code>.</p></li>\n<li><p>In most cases you can drop the vendor prefixes for the <code>border-radius</code> property. Figure out what you actually need here: <a href=\"http://caniuse.com/border-radius\">http://caniuse.com/border-radius</a></p></li>\n<li><p>I don't know why you are selecting <code>form div</code> and <code>form div p</code> and why you change the styles for these elements like you did. Adding the bottom margin there should be enough for block-level elements.</p>\n\n<p>Other than this it's generally a bad idea to just select all <code>div</code>'s inside a certain element. Assign classes to the div's and use them. The selector <code>form div p</code> could be written as <code>form p</code>.</p></li>\n<li><p>You're selecting <code>input, input[type=checkbox], input[type=radio], textarea, select</code>. Remove <code>input[type=checkbox], input[type=radio],</code> from the selector, because you're already selecting <em>all</em> <code>input</code> elements.</p></li>\n<li><p>Selectors like <code>span.error</code> are overqualified. You should have a better, more descriptive class name and select like <code>.error-invalid-input</code>, etc.</p></li>\n<li><p>Same thing for <code>*.disabled, ...</code>. You can shorten this selector by just using the blass there:</p>\n\n<pre><code>.disabled, .disabled:hover\n</code></pre></li>\n<li><p>If you select list-items in a list, don't add <code>ul</code> to the selector, because a list-item is a child of a list anyway:</p>\n\n<pre><code>#mainMenu .subMenu li\n</code></pre>\n\n<p>Similar thing for the links:</p>\n\n<pre><code>#mainMenu .subMenu a\n</code></pre></li>\n<li><p>Again, I have no idea what you did there:</p>\n\n<pre><code>#contactDetails div div {\n display: none;\n}\n</code></pre>\n\n<p>Use classes instead of exzessive use of type selectors. Especially if you need it for things like the <code>display</code> property. You have declared a <code>hidden</code> class anyway, why not use this?</p></li>\n<li><p>You have heavy redundancy in your icon CSS. You repeat the <code>width</code> and <code>height</code> declarations over and over. Use something like this instead:</p>\n\n<pre><code>.icon {\n width: 35px;\n height: 35px;\n}\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T04:05:17.970",
"Id": "72692",
"Score": "0",
"body": "I appreciate HTML #1 and 2, and your CSS #3! I *hate* sites which have horizontal scrolling..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T07:00:13.823",
"Id": "72705",
"Score": "1",
"body": "@axel if you're building a proper site, you don't need to hide the scrollbars."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T11:10:29.957",
"Id": "41952",
"ParentId": "41947",
"Score": "21"
}
}
] |
{
"AcceptedAnswerId": "41952",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T10:32:58.543",
"Id": "41947",
"Score": "15",
"Tags": [
"php",
"html",
"css",
"html5",
".htaccess"
],
"Title": "Portable website template"
}
|
41947
|
<p>because Arduino platforms are fairly limited in its capacities, I wrote a small process scheduler. I append a function to an array and define a tickrate. After this tickrate elapses, the function should be called. Additionally I set a small delay. If several function share the same tickrate, this delays hinders them to get called very shortly together. In case, that the serial bus is used, this could avoid write/read blocks.
I never wrote something similiar and wouldn't say that my approach with the delay is elegant. Maybe someone has ideas to enhance this story. </p>
<p>Ads:
- CAPITALS are #defines</p>
<p>Sample:</p>
<pre><code>Emitter emitMain(&main_loop, MAIN_LOOP_T_MS);
// Prepare scheduler for the main loop ..
_SCHED.addEmitter(&emitMain, 0);
_SCHED.run();
</code></pre>
<p>Code *.h:</p>
<pre><code>class Emitter {
public:
Emitter(void (*pf_foo)(), uint16_t delay = 0);
bool emit();
void reset();
uint16_t getDelay(uint16_t iNum);
private:
bool bSend;
uint16_t iDelay;
void (*pfEmitter)();
};
///////////////////////////////////////////////////////////
// Container for emitter objects
///////////////////////////////////////////////////////////
class Emitters {
private:
const AP_HAL::HAL *m_pHAL;
uint8_t m_iItems; // Current number of items in the arrays below
uint32_t m_timerList [MAX_NO_PROC_IN_SCHED];
Emitter *m_functionList[MAX_NO_PROC_IN_SCHED];
uint16_t m_tickrateList[MAX_NO_PROC_IN_SCHED];
protected:
///////////////////////////////////////////////////////////
// pEmitters: Array of iSize_N elements
// iTickRates: The times in ms until the emitter in the array will emit again
// iTimerList: Array holding the timers for each element
// iSize_N: The number of emitters in the array
///////////////////////////////////////////////////////////
void scheduler(Emitter **pEmitters, uint16_t *iTickRates, uint32_t *iTimerList, const uint8_t iSize_N);
public:
Emitters(const AP_HAL::HAL *);
void addEmitter(Emitter *, uint16_t iTickRate);
void run();
};
</code></pre>
<p>Code *.cpp:</p>
<pre><code>#include "emitter.h"
Emitter::Emitter(void (*pf_foo)(), uint16_t delay) {
bSend = false;
iDelay = delay;
pfEmitter = pf_foo;
}
bool Emitter::emit() {
if(!bSend && pfEmitter != NULL) {
pfEmitter();
bSend = true;
return true;
}
return false;
}
void Emitter::reset() {
bSend = false;
}
uint16_t Emitter::getDelay(uint16_t iNum) {
return iDelay * (iNum+1);
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
Emitters::Emitters(const AP_HAL::HAL *p) {
m_pHAL = p;
memset(m_functionList, NULL, sizeof(m_functionList));
memset(m_tickrateList, 0, sizeof(m_tickrateList));
m_iItems = 0;
uint32_t timer = m_pHAL->scheduler->millis();
for(uint8_t i = 0; i < MAX_NO_PROC_IN_SCHED; i++) {
m_timerList[i] = timer;
}
}
void Emitters::addEmitter(Emitter *p, uint16_t iTickRate) {
if(m_iItems < sizeof(m_functionList)-1 && p != NULL) {
m_functionList[m_iItems] = p;
m_tickrateList[m_iItems] = iTickRate;
m_iItems++;
}
}
void Emitters::scheduler(Emitter **pEmitters, uint16_t *iTickRates, uint32_t *iTimerList, const uint8_t iSize_N) {
if(m_pHAL == NULL)
return;
for(uint8_t i = 0; i < iSize_N; i++) {
uint32_t time = m_pHAL->scheduler->millis() - iTimerList[i];
if(time > iTickRates[i] + pEmitters[i]->getDelay(i) ) {
if(pEmitters[i]->emit() ) {
if(i == (iSize_N - 1) ) { // Reset everything if last emitter successfully emitted
for(uint16_t i = 0; i < iSize_N; i++) {
pEmitters[i]->reset();
}
iTimerList[i] = m_pHAL->scheduler->millis();
}
}
}
}
}
void Emitters::run() {
scheduler(m_functionList, m_tickrateList, m_timerList, m_iItems);
}
</code></pre>
<p>EDIT after first answer: Initially my scheduler had a completely other design. I was not testing the current code so far. But with the help of palacsint I made a few changes in comparison to the example above. If there are further suggestion I will change the code after this section.</p>
<p>SAMPLE: </p>
<pre><code>// function, delay, multiplier of the delay
Emitter emitAtti(&send_atti, 3, 0);
Emitter emitRC (&send_rc, 37, 0);
Emitter emitComp(&send_comp, 44, 0);
Emitter emitBaro(&send_baro, 66, 0);
Emitter emitGPS (&send_gps, 66, 1);
Emitter emitBat (&send_bat, 75, 0);
Emitter emitPID (&send_pids, 75, 1);
</code></pre>
<p>IMPLEMENTATION:</p>
<pre><code>Emitter::Emitter(void (*pf_foo)(), uint16_t delay, uint8_t mult) {
m_bSend = false;
m_iDelay = delay;
pfEmitter = pf_foo;
m_iDelayMultplr = mult;
uint32_t m_iTimer = 0;
}
bool Emitter::emit() {
if(!m_bSend && pfEmitter != NULL) {
pfEmitter();
m_bSend = true;
return true;
}
return false;
}
void Emitter::reset() {
m_bSend = false;
}
uint32_t Emitter::getTimer() {
return m_iTimer;
}
void Emitter::setTimer(const uint32_t iTimer) {
m_iTimer = iTimer;
}
uint16_t Emitter::getDelay() {
return m_iDelay * m_iDelayMultplr;
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
Emitters::Emitters(const AP_HAL::HAL *p) {
m_pHAL = p;
memset(m_functionList, NULL, sizeof(m_functionList));
memset(m_tickrateList, 0, sizeof(m_tickrateList));
m_iItems = 0;
}
void Emitters::addEmitter(Emitter *p, uint16_t iTickRate) {
if(m_iItems < NO_PRC_SCHED && p != NULL) {
m_functionList[m_iItems] = p;
m_tickrateList[m_iItems] = iTickRate;
m_iItems++;
}
}
bool Emitters::isEmitted(const uint8_t i) {
Emitter *pCurEmit = m_functionList[i];
uint32_t time = m_pHAL->scheduler->millis() - pCurEmit->getTimer();
// Time yet to start the current emitter?
if(time <= m_tickrateList[i] + pCurEmit->getDelay() ) {
return false;
} else {
// Release the block for the transmitter
pCurEmit->reset();
}
if(pCurEmit->emit() ) {
// Set timer to the current time
pCurEmit->setTimer(m_pHAL->scheduler->millis() );
} else {
return false;
}
return true;
}
void Emitters::resetAll() {
// Reset everything if last emitter successfully emitted
for(uint16_t i = 0; i < m_iItems; i++) {
m_functionList[i]->reset();
}
}
void Emitters::run() {
if(m_pHAL == NULL)
return;
for(uint8_t i = 0; i < m_iItems; i++) {
// Run all emitters
if(!isEmitted(i) ) {
continue;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Just a few minor notes: <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\">guard clauses</a> (inverting a few conditions and using <code>continue</code>) would make the code flatten and easier to read:</p>\n\n<pre><code>for(uint8_t i = 0; i < iSize_N; i++) {\n uint32_t time = m_pHAL->scheduler->millis() - iTimerList[i];\n if(time <= iTickRates[i] + pEmitters[i]->getDelay(i) ) {\n continue;\n }\n if(!pEmitters[i]->emit()) {\n continue;\n }\n if(i != (iSize_N - 1) ) { \n continue;\n }\n\n // Reset everything if last emitter successfully emitted\n for(uint16_t i = 0; i < iSize_N; i++) {\n pEmitters[i]->reset();\n }\n iTimerList[i] = m_pHAL->scheduler->millis();\n}\n</code></pre>\n\n<p>Accessing <code>pEmitters[i]</code> happens <del>three</del> two times. You could create a named local variable for that. The third one is easy to misread (as I did) since both for loops use the same loop variable. It would be more readable if they used different variables or the inner loop was extracted out to a named function.</p>\n\n<p>The function could be called <code>resetEverything</code> (something more conrete would be better). This eliminates the first part of the comment. The second part of the comment could be also a function, <code>isLastEmitterSuccessfullyEmitted</code> which contains the conditions.</p>\n\n<pre><code>for(uint8_t i = 0; i < iSize_N; i++) {\n if (!isLastEmitterSuccessfullyEmitted(...)) {\n continue;\n }\n resetEverything(...);\n}\n\nboolean isLastEmitterSuccessfullyEmitted(...) {\n uint32_t time = m_pHAL->scheduler->millis() - iTimerList[i];\n if(time <= iTickRates[i] + pEmitters[i]->getDelay(i) ) {\n return false;\n }\n if(!pEmitters[i]->emit()) {\n return false;\n }\n if(i != (iSize_N - 1) ) { \n return false;\n }\n}\n\nvoid resetEverything(...) {\n // Reset everything if last emitter successfully emitted\n for(uint16_t i = 0; i < iSize_N; i++) {\n pEmitters[i]->reset();\n }\n iTimerList[i] = m_pHAL->scheduler->millis();\n}\n</code></pre>\n\n<p>It increases the abstraction level of the code and gives a high level overview for readers/maintainers while the details are hidden in the functions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T12:37:16.467",
"Id": "72270",
"Score": "1",
"body": "It really is better to read, if I turn the comparisons. Was not thinking about this!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T12:18:47.393",
"Id": "41956",
"ParentId": "41954",
"Score": "5"
}
},
{
"body": "<p>Your application looks like a typical periodic real-time task scheduler. There are many known and good algorithms for this, the two most widely used are <a href=\"http://en.wikipedia.org/wiki/Earliest_deadline_first_scheduling\" rel=\"nofollow\">Earliest Deadline First(EDF)</a> and <a href=\"http://en.wikipedia.org/wiki/Rate-monotonic_scheduling\" rel=\"nofollow\">Rate Monotonic (RM)</a>. By the looks of your example you do not seem to have a pre-emptive scheduling model, which is fine if you don't want to deal with processes and context switches.</p>\n\n<p>A <code>Task</code> is a periodic processing that has to be done. We call each period of a <code>Task</code> for a <code>job</code>. The task releases jobs to be executed periodically, and each job has a deadline. The deadline is equal to the <code>time_of_release + period</code>, which coincidentally is the time of the next job release. Jobs are executed in order of earliest deadline first after they have been released. Each job has a designed \"worst case execution time\" (WCET), which you can determine experimentally or preferably by analysis. Or if you don't care about hard real-time constraints, you can simply set it to 0. It only affects schedulability analysis, and has no impact on actual scheduling.</p>\n\n<p>The following implements a rudimentary (not-tested) non-preemptive EDF scheduler.</p>\n\n<p><strong>Please note: I have written this from the top of my head, and this is not suitable for use in any real-time system without a thorough code review and testing. This is provided for demonstrative purposes only!</strong></p>\n\n<pre><code>class EdfScheduler;\n\nclass Task{\npublic:\n // period: The period the task must be executed with.\n // wcet: The worst case execution time of the task.\n Task(int period, int wcet, int start_time)\n : m_period(period), m_wcet(wcet), m_next_deadline(start_time)\n {}\n virtual ~Task();\n virtual void run() = 0;\nprivate:\n\n bool canRun(int time){\n int job_start = m_next_deadline - m_period;\n return job_start >= time;\n }\n int nextRun(){\n return m_next_deadline;\n }\n const int m_period;\n const int m_wcet;\n\n int m_next_deadline; // And coincidental job-release\n friend class EdfScheduler;\n};\n\nclass EdfScheduler{\n static const int MAX_TASKS = 8;\n static const int MAX_SLEEP = 200;\npublic:\n EdfScheduler(){\n for(int i = 0; i < MAX_TASKS; ++i){\n m_tasks[i] = NULL;\n }\n m_processor_load = 0.0f;\n }\n\n bool addTask(Task* t){\n bool added = false;\n for(int i = 0; i < MAX_TASKS; ++i){\n if(m_tasks[i] == NULL){\n m_tasks[i] = t;\n added = true;\n break;\n }\n }\n if(!added)\n return false;\n\n t->m_next_deadline += t->m_period;\n\n float wcet_max = 0;\n for(int i = 0; i < MAX_TASKS; ++i){\n if(m_tasks[i] != NULL){\n wcet_max = max(wcet_max, m_tasks[i]->m_wcet);\n }\n }\n float load = 0;\n for(int i = 0; i < MAX_TASKS; ++i){\n if(m_tasks[i] != NULL){\n load += (m_tasks[i]->m_wcet + wcet_max) / m_tasks[i]->m_period;\n }\n }\n\n if(load > 1.0f)\n warning(\"System is overloaded and may not meet deadlines.\");\n return true;\n }\n\n void runScheduler(){\n while(1){\n Task* edf = NULL;\n\n int next_run = MAX_SLEEP;\n for(int i = 0; i < MAX_TASKS; ++i){\n if(m_tasks[i] != NULL){\n if(m_tasks[i]->canRun()){\n if(edf == NULL){\n edf = m_tasks[i];\n }else if( m_tasks[i]->m_next_deadline < edf->m_next_deadline){\n edf = m_tasks[i];\n }\n }\n next_run = min(next_run, m_tasks[i]->nextRun());\n }\n }\n\n if(!edf){\n sleep(next_run);\n continue;\n }\n\n edf->run();\n edf->m_next_deadline += edf->m_period; // Perpare it for running the next time.\n }\n }\n\nprivate:\n Task* m_tasks[MAX_TASKS];\n float m_processor_load;\n};\n</code></pre>\n\n<p>I realize I might have gone over-board with this but I hope you find it helpful or at least interesting in some way :rollseyes:</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T09:08:14.863",
"Id": "72466",
"Score": "0",
"body": "Interesting. I think I will make some performance comparisons for different situations in future."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T09:51:55.340",
"Id": "72473",
"Score": "0",
"body": "In general, scheduling is difficult to get right. Especially for real-time systems. And although you didn't state it, your problem looks like a real-time system. Attempting to schedule real-time tasks without a properly implemented real-time scheduling algorithm will cause problems. I would advise to read up on existing algorithms and choose a suitable one. For your case you'd be looking at non-preemptive scheduling. Disclaimer: I have done academic research on real-time scheduling algorithms."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T10:31:18.463",
"Id": "72481",
"Score": "0",
"body": "I write my own quadrocopter firmware. Things started easy at the beginning. Just one loop with maximum performance for inertial readout and reading a control command. Then I added support for other devices and sensors, functions for serial output, everything at once was too much for the serial ports and/or the ATMega. Then I used timers, which started to mess up the code. This is why I started to write a preliminary \"something like a\" scheduler. Ideally the scheduler should privilege the control task. But there are exceptions as well. I think there are always optimizations possible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T12:16:04.497",
"Id": "72500",
"Score": "0",
"body": "By the sound of it, you definitely have a real-time system on your hands. The beauty of a real-time scheduler is that it will guarantee that all your tasks will get the WCET amount of execution time within their period. As long as the feasibility test succeeds (the last few rows in `addTask`). So you don't need to think about privilege or priorities that much."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T22:46:00.557",
"Id": "42019",
"ParentId": "41954",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "42019",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T11:52:04.593",
"Id": "41954",
"Score": "5",
"Tags": [
"c++",
"arduino"
],
"Title": "Simple and fair scheduler for function calls on Arduino"
}
|
41954
|
<p>I am new user of CodeIgniter and I am trying to build an application that there are lots of jQuery dynamical content.</p>
<p>Below I provide a code that I am using in order to be precise. The code below is running and I cannot see any problem. However, since I will be using pieces of code like this in several different parts of my application, I would like to know if this is a good design. If it is not, please let me know how to proceed.</p>
<p>The code below basically describe a search form in which the results are dynamically included.</p>
<p>This is my view:</p>
<pre><code><html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("form#searchForm").submit(function() {
var theCity = $("select#chooseCity").val();
$.post("welcome/searchPeopleResults/", {theCity: theCity}, function(data) {
$("div#searchResults").html(data);
});
return false
});
});
</script>
</head>
<body>
<FORM id="searchForm">
<h2>Selecione uma cidade: </h2>
<select id="chooseCity">
<?php
$theCitiesOptionsHTML = "cityOptions.html"; <!-- A large list of cities -->
require($thePathDataFiles.$theCitiesOptionsHTML);
?>
</select>
</FORM>
<div id="searchResults">
<!-- Search results should arise here -->
</div>
</body>
</html>
</code></pre>
<p>This is my controller:</p>
<pre><code> class Welcome extends CI_Controller {
public function index()
{
$this->load->view('searchPeople');
$this->load->view('css/format');
}
public function searchPeopleResults(){
$theCity=$this->input->post('theCity');
$this->load->model('MSearchPeople');
$data=$this->MSearchPeople->provideSearchPeopleResults($theCity);
echo $data;
}
}
</code></pre>
<p>This is my model:</p>
<pre><code>Class MSearchPeople extends CI_Model {
function provideSearchPeopleResults($theCity) {
// Here I got my database query ($theUsername, $theFirstName, $theLastName, $theSummary) and call the function presented below "writeHtmlSearchPeople".
return $theHtml;
}
}
</code></pre>
<p>Note that that after querying the database, the model above generates the necessary pieces of HTML code to be returned to the scope of the <code>$.ṕost()</code> function.</p>
<p>Precisely, inside the function <code>provideSearchPeopleResults($theCity)</code>, I call another function that generates the html code for me. Something like that:</p>
<pre><code><?php
function writeHtmlSearchPeople($theUsername, $theFirstName, $theLastName, $theSummary) {
$theCompleteName = $theFirstName . " " . $theLastName;
$theFigureName = base_url() . "application/views/photos/" . $theUsername;
?>
<table border = "0" width = "75%">
<tr>
<td width = "20%">
<img src="<?php echo $theFigureName ?>" alt=" " width= "150">
</td>
<td width = "80%">
<a class="supplierPage" data-username="<?php echo $theUsername ?>" href = "" > "<?php echo $theCompleteName ?>"</a> "<?php echo $theSummary ?>"
</td>
</tr>
</table>
<?php
}
?>
</code></pre>
<p>I am particularly worried with the fact that I am generating HTML code from my model (note that this HTML code is just being returned as data to the scope of the <code>$post()</code> function). However, I am not sure if there is a better practice for this!</p>
<p>Furthermore, I would like to implement explicitly the MVC design. Although views and models are in different files, they are not connected by the controller. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T01:59:10.167",
"Id": "72430",
"Score": "0",
"body": "I would suggest that you use a templating framework (ex: handlebar just to name one) in the client side and simply send json instead of html in your ajax calls/ api.Also, I really recommend people using jQuery for what it is a library not a framework. If you plan on building an app that can grow. Go for a framework."
}
] |
[
{
"body": "<p>You are right with your concerns regarding the model rendering the output. But you're almost there ain't you? Why don't you let your model return the data instead of the HTML-Code and let the controller call <code>writeHtmlSearchPeople</code>: </p>\n\n<pre><code>class MSearchPeople extends CI_Model {\n function provideSearchPeopleResults($theCity) {\n $result = // db query, normalize data,\n return $result;\n }\n}\n\nclass Welcome extends CI_Controller {\n public function searchPeopleResults() {\n $theCity = $this->input->post('theCity');\n $this->load->model('MSearchPeople');\n $data = $this->MSearchPeople->provideSearchPeopleResults($theCity);\n echo writeHtmlSearchPeople($data); // or however you rendered the data\n }\n}\n</code></pre>\n\n<p>Now this the controller acts as the mediator between your view and your model. In my opinion it is important that the controller never contains any view logic besides returning or echo-ing it. If the data from your model requires iterations, put these in your view. </p>\n\n<p>Other remarks: </p>\n\n<ul>\n<li>I don't know CI, yet you might want to check to validate your input\n(<code>$theCity</code>) for invalid values and react accordingly</li>\n<li>Code Style: \n<ul>\n<li><code>Class MSearchPeople</code>, the <code>class</code> keyword probably should be lower-case</li>\n<li>Indentation: might be a copy & paste problem, though try to keep it consistent. </li>\n<li>Whitespaces in assignments: More of a personal thing though widely used: a whitespace before and after an assignment operator: <code>$theCity = $this->input->post('theCity');</code>. Makes it easier to read.</li>\n</ul></li>\n<li>Variable & class naming: probably the second most difficult things in programming (after writing comments). Maybe you can find better names for your variables and names? Some examples:\n<ul>\n<li><code>Welcome</code> Controller? What is it's responsibility? I really can't tell in what way it has to do with welcoming whatever being. </li>\n<li><code>$theCity=$this->input->post('theCity');</code> This name indicates for me a <strong>one</strong> valid city entity. But rather more ain't it the current <code>$searchTerm</code>? In general I'd consider variables starting the <code>the</code> very bad practice. <code>The</code> in a name would indicate the final single entity resulted from a long journey. But even then I'd skip the <code>the</code> as it puts too much emphasis on the <code>the</code> and not on the following object. I'd go with <code>$matchingCities</code> instead. </li>\n<li>I'd consider the hungarian notation obsolete in typed languages (<code>MSearchPeople</code> => <code>SearchPeople</code>) (bluntly assumung that the <code>M</code> stands for <code>Model</code>).</li>\n<li><code>provideSearchPeopleResults</code> this name indicates that this information is made available by other means and not returned. The common pattern when returning data is <code>get</code> -> <code>getSearchPeopleResults</code>. As this function is called on the <code>MSearchPeople</code> model, the <code>SearchPeople</code> part in this function name is duplicate information too. The function name could be shortened to <code>search</code>. </li>\n</ul></li>\n<li>While I only know very little of your code, I'd consider search part of either the <code>People</code> model or better, repository. There is no need for a dedicated model for searching. Of course this highly depends on the business model you are modeling. </li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T02:05:45.320",
"Id": "72431",
"Score": "1",
"body": "Thank you for your answer. I expected this kind of answer. The point is that as you assume the data may have lots of results and I would have to transfer this to the view. On other hand, I also was influenced by http://stackoverflow.com/questions/13813046/how-is-mvc-supposed-to-work-in-codeigniter. What do you think about this? Thank you for the other suggestions, but most of them are related to CodeIgniter style: \"Welcome\", \"MSearchModel\". In fact, this is just a part of a large application and there are several \"search\" situations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T09:24:10.923",
"Id": "72467",
"Score": "0",
"body": "Don't worry about this \"transfering\", this won't impose any performance problems as PHP optimizes this on it's own. Furthermore don't let your architecture be driven by premature optimization. You can optimize later on if this really turns out to be a bottleneck (which I highly doubt it will ever be). The author of the post is right. And in my opinion what you use is a model is a mixture of a model, repository and mapper (violating the single responsibility principle of course). On the View accessing model discussion: I don't like the view depending on the model. ViewModels come to mind here."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T23:36:03.120",
"Id": "42027",
"ParentId": "41959",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "42027",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T13:25:17.137",
"Id": "41959",
"Score": "3",
"Tags": [
"php",
"jquery",
"html",
"mvc",
"codeigniter"
],
"Title": "Best practice for generating jQuery dynamical content"
}
|
41959
|
<p>I have been collecting snippets from all over the place and then put them all together creating the following .htaccess file.</p>
<p>I really don't understand if what I have done below is good/should work as expected, so your opinion is really appreciated.</p>
<p>I also don't understand the bit just after <code>#Leverage Browser Caching</code>. Can anyone please explain it to me?</p>
<pre><code># Date 2 2 2014
ErrorDocument 404 /404
RewriteEngine On
RewriteBase /
# Redirect if it begins with www.
RewriteCond %{HTTP_HOST} ^www\.(.*)$
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
# Remove enter code here.php; use THE_REQUEST to prevent infinite loops
# By puting the L-flag here, the request gets redirected immediately
RewriteCond %{THE_REQUEST} ^GET\ (.*)\.php\ HTTP
RewriteRule (.*)\.php$ $1 [R=301,L]
# Remove /index
# By puting the L-flag here, the request gets redirected immediately
# The trailing slash is removed in a next request, so be efficient and dont put it on there at all
RewriteRule (.*)/index$ $1 [R=301,L]
# Remove slash if not directory
# By puting the L-flag here, the request gets redirected immediately
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /$
RewriteRule (.*)/ $1 [R=301,L]
# Add .php to access file, but don't redirect
# On some hosts RewriteCond %{REQUEST_FILENAME}.php -f will be true, even if
# no such file exists. Be safe and add an extra condition
# There is no point in escaping a dot in a string
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !(/|\.php)$
RewriteRule (.*) $1.php [L]
# Change the sitemap extension from .php to .xml
RewriteRule ^sitemap.xml(.*)$ /sitemap.php?$1
# Leverage Browser Caching
# 480 weeks
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
Header set Cache-Control "max-age=290304000, public"
</FilesMatch>
# 2 DAYS
<FilesMatch "\.(xml|txt)$">
Header set Cache-Control "max-age=172800, public, must-revalidate"
</FilesMatch>
# 2 HOURS
<FilesMatch "\.(html|htm)$">
Header set Cache-Control "max-age=7200, must-revalidate"
</FilesMatch>
<IfModule mod_deflate.c>
#The following line is enough for .js and .css
AddOutputFilter DEFLATE js css
AddOutputFilterByType DEFLATE text/plain text/xml application/xhtml+xml text/css application/xml application/rss+xml application/atom_xml application/x-javascript application/x-httpd-php application/x-httpd-fastphp text/html
#The following lines are to avoid bugs with some browsers
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
</code></pre>
|
[] |
[
{
"body": "<p>Leverage browser caching is designed to prevent browsers from using a cache for too long. If your website is dynamic, this is necessary to prevent users' browsers from storing your website for too long.</p>\n\n<p>The way your file does this is by checking the type of file, and making a browser's cache of it expire after a specified amount of time. Images the other files you listed generally change little, so that part of you code is good unless you create dynamic images often. Your XML and TXT file deadline is okay unless you have XML news feeds or similar. HTML expiration date is also good as those files are usually the most often edited.</p>\n\n<p>Overall, your file structure is good. I am sorry if this did not answer your question.</p>\n\n<p><em>Edit:</em>\nNote that a browser doesn't have to obey you request to revalidate the page.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T16:03:04.377",
"Id": "72322",
"Score": "0",
"body": "This is a great answer thank you, however how can I change the time? or what is the actually dead-time? i.e when stuff die?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T16:22:20.383",
"Id": "72325",
"Score": "0",
"body": "Your comments reveal this. If 7200 means two days, as shown in your comments, then 3600 means one day. This is when the browser will request the page again instead of accessing a cache."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T15:52:53.773",
"Id": "41972",
"ParentId": "41964",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T14:35:48.770",
"Id": "41964",
"Score": "3",
"Tags": [
"cache",
".htaccess",
"compression"
],
"Title": "htaccess for URL remapping, caching, and compression"
}
|
41964
|
<p>I want to parse a command line using <a href="http://www.boost.org/doc/libs/1_55_0/doc/html/program_options.html" rel="nofollow"><code>boost.program_options</code></a>. Most of my command line arguments will be intervals, which I could implement as something like <code>--x-min=2000</code> and <code>--x-max=2500</code>.</p>
<p>However, I thought about adding a class that can be written to/read from streams that allows me to handle an option of that reads <code>--x=2000:2500</code>. The following code seems to work fine, but I'm not sure if this "range" approach is advisable at all:</p>
<pre><code>#include <iostream>
template<typename T>
struct Interval
{
/** sep should not be specific to each template instantiation, should it? **/
static const char sep = ':';
T lowest;
T highest;
};
template<typename T>
std::ostream& operator<<(std::ostream& o, const Interval<T>& t)
{
o << t.lowest << Interval<T>::sep << t.highest;
return o;
}
template<typename T>
std::istream& operator>>(std::istream& i, Interval<T>& t)
{
// don't read from failed stream
if(i.fail())
{
return i;
}
// read value left of separator
T l;
i >> l;
// read separator
char c;
i >> c;
if (c != Interval<T>::sep)
{
i.setstate(std::ios::failbit);
return i;
}
// read value right of separator
T r;
i >> r;
// prefer less-than comparison over >=
if (r < l)
{
i.setstate(std::ios::failbit);
return i;
}
// set given Interval's members
t.lowest = l;
t.highest = r;
return i;
}
using namespace std;
int main()
{
Interval<double> i;
i.lowest = 0;
i.highest = 10;
cout << "range is " << i << endl << "enter new range: ";
cin >> i;
cout << "new range is " << i << endl;
return 0;
}
</code></pre>
<p>This code uses available stream operators for <code>T</code>, which simplifies things, and it looks clean enough so that I think it can't be too wrong.</p>
<p>One potential problem I see is that I cannot constrain one end of x, which would work with individual <code>--x-min</code> and <code>--x-max</code> options. Such an implementation of <code>Interval</code> would need to accept <code>--x=:2500</code> and <code>--x=2000:</code>. I'd have to add handling of optional values, which could get messy.</p>
<ol>
<li>Are there any serious pitfalls in my current implementation?</li>
<li>Would you advise to use such a command line format at all?</li>
</ol>
<p>A possible extension of this could be used to create regularly spaced lists of values, like Matlab's <code>linspace</code> and <code>logspace</code> functions do: <code>--x=0:100:101</code> and <code>--x=10:1000:20,log</code>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T15:04:39.897",
"Id": "41967",
"Score": "4",
"Tags": [
"c++",
"parsing",
"console",
"stream",
"boost"
],
"Title": "Reading Intervals from command line"
}
|
41967
|
<p>This code works. It is designed to retrieve website data directly, parse it, and open it as normal. I will develop it further later. Right now I want to know if there is any way to improve efficiency, such as not using a file etc. I would also like to know if my code could be made more pythonic (this would include PEP standards), or incidences where concatenation would be acceptable to readability. Here is the code:</p>
<pre><code>import urllib.request
from tkinter import *
import webbrowser
import os
proxy_handler = urllib.request.ProxyHandler(proxies=None)
opener = urllib.request.build_opener(proxy_handler)
def navigate(query):
response = opener.open(query)
html = response.read()
return html
def parse(junk):
ugly = str(junk)[2:-1]
lines = ugly.split('\\n')
return lines
while True:
url = input("Path: ")
dump = navigate(url)
content = parse(dump)
with open('cache.html', 'w') as f:
for line in content:
f.write(line)
webbrowser.open_new_tab(os.path.dirname(os.path.abspath(__file__))+'/cache.html')
</code></pre>
|
[] |
[
{
"body": "<p><strong>1.</strong> Make sure your variable names are both short and to the point, using a parameter called junk is pointless. Also, this could cause conflicts if you ever write other code and import this.</p>\n\n<pre><code>def parse(junk):\n ugly = str(junk)[2:-1]\n lines = ugly.split('\\\\n')\n return lines\n</code></pre>\n\n<p><strong>2.</strong> urllib is outdated. Unless there is a specific reason you need to use urllib, you should use urllib2. Urllib2 is faster and more simple.</p>\n\n<p><code>import urllib.request</code></p>\n\n<p><strong>3.</strong> This part looks a bit messy:\n<code>webbrowser.open_new_tab(os.path.dirname(os.path.abspath(__file__))+'/cache.html')</code>\nPerhaps separate into multiple lines for readability.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T17:37:02.320",
"Id": "72332",
"Score": "0",
"body": "Thanks alot, but I get an importerror for urllib2 running python 3.3.2"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T17:38:43.173",
"Id": "72334",
"Score": "0",
"body": "Okay. Maybe ask on StackOverflow about that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T01:52:30.327",
"Id": "72427",
"Score": "1",
"body": "`urllib` is outdated in Python 2, but in Python 3, `urllib` was removed and `urllib2` was renamed to `urllib.request`. As such, `import urllib.request` should not be a problem."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T16:18:02.707",
"Id": "41975",
"ParentId": "41970",
"Score": "2"
}
},
{
"body": "<p>Your code does seem to follow PEP 8 which is a good thing. Also, the logic is splitted in different small functions which is even better.</p>\n\n<p>If you want to make your code portable, you probably shouldn't hardcode <code>/</code> in your path but use <a href=\"http://docs.python.org/2/library/os.html#os.sep\" rel=\"nofollow\">os.sep</a> or even better <a href=\"http://docs.python.org/2/library/os.path.html#os.path.join\" rel=\"nofollow\">os.path.join</a> instead.</p>\n\n<p>In order not to call <code>write</code> multiple times, you could use <a href=\"http://docs.python.org/2/library/stdtypes.html#file.writelines\" rel=\"nofollow\">writelines</a>.</p>\n\n<p>Now, from a functional point of view, it might be a good idea to create temporary files with <a href=\"http://docs.python.org/2/library/tempfile.html\" rel=\"nofollow\">tempfile</a> for instance. If you don't want to use it, it might be better to use a hash of the original url or of the content and use it in the name of the new file.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T17:39:32.657",
"Id": "72335",
"Score": "0",
"body": "Thank you, I never would have thought of that stuff. Could you explain more to a n00b why using tempfile would be advantageous to my programs functionality?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T16:18:37.530",
"Id": "41976",
"ParentId": "41970",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41976",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T15:40:00.723",
"Id": "41970",
"Score": "4",
"Tags": [
"python",
"file-system",
"http"
],
"Title": "Proxy evasion browser in Python"
}
|
41970
|
<p>I would appreciate some insights / comments from Clojure regulars out there about my submission <a href="https://github.com/exercism/exercism.io/tree/master/assignments/clojure/word-count" rel="nofollow">here</a>.</p>
<pre><code>(ns phrase)
(require '[clojure.string :as s])
(defn word-array
[phrase]
(-> (s/lower-case phrase)
(s/split #"\W+")))
(defn word-count
[phrase]
(-> (word-array phrase)
(frequencies)))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T18:32:17.790",
"Id": "72347",
"Score": "0",
"body": "It seems like a copy of the example code provided in the linked repository. What kind of feedback would you like about it ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T01:00:36.467",
"Id": "72417",
"Score": "0",
"body": "Well I think it's a little bit shorter than the example. I just reworked my solution until I got the shortest form of it. I just wanted some comments on if this is like succinct clojure code and is it idiomatic."
}
] |
[
{
"body": "<p>I would format it like this:</p>\n\n<pre><code>(ns phrase\n (:require [clojure.string :as s]))\n\n(defn word-array [phrase]\n (s/split (s/lower-case phrase) #\"\\W+\"))\n\n(defn word-count [phrase]\n (frequencies (word-array phrase)))\n</code></pre>\n\n<p>Notice that I included the <code>require</code> statement as part of the <code>ns</code> definition. </p>\n\n<p>Whether or not you use threading macros (<code>-></code>, <code>->></code>) is generally a matter of personal preference, and there's nothing wrong with using them here, but I think in this case since you're only using 2 functions, I find the above easier to read. You might also consider using <code>comp</code>:</p>\n\n<pre><code>(def word-array (comp #(s/split % #\"\\W+\") s/lower-case)\n(def word-count (comp frequencies word-array))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T13:49:04.613",
"Id": "44750",
"ParentId": "41978",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T16:31:23.503",
"Id": "41978",
"Score": "4",
"Tags": [
"clojure",
"exercism"
],
"Title": "Exercism assignment for word-count in Clojure"
}
|
41978
|
exercism.io is intended to be a conversation about what good code might look like.
The point is to pass the provided unit tests with expressive, readable code.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T16:36:49.607",
"Id": "41980",
"Score": "0",
"Tags": null,
"Title": null
}
|
41980
|
<p>I created the following HtmlHelper extension method for my Asp.Net MVC Razor views because the ternary syntax sucks when you need to use it intermixed with markup.</p>
<p>Is there a better way to write this and are there any potential type safety issues with it?</p>
<pre><code>public static string GetValueTernary(this HtmlHelper htmlHelper, object a, object b, object valueIfEqual, object valueIfNotEqual)
{
return a.Equals(b) ? valueIfEqual.ToString() : valueIfNotEqual.ToString();
}
</code></pre>
<p>and its usage in a Razor view is like this:</p>
<pre><code><div class="@Html.GetValueTernary(Model.UserVoteTypeId, VoteType.UpVote, "us", "u")">...</div>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T16:51:11.767",
"Id": "72326",
"Score": "4",
"body": "Main issue I can see is that all arguments will be evaluated no matter what. Also your code could be factorised out : `return (a.Equals(b) ? valueIfEqual : valueIfNotEqual).ToString()`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T17:31:16.570",
"Id": "72330",
"Score": "2",
"body": "Can't you instead write `<div class=\"@(Model.UserVoteTypeId == VoteType.UpVote ? \"us\" : \"u\")\">...</div>`?"
}
] |
[
{
"body": "<p>Your code will throw an exception when <code>a</code> is <code>null</code>. A safe way to compare values is <a href=\"http://msdn.microsoft.com/en-us/library/w4hkze5k\">the static version of <code>object.Equals()</code></a>:</p>\n\n<pre><code>object.Equals(a, b)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T17:28:32.043",
"Id": "41987",
"ParentId": "41982",
"Score": "10"
}
},
{
"body": "<p>I would change your method to use generics (so that the return value is meaningful) and not call <code>.ToString()</code> internally. This will enable you to use it in more scenarios.</p>\n\n<pre><code>public static T GetValueTernary<T>(this HtmlHelper html, object a, object b, T valueIfEqual, T valueIfNotEqual)\n{\n return object.Equals(a, b) ? valueIfEqual : valueIfNotEqual;\n}\n</code></pre>\n\n<p>Now you can use it like this as well and also it will enable you to use <code>HtmlString</code>-s as values.</p>\n\n<pre><code><div class=\"@Html.GetValueTernary(Model.UserVoteTypeId, VoteType.UpVote, \"us\", \"u\").ToUpper()\">...</div>\n</code></pre>\n\n<p>You could also benefit (depends on your actual usage) from not using <code>object</code> for the compared values - by using a generic the compiler will complain if the types of the two are not compatible (for example, you are comparing <code>string</code> to <code>int</code>):</p>\n\n<pre><code>public static TReturn GetValueTernary<TValue, TReturn>(this HtmlHelper html, TValue a, TValue b, TReturn valueIfEqual, TReturn valueIfNotEqual)\n{\n return object.Equals(a, b) ? valueIfEqual : valueIfNotEqual;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T18:13:43.320",
"Id": "72338",
"Score": "0",
"body": "p.s. `object.Equals` bit was borrowed from the answer by @svick"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T18:12:50.550",
"Id": "41991",
"ParentId": "41982",
"Score": "11"
}
},
{
"body": "<p>I would do this a little differently...</p>\n\n<pre><code>/// <summary>\n/// Uses <see cref=\"EqualityComparer{TValue}\"/> to determine if <paramref name=\"left\"/> is\n/// equal to <paramref name=\"right\"/>. If it is, <paramref name=\"returnIfEqual\"/> is returned,\n/// otherwise, <paramref name=\"returnIfNotEqual\" /> is returned.\n/// </summary>\npublic static TResult IfEqualReturn<TValue, TResult>(this HtmlHelper html, TValue left, TValue right, TResult returnIfEqual, TResult returnIfNotEqual)\n{\n return EqualityComparer<TValue>.Default.Equals(left, right) ? returnIfEqual : returnIfNotEqual;\n}\n</code></pre>\n\n<p><strong>Notes:</strong></p>\n\n<ul>\n<li>Use generics instead of <code>object</code> <a href=\"http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx\" rel=\"nofollow\">to avoid boxing</a>.</li>\n<li>Use <a href=\"http://msdn.microsoft.com/en-us/library/ms132123.aspx\" rel=\"nofollow\"><code>EqualityComparer<TValue></code></a> to check for equality. This class is very efficient, avoids boxing, and does a good job of handling the primitive types correctly, uses <a href=\"http://msdn.microsoft.com/en-us/library/ms131187.aspx\" rel=\"nofollow\"><code>IEquatable<T></code></a> if <code>TValue</code> implements it, and correctly evaluates reference equality versus value equality depending on <code>TValue</code>. It also will not throw an exception if <code>left</code> or <code>right</code> is null.</li>\n<li><p>When you create any function (but extensions methods in particular), choosing a descriptive but succinct name is <em>critical</em>. Ideally, the name should be enough information for another developer to know what the function does without looking at its code. </p>\n\n<ul>\n<li>I chose <code>IfEqualReturn</code> because, to me, the most important thing to understand about the function is that it evaluates the equality of <code>left</code> and <code>right</code> to determine what to return-- remember, any boolean value can be used for a <a href=\"http://msdn.microsoft.com/en-us/library/ty67wk28.aspx\" rel=\"nofollow\">ternary expression</a>, so <code>GetValueTernary</code> leaves out the critical detail that this function specifically evaluates equality.</li>\n<li>Using <a href=\"http://msdn.microsoft.com/en-us/library/b2s063f7.aspx\" rel=\"nofollow\">XML comments</a> is particularly important for extension methods. When you write your <a href=\"http://msdn.microsoft.com/en-us/library/2d6dt3kf.aspx\" rel=\"nofollow\"><code><summary></code></a>, imagine that another developer is reading your code, and explain what he would need to know to understand what the call will do. Keep it brief-- it should fit easily in a tooltip. If you feel like you need to explain more, add a <a href=\"http://msdn.microsoft.com/en-us/library/3zw4z1ys.aspx\" rel=\"nofollow\"><code><remarks></code></a> element.</li>\n</ul></li>\n</ul>\n\n<hr>\n\n<p>Here are some other suggestions.</p>\n\n<p>The <a href=\"http://msdn.microsoft.com/en-us/library/ms132151.aspx\" rel=\"nofollow\">.NET Framework interface <code>IEqualityComparer<T></code></a> allows you to create classes that evaluate equality of a given type <code>T</code>. The following function allows someone to pass in an instance, and falls back on <code>EqualityComparer<T>.Default</code> if one is not specified.</p>\n\n<pre><code>public static TResult IfEqualReturn<TValue, TResult>(this HtmlHelper html, TValue left, TValue right, TResult resultIfEqual, TResult resultIfNotEqual, IEqualityComparer<TValue> equalityComparer = null)\n{\n if (equalityComparer == null) \n equalityComparer = EqualityComparer<TValue>.Default;\n\n return equalityComparer.Equals(left, right) ? resultIfEqual : resultIfNotEqual;\n}\n</code></pre>\n\n<p>One place where this comes in handy is when comparing strings (see <a href=\"http://msdn.microsoft.com/en-us/library/system.stringcomparer%28v=vs.110%29.aspx\" rel=\"nofollow\">StringComparer</a>). Usage:</p>\n\n<pre><code>var r1 = Html.IfEqualReturn(\"str1\", \"str2\", true, false, StringComparer.Invariant); // r1 = false\nvar r2 = Html.IfEqualReturn(\"str1\", \"str1\", true, false, StringComparer.Invariant); // r2 = true\nvar r3 = Html.IfEqualReturn(\"str1\", \"STR1\", true, false, StringComparer.Invariant); // r3 = false\nvar r4 = Html.IfEqualReturn(\"str1\", \"STR1\", true, false, StringComparer.InvariantIgnoreCase); // r4 = true\n</code></pre>\n\n<p>... or you could create one that uses a lambda expression:</p>\n\n<pre><code>public static TResult IfTrueThen<TValue, TResult>(this HtmlHelper html, TValue left, TValue right, TResult returnIfTrue, TResult returnIfFalse, Func<TValue, TValue, bool> evaluateFunc)\n{\n return evaluateFunc(left, right) ? returnIfTrue : returnIfFalse;\n}\n\n// Usage:\nvar r1 = Html.IfTrueThen(0, 1, true, false, (l, r) => l == r); // r1 = false\nvar r2 = Html.IfTrueThen(\"string\", \"STRING\", true, false, (l, r) => String.Equals(l, r, StringComparison.InvariantIgnoreCase)); // r2 = true\n</code></pre>\n\n<p>Another way:</p>\n\n<pre><code>public static TResult IfTrueThen<TResult>(this HtmlHelper html, Func<HtmlHelper, bool> evaluateFunc, TResult resultIfTrue, TResult resultIfFalse)\n{\n return evaluateFunc(html) ? resultIfTrue : resultIfFalse;\n}\n\n// Usage:\nint v1 = 0, v2 = 0;\nvar r1 = Html.IfTrueThen(h => v1 == v2, true, false); // r1 = true\n\nv1 = 4;\nvar r2 = Html.IfTrueThen(h => v1 == v2, true, false); // r2 = false\nvar r3 = Html.IfTrueThen(h => (v1 - 4) == v2, true, false); // r3 = true\n</code></pre>\n\n<p>or...</p>\n\n<pre><code><div class=\"@Html.IfTrueThen(h => Model.UserVoteTypeId == VoteType.UpVote, \"us\", \"u\")\">...</div>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:47:55.607",
"Id": "42011",
"ParentId": "41982",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41991",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T16:39:34.697",
"Id": "41982",
"Score": "7",
"Tags": [
"c#",
"asp.net-mvc-4",
"extension-methods",
"razor"
],
"Title": "Ternary extension method"
}
|
41982
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.