body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I've written this class to create <code>RapportColumn</code> objects for each column that is written in the query. And I would like to get your feedback.</p>
<p>The query that is given in the <code>GetRapportColumnsList()</code> method is always a valid query. That check has been done in a previous class.</p>
<p>I am specifically asking about the <code>CreateColumns</code> class, but any other comments are greatly appreciated. Can I optimize this code any further?</p>
<pre><code>class RapportService
{
static void Main(string[] args)
{
var service = new RapportService();
var query =
"SELECT columna, columnaa, columnb, columnc, DATE_FORMAT(columnd, '%Y-%m-%d'), DATE_FORMAT(columnd, '%T') , IF(columne = (SELECT count(*) FROM tablea WHERE columna = m.columnb AND columnc = 0 AND columnd = 1), 'Goed', 'Fout') as somestring FROM tableb m WHERE columna = 64 AND columnb >= '2018-09-04 00:00:00' AND columnd <= '2018-09-08 00:00:00' ORDER BY columnb ASC";
var x = service.GetRapportColumnsList(query, 5);
Console.Read();
}
private Queue<string> columnQueue = new Queue<string>();
private List<RapportColumn> columns = new List<RapportColumn>();
// param -> part of query everthing between select and from
// split on ',' and add it in a queue
private void AddColumnStringsToQueue(string query)
{
var columns = query.Split(',');
foreach (var column in columns)
{
columnQueue.Enqueue(column);
}
}
// param query and rapport_id
// get the part of the query between SELECT and FROM
// calls the method to put everythin in the queue
// calls the method to create the column objects
public List<RapportColumn> GetRapportColumnsList(string query, int rapport_id)
{
var i = query.LastIndexOf(SqlClauseEnum.FROM, StringComparison.CurrentCultureIgnoreCase);
var res = query.Substring(SqlClauseEnum.SELECT.Length, i - SqlClauseEnum.SELECT.Length);
AddColumnStringsToQueue(res);
CreateColumns(rapport_id);
return columns;
}
// loop trough queue and create RapportColumn objects
private void CreateColumns(int rapport_id)
{
var stack = new Stack<char>();
var count = 0;
while (columnQueue.Count > 0)
{
var builder = new StringBuilder();
count++;
var rapportColumn = new RapportColumn();
var item = columnQueue.Dequeue();
builder.Append(item);
var bracket = GetOpeningBracket(item);
if (bracket == BracketsEnum.ParenthesisOpen)
{
if (!IsSurrounded(item))
{
stack.Push(bracket);
while (columnQueue.Count > 0)
{
var newItem = columnQueue.Peek();
var newBracket = GetOpeningBracket(newItem);
if (newBracket == BracketsEnum.ParenthesisOpen)
{
if (!IsSurrounded(item))
{
stack.Push(newBracket);
}
}
builder.Append(", ");
builder.Append(newItem);
columnQueue.Dequeue();
if (GetClosingBracket(newItem) == BracketsEnum.ParenthesisClose)
{
if (!IsSurrounded(item))
{
stack.Pop();
if (stack.Count == 0)
{
break;
}
}
}
}
}
}
var query = builder.ToString();
if (query.IndexOf("AS", StringComparison.CurrentCultureIgnoreCase) > 0)
{
var parts = Regex.Split(query, "AS", RegexOptions.IgnoreCase);
rapportColumn.RC_ColumnQuery = parts[0];
rapportColumn.RC_ColumnLabel = parts[1];
}
else
{
rapportColumn.RC_ColumnQuery = query;
}
rapportColumn.Rapport_Id = rapport_id;
rapportColumn.RC_Order = count;
columns.Add(rapportColumn);
}
}
// checks if there is a opening parenthesis in the string
private char GetOpeningBracket(string item)
{
var arr = item.ToCharArray();
foreach (var charr in arr)
{
switch (charr)
{
case BracketsEnum.ParenthesisOpen:
return charr;
default:
continue;
}
}
return '\0';
}
// checks if there is a closing parenthesis in the string
private char GetClosingBracket(string item)
{
var arr = item.ToCharArray();
foreach (var charr in arr)
{
switch (charr)
{
case BracketsEnum.ParenthesisClose:
return charr;
default:
continue;
}
}
return '\0';
}
// checks if there are as much closing as opening parenthesis in the string
private bool IsSurrounded(string item)
{
var stack = new Stack<int>();
var isSurrounded = false;
for (var i = 0; i < item.Length; i++)
{
switch (item[i])
{
case BracketsEnum.ParenthesisOpen:
stack.Push(i);
break;
case BracketsEnum.ParenthesisClose:
var index = stack.Any() ? stack.Pop() : -1;
break;
default:
break;
}
}
return stack.Count <= 0;
}
}
class RapportColumn
{
public int RC_Id { get; set; }
public int Rapport_Id { get; set; }
public string RC_ColumnName { get; set; }
public string RC_ColumnLabel { get; set; }
public string RC_ColumnQuery { get; set; }
public int RC_Order { get; set; }
public bool RC_checked { get; set; }
}
class SqlClauseEnum
{
public const string FROM = "FROM";
public const string WHERE = "WHERE";
public const string GROUP_BY = "GROUP BY";
public const string HAVING = "HAVING";
public const string SELECT = "SELECT";
public const string ORDER_BY = "ORDER BY";
public const string LIMIT = "LIMIT";
}
class BracketsEnum
{
public const char ParenthesisOpen = '(';
public const char ParenthesisClose = ')';
}
</code></pre>
| [] | [
{
"body": "<h2>Bugs</h2>\n\n<p>Performance doesn't matter when the results aren't correct. First make it work <em>goed</em>, then make it work <em>snel</em>! ;)</p>\n\n<p>Your approach to parsing SQL queries is broken. You can't just split on commas or check for the presence of keywords or parenthesis like that. Column and table names can contain keywords, and when quoted, can also contain commas and parenthesis. The same goes for strings. Here are a few queries that produce incorrect results:</p>\n\n<ul>\n<li><code>SELECT smell FROM fromage</code> - note the <code>from</code> in <code>fromage</code>.</li>\n<li><code>SELECT passport FROM items</code> - note the <code>as</code> in <code>passport</code>.</li>\n<li><code>SELECT `foo,bar` FROM table</code> - this should produce a single column, not two.</li>\n<li><code>SELECT IF(condition, '1) success', '2) failure') FROM table</code> - likewise, a single column, not two.</li>\n</ul>\n\n<hr>\n\n<p>There's another bug: <code>columns</code> isn't cleared, so calling <code>GetRapportColumnsList</code> twice in a row produces incorrect results. Another problem is that, because <code>columns</code> is returned directly, a caller that modifies its results affects the results of any other caller as well.</p>\n\n<h2>Other notes</h2>\n\n<ul>\n<li>Instead of letting <code>AddColumnStringsToQueue</code> and <code>CreateColumns</code> store their results in instance fields, I would let them return their results instead. I'd also modify <code>CreateColumns</code> to take the column parts queue as a parameter. This makes the dependency between them more obvious, and makes it more difficult to use them incorrectly (such as calling them in the wrong order). There doesn't seem to be any reason to keep <code>columns</code> around after <code>GetRapportColumnsList</code> returns anyway.</li>\n<li>With the above change, <code>RapportService</code> has become stateless, and so the parsing methods might as well be made <code>static</code>. They're 'pure' functions whose outputs only depend on their inputs.</li>\n<li>Why use a queue instead of passing an array or list, and iterating it with foreach?</li>\n<li><code>GetOpeningBracket(input)</code> can be replaced by <code>input.Contains(BracketsEnum.ParenthesisOpen)</code>. The same goes for <code>GetClosingBracket</code>.</li>\n<li>The name <code>IsSurrounded</code> is somewhat misleading: that method actually checks if the parenthesis in the input are properly balanced - and an input without parenthesis is also balanced.</li>\n<li>Personally I wouldn't add an <code>Enum</code> suffix to a class name, especially since they're not enums. I would also put those constants in a single place, not spread across two classes.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-07T15:46:34.153",
"Id": "209219",
"ParentId": "209211",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "209219",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-07T14:11:55.893",
"Id": "209211",
"Score": "3",
"Tags": [
"c#",
"sql",
"parsing"
],
"Title": "Generating report columns from SQL query"
} | 209211 |
<p>I am quite bad at data manipulation and after a lot of time I was finally able to get it working how I wanted. The thing is I don't like all the delete operations, I think the code can be a lot cleaner and the runtime seems somewhat slow on a lot of data. Code readability is very important here but it needs to be small, contained and fast. ES6+ i welcome and of course so are tips and general information.</p>
<h2>Input Data:</h2>
<pre><code>{
agency: "",
agent: "",
agent_email: "",
agent_phone: "",
date_of_birth: "2007-05-30",
delivery_address: "address - 1",
delivery_city: "city - 1",
delivery_country: "PE",
delivery_state: "state - 1",
delivery_zipcode: "zip_code - 1",
facebook: "",
instagram: "",
name: "Dustin Peter",
primary_email: "wagnerpeter@bailey-schroeder.example.com",
primary_phone_number: "+31622064234",
residential_address: "address - 0",
residential_city: "city - 0",
residential_country: "LC",
residential_state: "state - 0",
residential_zipcode: "zip_code - 0",
secondary_email: "garzajustin@vasquez.example.com",
secondary_phone_number: "+39349330249",
shoe_size: "38"
snapchat: "",
twitter: "",
url: "",
youtube: "",
}
</code></pre>
<h2>End Result:</h2>
<p><strong>Data Set 1:</strong></p>
<pre><code>{
name: "Dustin Peter",
primary_email: "wagnerpeter@bailey-schroeder.example.com",
primary_phone_number: "+31622064234",
}
</code></pre>
<p><strong>Data Set 2:</strong></p>
<pre><code>{
date_of_birth: "2007-05-30",
delivery_address: {
address: "address - 1",
city: "city - 1",
country: "PE",
state: "state - 1",
zip_code: "zip_code - 1",
}
residential_address: {
address: "address - 0",
city: "city - 0",
country: "LC",
state: "state - 0",
zip_code: "zip_code - 0",
}
secondary_email: "garzajustin@vasquez.example.com",
secondary_phone_number: "+39349330249",
shoe_size: "38",
}
</code></pre>
<h2>My Working Code:</h2>
<pre><code>const dataSet1 = {
name: data.name,
primary_email: data.primary_email,
primary_phone_number: data.primary_phone_number,
};
const dataSet2 = {};
Object.keys(data).forEach((prop) => {
if (data[prop]) { dataSet2[prop] = data[prop]; }
});
dataSet2.residential_address = {
address: dataSet2.residential_address,
city: dataSet2.residential_city,
country: dataSet2.residential_country,
state: dataSet2.residential_state,
zip_code: dataSet2.residential_zipcode,
};
dataSet2.delivery_address = {
address: dataSet2.delivery_address,
city: dataSet2.delivery_city,
country: dataSet2.delivery_country,
state: dataSet2.delivery_state,
zip_code: dataSet2.delivery_zipcode,
};
delete dataSet2.name;
delete dataSet2.primary_email;
delete dataSet2.primary_phone_number;
delete dataSet2.residential_city;
delete dataSet2.residential_country;
delete dataSet2.residential_state;
delete dataSet2.residential_zip_code;
delete dataSet2.delivery_city;
delete dataSet2.delivery_country;
delete dataSet2.delivery_state;
delete dataSet2.delivery_zip_code;
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-07T18:29:48.380",
"Id": "404380",
"Score": "0",
"body": "These are not real names, not, and/or email addresses, are they? In the case they are, please delete the question, anonymize that data and post a new one"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-07T21:29:18.210",
"Id": "404398",
"Score": "1",
"body": "Nop, they are random data generated in our server."
}
] | [
{
"body": "<p>You can use <code>Object.entries()</code> and <code>.filter()</code> with <code>RegExp</code> <code>/date|delivery|residential|secondary|shoe/</code> and <code>.test()</code> to filter data from <code>data</code>, create a function expecting property name and optional separator character to concatenate to property name to replace in returned object spread as values passed to second parameter of <code>Object.assign()</code></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const data = {\n agency: \"\",\n agent: \"\",\n agent_email: \"\",\n agent_phone: \"\",\n date_of_birth: \"2007-05-30\",\n delivery_address: \"address - 1\",\n delivery_city: \"city - 1\",\n delivery_country: \"PE\",\n delivery_state: \"state - 1\",\n delivery_zipcode: \"zip_code - 1\",\n facebook: \"\",\n instagram: \"\",\n name: \"Dustin Peter\",\n primary_email: \"wagnerpeter@bailey-schroeder.example.com\",\n primary_phone_number: \"+31622064234\",\n residential_address: \"address - 0\",\n residential_city: \"city - 0\",\n residential_country: \"LC\",\n residential_state: \"state - 0\",\n residential_zipcode: \"zip_code - 0\",\n secondary_email: \"garzajustin@vasquez.example.com\",\n secondary_phone_number: \"+39349330249\",\n shoe_size: \"38\",\n snapchat: \"\",\n twitter: \"\",\n url: \"\",\n youtube: \"\"\n}\n\nlet [filters, filtered] = [\n ['date', 'delivery', 'residential', 'secondary', 'shoe']\n, (data, props) => Object.entries(data)\n .filter(([key, value]) =>\n new RegExp(props.join`|`)\n .test(key))\n];\n \nconst handleProps = (prop, r = '', props = filtered(data, filters)) => \n ([...p] = props.filter(([key, value]) => \n new RegExp(prop).test(key)).map(([key, value]) => \n (r ? {[key.replace(new RegExp(prop + r), '')]: value} : value))\n , r ? p : p.pop());\n\nconst dataSet2 = {\n date_of_birth:handleProps('date_of_birth')\n, delivery_address: Object.assign({}, ...handleProps('delivery', '_'))\n, residential_address: Object.assign({}, ...handleProps('residential', '_'))\n, secondary_email: handleProps('secondary_email')\n, secondary_phone_number: handleProps('secondary_phone_number')\n, shoe_size: handleProps('shoe_size')\n};\n \nconsole.log(dataSet2);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-07T18:36:42.600",
"Id": "209229",
"ParentId": "209214",
"Score": "3"
}
},
{
"body": "<p>What do you think about this?</p>\n\n<ol>\n<li>Define a regular expression to extract <code>delivery_address</code> and <code>residential_address</code>.</li>\n<li>Define <code>dataSet1</code> and <code>dataSet2</code> so you can fill them later.</li>\n<li>Store <em>primary values</em> into <code>dataSet1</code> and delete them from <code>data</code>, since you don’t need them anymore.</li>\n<li>Loop through the properties of the <code>data</code> object and store non-empty values into <code>dataSet2</code>. If the property matches the regular expression, store its value in the appropriate address sub-object. Otherwise store it <em>directly</em> to <code>dataSet2</code>.</li>\n</ol>\n\n<p><strong>Ready example:</strong></p>\n\n<pre><code>const addr_rgxp = /^(delivery|residential)_(\\w+)$/,\n dataSet1 = {},\n dataSet2 = {\n residential_address: {},\n delivery_address: {}\n };\n\nfor (let prop of ['name', 'primary_email', 'primary_phone_number']) {\n dataSet1[prop] = data[prop];\n delete data[prop];\n}\n\nfor (let prop in data) {\n if (data[prop]) {\n let m = prop.match(addr_rgxp);\n if (m) {\n let addr_type = m[1] + '_address';\n dataSet2[addr_type][m[2]] = data[prop];\n } else {\n dataSet2[prop] = data[prop];\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T04:18:29.623",
"Id": "209587",
"ParentId": "209214",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-07T14:32:44.620",
"Id": "209214",
"Score": "3",
"Tags": [
"javascript",
"ecmascript-6"
],
"Title": "Data formatting, splitting objects & deleting key's/values"
} | 209214 |
<p>I am trying to assign <code>0</code> to random cells in a one dimensional <code>pandas.DataFrame</code>.
The below code is the best way I could think of doing this, however I believe there may be a neater approach to this problem.</p>
<pre><code>import numpy as np
import pandas as pd
from random import randint
df = pd.DataFrame(np.random.randint(20, size=(10, 1)), columns=list('A'))
col_size = len(df.columns)
row_size = len(df.index)
df[df.columns[randint(0, col_size-1)]][randint(0, row_size-1)] = 0
</code></pre>
<p>Could someone please review and suggest if this is a good approach or there are better ways to do this?</p>
| [] | [
{
"body": "<p>Right now, you are only setting a single cell to zero. If this is what you want, then your solution works well. However, if you want to randomly set cells to be 0, then the solutions below might be better.\nFor an arbitrary dimensional df:</p>\n\n<pre><code># Create Random Mask\nrand_zero_one_mask = np.random.randint(2, size=df.shape)\n# Fill df with 0 where mask is 0\ndf = df.where(rand_zero_one_mask==0, 0)\n</code></pre>\n\n<p>Note: <a href=\"https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.where.html\" rel=\"nofollow noreferrer\">df.where</a> is not to be confused with <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html\" rel=\"nofollow noreferrer\">np.where</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-07T21:09:10.570",
"Id": "209241",
"ParentId": "209222",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "209241",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-07T16:30:30.793",
"Id": "209222",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"random",
"pandas"
],
"Title": "Assigning zero to random cells in a pandas.DataFrame"
} | 209222 |
<p>I'm trying to build a complex Newton's method. I've submitted a PR <a href="https://github.com/boostorg/math/pull/165/files" rel="nofollow noreferrer">here</a>, where you can see the documentation and tests, as well as get a compiling example. I'd appreciate y'alls help reducing the workload on the maintainer.</p>
<p>This uses the idea that if x<sub>n</sub> converges to x*, then f(x*) = 0 whenever f' is continuous at x*. If f'(x<sub>n</sub>) = 0 at some point, it resorts to Muller's method. </p>
<pre><code>#ifndef BOOST_NO_CXX11_AUTO_DECLARATIONS
/*
* Why do we set the default maximum number of iterations to the number of digits in the type?
* Because for double roots, the number of digits increases linearly with the number of iterations,
* so this default should recover full precision even in this somewhat pathological case.
* For isolated roots, the problem is so rapidly convergent that this doesn't matter at all.
*/
template<class Complex, class F>
Complex complex_newton(F g, Complex guess, int max_iterations=std::numeric_limits<typename Complex::value_type>::digits)
{
typedef typename Complex::value_type Real;
using std::norm;
using std::abs;
using std::max;
// z0, z1, and z2 cannot be the same, in case we immediately need to resort to Muller's Method:
Complex z0 = guess + Complex(1,0);
Complex z1 = guess + Complex(0,1);
Complex z2 = guess;
do {
auto pair = g(z2);
if (norm(pair.second) == 0)
{
// Muller's method. Notation follows Numerical Recipes, 9.5.2:
Complex q = (z2 - z1)/(z1 - z0);
auto P0 = g(z0);
auto P1 = g(z1);
Complex qp1 = static_cast<Complex>(1)+q;
Complex A = q*(pair.first - qp1*P1.first + q*P0.first);
Complex B = (static_cast<Complex>(2)*q+static_cast<Complex>(1))*pair.first - qp1*qp1*P1.first +q*q*P0.first;
Complex C = qp1*pair.first;
Complex rad = sqrt(B*B - static_cast<Complex>(4)*A*C);
Complex denom1 = B + rad;
Complex denom2 = B - rad;
Complex correction = (z1-z2)*static_cast<Complex>(2)*C;
if (norm(denom1) > norm(denom2))
{
correction /= denom1;
}
else
{
correction /= denom2;
}
z0 = z1;
z1 = z2;
z2 = z2 + correction;
}
else
{
z0 = z1;
z1 = z2;
z2 = z2 - (pair.first/pair.second);
}
// See: https://math.stackexchange.com/questions/3017766/constructing-newton-iteration-converging-to-non-root
// If f' is continuous, then convergence of x_n -> x* implies f(x*) = 0.
// This condition approximates this convergence condition by requiring three consecutive iterates to be clustered.
Real tol = max(abs(z2)*std::numeric_limits<Real>::epsilon(), std::numeric_limits<Real>::epsilon());
bool real_close = abs(z0.real() - z1.real()) < tol && abs(z0.real() - z2.real()) < tol && abs(z1.real() - z2.real()) < tol;
bool imag_close = abs(z0.imag() - z1.imag()) < tol && abs(z0.imag() - z2.imag()) < tol && abs(z1.imag() - z2.imag()) < tol;
if (real_close && imag_close)
{
return z2;
}
} while(max_iterations--);
// The idea is that if we can get abs(f) < eps, we should, but if we go through all these iterations
// and abs(f) < sqrt(eps), then roundoff error simply does not allow that we can evaluate f to < eps
// This is somewhat awkward as it isn't scale invariant, but using the Daubechies coefficient example code,
// I found this condition generates correct roots, whereas the scale invariant condition discussed here:
// https://scicomp.stackexchange.com/questions/30597/defining-a-condition-number-and-termination-criteria-for-newtons-method
// allows nonroots to be passed off as roots.
auto pair = g(z2);
if (abs(pair.first) < sqrt(std::numeric_limits<Real>::epsilon()))
{
return z2;
}
return {std::numeric_limits<Real>::quiet_NaN(),
std::numeric_limits<Real>::quiet_NaN()};
}
#endif
</code></pre>
<p>Usage:</p>
<pre><code>boost::math::tools::polynomial<std::complex<double>> p{{1,0}, {0, 0}, {1,0}};
std::complex<double> guess{1,1};
boost::math::tools::polynomial<std::complex<double>> p_prime = p.prime();
auto f = [&](std::complex<double> z) { return std::make_pair<std::complex<double>, std::complex<double>>(p(z), p_prime(z)); };
std::complex<double> root = complex_newton(f, guess);
</code></pre>
<p>For a more intense example usage, see <a href="https://github.com/boostorg/math/blob/37336e2372e02fa0d2a8ced2313f6e6cbb21337e/example/daubechies_coefficients.cpp" rel="nofollow noreferrer">here</a></p>
| [] | [
{
"body": "<p>I can't see too much that needs improving. I'd suggest that the correction logic be simplified to:</p>\n\n<pre><code> Complex denom1 = B + rad,\n denom2 = B - rad,\n correction = (z1-z2)*static_cast<Complex>(2)*C,\n denom_corr;\n if (norm(denom1) > norm(denom2))\n denom_corr = denom1;\n else\n denom_corr = denom2;\n\n z0 = z1;\n z1 = z2;\n z2 += correction/denom_corr;\n</code></pre>\n\n<p>Elsewhere, combine your types and use commas where there are multiple variable declarations. It's a stylistic choice, but I don't like to repeat myself.</p>\n\n<p>And this:</p>\n\n<pre><code>z2 = z2 - (pair.first/pair.second);\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>z2 -= pair.first/pair.second;\n</code></pre>\n\n<p>Order of operations still applies so you don't need parens, and use combined operation+assignment.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-07T18:33:29.397",
"Id": "209228",
"ParentId": "209224",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "209228",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-07T17:08:43.857",
"Id": "209224",
"Score": "4",
"Tags": [
"c++",
"numerical-methods",
"complex-numbers"
],
"Title": "Complex Newton's Method"
} | 209224 |
<p>I have a data frame like:</p>
<pre><code>import datetime as dt
import pandas as pd
s = pd.Series(
range(8),
pd.to_datetime(
[
'20130101 10:34',
'20130101 10:34:08',
'20130101 10:34:08',
'20130101 10:34:15',
'20130101 10:34:28',
'20130101 10:34:54',
'20130101 10:34:55',
'20130101 10:35:12'
]
)
)
df = s.to_frame()
df = df.reset_index()
df = df.rename(columns=
{
0 : 'value',
'index' : 'start'
}
)
df['ID'] = [1,2,1,2,1,2,1,2]
sec = dt.timedelta(seconds=30)
df['end'] = df['start'].map(lambda t: t + sec)
</code></pre>
<p>.</p>
<pre><code> df
start val ID end
0 2013-01-01 10:34:00 0 1 2013-01-01 10:34:30
1 2013-01-01 10:34:08 1 2 2013-01-01 10:34:38
2 2013-01-01 10:34:08 2 1 2013-01-01 10:34:38
3 2013-01-01 10:34:15 3 2 2013-01-01 10:34:45
4 2013-01-01 10:34:28 4 1 2013-01-01 10:34:58
5 2013-01-01 10:34:54 5 2 2013-01-01 10:35:24
6 2013-01-01 10:34:55 6 1 2013-01-01 10:35:25
7 2013-01-01 10:35:12 7 2 2013-01-01 10:35:42
</code></pre>
<p>I have to sum the values of each ID for all rows between the start and end time stamps.
To be accurate my result should have this meaning:</p>
<pre><code>p_ = []
#CICLE IS a problem
for row in range(len(df)):
p_.append(
#USING LOC IS A PROBLEM
df.loc[
(df['start'] >= df['start'][row]) &
(df['start'] <= df['end'][row]) &
(df['ID'] == df['ID'][row])
]
['value']\
.sum()
)
df
start val ID end sum_of_values for_ID_in_time_period
0 2013-01-01 10:34:00 0 1 2013-01-01 10:34:30 6
1 2013-01-01 10:34:08 1 2 2013-01-01 10:34:38 4
2 2013-01-01 10:34:08 2 1 2013-01-01 10:34:38 6
3 2013-01-01 10:34:15 3 2 2013-01-01 10:34:45 3
4 2013-01-01 10:34:28 4 1 2013-01-01 10:34:58 10
5 2013-01-01 10:34:54 5 2 2013-01-01 10:35:24 12
6 2013-01-01 10:34:55 6 1 2013-01-01 10:35:25 6
7 2013-01-01 10:35:12 7 2 2013-01-01 10:35:42 7
</code></pre>
<p>Instead of the <code>for</code> cycle and the <code>loc</code> I would like to ask for help to transform this problem to some kind of <code>groupby</code>, <code>map</code> solution because my real data set is hardly fits into memory and I have to come up with something faster.
I have tried to use:</p>
<pre><code>df.groupby(
[
df.start.map(lambda t: t.minute),
'ID'
]
)[['value']]\
.sum()
</code></pre>
<p>but this transforms my result something what is not depending on the end column.</p>
<pre><code> value
start ID
34 1 12
2 9
35 2 7
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-07T17:30:27.303",
"Id": "209225",
"Score": "1",
"Tags": [
"python",
"pandas"
],
"Title": "Groupby Count on user defined time periods pandas"
} | 209225 |
<p><strong>About</strong></p>
<p>MobX is a tested library that makes state management simple and scalable by transparently applying functional reactive programming (TFRP).</p>
<p><strong>Links</strong></p>
<ul>
<li><a href="https://github.com/mobxjs/mobx" rel="nofollow noreferrer">Github</a></li>
<li><a href="https://mobx.js.org/" rel="nofollow noreferrer">Api Documentation</a></li>
<li><a href="https://github.com/mobxjs/mobx-react-devtools" rel="nofollow noreferrer">MobX-React Devtools</a></li>
</ul>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-07T19:04:57.853",
"Id": "209231",
"Score": "0",
"Tags": null,
"Title": null
} | 209231 |
Functional reactive programming library in JavaScript. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-07T19:04:57.853",
"Id": "209232",
"Score": "0",
"Tags": null,
"Title": null
} | 209232 |
<p>Although I should know better, I wrote my own linked list implementation in C. </p>
<p>My goal was to make it a true generic collection, with no need to modify the structure being listed. I only implemented <code>push</code>, <code>pop</code>, <code>peek</code>, <code>append</code>, <code>size</code>, and <code>next</code>. This is sufficient for implementing stacks or queues. </p>
<p>I welcome feedback, suggestions for improvement, use cases that break it. I'd love an idea for a compiler-independent way of returning a value from <code>l0_size()</code>.</p>
<pre><code>#ifndef L0__H_
#define L0__H_
//# LIST0 - A Generic Linked-List Header-only Library for C
#include <stdlib.h> //for calloc/free
/* PRIVATE helpers, start with l0__ (double underscore). Here be dragons. */
#define l0__nexta(hd) (void **)((hd)+1) //address of next ptr
#define l0__nextv(hd) (*l0__nexta((hd))) //value of next ptr
#define l0__create(hd, val) (((hd)=calloc(1,sizeof(*(hd))+sizeof((hd))))?*(hd)=(val):(val))
#define l0__gototail(hd) do {} while ((l0_next((hd)))&&((hd)=l0__nextv((hd))))
/* Public Interface */
#define l0_next(head) ((head) ? l0__nextv(head) : NULL)
#define l0_peek(head) (*(head))
#define l0_add(head, value) do { \
if (!(head)) { l0__create((head), value); } \
else { void *save__0l = (head); \
l0__gototail(head); \
void **next__0l = l0__nexta(head); \
l0__create((head), value); \
*next__0l = (head); \
(head) = save__0l; \
} } while (0)
#define l0_push(head, value) do { \
void *rest__0l = (head); \
l0__create((head), value); \
l0__nextv(head) = rest__0l; \
} while (0)
#define l0_pop(head) do { \
void *dead__0l = (head); \
(head) = l0_next(head); \
free(dead__0l); \
} while (0)
#define l0_isempty(head) ((head)==NULL)
#define l0_listof(type) type *
#if defined(___GNUC__) || defined(__clang__)
//return val version. //needs "statement expression" support
#define l0_size(head) ({int len__0l=0; void* head__0l=(head); \
for (; (head); (head)=l0__nextv(head) ) { ++len__0l; } \
(head)=head__0l; len__0l;})
#else
//getter version, pass &int;
#define l0_size(head, sz_out) do { void* head__0l=(head); \
for (*sz_out=0; (head); (head)=l0__nextv(head) ) { (*sz_out)+=1; } \
(head)=head__0l; \
} while (0)
#endif
#endif
</code></pre>
<p>Test program:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "l0.h"
int main(int argc, const char* argv[]) {
typedef l0_listof(float) float_list;
float_list listp = NULL;
// Initial list is empty
assert(l0_size(listp) == 0);
assert(l0_isempty(listp));
//add an element - it is there
l0_add(listp, 1);
assert(l0_size(listp) == 1);
assert(!l0_isempty(listp));
assert(l0_peek(listp) == 1.0);
//add a second element - the list grows, the head does not change
l0_add(listp, 2.1f);
assert(l0_size(listp) == 2);
assert(!l0_isempty(listp));
assert(l0_peek(listp) == 1.0);
//pop the head - the list shrinks, the head changes
l0_pop(listp);
assert(l0_size(listp) == 1);
assert(!l0_isempty(listp));
assert(l0_peek(listp) == 2.1f);
//pop the head - the list is empty again
l0_pop(listp);
assert(l0_size(listp) == 0);
assert(l0_isempty(listp));
//pop an empty list, no change
l0_pop(listp);
assert(l0_size(listp) == 0);
assert(l0_isempty(listp));
//push onto a list - element is present
l0_push(listp, 3.3f);
assert(l0_size(listp) == 1);
assert(!l0_isempty(listp));
assert(l0_peek(listp) == 3.3f);
//push again onto a list - list grows, new element is front
l0_push(listp, 4.4f);
assert(l0_size(listp) == 2);
assert(!l0_isempty(listp));
assert(l0_peek(listp) == 4.4f);
//push again onto a list - list grows, new element is front
l0_push(listp, 5.5f);
assert(l0_size(listp) == 3);
assert(!l0_isempty(listp));
assert(l0_peek(listp) == 5.5);
//walk the list
float expected[] = {5.5f, 4.4f, 3.3f};
int n=0;
for (float_list i = listp; i!=NULL; i=l0_next(i))
{
printf("%f ",*i);
assert(*i == expected[n++]);
}
printf("\n");
//pop the head - the list shrinks, the head changes
l0_pop(listp);
assert(l0_size(listp) == 2);
assert(!l0_isempty(listp));
assert(l0_peek(listp) == 4.4f);
//arbitrary things can be in lists
typedef struct {
int n;
float f;
} blob;
#define BLOB(name, n) blob name = {n,n}
#define BLOBEQ(a,b) (a.n==b.n && a.f == b.f)
l0_listof(blob) sl;
assert(l0_size(sl)==0);
BLOB(one,1);
BLOB(two,2);
BLOB(three,3);
// Initial list is empty
assert(l0_size(sl) == 0);
assert(l0_isempty(sl));
//add an element - it is there
l0_add(sl, one);
assert(l0_size(sl) == 1);
assert(!l0_isempty(sl));
assert(BLOBEQ(l0_peek(sl), one));
//push onto a list - list grows, new element is front
l0_push(sl, two);
assert(l0_size(sl) == 2);
assert(!l0_isempty(sl));
assert(BLOBEQ(l0_peek(sl), two));
//add to end - the list grows, the head does not change
l0_add(sl, three);
assert(l0_size(sl) == 3);
assert(!l0_isempty(sl));
assert(BLOBEQ(l0_peek(sl), two));
//pop the head - the list shrinks, the head changes
l0_pop(sl);
assert(l0_size(sl) == 2);
assert(!l0_isempty(sl));
assert(BLOBEQ(l0_peek(sl), one));
//pop the head - the list shrinks, the head changes
l0_pop(sl);
assert(l0_size(sl) == 1);
assert(!l0_isempty(sl));
assert(BLOBEQ(l0_peek(sl), three));
//pop the head - the list is empty again
l0_pop(sl);
assert(l0_size(sl) == 0);
assert(l0_isempty(sl));
printf(" PASS! \n");
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-07T19:23:55.053",
"Id": "404386",
"Score": "1",
"body": "Sigh. Stuff like `l0__create` makes me sad. This is macro-heavy, and thus fairly unmaintainable. What's your justification for all of the macros? You know you can define entire functions in C in a header file, right? Just ensure that they're declared `static`, and then you can write sane code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-07T19:48:21.420",
"Id": "404389",
"Score": "1",
"body": "Macros are the only way to make type-safe generics in C. A function needs to accept a specific type. Which would require either casts to void, or macro wrappers to define type-specific versions. I think this is safer and easier to use"
}
] | [
{
"body": "<h3>API design</h3>\n\n<blockquote>\n <p>I only implemented <code>push</code>, <code>pop</code>, <code>peek</code>, <code>append</code>, <code>size</code>, and <code>next</code>. This is sufficient for implementing stacks or queues.</p>\n</blockquote>\n\n<p>I find this API confusing:</p>\n\n<ul>\n<li>What's the difference between <code>push</code> and <code>append</code>?</li>\n<li>What is <code>next</code>?</li>\n</ul>\n\n<p>I think it would be better to implement a list Abstract Data Type with methods that are perfectly clear and intuitive. If you also want to provide stacks and queues, you could provide specialized APIs for those, and implement them in terms of the lower list, which will be a hidden implementation detail, and you can save users from any confusion.</p>\n\n<p>From a list I would expect methods <code>insert</code>, <code>append</code>, <code>remove</code>, <code>size</code>, <code>isEmpty</code>, <code>first</code>, <code>last</code>.</p>\n\n<p>A stack could be implemented on top of that, with methods <code>push</code>, <code>pop</code>, <code>isEmpty</code>, which would internally use a list, without exposing other methods of the list that may confuse users. Same thing for a queue.</p>\n\n<h3>Implementation</h3>\n\n<p>The implementation of the list is entirely in macros.\nAs a commenter pointed out, this is considered by some people a <a href=\"https://stackoverflow.com/questions/14041453/why-are-preprocessor-macros-evil-and-what-are-the-alternatives/14041847#14041847\">nightmare to maintain</a>.\nYou responded that <em>\"macros are the only way to make type-safe generics in C\"</em>.\nWhich is true, but I believe you can take a sort of hybrid approach,\nseparating the essential generic code that can only be implemented with macros,\nand other parts that can be implemented in regular C.</p>\n\n<p>In particular, the only part that needs to be generic is the value stored in list nodes.\nThe operations on the nodes, the behavior of the list is independent from the payload in the nodes.\nTherefore, I believe you can implement the list operations in regular C,\nand limit the use of macros for the nodes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T19:30:34.503",
"Id": "404678",
"Score": "0",
"body": "I take your point about naming and separation of concerns. Isn't `next` a fairly standard name for the next element in a list? However, I'm not happy with \"MACROS BAD\" as a criticism. With the exception of `create`, which I'm happy to separate into `allocate` and `initialize` components, what is unmaintainable or nightmarish about these macros, which are broken down into simple sequences of steps?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T19:53:54.453",
"Id": "404680",
"Score": "0",
"body": "For \"next\" to make sense, it needs a reference point: \"next\" from what? I don't know what that means in the context of a list. What's wrong with macros? Lot's of things, as widely known, I don't understand why you ask... https://stackoverflow.com/a/14041847/641955"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T20:46:25.920",
"Id": "404683",
"Score": "0",
"body": "Honestly, every example in the accepted answer there is terrible. Yes, you can write terrible macros with unintended side effects. I have done my best to avoid doing that, and to write ones that are hard to abuse. I know I need to fix `create`. Are there other actual use cases that will break my code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T08:55:28.703",
"Id": "404749",
"Score": "0",
"body": "@AShelly I rephrased my remark about macros. Some people consider them a nightmare to maintain, myself included. You are not one of those people, and that's fine. Do note that I acknowledged the necessity in your use case, so I cannot recommend to remove completely, I only recommend to make it as minimal as possible. If you don't agree that by doing so your code will become more maintainable, that's fine as well. It's up to you which recommendations you find useful and actually put to use and which you don't. If you think my answer contains bad recommendation, then I suggest to downvote it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T14:18:26.863",
"Id": "209270",
"ParentId": "209233",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-07T19:11:53.900",
"Id": "209233",
"Score": "1",
"Tags": [
"c",
"linked-list",
"generics"
],
"Title": "Generic Linked List (header-only and non-intrusive)"
} | 209233 |
<p>I'm working with C#, and I have working code where I repeated same code every line, and that's because I'm creating list, conversions, extracting data, etc.</p>
<p>I have multiple <code>foreach</code> clauses, multiple <code>lists</code>, multiple conversions of <code>list</code> to <code>datatables</code>. My question is, what can I do to refactor this in order to have clean code?</p>
<pre><code> private void BtnLoadReport_Click(object sender, EventArgs e)
{
var db = new SQLDataMgr();
List<string> DesignStatusList = new List<string>();
List<string> ShopStatusList = new List<string>();
List<string> CustomerTypeList = new List<string>();
List<string> CustomerList = new List<string>();
List<string> ResellerList = new List<string>();
List<string> StateList = new List<string>();
List<string> ProjectManagerList = new List<string>();
List<string> SalesRepresentativeList = new List<string>();
var checkedDesignStatus = cboDesignStatus.CheckBoxItems.Where(x => x.Checked);
var checkedShopStatus = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedCustomerType = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedCustomer = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedReseller = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedState = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedProjectManager = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
var checkedSalesRepresentative = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
foreach (var i in checkedDesignStatus)
{
DesignStatusList.Add(i.Text);
}
foreach (var i in checkedShopStatus)
{
ShopStatusList.Add(i.Text);
}
foreach (var i in checkedCustomerType)
{
CustomerTypeList.Add(i.Text);
}
foreach (var i in checkedCustomer)
{
CustomerList.Add(i.Text);
}
foreach (var i in checkedReseller)
{
ResellerList.Add(i.Text);
}
foreach (var i in checkedState)
{
StateList.Add(i.Text);
}
foreach (var i in checkedProjectManager)
{
ProjectManagerList.Add(i.Text);
}
foreach (var i in checkedSalesRepresentative)
{
SalesRepresentativeList.Add(i.Text);
}
DataTable designStatusParameters = ToStringDataTable(DesignStatusList);
DataTable shopStatusParameters = ToStringDataTable(ShopStatusList);
DataTable customerTypeParameters = ToStringDataTable(CustomerTypeList);
DataTable customerParameters = ToStringDataTable(CustomerList);
DataTable resellerParameters = ToStringDataTable(ResellerList);
DataTable stateParameters = ToStringDataTable(StateList);
DataTable projectManagerParameters = ToStringDataTable(ProjectManagerList);
DataTable salesRepresentativerParameters = ToStringDataTable(SalesRepresentativeList);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T00:31:35.530",
"Id": "404418",
"Score": "1",
"body": "Welcome to Code Review! Please tell us, what does this code accomplish? Also make that the title of the question — see [ask]. Furthermore, you should ensure that you include enough context so that we can make sense of this code and give you good advice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T08:00:18.037",
"Id": "404445",
"Score": "0",
"body": "(Please specify in every code you create what it is to accomplish, using the best mechanisms provided by the language or development environment of choice.)"
}
] | [
{
"body": "<p>First step is to look at the repeated code then copy an single into a method.\nIn this case a could method name would seem to be <code>CreateDataTable</code>.</p>\n\n<p>What are the commonalities?</p>\n\n<ul>\n<li>A <code>ComboBox</code> that has checked items.</li>\n<li>Get an <code>IQueryable</code> or <code>IEnumerable</code> depending on which is returned by the where clause</li>\n<li>Creates a list of the text value from each checked item</li>\n<li>Creates a <code>DataTable</code> using <code>ToStringDataTable(parameters</code></li>\n</ul>\n\n<p>Since the type in and type out is all the same, this makes it much easier to refactor out into a method. The question then is what input and what output?</p>\n\n<p>Input = <code>ComboBox</code>, output = `DataTable'. This give the method signature needed:</p>\n\n<pre><code>DataTable CreateDataTable(ComboBox cbo) {\n}\n</code></pre>\n\n<p>Now put in those lines that are repeated and change the <code>*Status</code> to <code>cbo</code> and instead of assigning the <code>DataTable</code> just <code>return</code> the result of <code>ToStringDataTable(parameters)</code>.</p>\n\n<pre><code>DataTable CreateDataTable(ComboBox cbo) {\n\n var checkedItems = cbo.CheckBoxItems.Where(x => x.Checked);\n List<string> parameterList = new List<string>();\n foreach (var i in checkedItms) {\n parameter.Add(i.Text);\n }\n\n return ToStringDataTable(parameters);\n}\n</code></pre>\n\n<p>Now clean up the original method:</p>\n\n<pre><code>public class Refactor {\n private void BtnLoadReport_Click(object sender, EventArgs e)\n {\n var db = new SQLDataMgr();\n\n var designStatusParameters = CreateDataTable(cboDesignStatus);\n var shopStatusParameters = CreateDataTable(cboShopStatus);\n var customerTypeParameters = CreateDataTable(cboCustomerType);\n var customerParameters = CreateDataTable(cboCustomer);\n var resellerParameters = CreateDataTable(cboReseller);\n var stateParameters = CreateDataTable(cboState);\n var projectManagerParameters = CreateDataTable(cboProjectManager);\n var salesRepresentativeParameters = CreateDataTable(cboSalesRepresentative);\n //Rest of the method\n } \n}\n</code></pre>\n\n<p>This could be further improved by using some additional LINQ chains if the items returned by the where clause supports them.</p>\n\n<p>Example:</p>\n\n<pre><code>List<String> parameters = cbo.CheckBoxItems.Where(x => x.Checked).Select(x => x.Text).ToList();\n</code></pre>\n\n<p>which would simplifying the method even further:</p>\n\n<pre><code>DataTable CreateDataTable(ComboBox cbo) {\n\n List<string> parameterList = List<String> parameters = cbo.CheckBoxItems.Where(x => x.Checked).Select(x => x.Text).ToList();\n\n return ToStringDataTable(parameters);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T00:56:57.803",
"Id": "209251",
"ParentId": "209238",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-07T20:17:01.773",
"Id": "209238",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Creating method to use one foreach instead multiple"
} | 209238 |
<p>I've written a small Python function to check whether a string is a valid IPv4 subnet mask.</p>
<p>It works but maybe it's too convoluted and terse? Or maybe it could be improved / optimised / rewritten in a cleverer way than just to check 1's in a string?..</p>
<p>IsIPv4Address is another function of mine (<strong>EDIT 1</strong>: added it into the question).
I specifically don't want to use any libraries / external functions as this is rather a study in Python :)</p>
<pre><code>def IsIPv4Address(ipAdd):
"""Validate an IPv4 address"""
octets = ipAdd.split(".")
if len(octets) != 4:
return False
for octet in octets:
if not IsInteger(octet):
return False
if int(octet) > 255 or int(octet) < 0:
return False
return True
def IsIPv4Mask(ipMask):
"""Validate an IPv4 subnet mask"""
# Each mask looks like an IPv4 address and must pass the checks
if not IsIPv4Address(ipMask):
return False
ipMaskBinary = ""
ipMaskBinary = ipMaskBinary.join([bin(int(oct))[2:] for oct in ipMask.split(".")])
isBitZero = ipMask[0] == "0"
for bit in ipMaskBinary[1:]:
if bit == "1" and isBitZero:
return False
if bit == "0":
isBitZero = True
return True
</code></pre>
| [] | [
{
"body": "<p><code>IsIPv4Address</code> should pass a value of 3 for <code>maxsplit</code> on your <code>split</code> call.</p>\n\n<p>Most of that function (after the len check) can be condensed to:</p>\n\n<pre><code>return all(IsInteger(o) and 0 <= o < 256 for o in octets)\n</code></pre>\n\n<p>Your <code>IsIPv4Mask</code> should probably be done in a very different manner - rather than string-ifying the octets to binary text, it should convert the words to a single 32-bit integer (as is done everywhere else), for efficiency. At that point, write a loop that</p>\n\n<ul>\n<li>checks the current LSB </li>\n<li>shifts the integer by 1</li>\n<li>loops until the integer is equal to 0</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-07T22:10:42.023",
"Id": "209244",
"ParentId": "209243",
"Score": "3"
}
},
{
"body": "<p>As recommended in PEP 8, the official style guide, <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"noreferrer\">function names should be <code>lower_case_with_underscores</code></a> unless you have a good reason for making an exception.</p>\n\n<p>Functions like this are perfect places to write <a href=\"https://docs.python.org/3/library/doctest.html\" rel=\"noreferrer\">doctests</a>, to explain how the function should behave while providing unit tests at the same time.</p>\n\n<hr>\n\n<p>The <code>IsIPv4Address()</code> function is easy to implement. I would take advantage of the <a href=\"https://docs.python.org/3/library/functions.html#all\" rel=\"noreferrer\"><code>all()</code></a> function with a <a href=\"https://docs.python.org/3/tutorial/classes.html#generator-expressions\" rel=\"noreferrer\">generator expression</a> and a <a href=\"https://docs.python.org/3/reference/expressions.html#comparisons\" rel=\"noreferrer\">double-ended inequality</a>.</p>\n\n<pre><code>def is_ipv4_address(dotquad):\n \"\"\"\n Validate an IPv4 address in dotted-quad notation.\n\n >>> is_ipv4_address(\"1.2.3.4\")\n True\n >>> is_ipv4_address(\"127.0.0.1/8\")\n False\n >>> is_ipv4_address(\"1.2.3.4.5\")\n False\n >>> is_ipv4_address(\"1.2.3\")\n False\n >>> is_ipv4_address(\"1.2.3.256\")\n False\n >>> is_ipv4_address(\"1.2.3.-4\")\n False\n >>> is_ipv4_address(\"fe80::\")\n False\n \"\"\"\n octets = dotquad.split(\".\")\n return len(octets) == 4 and \\\n all(o.isdigit() and 0 <= int(o) < 256 for o in octets)\n</code></pre>\n\n<hr>\n\n<p>The netmask verifier is trickier to write well. You have chosen to use <code>bin()</code> to stringify the 32-bit number. I'd avoid using strings for something that can be done arithmetically, since string manipulation is relatively inefficient.</p>\n\n<p>Furthermore, I'd suggest that instead of writing just a validation function, you may as well write a function to tell you the length of the netmask, since it's nearly the same amount of work, but you can get more useful information that way.</p>\n\n<pre><code>def ipv4_mask_len(dotquad):\n \"\"\"\n Finds the number of bits set in the netmask.\n\n >>> ipv4_mask_len(\"255.255.255.0\")\n 24\n >>> ipv4_mask_len(\"0.0.0.0\")\n 0\n >>> ipv4_mask_len(\"255.255.255.255\")\n 32\n >>> ipv4_mask_len(\"127.0.0.0\")\n Traceback (most recent call last):\n ...\n ValueError: Invalid netmask: 127.0.0.0\n \"\"\"\n if not is_ipv4_address(dotquad):\n raise ValueError(\"Invalid netmask: {0}\".format(dotquad))\n a, b, c, d = (int(octet) for octet in dotquad.split(\".\"))\n mask = a << 24 | b << 16 | c << 8 | d\n\n if mask == 0:\n return 0\n\n # Count the number of consecutive 0 bits at the right.\n # https://wiki.python.org/moin/BitManipulation#lowestSet.28.29\n m = mask & -mask\n right0bits = -1\n while m:\n m >>= 1\n right0bits += 1\n\n # Verify that all the bits to the left are 1's\n if mask | ((1 << right0bits) - 1) != 0xffffffff:\n raise ValueError(\"Invalid netmask: {0}\".format(dotquad))\n return 32 - right0bits\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T15:00:30.377",
"Id": "404469",
"Score": "0",
"body": "You should pass a value for maxsplit so that split can terminate early on degenerate input."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T15:43:56.487",
"Id": "404473",
"Score": "0",
"body": "Thanks @200_success! I knew that string-parsing is not the best solution :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T00:01:04.693",
"Id": "209250",
"ParentId": "209243",
"Score": "7"
}
},
{
"body": "<p>The following code is so very ineffective, yet it will rarely matter, so I prefer it being less lines.</p>\n<pre><code>def is_ipv4_netmask(str):\n ip = ipaddress.IPv4Address(str)\n binmask = bin(int.from_bytes(ip.packed, "big"))\n return bool(re.match('^0b(1*)(0+)$', binmask))\n</code></pre>\n<p>Read properly the IPv4Network, and it's usable for me, so I'm doing the following, which also accepts host-masks in the form of "0.0.0.255" being equal to "255.255.255.0", thus I must let it normalize it to the latter form.</p>\n<pre><code># raises ipaddress.NetmaskValueError for an invalid netmask\ndef normalize_ipv4_mask(mask):\n return str(ipaddress.IPv4Network((0, mask)).netmask)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-20T01:03:45.523",
"Id": "263231",
"ParentId": "209243",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "209250",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-07T21:42:03.163",
"Id": "209243",
"Score": "4",
"Tags": [
"python",
"reinventing-the-wheel",
"ip-address"
],
"Title": "Verify a subnet mask for validity in Python"
} | 209243 |
<p>The task is find by pattern d--m--y---- all occurrences in text, reformat it to yyyy:mm:dd and print it separately from initial text. Actually I done all except formatting. And even in my written code I have some doubts because I just begun to learn this language. Maybe someone would help me and say what's wrong with my code and how to finish that task on a better way. Any comments are appreciated. </p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXLINE 1000
#define CONT 1000000
int getlin(char *, int);
int pickDates(char *, char *);
int isDate(char *, int);
int main()
{
int len;
char line[MAXLINE];
char accum[CONT];
char *dates = malloc(sizeof(char *) * CONT);
while ((len = getlin(line, MAXLINE)) > 0)
strcat(accum, line);
pickDates(dates, accum);
printf("%s\n", dates);
free(dates);
return 0;
}
int getlin(char *s, int lim) {
int i, c, j = 0;
for (i = 0; (c = getchar()) != EOF && c != '\n'; ++i)
if (i < lim - 2)
{
s[j] = c;
++j;
}
if (c == '\n')
{
s[j] = c;
++i;
++j;
}
s[j] = '\0';
return i;
}
int pickDates(char *dates, char *cont)
{
int j = 0;
const char *template = "d--m--y----";
char *date;
int temp_len = strlen(template);
for (int i = 0; i < strlen(cont); i++)
if (cont[i] == template[0] && cont[i+3] == template[3] && cont[i+6] == template[6])
{
date = malloc(sizeof(char) * temp_len);
memcpy(date, &cont[i], temp_len);
if (isDate(date, temp_len))
{
j += 8;
strcat(dates, date);
}
free(date);
}
dates = realloc(dates, sizeof(char) * j);
return 0;
}
int isDate(char *date_str, int len)
{
int i = 0;
int dd = atoi(&date_str[i+1]);
int mm = atoi(&date_str[i+4]);
int yy = atoi(&date_str[i+7]);
char tmp[5] = {'0'};
memset(date_str, 0, len - 3);
date_str = realloc(date_str, sizeof(char) * (len - 3));
if (dd < 32 && dd > 0 && mm < 13 && mm > 0 && yy > 0)
{
sprintf(tmp, "%04d", yy);
strcat(date_str, tmp);
sprintf(tmp, "%02d", mm);
strcat(date_str, tmp);
sprintf(tmp, "%02d", dd);
strcat(date_str, tmp);
return 1;
}
else return -1;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T00:00:39.747",
"Id": "404403",
"Score": "1",
"body": "the posted code produces MANY warnings when run through the compiler. When compiling, always enable the warnings, then fix those warnings. (for `gcc`, at a minimum use: `-Wall -Wextra -Wconversion -pedantic -std=gnu11` ) Note other compilers use different options to produce the same results"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T00:02:37.940",
"Id": "404405",
"Score": "1",
"body": "regarding: `char accum[CONT];` this is a mighty large array to be placing on the stack. Suggest moving to 'file' scope (I.E. outside of any function"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T00:04:36.020",
"Id": "404406",
"Score": "1",
"body": "OT: regarding: `char *dates = malloc(sizeof(char *) * CONT);` when calling any of the heap allocation functions: `malloc` `calloc` `realloc`, always check (!=NULL) the returned value to assure the operation was successful"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T00:06:58.617",
"Id": "404409",
"Score": "1",
"body": "in function: `getlin()` strongly suggest including braces '{' and '}' around the body of the `for()` statement"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T00:12:09.293",
"Id": "404412",
"Score": "0",
"body": "regarding: `strcat(accum, line);` the function `strcat()` searches for a NUL byte, then appends the `line` beginning at the NUL byte. However, the posted code does not set the first byte in `accum[]` to '\\0', so it is unknown where the `line` will actually be appended. This is undefined behavior and must be corrected"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T00:14:19.313",
"Id": "404414",
"Score": "0",
"body": "regarding: `int pickDates(char *dates, char *cont)` The array `dates[]` is defined as an array of pointers, but that is not how it is being defined in the parameter list"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T00:19:09.710",
"Id": "404415",
"Score": "0",
"body": "regarding: `for (int i = 0; i < strlen(cont); i++)` `cont` is a pointer, not the actual array. Suggest: `for (int i = 0; i < strlen(*cont); i++)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T00:23:14.750",
"Id": "404416",
"Score": "0",
"body": "There are other problems with the posted code beside the above comments. However, this should get you started in the right direction"
}
] | [
{
"body": "<p>Whenever declaring a function that you only expect to use in the current file, mark it <code>static</code>.</p>\n\n<p>The (anonymous) user in the comments above is correct to indicate that <code>accum</code> is quite large; however, rather than allocating it statically as a global I'd suggest that it be allocated from the heap (<code>malloc</code>).</p>\n\n<p><code>printf(\"%s\\n\", dates)</code> is equivalent to <code>puts(dates)</code>, but the latter is more efficient.</p>\n\n<p>Having to predeclare variables in C hasn't been needed since the 90s. Do not predeclare variables. Declare them where they're used; i.e.</p>\n\n<pre><code>for (int i = 0;\n</code></pre>\n\n<p>That loop doesn't do what you think it does. You're missing braces. The loop will only apply to the first <code>if</code>.</p>\n\n<pre><code>j += 8\n</code></pre>\n\n<p>Where does <code>8</code> come from? Declare this as a constant. Magic numbers are bad.</p>\n\n<p>It's pointless to have a return value for <code>pickDates</code>, so make it <code>void</code>.</p>\n\n<p><code>date_str</code> in <code>isDate</code> should be a <code>const char *</code> because you shouldn't be modifying it. The same applies to <code>dates</code> in <code>pickDates</code>.</p>\n\n<p>Later, where you have a series of <code>sprintf</code> / <code>strcat</code>, do not use <code>strcat</code>, nor a <code>tmp</code> array. You can write to <code>date_str</code> via a temporary pointer that you increment based on the return value of <code>sprintf</code>.</p>\n\n<p>I suggest inverting this logic:</p>\n\n<pre><code>if (dd < 32 && dd > 0 && mm < 13 && mm > 0 && yy > 0)\n{\n // ...\n return 1;\n}\nelse return -1;\n</code></pre>\n\n<p>to</p>\n\n<pre><code>if (dd < 0 || dd > 31 || mm < 0 || mm > 12 || yy < 0)\n return -1;\n// ...\nreturn 1;\n</code></pre>\n\n<p>Also, if that return value indicates success or failure, you should use a boolean from stdbool.h and use true/false instead of an integer.</p>\n\n<p>This:</p>\n\n<pre><code>int i = 0;\nint dd = atoi(&date_str[i+1]);\nint mm = atoi(&date_str[i+4]);\nint yy = atoi(&date_str[i+7]);\n</code></pre>\n\n<p>doesn't make a whole lot of sense; <code>i</code> might as well not exist and you might as well do</p>\n\n<pre><code>int dd = atoi(date_str + 1),\n mm = atoi(date_str + 4),\n yy = atoi(date_str + 7);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T01:07:47.190",
"Id": "209252",
"ParentId": "209246",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-07T22:50:13.610",
"Id": "209246",
"Score": "2",
"Tags": [
"beginner",
"c",
"datetime"
],
"Title": "Extracting and reformatting dates from text"
} | 209246 |
<p>I would like some feedback for a collection of what I call "vector functionals", by which I mean maps <span class="math-container">\$\ell\colon \mathbb{K}^{n} \to \mathbb{K}\$</span>, where the field <span class="math-container">\$\mathbb{K} = \mathbb{R}\$</span> or <span class="math-container">\$\mathbb{C}\$</span>.</p>
<p>Many of these maps have trivial implementations, but still they are well-defined and must be put into a function <em>somewhere</em>, and they still take time and effort and hence it makes sense to place them into some sort of canonical point of authority, which I am trying to do. In addition, a few of the maps (like the Hoyer sparsity and the Gini coefficient) could use popularizing.</p>
<p>I would like feedback on the following:</p>
<ul>
<li>Is the design clean? Can it be improved? I have a particular antipathy towards the <code>typedef typename std::remove_const<...</code> everywhere, and I'd like some way to make the iterators for the non-modifying functions "const" in some sense.</li>
<li>What other "vector functionals" do you think should be added? Or is the notion of "vector functionals" simply too broad, and this should be split into those functions traditionally found in statistics, split into numerical analysis, split into signal processing?</li>
<li>Have I missed any edge cases? For instance, one common edge case is overflow in <span class="math-container">\$\ell^{p}\$</span> norms. Another is not using Welford's algorithm for computing variance. In particular, I could not find any literature on rapid and numerically stable evaluation of the Gini coefficient.</li>
<li>I checked for generation of avx instructions on godbolt for a few of the functions, but is there anything I'm doing which will prevent generation of the AVX instructions in general?</li>
</ul>
<p>Without further ado, the PR is <a href="https://github.com/boostorg/math/pull/169" rel="nofollow noreferrer">here</a>, the documentation <a href="https://raw.githubusercontent.com/boostorg/math/bce92d78bafc3765df28f757dd9fd814cd680a3f/doc/vector_functionals/vector_functionals.qbk" rel="nofollow noreferrer">here</a>, and the complete code below:</p>
<pre><code>#ifndef BOOST_MATH_TOOLS_VECTOR_FUNCTIONALS_HPP
#define BOOST_MATH_TOOLS_VECTOR_FUNCTIONALS_HPP
#include <algorithm>
#include <iterator>
#include <boost/type_traits.hpp>
#include <boost/assert.hpp>
#include <boost/multiprecision/detail/number_base.hpp>
/*
* A set of tools for computing scalar quantities associated with lists of numbers.
*/
namespace boost{ namespace math{ namespace tools {
template<class ForwardIterator>
auto
mean(ForwardIterator first, ForwardIterator last)
{
typedef typename std::remove_const<typename std::remove_reference<decltype(*std::declval<ForwardIterator>())>::type>::type Real;
BOOST_ASSERT_MSG(first != last, "At least one sample is required to compute the mean.");
Real mu = 0;
Real i = 1;
for(auto it = first; it != last; ++it) {
mu = mu + (*it - mu)/i;
i += 1;
}
return mu;
}
template<class ForwardIterator>
auto
mean_and_population_variance(ForwardIterator first, ForwardIterator last)
{
typedef typename std::remove_const<typename std::remove_reference<decltype(*std::declval<ForwardIterator>())>::type>::type Real;
BOOST_ASSERT_MSG(first != last, "At least one sample is required to compute mean and variance.");
// Higham, Accuracy and Stability, equation 1.6a and 1.6b:
Real M = *first;
Real Q = 0;
Real k = 2;
for (auto it = first + 1; it != last; ++it)
{
Real tmp = *it - M;
Q = Q + ((k-1)*tmp*tmp)/k;
M = M + tmp/k;
k += 1;
}
return std::make_pair(M, Q/(k-1));
}
template<class RandomAccessIterator>
auto median(RandomAccessIterator first, RandomAccessIterator last)
{
size_t num_elems = std::distance(first, last);
BOOST_ASSERT_MSG(num_elems > 0, "The median of a zero length vector is undefined.");
if (num_elems & 1)
{
auto middle = first + (num_elems - 1)/2;
nth_element(first, middle, last);
return *middle;
}
else
{
auto middle = first + num_elems/2 - 1;
nth_element(first, middle, last);
nth_element(middle, middle+1, last);
return (*middle + *(middle+1))/2;
}
}
template<class RandomAccessIterator>
auto absolute_median(RandomAccessIterator first, RandomAccessIterator last)
{
using std::abs;
typedef typename std::remove_const<typename std::remove_reference<decltype(*std::declval<RandomAccessIterator>())>::type>::type RealOrComplex;
size_t num_elems = std::distance(first, last);
BOOST_ASSERT_MSG(num_elems > 0, "The median of a zero-length vector is undefined.");
auto comparator = [](RealOrComplex a, RealOrComplex b) { return abs(a) < abs(b);};
if (num_elems & 1)
{
auto middle = first + (num_elems - 1)/2;
nth_element(first, middle, last, comparator);
return abs(*middle);
}
else
{
auto middle = first + num_elems/2 - 1;
nth_element(first, middle, last, comparator);
nth_element(middle, middle+1, last, comparator);
return (abs(*middle) + abs(*(middle+1)))/abs(static_cast<RealOrComplex>(2));
}
}
// Mallat, "A Wavelet Tour of Signal Processing", equation 2.60:
template<class ForwardIterator>
auto total_variation(ForwardIterator first, ForwardIterator last)
{
using std::abs;
typedef typename std::remove_const<typename std::remove_reference<decltype(*std::declval<ForwardIterator>())>::type>::type Real;
BOOST_ASSERT_MSG(first != last && std::next(first) != last, "At least two samples are required to compute the total variation.");
Real tv = 0;
auto it = first;
Real tmp = *it;
while (++it != last)
{
tv += abs(*it - tmp);
tmp = *it;
}
return tv;
}
// Mallat, equation 10.4 uses the base-2 logarithm.
template<class ForwardIterator>
auto shannon_entropy(ForwardIterator first, ForwardIterator last)
{
typedef typename std::remove_const<typename std::remove_reference<decltype(*std::declval<ForwardIterator>())>::type>::type Real;
using std::log;
Real entropy = 0;
for (auto it = first; it != last; ++it)
{
if (*it != 0)
{
entropy += (*it)*log(*it);
}
}
return -entropy;
}
template<class ForwardIterator>
auto sup_norm(ForwardIterator first, ForwardIterator last)
{
BOOST_ASSERT_MSG(first != last, "At least one value is required to compute the sup norm.");
typedef typename std::remove_const<typename std::remove_reference<decltype(*std::declval<ForwardIterator>())>::type>::type RealOrComplex;
using std::abs;
if constexpr (boost::is_complex<RealOrComplex>::value ||
boost::multiprecision::number_category<RealOrComplex>::value == boost::multiprecision::number_kind_complex)
{
auto it = std::max_element(first, last, [](RealOrComplex a, RealOrComplex b) { return abs(b) > abs(a); });
return abs(*it);
}
else
{
auto pair = std::minmax_element(first, last);
if (abs(*pair.first) > abs(*pair.second))
{
return abs(*pair.first);
}
else
{
return abs(*pair.second);
}
}
}
template<class ForwardIterator>
auto l1_norm(ForwardIterator first, ForwardIterator last)
{
using std::abs;
decltype(abs(*first)) l1 = 0;
for (auto it = first; it != last; ++it)
{
l1 += abs(*first);
}
return l1;
}
template<class ForwardIterator>
auto l2_norm(ForwardIterator first, ForwardIterator last)
{
typedef typename std::remove_const<typename std::remove_reference<decltype(*std::declval<ForwardIterator>())>::type>::type RealOrComplex;
using std::abs;
using std::norm;
using std::sqrt;
using std::is_floating_point;
if constexpr (boost::is_complex<RealOrComplex>::value ||
boost::multiprecision::number_category<RealOrComplex>::value == boost::multiprecision::number_kind_complex)
{
typedef typename RealOrComplex::value_type Real;
Real l2 = 0;
for (auto it = first; it != last; ++it)
{
l2 += norm(*it);
}
Real result = sqrt(l2);
if (!isfinite(result))
{
Real a = sup_norm(first, last);
l2 = 0;
for (auto it = first; it != last; ++it)
{
l2 += norm(*it/a);
}
return a*sqrt(l2);
}
return result;
}
else if constexpr (is_floating_point<RealOrComplex>::value ||
boost::multiprecision::number_category<RealOrComplex>::value == boost::multiprecision::number_kind_floating_point)
{
RealOrComplex l2 = 0;
for (auto it = first; it != last; ++it)
{
l2 += (*it)*(*it);
}
RealOrComplex result = sqrt(l2);
if (!isfinite(result))
{
RealOrComplex a = sup_norm(first, last);
l2 = 0;
for (auto it = first; it != last; ++it)
{
RealOrComplex tmp = *it/a;
l2 += tmp*tmp;
}
return a*sqrt(l2);
}
return result;
}
}
template<class ForwardIterator>
size_t l0_pseudo_norm(ForwardIterator first, ForwardIterator last)
{
typedef typename std::remove_const<typename std::remove_reference<decltype(*std::declval<ForwardIterator>())>::type>::type RealOrComplex;
size_t count = 0;
for (auto it = first; it != last; ++it)
{
if (*it != RealOrComplex(0))
{
++count;
}
}
return count;
}
template<class ForwardIterator>
auto lp_norm(ForwardIterator first, ForwardIterator last, typename std::remove_const<typename std::remove_reference<decltype(*std::declval<ForwardIterator>())>::type>::type p)
{
using std::pow;
using std::is_floating_point;
using std::isfinite;
typedef typename std::remove_const<typename std::remove_reference<decltype(*std::declval<ForwardIterator>())>::type>::type RealOrComplex;
if constexpr (boost::is_complex<RealOrComplex>::value ||
boost::multiprecision::number_category<RealOrComplex>::value == boost::multiprecision::number_kind_complex)
{
BOOST_ASSERT_MSG(p.real() >= 0, "For p < 0, the lp norm is not a norm.");
BOOST_ASSERT_MSG(p.imag() == 0, "For imaginary p, the lp norm is not a norm.");
using std::norm;
decltype(p.real()) lp = 0;
for (auto it = first; it != last; ++it)
{
lp += pow(norm(*it), p.real()/2);
}
auto result = pow(lp, 1/p.real());
if (!isfinite(result))
{
auto a = boost::math::tools::sup_norm(first, last);
decltype(p.real()) lp = 0;
for (auto it = first; it != last; ++it)
{
lp += pow(abs(*it)/a, p.real());
}
result = a*pow(lp, 1/p.real());
}
return result;
}
else if constexpr (is_floating_point<RealOrComplex>::value ||
boost::multiprecision::number_category<RealOrComplex>::value == boost::multiprecision::number_kind_floating_point)
{
BOOST_ASSERT_MSG(p >= 0, "For p < 0, the lp norm is not a norm");
RealOrComplex lp = 0;
for (auto it = first; it != last; ++it)
{
lp += pow(abs(*it), p);
}
RealOrComplex result = pow(lp, 1/p);
if (!isfinite(result))
{
RealOrComplex a = boost::math::tools::sup_norm(first, last);
lp = 0;
for (auto it = first; it != last; ++it)
{
lp += pow(abs(*it)/a, p);
}
result = a*pow(lp, 1/p);
}
return result;
}
else
{
BOOST_ASSERT_MSG(false, "Unable to determine if the input type is real or complex.");
}
}
template<class ForwardIterator>
auto gini_coefficient(ForwardIterator first, ForwardIterator last)
{
typedef typename std::remove_const<typename std::remove_reference<decltype(*std::declval<ForwardIterator>())>::type>::type Real;
BOOST_ASSERT_MSG(first != last && std::next(first) != last, "Computation of the Gini coefficient requires at least two samples.");
std::sort(first, last);
Real i = 1;
Real num = 0;
Real denom = 0;
for (auto it = first; it != last; ++it) {
num += *it*i;
denom += *it;
++i;
}
// If the l1 norm is zero, all elements are zero, so every element is the same.
if (denom == 0)
{
return Real(0);
}
return ((2*num)/denom - i)/(i-2);
}
template<class ForwardIterator>
auto absolute_gini_coefficient(ForwardIterator first, ForwardIterator last)
{
typedef typename std::remove_const<typename std::remove_reference<decltype(*std::declval<ForwardIterator>())>::type>::type RealOrComplex;
BOOST_ASSERT_MSG(first != last && std::next(first) != last, "Computation of the Gini coefficient requires at least two samples.");
std::sort(first, last, [](RealOrComplex a, RealOrComplex b) { return abs(b) > abs(a); });
decltype(abs(*first)) i = 1;
decltype(abs(*first)) num = 0;
decltype(abs(*first)) denom = 0;
for (auto it = first; it != last; ++it)
{
decltype(abs(*first)) tmp = abs(*it);
num += tmp*i;
denom += tmp;
++i;
}
// If the l1 norm is zero, all elements are zero, so every element is the same.
if (denom == 0)
{
decltype(abs(*first)) zero = 0;
return zero;
}
return ((2*num)/denom - i)/(i-2);
}
// The Hoyer sparsity measure is defined in:
// https://arxiv.org/pdf/0811.4706.pdf
template<class ForwardIterator>
auto hoyer_sparsity(const ForwardIterator first, const ForwardIterator last)
{
using std::abs;
using std::sqrt;
BOOST_ASSERT_MSG(first != last, "Computation of the Hoyer sparsity requires at least one sample.");
decltype(abs(*first)) l1 = 0;
decltype(abs(*first)) l2 = 0;
decltype(abs(*first)) n = 0;
for (auto it = first; it != last; ++it)
{
decltype(abs(*first)) tmp = abs(*it);
l1 += tmp;
l2 += tmp*tmp;
n += 1;
}
decltype(abs(*first)) rootn = sqrt(n);
return (rootn - l1/sqrt(l2) )/ (rootn - 1);
}
}}}
#endif
</code></pre>
| [] | [
{
"body": "<p>I think it would be interesting to have such a collection of tools be standardized.</p>\n\n<p>However, it will require a bit more thinking. I would not want to use these tools as they are now.</p>\n\n<h1><code>mean()</code></h1>\n\n<p>I wrote this simple test program:</p>\n\n<pre><code>#include <vector_functionals.hpp>\n#include <iostream>\n#include <vector>\n\nint main() {\n std::vector<std::uint8_t> test1{ 5, 4, 4 };\n std::vector<std::uint8_t> test2{ 4, 4, 5 };\n std::cout << \"mean of test1 = \" << (int)boost::math::tools::mean( test1.begin(), test1.end() ) << '\\n';\n std::cout << \"mean of test2 = \" << (int)boost::math::tools::mean( test2.begin(), test2.end() ) << '\\n';\n}\n</code></pre>\n\n<p>This is the output:</p>\n\n<pre><code>mean of test1 = 5\nmean of test2 = 4\n</code></pre>\n\n<p>The order of the elements in the array affects the mean? No!</p>\n\n<p>Similarly, it computes the mean of integers <code>{255, 0, 0, 0}</code> not as <code>255.0/4=63.75</code>, not as that value rounded up or down, but as 65.</p>\n\n<p><code>mean_and_population_variance()</code> will have similar issues, and it will overflow.</p>\n\n<p>I would expect <code>mean()</code> to return a <code>double</code> if the input is integer. But determining the correct output type is not possible to do in a generic way. I'd suggest you require type traits to exist for the arithmetic type being used, and that one of these type traits be the type of the output for these functions. I believe other Boost modules work similarly.</p>\n\n<h1><code>median()</code></h1>\n\n<p>This one is really only useful for arithmetic types, and that is a shame. It'd be interesting if it could return the median of a set of words, for example. But you can't do <code>(word1 + word2) / 2</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T16:37:18.203",
"Id": "404485",
"Score": "0",
"body": "You're right; I think it should give a compilation error for integer types, or it should do \"arg promotion\" and return a double when integral types are provided. Why do you think `mean_and_population_variance` will overflow?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T17:04:37.830",
"Id": "404489",
"Score": "0",
"body": "@user14717: again in the uint8 case: if the first element is 255, the second is 0, then `tmp` is 255 and `tmp*tmp` will overflow. If they are sorted the other way around, then `tmp` will be 0 instead of -255. Unsigned arithmetic cannot be used in this function, and variance computation just needs floating-point arithmetic. The mean can be computed correctly using a larger int type using the trivial sum/count method, but your implementation is less likely to overflow in the general case. I don’t know what to recommend there, if you need to keep these generic, sorry."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T17:06:50.423",
"Id": "404490",
"Score": "0",
"body": "@user14717: Also sorry for the short review, I got called away while writing it, and decided to just post what I had so far. Maybe I’ll have more time tonight to look at the other functions and your questions, but maybe you prefer to rethink the type logic and post a new question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T17:37:11.003",
"Id": "404492",
"Score": "0",
"body": "Really useful: It's clear that this is almost totally useless for image processing guys who use 8/16 bit int logic. Unfortunately, algorithm design depends on whether the data is fixed or floating point, so I don't see any way I could generically support both. I'll think about this more."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T19:43:04.683",
"Id": "404519",
"Score": "0",
"body": "@Chris Luengo: I think convention on this site is to not update the question as feedback comes in. I have added support for integer input where sensible in the PR; your feedback is very helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T20:18:00.133",
"Id": "404522",
"Score": "1",
"body": "@user14717: Yes, please don’t update your question. But feel free to post a new question with updates code. I will take another look at your code and the specific questions you had if I have time tonight."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T16:13:30.197",
"Id": "209279",
"ParentId": "209253",
"Score": "2"
}
},
{
"body": "<p>What is all this for?</p>\n\n<pre><code>typedef typename std::remove_const<typename std::remove_reference<decltype(*std::declval<ForwardIterator>())>::type>::type Real;\n</code></pre>\n\n<p>That's a really complex way of doing something.</p>\n\n<p>Let's break this down.</p>\n\n<pre><code>using T1 = std::declval<ForwardIterator> // Returns the reference version of `ForwardIterator`\n\n\n\nusing T2 = decltype(*T1()) // Creates a temporary object.\n // De-reference the temporary\n // Gets the type of the de-referenced value.2\n\n\nusing T3 = std::remove_reference<T2>::type; // removes references.\nusing T4 = std::remove_const<T3>::type; // removes an const ness.\n</code></pre>\n\n<p>Simpler to write:</p>\n\n<pre><code>typedef typename std::iterator_traits<ForwardIterator>::value_type Real;\n</code></pre>\n\n<p>Or if you want to use the modern syntax.</p>\n\n<pre><code>using Real = typename std::iterator_traits<ForwardIterator>::value_type;\n</code></pre>\n\n<p>Or if you are like me and hate using the <code>typename</code> everywhere you can create your own <code>template using</code> to make this simpler.</p>\n\n<pre><code>template<typename I>\nusing IterValue = typename std::iterator_traits<I>::value_type;\n</code></pre>\n\n<p>Now in your code you can use:</p>\n\n<pre><code>template<class ForwardIterator, ReturnType = IterValue<ForwardIterator>>\nReturnType mean(ForwardIterator first, ForwardIterator last)\n{\n BOOST_ASSERT_MSG(first != last, \"At least one sample is required to compute the mean.\");\n int i = 1; // The i value is always an int no matter what the data type is\n\n ReturnType mu = 0;\n for(auto it = first; it != last; ++it) {\n mu = mu + (*it - mu)/i; // Sure!\n i += 1;\n }\n return mu;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T20:47:54.437",
"Id": "404524",
"Score": "0",
"body": "The `using Real = typename ForwardIterator::value_type;` is such a clean syntax, but I can't get it to compile with a `std::array` input type on `g++-8` and `clang`: fatal error: type 'float *' cannot be used prior to '::' because it has no members"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T20:59:59.047",
"Id": "404527",
"Score": "0",
"body": "I kept `i` as a Real because I was worried it would generate an int -> Real cast on every iteration before the division. However, adding your change didn't generate any meaningful performance differences either way, so your simpler option is probably the best."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T21:24:25.580",
"Id": "404530",
"Score": "1",
"body": "@user14717: Fixed the issue with iterators that are pointers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T00:15:08.597",
"Id": "404541",
"Score": "0",
"body": "You could use `auto` for most type deductions (instead of manually deducing `Real`). Only caveat: The algorithms might not support iterators returning proxy objects (looking at you, `std::vector<bool>::iterator`). Technically, that's still standard library compatible, though, since that kind of iterator can at most fulfill the `InputIterator` requirements, and the algorithms seem to require `ForwardIterator`s, for which `reference` must be equal to `value_type&` or `const value_type&`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T00:56:25.243",
"Id": "404543",
"Score": "1",
"body": "@hoffmale Yes. Auto would be even better. Tried updating the answer. But the problem here is the `auto mu = 0;` Does not do what we need it to do. I could do `auto mu = *it; mu = 0;` But that seems a bit complex and likely to be messed with by a maintainer unless I have a significant comment. So we are back to manually working out the type."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T20:37:04.053",
"Id": "404875",
"Score": "0",
"body": "@MartinYork: You don't actually have to assign `0`: `auto mu = *first; for(auto it = std::next(first), i = 2; it != last; (void)++it, ++i) { mu = mu + (*it - mu) / i; }` (basically unrolled the first iteration of the loop)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T20:17:03.387",
"Id": "209287",
"ParentId": "209253",
"Score": "4"
}
},
{
"body": "<pre><code>Real i = 0;\nfor(auto it = first; it != last; ++it) {\n mu = mu + (*it - mu)/i;\n i += 1;\n}\n</code></pre>\n\n<p>Unsure what your <code>Real</code> type is, technically, for sufficiently large containers, <code>i</code> in this loop, and similar ones, will soon stop changing.</p>\n\n<p><code>l[02p]_norm</code>s would probably be better expressed via range-for or folds from <code><algorithm></code> (<code>std::accumulate</code> etc.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T14:42:05.703",
"Id": "404570",
"Score": "0",
"body": "`typedef typename std::remove_const<typename std::remove_reference<decltype(*std::declval<ForwardIterator>())>::type>::type Real;` declared a few lines earlier"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T15:37:35.747",
"Id": "404575",
"Score": "0",
"body": "Ah, yes, thank you. So could be, say, float thus growing no more past 2²⁴."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T07:48:49.643",
"Id": "209302",
"ParentId": "209253",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "209287",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T02:04:17.483",
"Id": "209253",
"Score": "3",
"Tags": [
"c++",
"statistics",
"c++17",
"numerical-methods",
"signal-processing"
],
"Title": "A collection of vector functionals"
} | 209253 |
<p>I was playing a fun little board game called <em>U.S. Patent No. 1</em> about time traveling to register your time machine as the first U.S. patent. I started to wonder what the dice probabilities were for basic attacks. In the game, you rolls 2 dice to attack, and your opponent rolls 1 die for defense. If the attack result is greater than the defense, then a time machine part is "disabled", and if it is greater by 5 or more, than it is "destroyed"; otherwise it "misses". However, this is not the end: players can also have attack and defense bonuses ranging from 0-12, which are added to the roll result before making the comparison.</p>
<p>To begin my program, I first did a straightforward brute force calculation, where each number in the array was a probability out of 216, and attack and defense bonus from 0 through 12 were cycled through.</p>
<p>But this was a bit slower than I wanted (~500ms, not terrible), so I decided to utilize a bit more math and hardcode the probability distribution of two dice to use multiplication instead of addition. I also replaced the dict with enum keys with a list where 0 is "MISSED", 1 is "DISABLED", and 2 is "DESTROYED", which seemed to significantly reduce overhead by my timings (from ~200ms to ~50ms).</p>
<p>But then I looked more carefully at my results and realized something that is in retrospect obvious about probability distributions of this nature: adding one to both the attack and defense bonus means the bonuses have no affect on the distribution. Represented symbolically, the distribution for A, D is always going to be the same as the distribution for A + N, D + N for integers N. So instead of calculating separate values for attack and defense bonuses, I can just calculate a raw value for attack shift (which also reformatted my array to be smaller and have different dimensions):</p>
<pre><code>from itertools import product
import numpy as np
def calculate():
two_dice_prob = [0, *range(6), *range(6,0,-1)]
result = np.zeros((25,3))
for attack_shift in range(-12, 13):
result_counts = [0] * 3
for defense, attack in product(range(1,7), range(2,13)):
base_attack = attack
attack += attack_shift
if attack - 5 >= defense:
result_counts[2] += two_dice_prob[base_attack]
elif attack > defense:
result_counts[1] += two_dice_prob[base_attack]
else:
result_counts[0] += two_dice_prob[base_attack]
result[attack_shift+12] = result_counts
return result
if __name__ == '__main__':
print("Result:")
print(calculate())
</code></pre>
<p>The result is a numpy array where the top is an attack with a penalty of -12, and the bottom is the attack with a bonus of 12, and every other row has an attack bonus of 1 more than the previous row. By merit of processing less cases, it now only takes ~6ms.</p>
<p>I was wondering how I could optimize the calculate function even more. I suspect I am not utilizing <code>numpy</code>'s efficiency fully, since I am still not completely familiar with it.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T06:55:14.367",
"Id": "404439",
"Score": "0",
"body": "How do 'bonuses' work? Is it whatever you roll plus it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T06:56:23.333",
"Id": "404440",
"Score": "0",
"body": "@Peilonrayz Yes; I'll make an edit."
}
] | [
{
"body": "<h3>1. Review</h3>\n\n<ol>\n<li><p>The name <code>calculate</code> is vague. Something like <code>attack_freq</code> would be more specific.</p></li>\n<li><p>There's no docstring. What does <code>calculate</code> do? What does it return?</p></li>\n<li><p>The values in <code>two_dice_prob</code> are not probabilities, they are <em>counts</em> or <em>frequencies</em>. (To get probabilities, you'd have to divide by 36.) I would use a name like <code>two_dice_freq</code>.</p></li>\n<li><p>By default <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html\" rel=\"nofollow noreferrer\"><code>numpy.zeros</code></a> gives you an array of floats, but the <code>result</code> array only contains integers, so you could specify <code>dtype=int</code> when creating it. (Alternatively, by constructing the result using NumPy throughout, it can be arranged that it has the right data type.)</p></li>\n<li><p>When working with NumPy it's nearly always fastest if you structure the code to consist of a sequence of whole-array operations, rather than looping over the elements in native Python.</p>\n\n<p>In this case we can use <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.mgrid.html\" rel=\"nofollow noreferrer\"><code>numpy.mgrid</code></a> to construct arrays containing all possibilities for attack shift, defence roll and attack roll:</p>\n\n<pre><code>shift, defence, attack = np.mgrid[-12:13, 1:7, 2:13]\n</code></pre>\n\n<p>Then we can find the difference between attack and defence simultaneously for all possibilities:</p>\n\n<pre><code>diff = attack + shift - defence\n</code></pre>\n\n<p>The three outcome classes can now be computed by comparing the difference against 0 and 5 to get arrays of Booleans, and then assembling the outcomes into a single array using <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.stack.html\" rel=\"nofollow noreferrer\"><code>numpy.stack</code></a>:</p>\n\n<pre><code>missed = diff <= 0\ndestroyed = diff >= 5\ndisabled = ~(missed | destroyed)\noutcome = np.stack((missed, disabled, destroyed), axis=1)\n</code></pre>\n\n<p>The reason for choosing to stack along <code>axis=1</code> is so that the <code>outcome</code> array has the right shape, that is, (25, 3, 6, 11). We multiply the last axis by the two-dice frequencies, and then sum over the last two axes. This leaves us with an array of frequencies with shape (25, 3) as required:</p>\n\n<pre><code>return (outcome * two_dice_freq).sum(axis=(2, 3))\n</code></pre>\n\n<p>If we had chosen to stack along axis=0, then at this point we would have an array with shape (3, 25) and we'd have to transpose it before returning. By choosing the right axis to stack along we avoided this transposition.</p></li>\n</ol>\n\n<h3>2. Revised code</h3>\n\n<pre><code>import numpy as np\n\ndef attack_freq():\n \"\"\"Return array with shape (25, 3), whose (i + 12)'th row contains the\n frequencies of the three outcome classes (missed, disabled,\n destroyed) when attack bonus minus defense bonus is i.\n\n \"\"\"\n two_dice_freq = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]\n shift, defence, attack = np.mgrid[-12:13, 1:7, 2:13]\n diff = attack + shift - defence\n missed = diff <= 0\n destroyed = diff >= 5\n disabled = ~(missed | destroyed)\n outcome = np.stack((missed, disabled, destroyed), axis=1)\n return (outcome * two_dice_freq).sum(axis=(2, 3))\n</code></pre>\n\n<p>This computes the same results as the code in the post:</p>\n\n<pre><code>>>> np.array_equal(calculate(), attack_freq())\nTrue\n</code></pre>\n\n<p>but it's roughly four times as fast:</p>\n\n<pre><code>>>> from timeit import timeit\n>>> timeit(calculate, number=1000)\n0.38954256599993187\n>>> timeit(attack_freq, number=1000)\n0.09676001900004394\n</code></pre>\n\n<p>The actual runtimes are so small, less than a millisecond, that this speedup doesn't really matter in practice, since you'd only need to build this table once. However, the general technique, of applying a series of whole-array NumPy operations instead of looping in native Python, can make <a href=\"https://codereview.stackexchange.com/a/161574/11728\">practical</a> <a href=\"https://codereview.stackexchange.com/a/196024/11728\">differences</a> <a href=\"https://codereview.stackexchange.com/a/42916/11728\">in other</a> <a href=\"https://codereview.stackexchange.com/a/41089/11728\">kinds of</a> <a href=\"https://codereview.stackexchange.com/a/84990/11728\">program</a>, so it's worth <a href=\"https://softwareengineering.stackexchange.com/a/254487/30159\">practicing the technique</a> even in small cases like this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T15:07:18.930",
"Id": "209273",
"ParentId": "209258",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209273",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T06:46:20.260",
"Id": "209258",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"numpy"
],
"Title": "Dice sums comparison probability"
} | 209258 |
<p>I am developing a card game in Android. This is my first time I am working in Android,. The game contains following features:</p>
<ul>
<li>It will be a 6 player game.</li>
<li>There are two decks on the table, one with hidden Cards(Dealt Deck), and other with shown cards(Discarded Deck).</li>
<li>There are multiple rounds in each set, and multiple set in each match.</li>
<li>In each round a new card will be added to user deck</li>
<li>User can either remove a single card or multiple cards if they belong to a particular category like "Three of a kind".</li>
<li>User then have to pick a single card either from Discarded Deck or from Dealt Deck.</li>
<li>Each card has it's own value, in the end of the match user with lowest no. of scores will win the match.</li>
</ul>
<p>For this I have created the following classes:</p>
<p><strong><code>MainActivity</code> class</strong>: Launcher class of the game</p>
<pre><code>public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.activity_main);
MySurfaceView surfaceView;
surfaceView = (MySurfaceView) findViewById((R.id.surfaceView));
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
</code></pre>
<p><strong><code>MySurfaceView</code> class</strong>: Most of important class, this class will handle all the operations of the game, showing cards on UI, handling of touch event, swapping of touch cards etc.</p>
<pre><code>public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = MySurfaceView.class.getSimpleName(); // To get name of class in Logging
private Context context;
private DisplayMetrics metrics;
private MySurfaceViewThread thread;
private int Screen_Width;
private int Screen_Height;
private float density;
private int Card_Width;
private int Card_Height;
private int Screen_Center_X;
private int Screen_Center_Y;
private int Screen_Bottom_Middle_X;
private int Screen_Bottom_Middle_Y;
private Deck MainPlayer;
private Deck DeatlDeck;
private Deck DiscardedDeck;
private Bitmap BlueBackCard;
private int DealtDeck_CurrentX;
private int DealtDeck_CurrentY;
private int DiscardedDeck_CurrentX;
private int DiscardedDeck_CurrentY;
private boolean isLongTouched=false;
final Handler longpressedhandler= new Handler();
private Card touchedcard=null;
private int cardindex=-1;
private Card replacedcard=null;
private GestureDetector gestureDetector;
private long startclicktime;
private final int MIN_CLICK_DURATION=1000;
private ArrayList<Card> tempLongtouchList= new ArrayList<>();
private ArrayList<Integer> tempListindex= new ArrayList<>();
public MySurfaceView(Context context) {
super(context);
this.context = context;
metrics = getResources().getDisplayMetrics();
setWillNotDraw(false);
gestureDetector = new GestureDetector(context, new GestureListener(this));
init(context);
}
public MySurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
metrics = getResources().getDisplayMetrics();
setWillNotDraw(false);
gestureDetector = new GestureDetector(context, new GestureListener(this));
init(context);
}
public MySurfaceView(Context context, AttributeSet attrs, int defstyles) {
super(context, attrs, defstyles);
this.context = context;
metrics = getResources().getDisplayMetrics();
setWillNotDraw(false);
gestureDetector = new GestureDetector(context, new GestureListener(this));
init(context);
}
private void init(Context context) {
this.context = context;
getHolder().addCallback(this);
thread = new MySurfaceViewThread(getHolder(), this);
setFocusable(true);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "Inside Surface Created method");
initializevariable();
AllocatedCardList();
thread.setRunning(true);
thread.start();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
thread.setRunning(false);
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
private void initializevariable() {
Screen_Width = getWidth();
Screen_Height = getHeight();
density = metrics.density;
Card_Width = (int) (125.0F * density);
Card_Height = (int) (93.0F * density);
Screen_Center_X = Screen_Width / 2;
Screen_Center_Y = Screen_Height / 2;
Screen_Bottom_Middle_X = Screen_Center_X - Card_Width;
Screen_Bottom_Middle_Y = Screen_Height - Card_Height;
BlueBackCard = DecodeSampleBitmapFromResource(getResources(), Card.GetBlueBackCardImageId(context), Card_Width, Card_Height);
MainPlayer = new Deck();
DeatlDeck = new Deck();
DiscardedDeck = new Deck();
DealtDeck_CurrentX = Screen_Center_X - Card_Width;
DealtDeck_CurrentY = Screen_Center_Y - Card_Height / 2;
DiscardedDeck_CurrentX= Screen_Center_X+Card_Width;
DiscardedDeck_CurrentY= Screen_Center_Y- Card_Height/2;
}
private void AllocatedCardList() {
Log.d(TAG, "inside AllocatedCardList method");
for (Suit suit : Suit.values()) {
for (Rank rank : Rank.values()) {
DeatlDeck.add(new Card(rank, suit, false, DealtDeck_CurrentX, DealtDeck_CurrentY , BlueBackCard));
}
}
DealCards();
}
private void DealCards() {
Log.d(TAG, "Inside Deal Card method");
MainPlayer.add(DeatlDeck.Deal(true));
MainPlayer.add(DeatlDeck.Deal(true));
// MainPlayer.add(DeatlDeck.Deal(true));
}
// @SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.d(TAG,"Inside Touch Event");
float lasttouched_X, lasttouched_Y;
Card localcard;
int index=-1;
Log.d(TAG,"Inside OnTouch event");
gestureDetector.onTouchEvent(event);
return true;
}
/**
* Method to swap Main Player card with
* either Dealt Deck or with Discarded
* Deck, this method will check whether
* user has touched Main Player deck,
* Dealt Deck or Discarded Deck, if
* user has touched Main Deck using
* long touch it will add those touch
* cards to temporary deck, till
* user does not touch Discarde/
* Dealt Deck
* @param e: to determine which type of event has performed.
*/
public void swapSingleTouchCard(MotionEvent e) {
float lasttouched_X, lasttouched_Y;
Card localcard;
int index = -1;
lasttouched_X = e.getX();
lasttouched_Y = e.getY();
// Code for long touch and single touch swap
if(((lasttouched_X >= DiscardedDeck_CurrentX && lasttouched_X < (DiscardedDeck_CurrentX + DiscardedDeck.getCard().getImage().getWidth())))==false &&isLongTouched) // Main Player Deck, card is touched
{
addTouchedCardToLongTouched(e);
}
else if (isLongTouched==false && touchedcard==null)
{
index = cardTouched((int) lasttouched_X, (int) lasttouched_Y);
if (index > -1) {
touchedcard = MainPlayer.getCard(index);
cardindex = index;
}
}
else if(lasttouched_X >= DiscardedDeck_CurrentX && lasttouched_X < (DiscardedDeck_CurrentX + DiscardedDeck.getCard().getImage().getWidth())) //if touched card is Discard deck
{
if(touchedcard!=null) // to replace with single card
{
replacedcard = DiscardedDeck.Deal(true);
Card swapcard = MainPlayer.swapCard(replacedcard, cardindex);
swapcard.setCurrent_X(DiscardedDeck_CurrentX);
swapcard.setCurrent_Y(DiscardedDeck_CurrentY);
DiscardedDeck.add(swapcard);
touchedcard = null;
cardindex = -1;
}
else if(isLongTouched)
{
int i=tempListindex.size()-1;
Card Discarddeckcard;
Discarddeckcard=DiscardedDeck.Deal(true);
while(i>=0)
{
MainPlayer.removeCard(tempListindex.get(i));
Card removecard= tempLongtouchList.remove(i);
removecard.setCurrent_X(DiscardedDeck_CurrentX);
removecard.setCurrent_Y(DiscardedDeck_CurrentY);
DiscardedDeck.add(removecard);
i--;
}
MainPlayer.add(Discarddeckcard);
isLongTouched=false;
}
}
}
private int cardTouched(int lasttouched_x, int lasttouched_y) {
int index=0;
Card localcard=null;
while (index<MainPlayer.Count())
{
localcard=MainPlayer.getCard(index);
if(lasttouched_x>= localcard.getCurrent_X() && lasttouched_x<(localcard.getCurrent_X()+localcard.getImage().getWidth())) //&& (lasttouched_y>=localcard.getCurrent_Y() &&lasttouched_y <(localcard.getCurrent_Y()+localcard.getImage().getWidth())))
{
return index;
}
index++;
}
return -1;
}
public void addTouchedCardToLongTouched(MotionEvent event)
{
float lasttouched_X, lasttouched_Y;
int index=-1;
lasttouched_X=event.getX();
lasttouched_Y=event.getY();
index=cardTouched((int)lasttouched_X,(int)lasttouched_Y);
isLongTouched=true;
if(index>-1)
{
tempLongtouchList.add(MainPlayer.getCard(index));
tempListindex.add(index);
}
}
public void render(Canvas canvas)
{
canvas.drawColor(Color.TRANSPARENT,PorterDuff.Mode.CLEAR);
drawDealtDeck(canvas);
if(DiscardedDeck.Count()==0) { //To add card in discarded deck only first time
setDiscardedDeck();
}
drawDiscardedDeck(canvas);
setMainPlayer();
DrawMainPlayerDeck(canvas);
}
private void drawDealtDeck (Canvas canvas){
Card localcard = DeatlDeck.getCard();
canvas.drawBitmap(localcard.getImage(), localcard.getCurrent_X(), localcard.getCurrent_Y(), null);
}
private void drawDiscardedDeck(Canvas canvas) {
Log.d(TAG,"Inside Draw Discarded deck");
Card localcard= DiscardedDeck.getCard();
canvas.drawBitmap(localcard.getImage(),localcard.getCurrent_X(),localcard.getCurrent_Y(),null);
}
private void setDiscardedDeck() {
Log.d(TAG,"Inside set Discarded Deck");
Card localcard;
Bitmap localimage;
localcard=DeatlDeck.Deal(true);
localimage= DecodeSampleBitmapFromResource(getResources(),localcard.GetImageId(context),Card_Width,Card_Height);
localcard.setImage(localimage);
localcard.setCurrent_X(DiscardedDeck_CurrentX);
localcard.setCurrent_Y(DiscardedDeck_CurrentY);
DiscardedDeck.add(localcard);
}
private void setMainPlayer ()
{
Log.d(TAG, "Inside Set Main Player Method");
Card localcard = null;
Bitmap localimage = null;
int currentiteration = 0;
int Down_Card_Gap = 0;
int Down_Card_Gap_positive = 0;
int Down_Card_Gap_negative = 0;
while (currentiteration < MainPlayer.Count()) {
localcard = MainPlayer.getCard(currentiteration);
localimage = DecodeSampleBitmapFromResource(getResources(), localcard.GetImageId(context), Card_Width, Card_Height);
localcard.setImage(localimage);
localcard.setCurrent_Y(Screen_Height - localcard.getImage().getHeight());
MainPlayer.setCurrentCard(localcard, currentiteration);
currentiteration++;
if (Down_Card_Gap >= 0) {
Down_Card_Gap_positive = Down_Card_Gap;
localcard.setCurrent_X(Screen_Center_X + Down_Card_Gap_positive);
Down_Card_Gap += 75;
} else {
Down_Card_Gap_negative = Down_Card_Gap;
localcard.setCurrent_X(Screen_Center_X + Down_Card_Gap_negative);
}
Down_Card_Gap *= -1;
}
}
private void DrawMainPlayerDeck (Canvas canvas)
{
Log.d(TAG, " Inside Draw Main Player Deck");
Card localcard;
int currentiteration = 0;
while (currentiteration < MainPlayer.Count()) {
localcard = MainPlayer.getCard(currentiteration);
canvas.drawBitmap(localcard.getImage(), localcard.getCurrent_X(), localcard.getCurrent_X(), null);
currentiteration++;
}
}
private Bitmap DecodeSampleBitmapFromResource (Resources res,int resId,
int reqWidth, int reqHeight){
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
private int calculateInSampleSize (BitmapFactory.Options options,int reqWidth, int reqHeight)
{
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
int heightratio= (int)Math.round((double)height/reqHeight);
int widthratio= (int)Math.round((double)width/reqWidth);
inSampleSize= heightratio < widthratio ? widthratio : heightratio;
}
return inSampleSize;
}
}
/**
* Class to implements Touch events
*/
class GestureListener extends GestureDetector.SimpleOnGestureListener{
private static final String TAG = GestureListener.class.getSimpleName(); //
To get name of class in Logging
MySurfaceView mySurfaceView;
public GestureListener(MySurfaceView paramMySurfaceView)
{
mySurfaceView=paramMySurfaceView;
}
@Override
public void onLongPress(MotionEvent e) {
Log.d(TAG,"Inside Long Pressed event");
mySurfaceView.addTouchedCardToLongTouched(e);
}
@Override
public boolean onDown(MotionEvent e) {
// don't return false here or else none of the other
// gestures will work
return false;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
mySurfaceView.swapSingleTouchCard(e);
return false;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
Log.d(TAG,"Inside On Double Tap event");
return false;
}
}
</code></pre>
<p><strong><code>MySurfaceViewThread</code></strong>: Thread class to start the game</p>
<pre><code>public class MySurfaceViewThread extends Thread {
private MySurfaceView mySurfaceView;
private SurfaceHolder mySurfaceHolder;
boolean running;
public MySurfaceViewThread(SurfaceHolder paramSurfaceHolder, MySurfaceView paramSurfaceView)
{
mySurfaceHolder=paramSurfaceHolder;
mySurfaceView=paramSurfaceView;
}
public void setRunning(boolean run){
running=run;
}
@SuppressLint("WrongCall")
@Override
public void run() {
Canvas c;
while(running)
{
c=null;
try{
c= mySurfaceHolder.lockCanvas();
mySurfaceView.render(c);
}
catch(Exception e)
{
Log.e("Thread Class run method","exception",e);
}
finally {
if (c!=null)
{
mySurfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}
</code></pre>
<p>Other classes:</p>
<p><strong><code>Card</code></strong></p>
<pre><code>public class Card {
private int current_X;
private int current_Y;
private boolean showcardface;
private Bitmap Image;
private Rank CardValue;
private Suit suit;
Card(Rank value, Suit suit,boolean showcardface, int current_X,int current_Y, Bitmap image)
{
this.CardValue=value;
this.suit=suit;
this.showcardface=showcardface;
this.current_X=current_X;
this.current_Y=current_Y;
this.Image= image;
}
public int GetImageId(Context currentcontext)
{
int cardimageid;
int imagenumber;
String imagename;
if(showcardface==false)
{
imagename="blueback";
}
else
{
imagename= suit.getName()+ CardValue.getImageName();
}
cardimageid= currentcontext.getResources().getIdentifier(imagename,"drawable",currentcontext.getPackageName());
return cardimageid;
}
public static int GetBlueBackCardImageId(Context currentcontext){
return currentcontext.getResources().getIdentifier("blueback","drawable",currentcontext.getPackageName());
}
public Bitmap getImage() {
return Image;
}
public int getCurrent_X() {
return current_X;
}
public int getCurrent_Y() {
return current_Y;
}
public boolean getShowCardFaced()
{
return showcardface;
}
public void setShowcardface(boolean showcardface) {
this.showcardface = showcardface;
}
public void setImage(Bitmap image)
{
this.Image=image;
}
public void setCurrent_X(int current_X) {
this.current_X = current_X;
}
public void setCurrent_Y(int current_Y) {
this.current_Y = current_Y;
}
}
</code></pre>
<p><strong><code>Deck</code> class</strong></p>
<pre><code>public class Deck {
private ArrayList<Card> deck= new ArrayList<>() ;
public Deck()
{
}
/**
* Method to add card in the deck
* @param card
*/
public void add(Card card) {
deck.add(card);
}
/**
* Method to get the top element of the deck
* @return The Top element of the deck
*/
public Card getCard()
{
return deck.get(deck.size()-1);
}
/**
*
* @param index
* @return Element at index value
*/
public Card getCard(int index)
{
return deck.get(index);
}
/**
* Method to get the size of the deck
* @return Deck size
*/
public int Count()
{
return deck.size();
}
/**
* Method to remove a single card from deck
* @return Removed card from the deck.
*/
public Card Deal()
{
int cardcount= Count();
Card dealcards= deck.get(cardcount-1);
deck.remove(cardcount-1);
dealcards.setShowcardface(true);
return dealcards;
}
/**
* Method to remove a single card from deck
* @return Removed card from the deck.
*/
public Card Deal(boolean showcardface)
{
int cardcount= Count();
Card dealcards= deck.get(cardcount-1);
deck.remove(cardcount-1);
dealcards.setShowcardface(showcardface);
return dealcards;
}
public void setCurrentCardImage(Bitmap image, int index)
{
getCard(index).setImage(image);
}
public void setCurrentCard(Card card, int index)
{
deck.set(index,card);
}
/**
* Method to swap between touch cards of the two decks
* @param replacedcard Card to be added {@index} of the deck
* @param index
* @return Remove the card from @param Index
*/
public Card swapCard(Card replacedcard, int index) {
Card removedcard= deck.remove(index);
deck.add(index,replacedcard);
return removedcard;
}
public void removeCard(int index)
{
Card removecard=deck.remove(index);
}
}
</code></pre>
<p><strong><code>Rank</code> enum</strong></p>
<pre><code>public enum Rank {
Ace(1,"ace","ace"),
Two(2,"two","2"),
Three(3,"three","3"),
Four(4,"four","4"),
Five(5,"five","5"),
Six(6,"six","6"),
Seven(7,"seven","7"),
Eight(8,"eight","8"),
Nine(9,"nine","9"),
Ten(10,"ten","10"),
Jack(11,"jack","jack"),
Queen(12,"queen","queen"),
King(13,"king","king");
private final int rank;
private final String name;
private final String imageName;
Rank(int rank,String name, String imageName){
this.rank=rank;
this.name=name;
this.imageName=imageName;
}
public String getImageName()
{return imageName;
}
}
</code></pre>
<p><strong>Suit enum</strong></p>
<pre><code>public enum Suit {
Clubs(1,"clubs"),
Spades(2,"spades"),
Hearts(3,"hearts"),
Diamond(4,"diamonds");
private final int value;
private final String name;
Suit(int value,String name)
{
this.value=value;
this.name=name;
}
public String getName()
{
return name;
}
}
</code></pre>
<p>Currently, I have completed it for main player only, and availability to swap only with a discarded deck. Since it is my first time, before going any forward I really like to know whether I am following right approach. All suggestions are welcome, especially regarding any approach that I could simplify. If you need help regarding any part of program, let me know I will explain it.</p>
| [] | [
{
"body": "<p>This is a bit large to offer a detailed review, but there are some things which stand out.</p>\n\n<h3>Whitespace</h3>\n\n<p>The indentation seems rather variable, and there are several places with multiple blank lines which don't appear to be to structure the code. The whitespace should help to show the structure: use consistent indentation and use blank lines consistently too.</p>\n\n<h3>Pointless code</h3>\n\n<p>For example, from <code>MainActivity</code>:</p>\n\n<blockquote>\n<pre><code> try {\n\n setContentView(R.layout.activity_main);\n MySurfaceView surfaceView;\n surfaceView = (MySurfaceView) findViewById((R.id.surfaceView));\n\n\n }\n catch (Exception e)\n {\n e.printStackTrace();\n }\n</code></pre>\n</blockquote>\n\n<p>(This also illustrates the previous points about whitespace).</p>\n\n<p>What purpose does <code>surfaceView</code> serve?</p>\n\n<h3>Comments contradicting code</h3>\n\n<blockquote>\n<pre><code>@Override\npublic boolean onDown(MotionEvent e) {\n\n // don't return false here or else none of the other\n // gestures will work\n\n return false;\n}\n</code></pre>\n</blockquote>\n\n<h3>God class anti-pattern</h3>\n\n<p><code>MySurfaceView</code> seems to do almost everything. I'm sure it could be refactored at least into one class for the game state and another class for the visualisation of the game state - the Model/View style. It's probably also worth pulling out one or two classes for two-dimensional Cartesian coordinates: maybe <code>Size</code> and <code>Point</code>. I haven't analysed in detail the way in which the coordinates are used, but it is quite noticeable that the fields of <code>MySurfaceView</code> include a number of decomposed 2D vectors.</p>\n\n<h3>DRY</h3>\n\n<blockquote>\n<pre><code>public MySurfaceView(Context context) {\n super(context);\n this.context = context;\n metrics = getResources().getDisplayMetrics();\n setWillNotDraw(false);\n gestureDetector = new GestureDetector(context, new GestureListener(this));\n init(context);\n}\n\npublic MySurfaceView(Context context, AttributeSet attrs) {\n super(context, attrs);\n this.context = context;\n metrics = getResources().getDisplayMetrics();\n setWillNotDraw(false);\n gestureDetector = new GestureDetector(context, new GestureListener(this));\n init(context);\n}\n\npublic MySurfaceView(Context context, AttributeSet attrs, int defstyles) {\n\n super(context, attrs, defstyles);\n this.context = context;\n metrics = getResources().getDisplayMetrics();\n setWillNotDraw(false);\n gestureDetector = new GestureDetector(context, new GestureListener(this));\n init(context);\n}\n</code></pre>\n</blockquote>\n\n<p>There are two ways to make this less redundant. The first is to move</p>\n\n<pre><code> this.context = context;\n metrics = getResources().getDisplayMetrics();\n setWillNotDraw(false);\n gestureDetector = new GestureDetector(context, new GestureListener(this));\n</code></pre>\n\n<p>into <code>init(context)</code>. The second, which is generally preferred, is to chain the constructors:</p>\n\n<pre><code>public MySurfaceView(Context context) {\n this(context, null);\n}\n\npublic MySurfaceView(Context context, AttributeSet attrs) {\n this(context, attrs, 0);\n}\n</code></pre>\n\n<p>Note that <a href=\"https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/view/SurfaceView.java\" rel=\"nofollow noreferrer\">this is exactly what the superclass does</a> (lines 198ff).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T11:06:45.767",
"Id": "209426",
"ParentId": "209265",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T11:10:19.510",
"Id": "209265",
"Score": "3",
"Tags": [
"java",
"android",
"playing-cards"
],
"Title": "Card based game in Android"
} | 209265 |
<p>I have merge two images into one. I already implemented it with some help from the internet but it takes around 2,5s. I'm testing on the simulator so let's take it as a reference.</p>
<p>I currently use <code>UIGraphicsBeingImageContext</code>. Is there any faster way to achieve it?</p>
<pre><code>extension UIImage {
func overlayWith(image: UIImage, posX: CGFloat, posY: CGFloat, topImageSize: CGSize,
combinedImage: @escaping (UIImage) -> Void) {
DispatchQueue.global(qos: .userInteractive).async {
let newWidth = self.size.width < posX + image.size.width ? posX + image.size.width : self.size.width
let newHeight = self.size.height < posY + image.size.height ? posY + image.size.height : self.size.height
let newSize = CGSize(width: newWidth, height: newHeight)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
self.draw(in: CGRect(origin: CGPoint.zero, size: self.size))
image.draw(in: CGRect(origin: CGPoint(x: posX, y: posY), size: topImageSize))
let newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
DispatchQueue.main.async {
combinedImage(newImage)
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T12:42:51.963",
"Id": "404567",
"Score": "0",
"body": "What is the size of the images you are using?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T14:00:38.427",
"Id": "404569",
"Score": "0",
"body": "@Carpsen90 the base image is iPhone image so it is around 3000x4000 and the top image is smaller ~1000x500. I implemented downsampling from WWDC 2018 session 219 (Image and graphics best practices) but it only shrinks down a photo. I tested it on iPhone 7 and it took me ~0,25s so it is almost instantaneous but maybe there are some tricks to speed up this process?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T15:28:12.753",
"Id": "404572",
"Score": "0",
"body": "And btw when I'm combining two photos I get a peak of memory use of about ~170 MB on iPhone 7."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T01:07:30.527",
"Id": "405076",
"Score": "0",
"body": "I've found that this code is almost twice as fast if `topImageSize` has the same with/height ratio as the size of `image`. Needed clarification: Could these images have some transparency, could the alpha channel be different from 1.0?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T08:00:58.253",
"Id": "405087",
"Score": "0",
"body": "@Carpsen90 yep, the top image is .png with transparent background but the base image is not - it is just image taken with iPhone camera"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T08:30:28.840",
"Id": "406076",
"Score": "0",
"body": "The peak in memory is due to image decoding: `/*RGBA*/ 4 * (/*base*/ 3000*4000 + /*overlay*/ 1000*500 + /*newImage*/ 3000*4000)` which is almost `93.47`Mbytes"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T08:35:03.010",
"Id": "406077",
"Score": "0",
"body": "@Carpsen90 yep, I know. So there is no way to optimize it without losing the quality?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T08:42:48.987",
"Id": "406078",
"Score": "0",
"body": "If speed is paramount, it seems that downsampling is the best way, but I'll keep looking. (Some pointers can be found [here](https://devstreaming-cdn.apple.com/videos/wwdc/2018/416n2fmzz0fz88f/416/416_ios_memory_deep_dive.pdf?dl=1))"
}
] | [
{
"body": "<p>On a simulator with the original code, it takes about <code>1.52s</code> on my machine. </p>\n\n<p>Since the base image won't get resized (<code>self.size</code> is passed in <code>self.draw(in:)</code>), and its alpha channel is always <code>1</code>, I could gain at least <code>200ms</code> by using the following :</p>\n\n<pre><code>self.draw(at: CGPoint.zero, blendMode: .copy, alpha: 1)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T21:49:28.613",
"Id": "406506",
"Score": "0",
"body": "thanks, cool trick. I managed to drop from `1.13`s to `1.07`s or even `0.98` on the simulator. Not a major improvement but a welcome one."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T09:12:05.083",
"Id": "210105",
"ParentId": "209267",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T12:22:26.783",
"Id": "209267",
"Score": "3",
"Tags": [
"image",
"swift"
],
"Title": "Merge two UIImages into one"
} | 209267 |
<p>I decided to do <a href="https://adventofcode.com/" rel="nofollow noreferrer">Advent of Code</a> this year in D, and the following is my solution to <a href="https://adventofcode.com/2018/day/8" rel="nofollow noreferrer">day 8</a>.</p>
<p>Algorithm aside, I was specifically wondering if there was a better way to use ranges in a recursive manner here. I feel like I should be able to do write the functions in a more generic way (not just <code>int[]</code>, avoiding the <code>.array</code> in <code>main</code>), and without destroying the original array in the process - avoiding the temporary variable <code>p1</code>.</p>
<p>My use of the <code>header</code> variable seems suspect to me as well - basically I want a <code>popFront</code> that returns a value, I think, but have been unable to find anything like that.</p>
<p>I'm also happy to hear general advice about usual best practices and efficiencies.</p>
<pre><code>import std.algorithm;
import std.conv;
import std.file;
import std.range;
import std.stdio;
import std.string;
int count_metadata(ref int[] r)
{
auto header = r.take(2);
int num_child = header.front;
int num_metadata = header.back;
r = r.drop(2);
int count;
for (int i; i < num_child; i++) {
count += r.count_metadata;
}
count += r.take(num_metadata).sum;
r = r.drop(num_metadata);
return count;
}
int node_value(ref int[] r)
{
auto header = r.take(2);
int num_child = header.front;
int num_metadata = header.back;
r = r.drop(2);
int[] child_values;
for (int i; i < num_child; i++) {
child_values ~= node_value(r);
}
int count;
if (num_child == 0) {
count = r.take(num_metadata).sum;
} else {
// ignore out of range
count = r.take(num_metadata).filter!(a => 0 < a && a <= child_values.length).map!(a => child_values[a - 1]).sum;
}
r = r.drop(num_metadata);
return count;
}
void main(string[] args)
{
// integers separated by spaces
auto input = readText(args[1]).split.map!(a => to!int(a)).array;
//auto input = [2, 3, 0, 3, 10, 11, 12, 1, 1, 0, 1, 99, 2, 1, 1, 2];
auto p1 = input.dup;
writeln("Metadata total: ", count_metadata(p1));
writeln("Node value: ", node_value(input));
}
</code></pre>
<p>(<code>args[1]</code> is a file with integers separated by spaces, sample input is commented out below it.)</p>
| [] | [
{
"body": "<p>First, I'd prefer to parse the <code>int[]</code> into a <code>Node[]</code> or somesuch - I'd even argue the name of <code>node_value</code> is a code smell indicating that it should be a member called <code>value</code> of a type called <code>Node</code>. I believe this is part of what causes your consternation with the <code>header</code> variable.</p>\n\n<p>Speaking of names, D naming conventions generally avoids underscores except for constants, so more idiomatic names would be <code>nodeValue</code> and <code>countMetadata</code> (which would perhaps more correctly be called <code>sumMetadata</code>).</p>\n\n<p>One of the reasons you should parse to <code>Node[]</code> is it factors out the common parts between <code>node_value</code> and <code>count_metadata</code>, making their responsibilities clearer and the code easier to follow - remember, you're writing code for the next person who looks at it; the computer is happy with a string of bits that nobody can read.</p>\n\n<p>Now, you mention genericity. For the most part, replacing <code>(ref int[] r)</code> with <code>(R)(ref R r) if (isForwardRange!R)</code> will deal with this. This templates the functions on the type of the range passed. Your code otherwise uses range functions (<code>front</code>, <code>popFront</code>, <code>take</code>, etc), so so no other change is necessary.</p>\n\n<p>However, due to the structure of the file format, you will need to read all child nodes before getting at the metadata of a node. This limits the possible laziness of the solution. Since you are always iterating over every node, this doesn't matter a whole lot, but since that's one of the great benefits of ranges, it's worth pointing out.</p>\n\n<p>As for consuming the range, there is no very simple, unobtrusive solution. You need to either create a temporary variable (like <code>p1</code>), have a duplicate function for the non-ref case, or use inner functions:</p>\n\n<p><code>\nint count_metadata(R)(R r0)\nif (isForwardRange!R)\n{\n int impl(ref R r) {\n // Same code as before, but call impl instead of count_metadata\n }\n return impl(r);\n}\n</code></p>\n\n<p>You also mentioned efficiency. I don't think I can improve much on that. Both <code>count_metadata</code> and <code>node_value</code> are O(n), and my proposed solution doesn't change that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T14:09:49.137",
"Id": "209363",
"ParentId": "209268",
"Score": "1"
}
},
{
"body": "<p>I spoke with some people on the #d IRC channel, and came up with a few things</p>\n\n<p>The main bit of which was using the recursive function to return the range, rather than the result and using a reference parameter as the actual output. Makes the function a bit \"harder\" to use, but ultimately makes the implementation much easier and more generalisable (see <code>R</code> template parameter). This also means that the <code>.array</code> and <code>.dup</code> can be removed from the main function</p>\n\n<p>I'd still like a function that pops and returns the value, so repeated <code>.front</code> & <code>.popFront()</code> isn't necessary, but seems like that might be a design decision, like C++'s <code>std::stack::pop</code></p>\n\n<p>Also added some <code>unittest</code> blocks to hold the examples</p>\n\n<pre><code>import std.algorithm;\nimport std.conv;\nimport std.file;\nimport std.range;\nimport std.stdio;\n\nR sum_metadata(R)(R r, ref int count)\n{\n int num_child = r.front;\n r.popFront;\n int num_metadata = r.front;\n r.popFront;\n\n for (int i; i < num_child; i++) {\n r = r.sum_metadata(count);\n }\n\n count += r.take(num_metadata).sum;\n return r.dropExactly(num_metadata);\n}\n\nR node_value(R)(R r, ref int count)\n{\n int num_child = r.front;\n r.popFront;\n int num_metadata = r.front;\n r.popFront;\n\n int[] child_values;\n for (int i; i < num_child; i++) {\n int val;\n r = r.node_value(val);\n child_values ~= val;\n }\n\n if (num_child == 0) {\n count += r.take(num_metadata).sum;\n } else {\n // Ignore out of range\n count += r.take(num_metadata).filter!(a => 0 < a && a <= child_values.length).map!(a => child_values[a - 1]).sum;\n }\n return r.drop(num_metadata);\n}\n\nvoid main(string[] args)\n{\n auto input = readText(args[1]).split.map!(a => to!int(a));\n int sum;\n input.sum_metadata(sum);\n writeln(\"Metadata total: \", sum);\n int val;\n input.node_value(val);\n writeln(\"Node value: \", val);\n}\n\nunittest\n{\n auto input = [2, 3, 0, 3, 10, 11, 12, 1, 1, 0, 1, 99, 2, 1, 1, 2];\n int sum;\n input.sum_metadata(sum);\n assert(sum == 138);\n}\n\nunittest\n{\n auto input = [2, 3, 0, 3, 10, 11, 12, 1, 1, 0, 1, 99, 2, 1, 1, 2];\n int val;\n input.node_value(val);\n assert(val == 66);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T14:34:43.420",
"Id": "405148",
"Score": "0",
"body": "For the combination of `front` and `popFront`, just define a function: `auto pop(R)(ref R r) { auto result = r.front(); r.popFront(); return result; }`, and use UFCS to call it: `auto c = r.pop;`. The same thing could be done for `take`/`drop`: `auto takeDropExactly(R)(R r, size_t n) { auto result = r.takeExactly(n); r.dropExactly(); return result; }`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T23:11:34.483",
"Id": "209483",
"ParentId": "209268",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T12:34:31.447",
"Id": "209268",
"Score": "1",
"Tags": [
"programming-challenge",
"recursion",
"tree",
"d"
],
"Title": "Recursive range iteration"
} | 209268 |
<p>I have written a Java program to calculate magic squares with recursion and backtracking. A 3*3 Magic square is calculated in about 1 sec, but a 4*4 needs about 50 minutes on my laptop with Intel i5. How i can improve the performance?</p>
<pre><code>import java.util.Scanner;
public class MagicSquare {
private byte[][] square;
private byte magicNumber;
private long tmp = 0;
public MagicSquare() {
Scanner sc = new Scanner(System.in);
byte size = sc.nextByte();
square = new byte[size][size];
sc.close();
magicNumber = (byte) ((size * size * size + size) / 2);
long start = System.currentTimeMillis();
solve(0, 0);
printSquare();
long duration = System.currentTimeMillis() - start;
System.out.println(tmp);
System.out.println(duration);
}
private boolean solve(int x, int y) {
tmp++;
if (x == square.length && y == square.length - 1 && isMagic()) {
return true;
}
if (x == square.length) {
y++;
x = 0;
}
for (byte i = 1; i <= square.length * square.length; i++) {
if (containsNumber(i) == false) {
if (isValidRow(x) && isValidCol(y)) {
square[x][y] = i;
if (solve(x + 1, y) == true) {
return true;
}
}
}
}
if (x < square.length && y < square.length) {
square[x][y] = 0;
}
return false;
}
private boolean isMagic() {
int diagonal1 = 0;
int diagonal2 = 0;
int col = 0;
int row = 0;
for (int i = 0; i < square.length; i++) {
for (int j = 0; j < square[0].length; j++) {
col = col + square[j][i];
row = row + square[i][j];
if (i == 0) {
diagonal1 = diagonal1 + square[j][j];
diagonal2 = diagonal2 + square[j][square.length - j - 1];
}
}
if (col != magicNumber || row != magicNumber || diagonal1 != magicNumber || diagonal2 != magicNumber) {
return false;
}
row = 0;
col = 0;
}
return true;
}
private boolean isValidRow(int row) {
int sum = 0;
for (byte i = 0; i < square.length; i++) {
sum = sum + square[row][i];
}
if (sum <= magicNumber)
return true;
return false;
}
private boolean isValidCol(int col) {
int sum = 0;
for (byte i = 0; i < square.length; i++) {
sum = sum + square[i][col];
}
if (sum <= magicNumber)
return true;
return false;
}
public boolean containsNumber(byte value) {
for (int i = 0; i < square.length; i++) {
for (int j = 0; j < square[0].length; j++) {
if (square[i][j] == value) {
return true;
}
}
}
return false;
}
private void printSquare() {
for (int i = 0; i < square.length; i++) {
for (int j = 0; j < square[0].length; j++) {
System.out.print(square[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
MagicSquare m = new MagicSquare();
}
}
</code></pre>
<p>Any help is really appreciated.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-12T23:01:49.183",
"Id": "408753",
"Score": "0",
"body": "Follow up question was posted [here](https://codereview.stackexchange.com/q/210648/100620)"
}
] | [
{
"body": "<p>You should use try-with-resources when you create a <code>Scanner</code>, and should only ever open a <code>Scanner</code> on <code>System.in</code> in your main program. If you do this, you can pass the required size as an argument to the <code>MagicSquare</code> constructor:</p>\n\n<pre><code>public static void main(String[] args) {\n try(Scanner sc = new Scanner(System.in)) {\n byte size = sc.nextByte();\n MagicSquare m = new MagicSquare(size);\n m.printSquare();\n }\n}\n</code></pre>\n\n<p>I’ve left construction of the magic square in the constructor (seems appropriate), but moved printing of the square to the main program. After all, you might not always want to print the magic square.</p>\n\n<hr>\n\n<p>You have numerous inefficiencies in your implementation:</p>\n\n<p>You use <code>square.length</code> and (worse!) <code>square[0].length</code> when you could simply use <code>size</code> if you stored the magic square’s size as a <code>size</code> member.</p>\n\n<p>You are testing <code>x < square.length && y < square.length</code> before resetting <code>square[x][y] = 0;</code>. The <code>x</code> and <code>y</code> values should always be valid if you reach this step of the <code>solve()</code> method. But there is one small possibility of them becoming invalid. After filling in the last square...:</p>\n\n<pre><code>if (x == square.length && y == square.length-1 && isMagic()) {\n return true;\n}\n</code></pre>\n\n<p>If it turns out <code>isMagic()</code> returns <code>false</code>, the method continues, loops over all values looking for an unused one (there aren’t any), and exits the method, returning <code>false</code>, but only after resetting <code>square[x][y] = 0;</code> which is why the check for invalid coordinates is required. If instead you used:</p>\n\n<pre><code>if (x == square.length && y == square.length-1) {\n return isMagic();\n}\n</code></pre>\n\n<p>... then the method always returns immediately, whether or not the completely filled in square is magic or not. Now, the <code>if</code> guarding <code>square[x][y] = 0;</code> becomes unnecessary.</p>\n\n<hr>\n\n<p>But the real issue comes from your algorithm as a whole. You loop over <span class=\"math-container\">\\$N^2\\$</span> squares, and for each square try each of the <span class=\"math-container\">\\$N^2\\$</span> values, and for each value check each of the <span class=\"math-container\">\\$N^2\\$</span> squares to see if the value is already used. This is an <span class=\"math-container\">\\$O(N^6)\\$</span> algorithm!</p>\n\n<p>The usage check can be reduced to <span class=\"math-container\">\\$O(1)\\$</span> by storing a “used” flag for each number:</p>\n\n<pre><code>boolean used[] = new boolean[size*size+1];\n</code></pre>\n\n<p>or</p>\n\n<pre><code>BitSet used = new BitSet(size*size + 1);\n</code></pre>\n\n<p>Then, simply checking <code>used[value]</code> or <code>used.get(value)</code> will return whether the value has been used or not. Set the flag for the value when you store it in the <code>square[][]</code>, and clear it when you replace the value. That one change will reduce your time complexity from <span class=\"math-container\">\\$O(N^6)\\$</span> to <span class=\"math-container\">\\$O(N^4)\\$</span>.</p>\n\n<hr>\n\n<p>The next speed up can come from the observation that, if you take a solved NxN magic square, and erased one row and one column, you could trivially recreate the erased values. If you know <code>N-1</code> values in a row or column, the remaining value must be the desired total less the sum of the filled in values. <code>1 + 8 + ? = 15</code> ... the missing value is <code>15-(1+8)=6</code>! Of course, since you are generating candidate values, you need to ensure the computed value is (a) possible, and (b) unused.</p>\n\n<hr>\n\n<p>Adding up numbers takes time. Why keep adding the values? You could keep a running total for each row and column:</p>\n\n<pre><code>square[x][y] = value;\nrow_sum[x] += value;\ncol_sum[y] += value;\n</code></pre>\n\n<p>... of course, you need to subtract the value out when backtracking, or replacing with a different candidate value.</p>\n\n<hr>\n\n<p>Magic Squares are horizontally, vertically, and rotationally symmetric. In a 4x4 magic square, there are only 3 unique locations the number “1” may appear in. The remaining 13 locations would all correspond to simple rotations or mirroring of the square. This would reduce the possible 4x4 squares from <code>16!</code> permutations down to <code>3*15!</code> ... an 81% reduction. However, you are not finding all permutations; you stop once the first magic square is found, so this reduction in search space likely won’t produce much savings, if any.</p>\n\n<hr>\n\n<p>While an 8x8 magic square seems huge, it is still within the realm of possibility. The <code>magicNumber</code>, however, would be 260 which is too large for a <code>byte</code>. Limiting the values themselves to a <code>byte</code> restricts the square to 15x15, and may be reasonable, but the sum should probably be an <code>int</code>. </p>\n\n<hr>\n\n<p>This code ordering seems reversed!</p>\n\n<pre><code> if (isValidRow(x) && isValidCol(y)) {\n square[x][y] = i;\n</code></pre>\n\n<p><code>square[x][y]</code> should be filled in before the <code>isValid</code> checks are done. Otherwise, an invalid state will prevent updating the square to a valid value. </p>\n\n<p>“Invalid”, in this case, only happens if the sum becomes too large, and subsequent values will only make matters worse, but if the code is relying on that, it should break out of the candidate values loop once an invalid state is reached, instead of continuing with the next value. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T00:04:17.620",
"Id": "404603",
"Score": "0",
"body": "I don't really understand it with the usedNumbers. for (int i = 1; i <= size * size; i++) {\n\n if (usedNumbers[i] == false) { \n \n \n square[x][y] = i;\n usedNumbers[i] = true;\n \n if (isValidRow(x) && isValidCol(y)) {\n \n \n if (solve(x + 1, y) == true) {\n return true;\n }\n }\n\n }\n }\n \n usedNumbers[square[x][y]] = false;\n square[x][y] = 0;\n \n return false; Why I get a square with only 0 as output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T01:35:14.177",
"Id": "404605",
"Score": "1",
"body": "Sounds like you've set `userNumbers[i]` for all `i` between 1 and `size*size`, but are only resetting `userNumbers[x]` for the last number. You need `userNumbers[i] = false;` at the end of the `for-i` loop, because the next iteration will overwrite the current value, making it unused."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T19:45:57.553",
"Id": "404679",
"Score": "0",
"body": "Now I can calculate a 4*4 Square in about 3min.When I try to calculate missing value in a row or col and use this value i dont't get a solution. if (row_sum[x] <= magicNumber && col_sum[y] <= magicNumber) {\n\n if(x==size-2 && magicNumber-row_sum[x]<=size*size) {\n square[x][y] = magicNumber-row_sum[x];\n value = magicNumber-row_sum[x];\n usedNumbers[value] = true;\n }else {\n square[x][y] = i;\n usedNumbers[i] = true;\n value = i;\n }\n \n if (solve(x + 1, y) == true) {\n return true;\n }\n }"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T20:47:08.027",
"Id": "404684",
"Score": "1",
"body": "Glad to hear you've made it to 3 minutes! O(N^6) to O(N^4) should be a N^2 improvement, 50 minutes / (4^2) = 3 minutes, so that tracks. `x==size-2`? I think you mean `x==size-1`. But it is really hard to debug code posted in comments, and I think the __review__ of the __original__ code is done. If you need help getting your _new, optimized code_ working, you should really post a question in Stack Overflow. Once you get your optimized code working, if you want a review of that, you should post a new question on Code Review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T20:50:49.690",
"Id": "404685",
"Score": "0",
"body": "Ok, I will try it and maybe post the question in Stack Overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T20:54:02.773",
"Id": "404686",
"Score": "0",
"body": "If you post a new question either on Stack Overflow or on Code Review, make sure to included a link back to this question, and add a comment here linking to the new question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-28T14:07:20.823",
"Id": "406875",
"Score": "0",
"body": "update: now I can calculate a 4*4 Square in about 250ms."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-28T17:36:39.417",
"Id": "406917",
"Score": "0",
"body": "Excellent! You could post it here as a self-answer (but no additional reviews will be possible), or as a new question if you want a review of your new code."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T03:35:03.840",
"Id": "209298",
"ParentId": "209272",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209298",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T14:37:51.007",
"Id": "209272",
"Score": "3",
"Tags": [
"java",
"performance",
"algorithm",
"recursion",
"backtracking"
],
"Title": "Speed up Magic square program"
} | 209272 |
<p>I'm studying the C language with a Harvey Deitel book.</p>
<p>Trying to solve an exercise that asked to write a good sorting algorithm, I did this:</p>
<pre><code>void sort(int v[], int d){
int max = 0;
for(int i = 0; i < d; i++){
if(v[i] > max)max = v[i];
}
int v2[max+1];
int v3[max+1];
for(int i = 0; i < max+1; i++){
v2[i] = -1;
v3[i] = 0;
}
for(int i = 0; i < d; i++){
if(v3[v[i]] == 0){
v2[v[i]] = v[i];
v3[v[i]]++;
}
else {
v3[v[i]]++;
}
}
int j = 0;
for(int i = 0; i < max+1; i++){
if(v2[i] != -1){
for(int k = 0; k < v3[i]; k++){
v[j] = v2[i];
j++;
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T15:49:12.007",
"Id": "404477",
"Score": "1",
"body": "(Without comments, this code is not maintainable. Whom do you expect to bother to analyse its behaviour from scratch? And foremost what *does* make a `good sorting algorithm` good?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T15:49:20.663",
"Id": "404478",
"Score": "1",
"body": "could you perhaps add more information about the task that you have been given? something like Acceptance Criteria, what type of sort you are being asked to create, any limitations provided by the text, etc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T15:51:53.927",
"Id": "404480",
"Score": "0",
"body": "the book presented the bubble sort algorithm and asked to develop a more efficient one"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T16:07:45.403",
"Id": "404482",
"Score": "2",
"body": "It would be good to provide at least a brief description of how this algorithm works, including reasoning about how it's better than bubble sort. If you are not able to reason why it's better overall than bubble sort, at least think about the conditions under which it is clearly better. If you cannot come up with even a basic reasoning, then there's no reason to believe it's better in any way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T16:50:36.047",
"Id": "404487",
"Score": "2",
"body": "I think that these comments should be written as answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T18:08:22.900",
"Id": "404501",
"Score": "2",
"body": "It looks like you're implementing a [Counting Sort](https://en.wikipedia.org/wiki/Counting_sort). That can indeed be a good choice for a sorting algorithm if the range of values is small. Be careful about negative numbers, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T05:36:42.040",
"Id": "404554",
"Score": "1",
"body": "You have re-invented bucket sort. With very fine grain buckets. Does not support negative numbers."
}
] | [
{
"body": "<p>basically you are trying to create a space the size of max value and fill it with values(count of the array values in their position in v3) >=0, then refill our array with the values from the space v3</p>\n\n<p>the only change I'd suggest is to completely remove the v2 array</p>\n\n<pre><code>void sort(int *v, int d) {\n\n int max = 0;\n for (int i = 0; i < d; i++) {\n if (v[i] > max)max = v[i];\n }\n\n int v3[max + 1];\n for (int i = 0; i < max + 1; i++) {\n v3[i] = 0;\n }\n\n for (int i = 0; i < d; i++) {\n v3[v[i]]++;\n }\n\n int j = 0;\n for (int i = 0; i < max + 1; i++) {\n if (v3[i] != 0) {\n for (int k = 0; k < v3[i]; k++) {\n v[j] = i;\n j++;\n }\n }\n }\n}\n</code></pre>\n\n<p>Note: </p>\n\n<ol>\n<li>this sort mechanism takes up too much memory in case of numbers with greatly varying differences </li>\n<li>will not support negative values</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T18:16:20.053",
"Id": "404505",
"Score": "2",
"body": "(Welcome to Code Review!) I especially like the `Note:`s. Do you happen to know a name that could be/is given to this sorting method? Do you have remarks/advice about *how* it is coded?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T20:15:40.910",
"Id": "404521",
"Score": "0",
"body": "Like @Yurim said in the comments on the question, It is called the Counting Sort here's [wiki page](https://en.wikipedia.org/wiki/Counting_sort) for the explanation"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T20:53:13.523",
"Id": "404526",
"Score": "0",
"body": "counting sort is just what I wanted to do. I did not know It. I just tried to make a more efficient algorithm of the Bubble Sort"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T10:11:55.400",
"Id": "404761",
"Score": "0",
"body": "Simplification: `if (v3[i] != 0)` not needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T12:24:27.747",
"Id": "404782",
"Score": "0",
"body": "yes programmatically it is not needed, but if we were to omit that computationally it will go to for loop and create `k` and then assign 0 to `k` and then compare `k<v[i]` which would increase the computational overhead by a small margin."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T18:01:46.453",
"Id": "209285",
"ParentId": "209275",
"Score": "3"
}
},
{
"body": "<p>I would do six changes:</p>\n\n<ul>\n<li>Better variable names, especially for the arguments</li>\n<li>Remove unnecessary temporary array</li>\n<li>Handle negative numbers</li>\n<li>Initialize temporary array with <code>memset</code> instead of a loop.</li>\n<li>Comments with pre and post conditions</li>\n<li>Dynamically allocate the temporary array to avoid problems with the stack for large arrays.</li>\n</ul>\n\n<p>The code looks like this:</p>\n\n<pre><code>/* Preconditions:\n array is a pointer to the array that should be sorted\n length is the number of elements in the array\n\n Postconditions:\n array is sorted\n*/\nvoid sort(int *array, size_t length) {\n if(!array || length<1) return;\n\n int max = array[0];\n int min = max;\n\n for (int i = 0; i < length; i++) {\n if(max < array[i]) max = array[i];\n if(min > array[i]) min = array[i];\n }\n\n const size_t range = max - min + 1;\n const size_t size = range * sizeof *array;\n int *tmp = malloc(size);\n if(!tmp) { /* Handle allocation error */ }\n memset(tmp, 0, size);\n\n for (int i = 0; i < length; i++) tmp[array[i] - min]++;\n\n int index = 0;\n for (int i = 0; i < range; i++) {\n for (int j = 0; j < tmp[i]; j++) {\n array[index] = i + min;\n index++;\n }\n }\n free(tmp);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T09:04:47.710",
"Id": "404634",
"Score": "0",
"body": "The one thing I'd do differently (apart from formatting) would be `for (int j = tmp[i] ; 0 <= --j ; ) array[++index] = i + min;`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T14:35:50.840",
"Id": "404809",
"Score": "0",
"body": "@greybeard Thank you. I named it list at first, but later changed it to array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T06:53:19.947",
"Id": "416228",
"Score": "0",
"body": "@chux Very late, but I fixed the problem with length == 0 and overflow problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T15:10:27.307",
"Id": "416288",
"Score": "0",
"body": "Minor idea: `max - min + 1` can overflow `int` math leading to UB. A better behaved alternative: `1LU + max - min` or even better `(size_t)1 + max - min`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T00:04:31.060",
"Id": "209330",
"ParentId": "209275",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "209285",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T15:40:49.510",
"Id": "209275",
"Score": "3",
"Tags": [
"algorithm",
"c",
"sorting"
],
"Title": "My own algorithm to sort integers"
} | 209275 |
<p>I am looking for feedback for the implementation for calculating factorial of a number. I have tried to do with a loop, recursion and in a mutlithreaded way.</p>
<pre><code>package org.spituk.study.programs;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
/**
* Class for calculating factorial of a number.
*
* @author Karan Khanna
* @version 1.0
* @since 12/8/2018
*/
public class Factorial {
private final static int JOB_SIZE = 10;
private final static int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors();
/**
* Calculates the factorial of the number with loop.
*
* @param number whose factorial is to be calculated.
* @return calculated factorial of the number
*/
public long getFactorialWithLoop(final int number) {
long factorial = 1;
for (int index = 2; index <= number; index++) {
factorial = factorial * index;
}
return factorial;
}
/**
* Calculates the factorial of the number with recursion.
*
* @param number whose factorial is to be calculated.
* @return calculated factorial of the number
*/
public long getFactorialWithRecursion(final int number) {
return factorialRecursion(number);
}
/**
* Calculates the factorial of the number with multiple threads.
*
* @param number whose factorial is to be calculated.
* @return calculated factorial of the number
*/
public long getFactorialMultiThreaded(final int number) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(AVAILABLE_PROCESSORS);
List<PartialFactorialJob> partialFactorialJobs = new ArrayList<PartialFactorialJob>();
int startIndex = 1;
int pivot = JOB_SIZE;
while(pivot <= number) {
if(pivot + JOB_SIZE > number) {
pivot = number;
}
partialFactorialJobs.add(new PartialFactorialJob(startIndex, pivot));
startIndex = pivot + 1;
pivot = pivot + JOB_SIZE;
}
try {
long factorial = 1;
final List<Future<Long>> futureList = executor.invokeAll(partialFactorialJobs);
for (Future<Long> future : futureList) {
factorial = factorial * future.get();
}
executor.shutdown();
return factorial;
} catch (InterruptedException | ExecutionException e) {
throw new Exception("Factorial couldn't be calculated.");
}
}
private long factorialRecursion(final int number) {
if (number <= 0) {
return 1;
}
return number * factorialRecursion(number - 1);
}
private class PartialFactorialJob implements Callable<Long> {
private final int startIndex;
private final int endIndex;
PartialFactorialJob(final int startIndex, final int endIndex) {
this.startIndex = startIndex;
this.endIndex = endIndex;
}
public Long call() {
long partialFactorial = 1;
int temp = startIndex;
while (temp <= endIndex) {
partialFactorial = partialFactorial * temp;
temp++;
}
return partialFactorial;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T17:54:00.120",
"Id": "404495",
"Score": "0",
"body": "What's the problem you are asking for? (I don't understand)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T17:55:34.760",
"Id": "404496",
"Score": "0",
"body": "A review for the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T18:05:30.600",
"Id": "404499",
"Score": "0",
"body": "Ok! I thought to be in stackoverflow, excuse me!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T18:19:19.780",
"Id": "404509",
"Score": "0",
"body": "What is the purpose of the multi-threaded version? Keep in mind that for `number >= 66` the result is always zero"
}
] | [
{
"body": "<p>A few comments:</p>\n\n<hr>\n\n<pre><code>import java.util.concurrent.*;\n</code></pre>\n\n<p>Never do wildcard imports unless you're doing a one-time, throw-away program. Maybe, in Java 20 or so, they introduce a class <code>java.util.concurrent.Factorial</code> (contrived example), and then you have a name collision with one of your classes. Better stick to individual imports (or have your IDE organize the imports).</p>\n\n<hr>\n\n<p>Thumbs up for attaching javadoc to all public elements.</p>\n\n<hr>\n\n<pre><code>public long getFactorialWithRecursion(final int number) {\n return factorialRecursion(number);\n}\n</code></pre>\n\n<p>I'd skip the indirection from <code>getFactorialWithRecursion()</code> calling <code>factorialRecursion()</code> and write</p>\n\n<pre><code>public long getFactorialWithRecursion(final int number) {\n if (number <= 0) {\n return 1;\n }\n return number * getFactorialWithRecursion(number - 1);\n}\n</code></pre>\n\n<hr>\n\n<p>Other SO members already commented that computing a factorial with multiple threads might not be a useful application, but I understand that this is for exerecise purposes.</p>\n\n<p>The <code>while</code> loop in <code>getFactorialMultiThreaded</code> makes it hard to read and understand the code, with the two loop variables <code>startIndex</code> and <code>pivot</code> having their operations spread over many lines of code. I'd write something like</p>\n\n<pre><code>for (int startIndex = 1; startIndex <= number; startIndex += JOB_SIZE) {\n int endIndex = Math.min(startIndex + JOB_SIZE - 1, number);\n partialFactorialJobs.add(new PartialFactorialJob(startIndex, endIndex));\n}\n</code></pre>\n\n<p>Similar thing applies to the <code>while</code> loop in your <code>call</code> method, I'd prefer a <code>for</code> loop instead.</p>\n\n<hr>\n\n<p>As your <code>PartialFactorialJob</code> class doesn't access anything from the enclosing <code>Factorial</code> instance, you should make it static (otherwise it carries around a useless internal reference to its enclosing instance, typically visible in your debugger as <code>this$1</code> or similar).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T22:00:31.003",
"Id": "209294",
"ParentId": "209278",
"Score": "4"
}
},
{
"body": "<h1>static</h1>\n\n<p>The <code>Factorial</code> class doesn't have any non-class data members, so it shouldn't have any non-static methods.</p>\n\n<p>In particular:</p>\n\n<ol>\n<li><code>getFactorialWithLoop()</code> can be made <code>static</code>.</li>\n<li><code>getFactorialWithRecursion()</code> can be made <code>static</code> if <code>factorialRecursion()</code> is also made <code>static</code>.</li>\n<li><code>getFactorialMultiThreaded()</code> can be made <code>static</code> if you change <code>class PartialFactorialJob</code> to be a <code>static</code> inner class.</li>\n</ol>\n\n<hr>\n\n<p><code>getFactorialWithLoop()</code>:</p>\n\n<p>Only change I'd make here would be to use the product-assignment operator.</p>\n\n<pre><code>factorial *= index;\n</code></pre>\n\n<hr>\n\n<h1>Tail-Recursion</h1>\n\n<p><code>getFactorialWithRecusion()</code> / <code>factorialRecursion()</code>:</p>\n\n<p>Since the value returned from a recursive call to <code>factorialRecursion()</code> is not directly returned from an outer call, tail-recursion-optimization cannot be performed. This means the stack can overflow if a deep recursive call is made. If the value returned from a recursive call is directly returned, tail-recursion-optimization by the compiler can eliminate recursive calls.</p>\n\n<pre><code>public long getFactorialWithRecursion(final int number) {\n return factorialRecursion(number, 1);\n}\n\nprivate long factorialRecursion(int number, long accumulator) {\n if (number <= 1)\n return accumulator;\n else\n return factorialRecursion(number - 1, accumulator * number);\n}\n</code></pre>\n\n<p>The statement <code>return factorialRecursion(number - 1, accumulator * number);</code> can be translated by the compiler into a jump to the start of the function, with modified arguments.</p>\n\n<hr>\n\n<h1>Job-Size</h1>\n\n<p>This loop is a no-op for values of <code>number</code> less than 10!</p>\n\n<pre><code> int pivot = JOB_SIZE;\n\n while(pivot <= number) {\n // ...\n }\n</code></pre>\n\n<p>So the multi-threaded factorial does not calculate the result properly for <code>number < 10</code>!</p>\n\n<p>The size of a <code>PartialFactorialJob</code> can exceed <code>JOB_SIZE</code>. Consider <code>number = 19</code>. <code>pivot</code> equals 10, so <code>pivot + JOB_SIZE > number</code> is <code>true</code>, and <code>pivot</code> is assigned <code>19</code>, so the first and only job submitted is <code>new PartialFactorialJob(1, 19)</code>.</p>\n\n<p>What you want is the while-loop to test for <code>startIndex</code> not greater than <code>number</code>:</p>\n\n<pre><code>int startIndex = 1;\n\nwhile (startIndex <= number) {\n int endIndex = Math.min(startIndex + JOB_SIZE - 1, number);\n partialFactorialJobs.add(new PartialFactorialJob(startIndex, endIndex));\n startIndex += JOB_SIZE;\n}\n</code></pre>\n\n<p>But now this looks like a for-loop:</p>\n\n<pre><code>for (startIndex = 1; startIndex <= number; startIndex += JOB_SIZE) {\n int endIndex = Math.min(startIndex + JOB_SIZE - 1, number);\n partialFactorialJobs.add(new PartialFactorialJob(startIndex, endIndex));\n}\n</code></pre>\n\n<hr>\n\n<h1>Argument Limits</h1>\n\n<p><code>21!</code> exceeds the size of a <code>long</code>. You might want:</p>\n\n<pre><code>if (number < 0 || number > 20)\n throw new IllegalArgumentException(\"Factorial out-of-range\")\n</code></pre>\n\n<p>Or you may want to use <code>BigInteger</code> for calculation of larger factorials.</p>\n\n<hr>\n\n<h1>Bonus Methods</h1>\n\n<p>You can also use the Stream API to calculate factorials:</p>\n\n<pre><code>long getFactorialWithStream(final int number) {\n return LongStream.rangeClosed(1, number)\n .reduce(1, (x,y) -> x*y);\n}\n\nlong getFactorialWithParallelStream(final int number) {\n return LongStream.rangeClosed(1, number)\n .parallel()\n .reduce(1, (x,y) -> x*y);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T22:33:11.783",
"Id": "209296",
"ParentId": "209278",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T16:06:41.010",
"Id": "209278",
"Score": "2",
"Tags": [
"java"
],
"Title": "Calculating the Factorial of a number"
} | 209278 |
<p>Recently I have been asked to implement a key map with expire time for each key and possibility to limit the number of keys, in Python. I've used a dictionary + heap to store the entries, e.g.:</p>
<pre><code>from datetime import datetime, timedelta
from heapq import heapify, heappop, heappush
class KeyMap:
def __init__(self, maxsize=None):
self.maxsize = maxsize
self.entries = {}
self.entries_heap = []
def set(self, key, value, expiration_time: timedelta):
expires_at = datetime.now() + expiration_time
entry = {'key': key, 'value': value, 'expires_at': expires_at}
self.entries[key] = entry
heappush(self.entries_heap, (expires_at, entry))
if len(self.entries) > self.maxsize:
_, oldest = heappop(self.entries_heap)
del self.entries[oldest['key']]
def get(self, key):
entry = self.entries[key]
if entry['expires_at'] < datetime.now():
del self.entries[key]
raise KeyError(key)
return entry[value]
def delete(self, key):
del self.entries[key]
for i in range(len(self.entries)):
if self.entries_heap[i][1]['key'] == key:
self.entries_heap[i] = self.entries_heap[-1]
self.entries_heap.pop()
heapify(self.entries_heap)
</code></pre>
<p>AFAIC, this should give O(log <em>n</em>) time for <code>set()</code>, O(1) for <code>get()</code> and O(n) for <code>delete()</code>. Are there any ways to improve the performance of <code>set()</code> and <code>delete()</code> methods?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T18:07:56.550",
"Id": "404500",
"Score": "0",
"body": "If it were possible to implement `set` in \\$O(1)\\$ then you could use this data structure to sort a list of numbers in \\$O(n)\\$ (by turning the numbers into `datetime` objects and using them as expiration times and then looking at the order they get evicted from the cache). But sorting a list of numbers takes \\$Ω(n\\log n)\\$."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T08:41:36.637",
"Id": "404630",
"Score": "0",
"body": "Actually, sorting numbers *can* be done in O(n) time, check [this](https://en.wikipedia.org/wiki/Bucket_sort), for example :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T08:48:00.720",
"Id": "404633",
"Score": "0",
"body": "I was afraid someone would offer that nitpick. But if you know all about bucket sort then you know why it's actually \\$Ω(n\\log n)\\$ in the general case."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T17:42:06.667",
"Id": "209284",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"interview-questions",
"cache"
],
"Title": "Implementing key map with expire and size limit"
} | 209284 |
<p>I recently asked for a review of a <a href="https://codereview.stackexchange.com/questions/206745/small-stack-based-language-in-rust">stack based language</a> I made in Rust. I made a lot of changes since then and a lot has changed. Hopefully I haven't gone backwards in progress.</p>
<p>Most notably:</p>
<ol>
<li><p>I refactored the code into a lexer and parser. In other words: there is a module for taking in a string and converting it into a vector of tokens. This vector of tokens is then executed.</p></li>
<li><p>I have added a better REPL that live updates each line. As you are writing code in the console the output is displayed in the bottom right corner.</p></li>
</ol>
<p>The only thing I didn't do from the answer was implement more than one data type than a float. See my comment on the answer for more details. However, there is now a <code>Float</code> structure for that AST.</p>
<p><strong>src/ast/mod.rs</strong></p>
<pre><code>//! This module contains functions and structures related to the AST of the im-
//! astack language. Most notably, it converts between "string" *tokens* and e-
//! num representation.
use std::str::FromStr;
use std::fmt;
use std::ops::Add;
use std::ops::Sub;
use std::ops::Mul;
use std::ops::Div;
/// Wrapper for `f64`.
///
/// *Note* This is needed for `strum` to operate correctly as `From<&'a str>`
/// needs to be implemented, which is impossible with a bare `f64`.
#[derive(Debug)]
pub struct Float(pub f64);
impl Clone for Float {
fn clone(&self) -> Float { Float(self.0) }
}
impl PartialEq for Float {
fn eq(&self, other: &Float) -> bool {
self.0 == other.0
}
}
impl<'a> From<&'a str> for Float {
#[inline]
fn from(s: &'a str) -> Self {
Float(s.parse::<f64>().unwrap_or(0.0).to_owned())
}
}
impl fmt::Display for Float {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl Into<usize> for Float {
#[inline]
fn into(self) -> usize {
self.0 as usize
}
}
impl Add for Float {
type Output = Float;
#[inline]
fn add(self, other: Float) -> Float {
Float(self.0 + other.0)
}
}
impl Sub for Float {
type Output = Float;
#[inline]
fn sub(self, other: Float) -> Float {
Float(self.0 - other.0)
}
}
impl Mul for Float {
type Output = Float;
#[inline]
fn mul(self, other: Float) -> Float {
Float(self.0 * other.0)
}
}
impl Div for Float {
type Output = Float;
#[inline]
fn div(self, other: Float) -> Float {
Float(self.0 / other.0)
}
}
#[derive(EnumString)]
pub enum Token {
#[strum(serialize="+")]
Add,
#[strum(serialize="-")]
Sub,
#[strum(serialize="*")]
Mul,
#[strum(serialize="/")]
Div,
#[strum(serialize="dup")]
Dup,
#[strum(serialize="swp")]
Swp,
#[strum(serialize="jnz")]
Jnz,
#[strum(serialize="print")]
Print,
#[strum(default="true")]
Number(Float)
}
impl Into<Float> for Token {
/// Convets Token into Float.
///
/// *Note* It tries the best it can, even though it doesn't make sense to
/// convert Token::Add to a float, it defaults this (as well as every other
/// operator to Float(0.0).
fn into(self) -> Float {
match self {
Token::Number(Float(x)) => Float(x),
_ => Float(0.0)
}
}
}
/// Compiles a vector of stringy tokens into the a vector of `Token`s.
///
/// *Note* It tires the best it can, if the token can't be parsed, convert it
/// to a `Float(0.0)` as default.
pub fn compile_program(tokens: &[&str]) -> Vec<Token> {
let mut ast = Vec::new();
for tok in tokens {
let res = match Token::from_str(tok) {
Ok(good_tok) => good_tok,
_ => Token::Number(Float(0.0))
};
ast.push(res);
}
ast
}
</code></pre>
<p><strong>src/words/mod.rs</strong></p>
<pre><code>//! The `word` module contains the verbs and nouns that create a program. Verbs
//! are functions (regardless of airity) and nouns are data.
use ast::Float;
/// Represents and "environment" for a programming language. In this small lan-
/// guage it is simply a "stack" that stores numbers and an "output vector" th-
/// at captures what the output would be.
pub struct Env {
pub stack: Vec<Float>,
pub output: Vec<Float>
}
impl Env {
/// Helper function for pushing onto the environment's stack.
#[inline(always)]
pub fn push(&mut self, item: Float) {
self.stack.push(item);
}
/// Helper function for pushing onto the environment's stack.
#[inline(always)]
pub fn pop(&mut self) -> Float {
self.stack.pop().unwrap_or(Float(0.0))
}
/// Extracts two values off the top of a stack.
#[inline(always)]
pub fn get_ops(&mut self) -> (Float, Float) {
(self.pop(), self.pop())
}
/// Parses a numerical value to a float.
///
/// # Arguments
///
/// `token` - The value to be converted to a float.
///
/// *Note* - If `parse_number` is **not** given a number, it will still return
/// `0.0`.
#[inline(always)]
pub fn push_number(&mut self, number: Float) {
self.push(number);
}
/// Pops the top two elements off the stack and adds them.
///
/// *Note* - If no number is available to pop from the stack, a default value
/// of `0.0` is used.
#[inline(always)]
pub fn add(&mut self) {
let (a, b) = self.get_ops();
self.push(a + b);
}
/// Pops the top two elements off the stack and subtracts them.
///
/// *Note* - If no number is available to pop from the stack, a default value
/// of `0.0` is used.
#[inline(always)]
pub fn sub(&mut self) {
let (a, b) = self.get_ops();
self.push(a - b);
}
/// Pops the top two elements off the stack and multiplies them.
///
/// *Note* - If no number is available to pop from the stack, a default value
/// of `0.0` is used.
#[inline(always)]
pub fn mul(&mut self) {
let (a, b) = self.get_ops();
self.push(a * b);
}
/// Pops the top two elements off the stack and divides them.
///
/// *Note* - If no number is available to pop from the stack, a default value
/// of `0.0` is used. If division by `0.0` occurs, then a value of `0.0` pushed
/// to `stack` instead.
#[inline(always)]
pub fn div(&mut self) {
let (a, b) = self.get_ops();
if b.0 == 0.0 {
self.push(Float(0.0));
} else {
self.push(a / b);
}
}
/// Pops the top element off the stack and pushes two copies of it on the stack.
///
/// *Note* - If no number is available to pop from the stack, a default value
/// of `0.0` is used, thus `0.0` is pushed on to the stack twice.
#[inline(always)]
pub fn dup(&mut self) {
let to_dup = self.pop();
let copy = to_dup.clone();
self.push(to_dup);
self.push(copy);
}
/// Pops the top two elements off the stack and swaps their values.
///
/// *Note* - If no number is available to pop from the stack, a default value
/// of `0.0` is used.
#[inline(always)]
pub fn swp(&mut self) {
let (first, second) = self.get_ops();
self.push(first);
self.push(second);
}
/// Pops off two values off the stack. If the first value is not zero, take the
/// value of the second value and jump to that location in code.
///
/// * `reg` - The the current location of the register.
///
#[inline(always)]
pub fn jnz(&mut self, reg: &mut usize) {
let (cond, jump) = self.get_ops();
if cond.0 != 0.0 {
*reg = jump.into();
}
}
/// Prints the top value of a particular stack.
///
/// *Note* - Does not "print" to stdout, instead it prints to the `output` par-
/// ameter. This is for better debugging and test.
#[inline(always)]
pub fn print_float(&mut self) {
let popped = self.pop();
self.output.push(popped);
}
}
</code></pre>
<p><strong>src/bin/imastack.rs</strong></p>
<pre><code>//! This the REPL for the imastack language. The output of the current line is
//! displayed at the bottom of the screen.
extern crate imastack;
extern crate ncurses;
use std::process;
/// Simple REPL for the imastack langauge.
fn main() {
ncurses::initscr();
ncurses::raw();
ncurses::noecho();
ncurses::keypad(ncurses::stdscr(), true);
let mut code: Vec<String> = Vec::new();
code.push(String::from(" "));
let mut current_line: usize = 0;
let mut current_col: usize = 0;
loop {
ncurses::mv(current_line as i32, current_col as i32);
let ch = ncurses::getch();
match ch {
ncurses::KEY_ENTER => {
code.push(String::from(" "));
current_line += 1;
current_col = 0;
},
// Also enter key...
10 => {
code.push(String::from(" "));
current_line += 1;
current_col = 0;
},
ncurses::KEY_UP => {
match current_line {
0 => { },
_ => current_line -= 1,
};
current_col = 0;
},
ncurses::KEY_DOWN => {
if current_line == code.len() {
} else {
current_line += 1;
}
current_col = 0;
},
// Exit with Tab key.
9 => process::exit(0),
character => {
code[current_line].push(character as u8 as char);
ncurses::addch(character as u64);
current_col += 1;
}
};
let env = imastack::eval(&code[current_line].as_str());
let mut footer = String::new();
for num in env.output {
footer.push_str(&num.to_string());
footer.push(' ');
}
ncurses::mv(ncurses::LINES() - 1, 0);
ncurses::clrtoeol();
ncurses::mvprintw(ncurses::LINES() - 1,
ncurses::COLS() - footer.len() as i32,
&mut footer.to_string());
}
}
</code></pre>
<p><strong>src/lib.rs</strong></p>
<pre><code>extern crate strum;
#[macro_use]
extern crate strum_macros;
pub mod ast;
pub mod words;
use ast::Token;
use words::Env;
/// Given a list of commands, execute the commands.
///
/// # Arguments
///
/// * `tokens` - A slice of tokens to be executed.
/// * `stack` - The stack to keep the current state of the program.
fn execute_program(tokens: &[Token],
env: &mut Env) {
// Analogous to the role of a "register" for a Turing machine.
let mut reg: usize = 0;
while let Some(tok) = tokens.get(reg) {
match tok {
Token::Add => env.add(),
Token::Sub => env.sub(),
Token::Mul => env.mul(),
Token::Div => env.div(),
Token::Dup => env.dup(),
Token::Swp => env.swp(),
Token::Jnz => env.jnz(&mut reg),
Token::Print => env.print_float(),
Token::Number(x) => env.push_number(x.clone()),
}
reg += 1;
}
}
/// Evaluates a string of code.
///
/// # Arguments
///
/// * `code` - The string of code to be executed.
///
/// *Note* The value returned is the "output" of the code. Output is not done
/// through stdout for easier debugging.
pub fn eval(code: &str) -> Env {
let tokens: Vec<&str> = code.split(' ').collect();
let mut env = Env {
stack: Vec::new(),
output: Vec::new(),
};
let ast = ast::compile_program(tokens.as_slice());
execute_program(ast.as_slice(), &mut env);
env
}
</code></pre>
<p><strong>tests/integration_test.rs</strong></p>
<pre><code>extern crate imastack;
use imastack::ast::Float;
#[test]
fn basic_add() {
assert_eq!(
imastack::eval("1 2 + print").output,
vec![Float(3.0)]);
}
#[test]
fn basic_sub() {
assert_eq!(
imastack::eval("1 2 - print").output,
vec![Float(1.0)]);
}
#[test]
fn basic_mul() {
assert_eq!(
imastack::eval("3 3 * print").output,
vec![Float(9.0)]);
}
#[test]
fn basic_div() {
assert_eq!(
imastack::eval("3 6 / print").output,
vec![Float(2.0)]);
}
#[test]
fn div_by_zero_is_zero() {
assert_eq!(
imastack::eval("0 1 / print").output,
vec![Float(0.0)]);
}
#[test]
fn basic_swp() {
assert_eq!(
imastack::eval("1 2 swp print print").output,
vec![Float(1.0), Float(2.0)]);
}
#[test]
fn basic_dup() {
assert_eq!(
imastack::eval("1 dup print print").output,
vec![Float(1.0), Float(1.0)]);
}
#[test]
fn basic_jnz() {
assert_eq!(
imastack::eval("1 4 jnz 0 1 print").output,
vec![Float(1.0)]);
}
</code></pre>
<p>The <a href="https://github.com/thyrgle/imastack" rel="nofollow noreferrer">Github is here</a>. You can start the REPL with:</p>
<pre><code>cargo run --bin imastack
</code></pre>
<p>and you can exit the REPL by pressing the <kbd>Tab</kbd> key.</p>
| [] | [
{
"body": "<p>Some basic comments.</p>\n\n<ol>\n<li><p>I'd pull the Float struct out into its own file - it makes the src/ast/mod.rs longer than it needs to be.</p></li>\n<li><p>I think you can derive Clone and PartialEq on Float, rather than implementing them manually. </p></li>\n<li><p>Consider deriving Copy on Float, since it's trivially copyable - that will allow you to remove some explicit calls to clone.</p></li>\n<li><p>Error handling seems \"lax\". In particular parsing and evaluation just default rather than error. Maybe that's OK here, but I try to avoid it. You probably want your own Result type. Once you use it in many places the code doesn't get any uglier, as most places rather than return the default you can just use the <code>?</code> operator. </p></li>\n</ol>\n\n\n\n<pre><code>pub fn compile_program(tokens: &[&str]) -> Vec<Token> {\n let mut ast = Vec::new();\n for tok in tokens {\n let res = match Token::from_str(tok) {\n Ok(good_tok) => good_tok,\n _ => Token::Number(Float(0.0))\n };\n ast.push(res);\n }\n ast\n}\n</code></pre>\n\n<p>would become</p>\n\n<pre><code>pub fn compile_program(tokens: &[&str]) -> Result<Vec<Token>> {\n let mut ast = Vec::new();\n for tok in tokens {\n ast.push(Token::from_str(tok)?);\n }\n ast\n}\n</code></pre>\n\n<p>Which can be made even neater using <code>map</code> and <code>collect</code> - I think you can do:</p>\n\n<pre><code>pub fn compile_program(tokens: &[&str]) -> Result<Vec<Token>> {\n tokens.map(Token::from_str).collect()\n}\n</code></pre>\n\n<ol start=\"5\">\n<li>The AST parsing code could probably do with some unit tests. </li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T22:36:46.637",
"Id": "405314",
"Score": "0",
"body": "Thanks! I have nearly implemented all your suggestions. One thing about the \"lax\" error handling: I don't intend on programming in this language. I can add a `strict_compile_program` function though! I'm working on evolving programs with genetic algorithms. They start off pretty dumb and need *a lot* of help. Having the programs error a lot at the beginning could easily kill of the entire population."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T01:34:07.037",
"Id": "209579",
"ParentId": "209289",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209579",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T20:36:50.270",
"Id": "209289",
"Score": "2",
"Tags": [
"rust",
"interpreter"
],
"Title": "Second take at a stack based langauge"
} | 209289 |
<p>I'm working my way through a book on algorithms. One of the first challenges is the merge sort. I've seen this implemented before, but as the book suggested I coded one from just the method without looking at the code. When I looked it was very different from mine. Many online examples match the way the book does it.</p>
<p>I am asking about this because I want to learn the reasons this code is better, or if there are trade-offs, or things that are merely style choices, rather than just adopting the pattern of the example code.</p>
<p>Here's mine in Python:</p>
<pre><code>A = [1,5,7,3,4,3,1,8,9,12,64,22,83,223,11]
def merge(A1,A2):
B1 = []
while(len(A1)>0 and len(A2) > 0):
if(A1[0] < A2[0]):
B1.append(A1.pop(0))
else:
B1.append(A2.pop(0))
B1 = B1 + A1 + A2
return B1
def mergesort(B):
if len(B)>1:
q = len(B)//2
B1 = mergesort(B[:q])
B2 = mergesort(B[q:])
return merge(B1,B2)
else:
return (B)
print("mergesort(A) =",mergesort(A))
</code></pre>
<p>Here's an example a lot like in my book and in many websites, from GeeksForGeeks</p>
<blockquote>
<p><strong>Python program for implementation of MergeSort</strong> </p>
<pre><code># Merges two subarrays of arr[].
# First subarray is arr[l..m]
# Second subarray is arr[m+1..r]
def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r- m
# create temp arrays
L = [0] * (n1)
R = [0] * (n2)
# Copy data to temp arrays L[] and R[]
for i in range(0 , n1):
L[i] = arr[l + i]
for j in range(0 , n2):
R[j] = arr[m + 1 + j]
# Merge the temp arrays back into arr[l..r]
i = 0 # Initial index of first subarray
j = 0 # Initial index of second subarray
k = l # Initial index of merged subarray
while i < n1 and j < n2 :
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Copy the remaining elements of L[], if there
# are any
while i < n1:
arr[k] = L[i]
i += 1
k += 1
# Copy the remaining elements of R[], if there
# are any
while j < n2:
arr[k] = R[j]
j += 1
k += 1
# l is for left index and r is right index of the
# sub-array of arr to be sorted
def mergeSort(arr,l,r):
if l < r:
# Same as (l+r)/2, but avoids overflow for
# large l and h
m = (l+(r-1))/2
# Sort first and second halves
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
# Driver code to test above
arr = [12, 11, 13, 5, 6, 7]
n = len(arr)
print ("Given array is")
for i in range(n):
print ("%d" %arr[i]),
mergeSort(arr,0,n-1)
print ("\n\nSorted array is")
for i in range(n):
print ("%d" %arr[i]),
# This code is contributed by Mohit Kumra
</code></pre>
</blockquote>
<p>First, I notice this is manipulating the initial list in place by tracking indices, and I am creating several copies of the data.</p>
<p>I would suppose that I am using more memory, however the example posted lower does create temporary lists to perform the merge. But there they also use index tracking instead of destroying the two arrays with pop as they are consumed.</p>
<p>So again, I'm trying to learn why the differences matter. Which is more educational than just taking on this way of doing it.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T22:12:32.980",
"Id": "404537",
"Score": "0",
"body": "Why was the second block of code edited to change the first comment to a header?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T22:34:49.543",
"Id": "404538",
"Score": "1",
"body": "because this second code isn't from you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T00:22:32.237",
"Id": "404542",
"Score": "0",
"body": "@PaulS For formatting. It was a code comment but it is also a descriptive title header so I made it into that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T01:27:22.663",
"Id": "404544",
"Score": "0",
"body": "I did mention that it wasn't from me and said where it came from. Is a header the standard way to note code that isn't yours or something?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T01:59:14.953",
"Id": "404545",
"Score": "2",
"body": "@PaulS No. I actually turned it into a header by mistake. (I somehow mangled it when I went to change it, when I fixed the mangle I chose to make it a header) The significant change was to enclose all of the code into a blockquote. ***THAT*** is how we distinguish code that isn't yours. Just like quoting text from other authors."
}
] | [
{
"body": "<p>There is a couple of problems with your implementation.</p>\n\n<ul>\n<li><p>The most important trait of the merge sort is stability: the elements compared equal retain their relative order. It does not matter when sorting integers, but is extremely important when sorting more complex data. The comparison</p>\n\n<pre><code> if(A1[0] < A2[0]):\n</code></pre>\n\n<p>loses stability, because in case <code>A1[0]</code> is equal to <code>A2[0]</code> the element from <code>A2</code> will be merged first. The correct way is to <code>if A1[0] <= A2[0]</code>.</p></li>\n<li><p><code>pop(0)</code> has a linear time complexity, which renders the overall performance quadratic. <code>B1 = B1 + A1 + A2</code> creates yet another copy of the list, and it doesn't help the performance either.</p></li>\n</ul>\n\n<p>Manipulating indices, if done right, does reduce memory allocations and deallocations indeed. Unfortunately the GeeksForGeeks code you provided doesn't do it right.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T23:21:30.507",
"Id": "209297",
"ParentId": "209291",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T21:13:20.530",
"Id": "209291",
"Score": "0",
"Tags": [
"python",
"algorithm",
"mergesort"
],
"Title": "Merge sort approach in Python"
} | 209291 |
<p>My app interacts with Google Calendar. This Service wraps <a href="https://developers.google.com/resources/api-libraries/documentation/calendar/v3/php/latest/class-Google_Service_Calendar.html" rel="nofollow noreferrer"><code>Google_Service_Calendar</code></a>:</p>
<pre><code><?php
declare(strict_types=1);
namespace App\Service;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class GoogleCalendarService extends \Google_Service_Calendar
{
public const CALENDAR_ID = '123example@group.calendar.google.com';
public function __construct(SessionInterface $session) {
$client = new \Google_Client();
$client->setAccessToken($session->get('google_access_token'));
parent::__construct($client);
}
}
</code></pre>
<p>I have the feeling that having the session as a dependency is not good practice. For a user of that service, it is absolutely not clear that the access token needs to be set in the session. </p>
<p>I could probably add some Exceptions for the case that it is not set, but I wonder whether there is a better way?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T00:50:51.670",
"Id": "503024",
"Score": "0",
"body": "should `$session` be an optional parameter? if not, then under what conditions would an exception be warranted?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T21:36:42.013",
"Id": "209292",
"Score": "6",
"Tags": [
"php",
"dependency-injection",
"session",
"wrapper",
"symfony3"
],
"Title": "Wrapper for Google_Service_Calendar as a Symfony service"
} | 209292 |
<p>I've written a very tiny script using class to scrape some titles of products from craigslist. My intention is to make use of <code>__str__()</code> method so that my script can print the result without explicitly calling that very method.</p>
<p>However, when I execute my script in the following way, I get the desired results.</p>
<p>Is this the only way I can print the result or there is anything better to print the result through dunder str method?</p>
<pre><code>import requests
from bs4 import BeautifulSoup
URL = "http://bangalore.craigslist.co.in/search/rea?s=120"
class DataSourcer:
def __init__(self,link):
self.link = link
self.datalist = []
def fetch(self):
res = requests.get(self.link)
soup = BeautifulSoup(res.text,"lxml")
for ilink in soup.select("li.result-row a[data-id]"):
self.datalist.append(ilink.text)
# return self.datalist #I do not wish to return "self.datalist" here
def __str__(self):
return self.datalist
if __name__ == '__main__':
crawler = DataSourcer(URL)
crawler.fetch()
print(crawler.__str__()) #I found it working this way
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T21:50:01.130",
"Id": "404531",
"Score": "0",
"body": "I'm not entirely sure what you're asking, but: `print(crawler.__str__())` should be `print(str(crawler))`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T21:54:39.010",
"Id": "404532",
"Score": "0",
"body": "That is exactly what you have surmised already I'm asking. Your suggested approach threw this error `TypeError: __str__ returned non-string (type list)` @Dair . Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T21:57:33.653",
"Id": "404533",
"Score": "3",
"body": "You should instead do `return str(self.datalist)`. `def __str__` should return a string type. Instead, you have returned a list. You can convert the list to a string by calling `str`, so `return str(self.datalist)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T22:12:23.050",
"Id": "404536",
"Score": "0",
"body": "Yep, this leads me to a better approach @Dair. Is there any way I can print the result in regular strings other than the list. I know I'm wrong but I tried it `for item in crawler: print(item)` and failed miserably. However, I get the result when i try like this (in my existing script) `for item in crawler.__str__(): print(item)`. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T09:51:30.263",
"Id": "404556",
"Score": "1",
"body": "`return \"\\n\".join(self.datalist)` would be the right way instead of `for ...: print(...)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T21:59:42.277",
"Id": "404595",
"Score": "0",
"body": "`#I do not wish to return \"self.datalist\" here` why not? What are you trying to achieve with this arbitrary limitation?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T21:42:39.460",
"Id": "209293",
"Score": "1",
"Tags": [
"python",
"object-oriented",
"python-3.x",
"web-scraping"
],
"Title": "Scraping and printing titles from Craigslist"
} | 209293 |
<p>What do you think about such an object function?</p>
<pre><code>const stc = {
delayTimer: {},
sleep: (m, name) => new Promise(r => stc.delayTimer[name] = setTimeout(r, m)),
sleepProlong: async (ms, name)=> {
if (stc.delayTimer[name])
clearTimeout(stc.delayTimer[name]);
delete stc.delayTimer[name];
return await stc.sleep(ms, name);
}
}
</code></pre>
<p>It is used to make a delay, but additionally when you call it again before the set time expires, it clears the counter and counts from the beginning, does not release the function any further.</p>
<pre><code>async function s (){
console.log("wy");
await stc.sleepProlong(5000, "mek");
console.log("my");
}
</code></pre>
<p>For example, when in the console you will start <code>s()</code> before 5 seconds elapses from the previous firing, "we" will not appear. when you stop, it will complete the last counting and "we" will be displayed.</p>
<p>What do you think? Can you do it better?</p>
| [] | [
{
"body": "<h1>What is it for?</h1>\n<p>Without knowing what you would use this for I can only go by your question.</p>\n<p>The behaviour of <code>stc</code> is not what the question's title suggests as it is very easy to make it fail or behave in a non intuitive manner.</p>\n<h2>Forever pending</h2>\n<p>Consider the following use example</p>\n<pre><code>stc.sleep(1000, "test").then(()=>log("Test timeout"); // this promise is never resolved\nsetTimeout(()=>{\n stc.sleepProlong(2000, "test").this(()=>log("Test prolonged timeout")\n },200);\n</code></pre>\n<p>The first promise is left pending and will never be resolved.</p>\n<h2>Some other potential problems</h2>\n<ul>\n<li>Each time <code>sleepProlong</code> is called you leave another promise unresolved.</li>\n<li>When <code>sleepProlong</code> is called the name implies that it "prolongs sleep", but if the sleep has already timeouted out it creates a new sleep???</li>\n<li>If sleep is called with the same name as an existing sleep, the previous sleep can no longer be prolonged,</li>\n<li>The <code>stc</code> interface exposes <code>delayTimer</code> making the state of <code>stc</code> untrustable.</li>\n</ul>\n<h2>Expectations?</h2>\n<p>From the question's title I would expect</p>\n<ul>\n<li>that there is only one promise for a named sleep.</li>\n<li>that the sleep and prolonged sleep can be canceled</li>\n<li>that the sleep can be prolonged indefinitely</li>\n<li>that attempting to prolong a sleep that has timeout does nothing.</li>\n<li>that calling <code>sleep</code> with the <code>name</code> of an unresolved existing sleep does nothing</li>\n</ul>\n<h2>Some general style and coding points</h2>\n<ol>\n<li>Function argument names are inconsistent you call the timeout delay <code>m</code> in one function and <code>ms</code> in the other.</li>\n<li>The line <code>delete stc.delayTimer[name];</code> is not needed as you overwrite the value by calling <code>sleep</code> on the next line.</li>\n<li>not using curlies <code>{}</code> to delimited statement blocks is a bad habit, Always delimit statement blocks with <code>{...}</code>.You had <code>if (stc.delayTimer[name]) clearTimeout(stc.delayTimer[name]);</code> is better as <code>if (stc.delayTimer[name]) { clearTimeout(stc.delayTimer[name]); }</code></li>\n<li>There is no need to check if the named timeout event handle exists. <code>clearTimeout</code> will ignore <code>undefined</code> and already timed out handles. Thus <code>if (stc.delayTimer[name]) { clearTimeout(stc.delayTimer[name]); }</code> can be <code>clearTimeout(stc.delayTimer[name]);</code> and not change the behaviour.</li>\n<li>This may just be my personal preference but it feels wrong having the time <code>m</code>, or <code>ms</code> as the first argument. Putting the <code>name</code> first and then the delay seems more natural (and thus easier to remember)</li>\n<li>You don't need to <code>await</code> the promise you return in the <code>async function</code>, Async functions do this automatically .</li>\n<li>Ensure that you protect important state variables. If entries in the object <code>delayTimer</code> are mutated then you lose the ability to maintain <code>stc</code>'s correct behaviour. You can protect it via closure.</li>\n</ol>\n<h2>Cleanup and keeping original behaviour</h2>\n<p>without changing the behaviour of you code I have made changes as outlined in the above points, and modified some names.</p>\n<pre><code>const stc = (() => {\n const handles = {};\n return {\n sleep(name, time) { return new Promise(r => handles[name] = setTimeout(r, time)) },\n async prolong(name, time) {\n clearTimeout(handles[name]);\n return stc.sleep(name, time);\n }\n };\n})();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T15:56:38.567",
"Id": "209318",
"ParentId": "209295",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T22:24:45.223",
"Id": "209295",
"Score": "0",
"Tags": [
"javascript",
"async-await"
],
"Title": "Sleep and prolong sleep"
} | 209295 |
<blockquote>
<p>A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before.</p>
<p>For example:</p>
<p>44 → 32 → 13 → 10 → 1 → 1</p>
<p>85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89</p>
<p>Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89.</p>
<p>How many starting numbers below ten million will arrive at 89?</p>
</blockquote>
<p>My solution doesn't finish in under a minute. I'm already caching the results of arrivesAt89, including all permutations. Any help is welcomed.</p>
<pre><code>#include<iostream>
#include<vector>
#include<unordered_map>
#include<algorithm>
int sumOfDigitsSquared(int n) {
auto digits = std::to_string(n);
int sum = 0;
for (auto c : digits) {
sum = (c - '0') * (c - '0');
}
return sum;
}
std::vector<int> permutations(int n) {
auto digits = std::to_string(n);
std::vector<int> res;
res.push_back(n);
do {
res.push_back(stoi(digits));
} while (std::next_permutation(digits.begin(), digits.end()));
return res;
}
bool arrivesAt89(int n) {
static auto cache = std::unordered_map<int,bool>();
int m = n;
while (m != 1) {
if(cache.find(m) != cache.end()) {
return cache.find(m)->second;
}
if (m == 89) {
auto perms = permutations(m);
for (auto p : perms) {
cache.insert({p, true});
}
return true;
}
m = sumOfDigitsSquared(m);
}
auto perms = permutations(n);
for (auto p : perms) {
cache.insert({p, false});
}
return false;
}
int main() {
int numberOf89s = 0;
for (int i = 1; i< 10000000; i++) {
if (arrivesAt89(i)) numberOf89s++;
}
std::cout << numberOf89s << std::endl;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T10:46:32.880",
"Id": "404559",
"Score": "2",
"body": "Although I've answered it now... This code simply doesn't work. It will quickly enter an infinite loop. Code that doesn't work is off-topic for codereview, and on-topic for stackoverflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T23:11:56.247",
"Id": "404601",
"Score": "0",
"body": "As an aside, it would be more logical to use the smallest number in the circle as the canonical example, rather than the second-largest. But that's for Project Euler themselves."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T23:26:21.277",
"Id": "404602",
"Score": "0",
"body": "Project Euler asks people not to share solution code for obvious reasons."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T00:06:58.783",
"Id": "404604",
"Score": "5",
"body": "@MichaWiedenmann [Consensus](https://codereview.meta.stackexchange.com/questions/157/project-euler-solutions) is that the goal of this site (code review) is more important than PE's request to keep solutions secret (which has obviously been ignored many times over on other sites including personal blogs, so the existence of solutions on SE isn't going to have any great effect)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T08:41:11.370",
"Id": "404629",
"Score": "0",
"body": "@user673679 Problem statements without MCVE are not often on-topic for Stack Overflow, so please doublecheck that."
}
] | [
{
"body": "<p>Obviously, the algorithm provided will set up a number of equivalence classes of numbers containing the same ciphers. E. g. 1012, 1210, and all other permutations of are equivalent.</p>\n\n<p>So you might want to sort the numbers by their digits (skipping all zeros), so you'd only have to store 112 for above numbers, or the other way round, only generate the sorted numbers by some appropriate algorithm.</p>\n\n<p>Finally, you can easily generate the number of permutations from these numbers. Example above:</p>\n\n<pre><code>00 000 112\n</code></pre>\n\n<p>There are 8! but we need to divide by the number of equivalent permutations (due to the five zeros and the two ones), so we get:</p>\n\n<pre><code>8! / 5! / 2!\n</code></pre>\n\n<p>A mentioned number generator might look like this one:</p>\n\n<pre><code>std::vector<unsigned int> current({1, 2, 3, 4, 5, 6, 7, 8, 9 });\nstd::vector<unsigned int> previous;\n\nfor(unsigned int i = 0; i < 7; ++i)\n{\n using std::swap;\n for(auto n : current)\n std::cout << n << ' ';\n std::cout << std::endl;\n swap(current, previous);\n current.clear();\n for(auto n : previous)\n {\n for(unsigned int m = 1; m <= n % 10; ++m)\n {\n current.push_back(n * 10 + m);\n }\n }\n}\n</code></pre>\n\n<p>producing all sorted numbers up to 7 digits (OK, within numbers, sorting order is invers, but that's not of relevance...).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T10:22:12.553",
"Id": "209307",
"ParentId": "209303",
"Score": "3"
}
},
{
"body": "<ul>\n<li>I guess the idea behind using permutations is that any permutation of the same digits will result in the same squared sum. However... in that case, shouldn't we simply calculate the squared sum and cache that?</li>\n<li>It appears that we're only caching the permutations of the digits at the end of the chain. i.e. we'll only ever end up with 1, 89 and 98 in the map! We should probably be caching all the values in the chain up to the final result.</li>\n<li><code>#include <string></code> for <code>std::to_string</code>.</li>\n<li>Converting to and from <code>std::string</code> is probably quite slow. We can use simple integer arithmetic to extract the individual digits.</li>\n<li>The implementation of <code>sumOfDigitsSquared</code> is clearly incorrect with basic testing.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T12:14:23.057",
"Id": "404564",
"Score": "0",
"body": "The `%` can also be slow. Don't assume your method is faster without measuring. (I don't say it's slower, but you have to measure before making assumptions)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T12:15:02.553",
"Id": "404565",
"Score": "0",
"body": "\"The implementation of sumOfDigitsSquared is clearly incorrect with basic testing\" can you explain why it's incorrect?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T13:19:09.087",
"Id": "404568",
"Score": "0",
"body": "You will be testing numbers up to 9,999,999 since 10,000,000 goes straight to 1. The sum of the digits squared of 9,999,999 is 7 * 81 = 567. Every number you test will be in the range 1..567 after one `sumOfDigitsSquared()` step. That will help you speed things up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T14:48:30.500",
"Id": "404571",
"Score": "2",
"body": "@Calak only the last iteration of the loop matters, it continuously overwrites `sum`. `+=` is probably needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T15:32:59.777",
"Id": "404574",
"Score": "1",
"body": "@WesTolemanWe I know, but I asked him to try to be more precise about why it doesn't work. Just telling \"it's broken\" without explaining why is almost pointless."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T16:24:06.417",
"Id": "404576",
"Score": "0",
"body": "@Calak I've removed mention of the `%` operator. Either way, calling `std::to_string` is definitely slower than it could be."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T16:33:48.620",
"Id": "404578",
"Score": "1",
"body": "@Calak I think it's much better for OP to find the exact problem themselves. It's not hard to find, and doing so helps more with the actual issue (OP needs to learn to debug and test code). The point of that statement is \"do basic testing\", not \"it's broken\"."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T10:44:22.910",
"Id": "209309",
"ParentId": "209303",
"Score": "11"
}
},
{
"body": "<pre><code>int sumOfDigitsSquared(int n) {\n auto digits = std::to_string(n);\n int sum = 0;\n\n for (auto c : digits) {\n sum += (c - '0') * (c - '0'); // I corrected the = into +=\n }\n\n return sum;\n}\n</code></pre>\n\n<p>Conversions come with a performance hit, especially when the conversion implies memory allocation and copy, as here with <code>std::to_string</code>. It would make perfect sense if you had some use for the <code>string</code>, but you don't, since you return another int. And the math behind it is really basic:</p>\n\n<pre><code>constexpr int sum_of_squared_digits(int n) {\n int res = 0;\n while (n) {\n const int digit = n % 10;\n res += digit * digit;\n n /= 10;\n }\n return res;\n}\n</code></pre>\n\n<p>I've marked it <code>constexpr</code>, only to hint that the whole algorithm could be performed at compile-time, but it wouldn't really be fair, so it won't.</p>\n\n<pre><code>bool arrivesAt89(int n) {\n static auto cache = std::unordered_map<int,bool>();\n</code></pre>\n\n<p><code>unordered_map</code> might not be necessary in this case. A simple array would suffice, with <code>0</code> meaning unexplored, <code>1</code> ending with <code>1</code> and <code>89</code> ending with <code>89</code>: it's even faster and all the memory allocation is done upfront.</p>\n\n<pre><code> int m = n;\n while (m != 1) {\n if(cache.find(m) != cache.end()) {\n return cache.find(m)->second;\n }\n if (m == 89) {\n auto perms = permutations(m);\n for (auto p : perms) {\n cache.insert({p, true});\n }\n return true;\n }\n m = sumOfDigitsSquared(m);\n</code></pre>\n\n<p>Here is I think the main weakness of your algorithm: you only cache the result for the number <code>n</code> and its permutations; all intermediary values are ignored, although they belong on the same path as <code>n</code> and would populate the <code>map</code> much faster. </p>\n\n<pre><code> }\n\n auto perms = permutations(n);\n for (auto p : perms) {\n cache.insert({p, false});\n }\n return false;\n}\n</code></pre>\n\n<p>Computing the permutations come with another heavy conversion, with memory allocation and copy (<code>std::to_string</code>) and a <code>std::vector</code> you won't use beyond feeding it to the <code>static std::unordered_map</code> inside your master function.</p>\n\n<pre><code>std::vector<int> permutations(int n) {\n auto digits = std::to_string(n);\n std::vector<int> res;\n res.push_back(n);\n\n do {\n res.push_back(stoi(digits));\n } while (std::next_permutation(digits.begin(), digits.end()));\n</code></pre>\n\n<p>Besides, it won't give you every permutation: if you want to go through all permutations with <code>std::next_permutation</code>, you need to start with a sorted <code>std::string</code>. </p>\n\n<pre><code> return res;\n}\n</code></pre>\n\n<p>Anyway, I don't think that permutations are the best way of testing the numbers equivalence: you don't need it if you keep track of intermediary values, because permutations will result in the same squared digits' sum.</p>\n\n<p>Here what I'd find correctly optimized:</p>\n\n<pre><code>auto precompute_results(int n) {\n std::vector<int> results(n, 0); \n // a vector instead of a map, \n // elements can be:\n // 0 = unexplored, 1 = ending in 1, 89 = ending in 89\n // n = on the same path as n\n for (int i = 1; i < n; ++i) {\n auto cur = results[i] ? results[i] : i;\n while (true) {\n if (cur == 1 || cur == 89) break;\n if (cur < n && results[cur]) {\n cur = results[cur];\n continue; // we go down the path to either 1 or 89\n }\n if (cur < n) results[cur] = i; // we memorize that cur in on the same path as i\n cur = sum_of_squared_digits(cur);\n }\n results[i] = cur;\n }\n return results;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T16:24:25.127",
"Id": "209374",
"ParentId": "209303",
"Score": "4"
}
},
{
"body": "<p>Sometimes it's good to remember the KISS principle. </p>\n\n<p>With this in mind, first the squares of each digit is constant therefore a constant int[] to store those values will eliminate constantly multiplying them.</p>\n\n<p>Integer math is much faster than string conversions.</p>\n\n<p>One solution taking this in to account could look like this:</p>\n\n<pre><code>const int squares[] = { 0,1,4,9,16,25,36,49,64,81 };\nbool IsSquareSum89(int num)\n{\n int sum = 0;\n while (num != 89 && num != 1)\n {\n sum = 0;\n while (num > 0)\n {\n int digit = num % 10;\n sum += squares[digit];\n num /= 10;\n }\n num = sum;\n }\n return num == 89;\n}\nint GetAnswer(int target)\n{\n int answer = 0;\n for (int i = target - 1; i > 0; --i)\n {\n if (IsSquareSum89(i))\n {\n ++answer;\n }\n }\n return answer;\n}\n</code></pre>\n\n<p>On my machine this finds the answer in about 2 seconds.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T01:43:52.933",
"Id": "404715",
"Score": "0",
"body": "So you optimize out a measly integer multiplication, that is right next to a division... that is wasted optimization effort. Plus: to fetch a value from an array requires an integer multiplication!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T01:50:38.973",
"Id": "404717",
"Score": "0",
"body": "@CrisLuengo \"to fetch a value from an array requires an integer multiplication\" - Not always. For byte arrays, no operation is required. For an int array like this, rather than multiplication, you shift the index left by two, which is pretty cheap."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T08:02:13.823",
"Id": "404743",
"Score": "0",
"body": "I'm pretty sure that the array access is more expensive than a multiplication: there is the memory access (maybe 100 × longer than a multiplication) and the offset calculation"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T12:17:58.770",
"Id": "404779",
"Score": "0",
"body": "@papagaga - when I compare this code with EmilyL's , which uses the same basic algorithm, this code is slightly faster. The difference is probably close enough to say that they're even."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T13:06:45.277",
"Id": "404797",
"Score": "0",
"body": "You're right: in this case, since your array is small enough to hold in a cache line, access won't cost more than a multiplication -but still not much less either, whereas it makes the program a little more complicated."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T22:20:05.340",
"Id": "209395",
"ParentId": "209303",
"Score": "2"
}
},
{
"body": "<p>Plenty of good answers have been given I'll just point out that 10 million is actually not a lot.</p>\n\n<p>The square sum of digits of 9999999 is 7*81=567 and this is the largest sum you can get. So to determine if any up to 7 digit number ends up as 1 or 89 cannot require more than 567 iterations of computing the sum of squared digits.</p>\n\n<p>Meaning that brute force 567*10M=5.67 G iterations of computing sum of digits squared will solve it. Sum of digits squared using the trivial integer division approach is 7 divisions with remainder, 6 additions and 7 multiples, plus loop overhead call it 30 instructions, so in total you'd need 5.67*30~=16G instructions.</p>\n\n<p>For a typical desktop computer with 4 GHz one core turbo and IPC of 2 (which is pessimistic for modern x86 CPUs) that amounts to 8 G instructions per second, <strong>which means brute force should take around two seconds</strong> if my math isn't completely of the charts wrong.</p>\n\n<p>So you can do a bunch of clever stuff but it won't save you more than two seconds of CPU time over just brute forcing it. And you can do much worse than brute force as OPs solution doesn't complete after a whole minute by computing ineffective sums, allocating a bunch of memory left right and center, generating permutations and what not.</p>\n\n<h1>Edit: To prove my point:</h1>\n\n<p>I implemented the brute force soloution:</p>\n\n<h2>pe.cpp</h2>\n\n<pre><code>#include <iostream>\n\nint ssd(int n){\n int ans = 0;\n while(n){\n int d = n%10;\n n = n/10;\n ans += d*d;\n }\n return ans;\n}\n\nint main(int, char**){\n int n89 = 0;\n for(int n = 2; n < 10000000; n++){\n int s = ssd(n);\n while(s != 1 && s != 89){\n s = ssd(s);\n }\n if(s==89){\n n89++;\n }\n }\n std::cout<<n89<<std::endl;\n}\n</code></pre>\n\n<p>And ran it, producing the correct solution in under half a second:</p>\n\n<pre><code>$ g++ -O3 pe.cpp -o pe && time ./pe\n8581146\n\nreal 0m0.423s\nuser 0m0.423s\nsys 0m0.000s\n</code></pre>\n\n<p>On my machine:</p>\n\n<pre><code>$ cat /proc/cpuinfo | grep \"model name\" | tail -n 1\nmodel name : Intel(R) Core(TM) i7-8700K CPU @ 3.70GHz\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T13:02:07.083",
"Id": "404793",
"Score": "0",
"body": "Completing a challenge from the Euler Project should ask for more than mere brute force. The criterium stated on the home page is that the algorithm shouldn't take more than one minute on an average machine to complete. Your machine isn't what I'd call average, and using C++ over other slower languages is already a boost. Even if the original poster devised a rather clumsy solution, I believe he's right in trying to beat brute force."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T22:30:20.367",
"Id": "404886",
"Score": "0",
"body": "I disagree, some of the early questions can be solved with just pen and paper. While my machine is quite strong, it also computed the solution in less than 0.5 s on one core. So a machine with 1/120 the single core performance of mine should still make the 1 minute mark. So even something that has only a fifth of the performance of a VIA Eden 1 GHz low power CPU should still be able to compute it in under a minute... I bet even a Pentium 200 would make it under one minute (https://www.cpubenchmark.net/singleThread.html). I think that's below average, yes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T22:38:55.543",
"Id": "404887",
"Score": "1",
"body": "@papagaga what I'm trying to say is that sometimes the brute force solution is the best one, or at least good enough. For example shaker sort (two sided bubble sort) of faster than quicksort on almost sorted arrays (https://codereview.stackexchange.com/a/159974/36120). Knowing when you can and should use an \"inefficient\" solution is an important skill for a software engineer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T07:52:51.327",
"Id": "404921",
"Score": "0",
"body": "@EmiliL: ... I'm not sure how it happened, but I was mixing up minutes and seconds. You're absolutely right."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T00:44:23.460",
"Id": "209403",
"ParentId": "209303",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T08:12:02.283",
"Id": "209303",
"Score": "5",
"Tags": [
"c++",
"performance",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Project Euler 92: count sum-squared-digits chains that reach 89"
} | 209303 |
<p>I made this piece of code as first step for a bigger project to iterate and manage bookmarks: open, rename, place in new folder structure, or delete each one of them. This first step is a parser to get a useful json file with the structure and data of each bookmark and folder. I've usex regex instead of beautifulsoup to get somehow legacy code, it's not that hard for the task (but maybe not the best implementation, I just know It works for me).</p>
<p>Im starting to publish my code and I am a little lost, I don't get to know why I can't draw feedback, and my main guess is that I'm doing something so wrong people don't even bother. My concerns are not about best practices but quite the opposite: which bad practices do you see here? My main concerns are following PEP8 (python style), having a clear and useful functionality, and clear comments to let the code explain itself.</p>
<p>I came here because I know that asking the right questions this community has really good answers based on experience and knowledge, and while I'm building up my own It's really nice when you guys shine some light into the darkness.</p>
<p>Without further ado, here is the code:</p>
<pre><code>import re
import json
class BookmarkParser():
def __init__(self, infile):
# Read input file, lines to list, strip each line.
# Utf8 because spanish
self.file_lines = []
with open(infile, encoding='utf8') as f:
self.file_lines = f.read().splitlines()
for i in range(len(self.file_lines)):
self.file_lines[i] = self.file_lines[i].strip()
# self.tree: dict with the whole structure
# root: key that holds all the structure in its value, it's used
# to have a root directory that is not the tree itself
self.tree = {'root':{}}
# list to store the path of the current directory through the iteration,
# used by change_folder
self.path = ['root']
# reference to the tree used by change_folder, stores current folder on iteration
self.folder = self.tree
self.change_folder()
self.iterate()
self.save()
def change_folder(self):
# change the folder reference to the last folder in path
self.folder = self.tree
for key in self.path:
self.folder = self.folder[key]
def iterate(self):
# Iterate html lines to parse structure from <DT H3 and </Dl, and data from <DT H3 and <DT A
for line in self.file_lines:
# If the first tag is DT
if line[1:3] == 'DT':
# And if the second tag is A
if line[5] == 'A':
# Its a link: get its parameters and append to current folder
name = re.findall('(?<=>).*?(?=<)', line)[1]
href = re.search('(?<=HREF=").*?(?=")', line).group()
add_date = re.search('(?<=ADD_DATE=").*?(?=")', line).group()
icono = re.search('(?<=ICON=").*?(?=")', line)
icon=''
if icono:
# Not all links have one
icon = icono.group()
info = {
'url':href,
'add_date':add_date,
'icon':icon
}
self.folder.update({name:info})
# If the second tag is H3
elif line[5:7] == 'H3':
# Its a folder: get its parameters, append to current folder,
# create self folder and set current folder to self
name = re.findall('(?<=>).*?(?=<)', line)[1]
last_modified = re.search('(?<=LAST_MODIFIED=").*?(?=")', line).group()
add_date = re.search('(?<=ADD_DATE=").*?(?=")', line).group()
info = {
'add_date':add_date,
'last_modified':last_modified
}
self.folder.update({name:{'meta':info}})
self.path.append(name)
self.change_folder()
# If tag is /DL we closed current folder: pop it from self.path and change folder
elif line[1:4] == '/DL':
self.path.pop()
self.change_folder()
def save(self):
# Save the tree dict to a json file. Using utf8 here because spanish.
with open('parsed_bookmarks.json','w',encoding='utf8') as outfile:
json.dump(self.tree, outfile, indent=4, ensure_ascii=False)
if __name__ == '__main__':
parser = BookmarkParser('bookmarks_chrome.html')
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T18:20:41.327",
"Id": "404584",
"Score": "0",
"body": "Please don't modify the code in the question after having received an answer. This edit (partially) invalidated the answer, so I have rolled back your last edit. Have a look at [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers). You can always ask a follow-up question with updated code (it is customary to link to the first question in this case, for reference)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T19:11:47.707",
"Id": "404585",
"Score": "1",
"body": "Thx! Neat to know, sorry for the mistake."
}
] | [
{
"body": "<p>As you said, regex is not meant for HTML parsing. But as you are aware of it and it's a conscious choice, parsing a well-defined tree is, I guess, OK. \nThe code is easy to read and follow. One improvement would be to break out the actual tag handling (the content of the ifs) from <code>iterate</code> to separate functions, like <code>handle_link</code>, <code>handle_folder</code>, etc. That way, it's even easier to scan the code for functionality without getting into the nitty gritty details.</p>\n\n<p>Opening, reading, and stripping the file could all be done inside the <code>with</code> statement. Keep closely related stuff together, easier to follow.</p>\n\n<p>The <code>change_folder</code> function is too complex. To get items from the end of a list, just use a negative index. The last item is thus [-1].</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T16:29:37.543",
"Id": "404577",
"Score": "0",
"body": "Thanks! I struggled with the change directory one completely forgetting the negative index thing, oh my! I'm working on a new approach reading the bookmarks file without parsing the export, but this little script really helped me to learn and I really appreciate your feedback"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T14:47:28.850",
"Id": "209314",
"ParentId": "209305",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T10:07:26.653",
"Id": "209305",
"Score": "1",
"Tags": [
"python",
"beginner",
"parsing"
],
"Title": "Parse html bookmarks export to a json with python for further management"
} | 209305 |
<p>From <a href="https://projecteuler.net/problem=119" rel="nofollow noreferrer">problem #119</a> of the <a href="https://projecteuler.net/about" rel="nofollow noreferrer">Project Euler</a> :</p>
<blockquote>
<p>The number 512 is interesting because it is equal to the sum of its digits raised to some power: 5 + 1 + 2 = 8, and 8<sup>3</sup> = 512. Another example of a number with this property is 614656 = 284.</p>
<p>We shall define a<sup>n</sup> to be the nth term of this sequence and insist that a number must contain at least two digits to have a sum.</p>
<p>You are given that a<sup>2</sup> = 512 and a<sup>10</sup> = 614656.</p>
<p>Find a<sup>30</sup>.</p>
</blockquote>
<p>The number 512 fits because :</p>
<blockquote>
<p>5+1+2 = 8
and 8<sup>3</sup> = 512.</p>
</blockquote>
<p>The number 17576 fits because :</p>
<blockquote>
<p>1+7+5+7+6 = 26
and 26<sup>3</sup> = 17576.</p>
</blockquote>
<p>There's my solution but it's extremely inefficient. I need the variable <code>c</code> to reach 25 but I haven't seen past 16.</p>
<pre><code> public static int c = 0;
public static void TryAll(long x, long y)
{
for (int i = 2; i < 10; i++)
{
double powered = Math.Pow(y, i);
if (x % y == 0 && powered == x && x % 10 != 0)
{
c++;
Console.WriteLine("----- {0}", c);
Console.WriteLine(powered);
Console.WriteLine(y);
Console.WriteLine(i);
}
}
}
public static void Main(string[] args)
{
int baseNum = 0;
for (c = c; c < 26; baseNum++)
{
if (baseNum > 9)
{
int sum = 0;
int baseNumD = baseNum;
while (baseNumD != 0)
{
sum += baseNumD % 10;
baseNumD /= 10;
}
TryAll(baseNum, sum);
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T20:16:07.740",
"Id": "404590",
"Score": "0",
"body": "Welcome on Code Review. I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. Code Review is not the site to ask for help in fixing or changing *what* your code does. Once the code does what you want, we would love to help you do the same thing in a cleaner way! Please see our [help center](/help/on-topic) for more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T21:32:31.027",
"Id": "404593",
"Score": "1",
"body": "@Calak This code does appear to be working. It's just so slow that getting the correct answer would take an infeasible amount of time to compute. This does appear to be ontopic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T21:33:52.250",
"Id": "404594",
"Score": "0",
"body": "OP, can you clarify if this code is in fact producing correct answers for smaller inputs?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T22:36:37.563",
"Id": "404599",
"Score": "0",
"body": "@Carcigenicate : \"I need the variable c to reach 25 but I haven't seen past 16\" that's sounds clear for me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T22:46:20.320",
"Id": "404600",
"Score": "1",
"body": "@Calek [Code that is only broken because of TLE \"errors\" is considered ontopic by a mod](https://codereview.meta.stackexchange.com/a/2586/46840). If that is in fact the problem (which even 200_success seems to agree is the case here), then this would be ontopic."
}
] | [
{
"body": "<p>If you don't need to print out results in order, you can inverse the logic and compute power value first, and check if the result equals to sum of digits. It's super fast:</p>\n\n<pre><code>using System;\n\npublic class Program\n{\n private const int MaxCount = 25;\n\n public static void Main(string[] args)\n {\n var c = 1;\n for (var i = 2; i < 100; i++)\n {\n for (var j = 2; j < 1000; j++)\n {\n var pow = (long)Math.Pow(j, i);\n var sum = SumOfDigits(pow);\n if (sum != j)\n {\n continue;\n }\n Console.WriteLine($\"{c}: {pow} = {sum} ^ {i}\");\n c++;\n if (c > MaxCount)\n {\n break;\n }\n }\n if (c > MaxCount)\n {\n break;\n }\n }\n Console.ReadLine();\n }\n\n private static long SumOfDigits(long value)\n {\n long sum = 0;\n while (value != 0)\n {\n sum = sum + (value % 10); \n value = value / 10; \n }\n\n return sum;\n }\n}\n</code></pre>\n\n<p>Please note loop limit values are arbitrary, large enough to satisfy requirement of 25 results.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T21:46:23.337",
"Id": "209325",
"ParentId": "209311",
"Score": "1"
}
},
{
"body": "<pre><code>for (c = c; c < 26; baseNum++)\n</code></pre>\n\n<p>This line lead to \"<code>warning CS1717: Assignment made to same variable; did you mean to assign something else?</code>\"</p>\n\n<pre><code>if (baseNum > 9)\n</code></pre>\n\n<p>Instead of pay for a comparison in each iteration of the loop, directly set <code>baseNum</code> to 9.</p>\n\n<pre><code>int sum = 0;\nint baseNumD = baseNum;\nwhile (baseNumD != 0)\n{\n sum += baseNumD % 10;\n baseNumD /= 10;\n}\n</code></pre>\n\n<p>You could move this into a function, because \"summing digits of number\" can be reused in many other challenges.</p>\n\n<pre><code>public static void TryAll(long x, long y)\n</code></pre>\n\n<p>Try to use meaningful names. What does <code>x</code> or <code>y</code> mean here?</p>\n\n<pre><code>for (int i = 2; i < 10; i++)\n</code></pre>\n\n<p>Same here, a better name for <code>i</code> could be <code>exp</code> or <code>exponent</code>. Note also that 10 might be to low to handle some cases (eg: a<sup>32</sup> = 81 920 000 000 000 000 = 20<sup>13</sup>).</p>\n\n<pre><code>double powered = Math.Pow(y, i);\n</code></pre>\n\n<p>Here, you don't have to try all exponentiations from exponents 2 to 9. There's <a href=\"https://stackoverflow.com/questions/4429044/check-if-one-integer-is-an-integer-power-of-another\">many other ways</a> to check if an integer is a power of another.</p>\n\n<pre><code>if (x % y == 0 && powered == x && x % 10 != 0)\n</code></pre>\n\n<p>Modulo <a href=\"https://stackoverflow.com/questions/15596318/is-it-better-to-avoid-using-the-mod-operator-when-possible\">have a cost</a> and here, it's useless, since you already computed the computation of the power and if <code>powered == x</code> the \"is divisible by\" check is pointless. Also, I don't understand the <code>x % 10</code>, some expected results are divisible by 10 (check a<sup>32</sup> above).</p>\n\n<hr>\n\n<p>Where your code become slow is that you check for all numbers until you reach the expected results count.</p>\n\n<p>Instead of checking for all of these iterations if the sum of digits can be powered to reach the current iteration, let's take the problem in another side.</p>\n\n<p>Let's try, only all the powered bases from 7 to 100 (arbitrary values that that match possibles representations) and check if the sum of its digits match the base. So, we only test number that are a n<sup>th</sup> power.\nPlace all these results in a list that you sort to get the real order.</p>\n\n<p>Here, for demonstration purpose, I used a struct embedding all info about results, but you can also just use a List and store the <code>number</code> part.</p>\n\n<p><em>(note that I'm not a c# guru, there's surely some improvements possibles)</em></p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\n\npublic class Program\n{\n private const int MinRadix = 7;\n private const int MaxRadix = 100;\n private static List<Result> results = new List<Result>();\n\n public struct Result\n {\n public long number;\n public long radix;\n public long exp;\n }\n\n public static void Main(string[] args)\n {\n ComputeResults();\n SortResults();\n PrintResults();\n }\n\n private static long SumOfDigits(long value)\n {\n long sum = 0;\n while (value > 0)\n {\n sum += value % 10; \n value /= 10; \n }\n return sum;\n }\n\n private static void ComputeResults()\n {\n int count = 0;\n for (long radix = MinRadix; radix <= MaxRadix; ++radix)\n {\n int exp = 1;\n var current = radix;\n\n while (current < long.MaxValue / radix)\n {\n ++exp; \n current *= radix;\n\n if (radix == SumOfDigits(current)) {\n Result result = new Result();\n result.number = current;\n result.radix = radix;\n result.exp = exp;\n results.Add(result);\n ++count;\n } \n }\n }\n }\n\n private static void SortResults()\n {\n results.Sort((x, y) => x.number.CompareTo(y.number));\n }\n\n private static void PrintResults()\n {\n for (int i = 0; i < results.Count; i++)\n {\n Console.WriteLine($\"{i+1}: {results[i].number} = {results[i].radix} ^ {results[i].exp}\"); \n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T10:03:17.327",
"Id": "404935",
"Score": "0",
"body": "Good answer. The only thing to add is with respect to \"*(arbitrary values that that match possibles representations)*\": with a bit of care the arbitrariness can be eliminated. The hint I'd give OP is to use a priority queue."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T22:04:18.147",
"Id": "405061",
"Score": "0",
"body": "@PeterTaylor I just did some little improvements"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T20:42:03.570",
"Id": "209390",
"ParentId": "209311",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T12:05:47.247",
"Id": "209311",
"Score": "9",
"Tags": [
"c#",
"beginner",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Project Euler #119 : Digit power sum"
} | 209311 |
<p>I have a 6 x 7 grid for a calendar = 42 <code>DateTimes</code>. I'm trying to display the displayed month/year at the top of the calendar. </p>
<p>If there are 3 months displayed, I only want to show the name for the middle month (October 2018, for instance). If 2 months are displayed, split the name (October - November 2018). If 2 months are displayed and have different years, append with year on both sides (December 2018 - January 2019).</p>
<p>This is what I have, and it works, but it's in a property that may be "getted" often and I want this to be as efficient as possible. Here's the code:</p>
<pre><code>public string ViewedMonthYearStr
{
get
{
if (_grid != null)
{
string first;
string middle = string.Empty;
string last = string.Empty;
HashSet<int> months = new HashSet<int> { _grid[0].Month, _grid[21].Month, _grid[41].Month };
if (months.Count == 3) first = _grid[21].ToString("MMMM yyyy");
else
{
first = _grid[0].ToString("MMMM");
middle = " - ";
last = _grid[41].ToString("MMMM yyyy");
}
if (_grid[0].Year != _grid[41].Year && months.Count != 3)
{
middle = $" {_grid[0].ToString("yyyy")} - ";
}
_viewedMonthYearStr = $"{first}{middle}{last}";
}
return _viewedMonthYearStr;
}
}
</code></pre>
<p>Is there a more efficient way to do this? My gut tells me that if/else's aren't the most efficient way.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T07:36:27.960",
"Id": "404623",
"Score": "1",
"body": "I find the title is misleading because this question isn't about displaying anything in a calender but rather about a _function_ that calculates something for the calender. You should update the title so that it properly describes the real porpose of the code. Besides I think it lacks context because it's reading some _magic_ values from the grid like (0, 21, 41) etc. You should improve it by adjusting the title accordingly and adding more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T09:35:42.227",
"Id": "404638",
"Score": "1",
"body": "@t3chb0t: I think there is sufficient context here: the `wpf` tag tells me that this property is likely bound to by a calendar view, and those magic values are used to get the first, middle and last date that are displayed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T17:54:21.253",
"Id": "404672",
"Score": "1",
"body": "@t3chb0t -- someone edited the title, I originally named it \"A more efficient way of parsing displayed month/year for calendar\". The \"grid\" is simply a list of datetimes, as I said, with 42 values (6*7) so 0 is the first date, 21 is the middle, 41 is the last -- I grab these because if there are 3 months to be shown, each of those will have a different month always."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T17:59:52.123",
"Id": "404673",
"Score": "0",
"body": "Oh, that was an unfortunate change. I restored it. This one is much better indeed. I didn't see the other edit."
}
] | [
{
"body": "<p>I wouldn't worry about this being inefficient - you're not doing anything crazy here, and a calendar header probably won't need to be refreshed millions of times per second anyway.</p>\n\n<p>Still, I can think of some changes that will improve readability and maintainability:</p>\n\n<ul>\n<li>I would use a guard clause to reduce nesting, and to make it more obvious what happens when grid is null: <code>if (_grid == null) return null;</code>. This also gets rid of edge-cases early on, while in the current code you have to scan down to the end to see if maybe there's still an else statement following.</li>\n<li>Adding an empty line between the end of the <code>else</code> block and the next <code>if</code> statement will make it more obvious that they're not related.</li>\n<li>However, the last <code>if</code> statement only applies when displaying two months, so why not put it inside the above <code>else</code> block? That also allows you to remove the <code>months.Count != 3</code> check.</li>\n<li>Putting <code>first = _grid[21]...</code> on the same line as that <code>if</code> statement, and without braces, makes the control flow more difficult to see at a glance. Omitting braces can also result in subtle bugs, so some people make a point of always using braces. Either way, consistency matters: if an <code>else</code> statement uses braces I'd expect the related <code>if</code> statement to also use them.</li>\n<li>Why assign the result to <code>_viewMonthYearStr</code> instead of returning it directly? That field does not seem to serve any purpose.</li>\n<li><code>0</code>, <code>21</code> and <code>41</code> are 'magic values': the meaning of those values isn't directly clear, and they easily break the code when the size of <code>_grid</code> needs to be changed. Replacing <code>_grid[0]</code> with <code>_grid.First()</code>, <code>_grid[41]</code> with <code>_grid.Last()</code> and <code>_grid[21]</code> with <code>_grid[_grid.Length / 2]</code> will make the code more robust and easier to understand. You could also assign their results to local variables, such as: <code>var middleDate = _grid[_grid.Length / 2];</code>. That simplifies the code somewhat, and it allows you to use <code>_grid[0]</code> and <code>_grid[_grid.Length - 1]</code> instead of <code>First</code> and <code>Last</code> without sacrificing readability, if you really need that little bit of performance gain.</li>\n<li>Instead of using the local variables <code>first</code>, <code>middle</code> and <code>last</code>, you can return results immediately. That will make the possible output formats easier to see.</li>\n<li>Instead of using a hash set, you can also check if the <code>Month</code> of the middle date is different from that of both the first and the last date. That will put a tiny bit less pressure on the GC.</li>\n<li>Instead of calling <code>date.ToString(format)</code>, and then using the result in an interpolated string, you can also specify the format in the interpolated string directly: <code>$\"{date:format}\"</code>.</li>\n<li>I'd rename <code>ViewedMonthYearStr</code> to <code>Header</code> or <code>Title</code> - that's what it's used for, after all.</li>\n</ul>\n\n<hr>\n\n<p>With all that, this is what I would end up with:</p>\n\n<pre><code>public string Header\n{\n get\n {\n if (_grid == null)\n return null;\n\n var firstDate = _grid.First();\n var middleDate = _grid[_grid.Length / 2];\n var lastDate = _grid.Last();\n\n // If more than 2 months are displayed, focus only on the middle month:\n if (middleDate.Month != firstDate.Month && middleDate.Month != lastDate.Month)\n return $\"{middleDate:MMMM yyyy}\";\n\n if (firstDate.Year != lastDate.Year)\n return $\"{firstDate:MMMM yyyy} - {lastDate:MMMM yyyy}\";\n\n return $\"{firstDate:MMMM} - {lastDate:MMMM yyyy}\";\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T18:04:22.480",
"Id": "404674",
"Score": "0",
"body": "That is much more readable, thank you. I had the extra if at the end so that if two months were shown of the same year then the year would only display on the last, but that's a minor thing that I think gets trumped by code elegance. I was trying to copy how Outlook does it in their calendar :) Oh, and about the private backer, it was there because I was always taught a block should only ever have 1 return statement -- slavish devotion to something that isn't important, I know, it's just automatic by now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T18:22:48.717",
"Id": "404675",
"Score": "1",
"body": "The same-year case is also taken care of - see the final return statement. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T09:40:39.710",
"Id": "209353",
"ParentId": "209321",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "209353",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T18:49:33.440",
"Id": "209321",
"Score": "1",
"Tags": [
"c#",
"datetime",
"wpf"
],
"Title": "Parsing displayed month/year for calendar"
} | 209321 |
<p>I have been working on a project in python which takes content from web links and find some important words from content of that page.
I used regular expression to do so.
But it takes huge time to get the results.</p>
<h2>How it works:</h2>
<ol>
<li>It makes request to given url</li>
<li>take whole html content and data from external js files(within src attribute of tag)</li>
<li>Save those things to list. (name it as file, used in re later)</li>
<li>and then perform searching of important data using regular expression.</li>
</ol>
<p>Here is the sample:</p>
<h2>List:</h2>
<p>list = <code>['secret', 'secret_key', 'token', 'secret_token', 'auth_token','access_token','username','password','aws_access_key_id','aws_secret_access_key', 'secretkey']</code></p>
<h2>Regular Expression:</h2>
<pre><code>for item in seclst:
try:
secregex = r'(["\']?[\w\-]*' + item + '[\w\-]*[\s]*["\']?[\s]*[:=>]{1,2}[\s]*["\'](.*?)["\'])'
matches = re.finditer(secregex, file, re.MULTILINE | re.IGNORECASE )
for matchNum, match in enumerate(matches):
if len(match.group(2)) > 0:
secretList.add(match.group())
except:
pass
</code></pre>
<p>There are some other functions too.</p>
<h2>Execution time and explanation:</h2>
<ol>
<li>When I use '<a href="https://www.facebook.com" rel="nofollow noreferrer">https://www.facebook.com</a>'(without cookies) it takes approximately 41 seconds (including doing other functionalities)</li>
<li>When I use '<a href="https://www.facebook.com" rel="nofollow noreferrer">https://www.facebook.com</a>'(with cookies) it takes approximately 5 to 6 min (including doing other functionalities)</li>
</ol>
<p>How can I optimize it?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T20:05:16.380",
"Id": "404589",
"Score": "3",
"body": "I find it implausible that any text analysis of a web page could take minutes. I think that there is something you haven't told us about what your code is doing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T02:48:04.917",
"Id": "404606",
"Score": "0",
"body": "You also tagged this question as [tag:multithreading], but there isn't any multithreading in this code. Voting to close this question as \"Unclear what you are asking\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T04:15:11.737",
"Id": "404616",
"Score": "2",
"body": "Also why are you looking for `aws_access_key_id` and `aws_secret_access_key`? I hope this isn't for anything nefarious."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T11:22:06.503",
"Id": "404644",
"Score": "0",
"body": "This project is for security purpose @BaileyParker ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T11:23:44.983",
"Id": "404645",
"Score": "0",
"body": "@200_success I have used multi-threading in this, but it doesn't helped me for this purpose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T12:41:18.787",
"Id": "404652",
"Score": "0",
"body": "Please post the whole program."
}
] | [
{
"body": "<p>One thing that might help is compiling into a single regex once before the loop:</p>\n\n<pre><code>p = re.compile(r'([\"\\']?[\\w\\-]*(?:' + '|'.join(seclst) + ')[\\w\\-]*[\\s]*[\"\\']?[\\s]*[:=>]{1,2}[\\s]*[\"\\'](.*?)[\"\\'])')\nfor item in seclst:\n try:\n matches = p.finditer(file, re.MULTILINE | re.IGNORECASE )\n for matchNum, match in enumerate(matches):\n if len(match.group(2)) > 0:\n secretList.add(match.group())\n except:\n pass\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T11:03:55.350",
"Id": "404944",
"Score": "0",
"body": "The time decreased to half. Thanks for that @solomon-ucko"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T11:27:45.960",
"Id": "404947",
"Score": "0",
"body": "@NeerajSonaniya Great! Glad I could help."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T12:42:24.923",
"Id": "209359",
"ParentId": "209323",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "209359",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T19:23:33.037",
"Id": "209323",
"Score": "-4",
"Tags": [
"python",
"python-3.x"
],
"Title": "Parsing million words of list in python regular expression is slow"
} | 209323 |
<p>I am making a C library that abstracts window creation with support for the new Vulkan API under a unified API;
I have a <a href="https://github.com/gabrielevierti/VKWF/tree/7438d58e3165379f28a58886ce590edea98f00ce" rel="nofollow noreferrer">github repository</a> that you can check out.</p>
<h1>main.c</h1>
<pre><code>#include "vkwf.h"
int main()
{
VKWFWindow* window = VKWFCreateWindow("Test Window", 800, 600);
while (!VKWFWindowShouldClose(window))
{
VKWFWindowUpdate(window);
}
free(window);
return 0;
}
</code></pre>
<p>The way I am handling this is creating a general <code>vkwf.h</code> file, that includes a list of functions, like this:</p>
<h1>vkwf.h</h1>
<pre><code>#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#ifdef VKWF_PLATFORM_WINDOWS
#include "win32_window.h"
#elif VKWF_PLATFORM_MACOS
#include "macos_window.h"
#elif VKWF_PLATFORM_LINUX
#include "linux_window.h"
#endif
VKWFWindow* VKWFCreateWindow(const char* title, int width, int height)
{
return VKWFPlatformCreateWindow(title, width, height);
}
VKWFBool VKWFWindowShouldClose(VKWFWindow* window)
{
return VKWFPlatformWindowShouldClose(window);
}
void VKWFWindowUpdate(VKWFWindow* window)
{
VKWFPlatformUpdate(window);
}
void VKWFDestroyWindow(VKWFWindow* window)
{
VKWFPlatformDestroyWindow(window);
}
#ifdef __cplusplus
}
#endif
</code></pre>
<p>All <code>VKWFPlatformX()</code> functions are functions that get defined by the <code>platform_window.h</code> files, like this:</p>
<h1>win32_window.h (short)</h1>
<pre><code>#define VKWFPlatformCreateWindow(title,width,height) VKWFWin32CreateWindow(title,width,height)
#define VKWFPlatformWindowShouldClose(window) VKWFWin32WindowShouldClose(window)
#define VKWFPlatformUpdate(window) VKWFWin32Update(window)
#define VKWFPlatformDestroyWindow(window) VKWFWin32DestroyWindow(window)
</code></pre>
<p>Does this look like a good approach?
Are there any drawbacks, or things that i could improve?</p>
| [] | [
{
"body": "<p>I wouldn't use <code>#define</code> macros. They expose the internal naming convention of your OS dependent functions to the world. Once you send out your library to others [as a shared library], you can <em>never</em> change your <em>internal</em> OS dependent names. The important thing is that <em>public</em> facing names be functions.</p>\n\n<p>For example, if two systems used <code>gcc</code> and created <code>ELF</code> binaries that <em>only</em> called your library functions, could you compile on (e.g.) FreeBSD and that binary would run <em>without</em> rebuild on linux. There are other issues with doing this, so it [probably] isn't practical, but, it's something to think about.</p>\n\n<p>A better way [what <em>I've</em> done when faced with a similar problem] is to put the OS dependent code in a <code>.c</code> and add <code>static</code> to the definitions.</p>\n\n<p>The public functions just call the <code>static</code> ones. The <code>static</code> function names are the <em>same</em>, regardless of platform</p>\n\n<p>The optimizer will either inline the static OS dependent function or will use tail call optimization. So, it's just as fast as macros but a lot cleaner.</p>\n\n<p><em>Side note:</em> Your naming convention is a bit [MS] Windows centric (i.e. camel hump case). I prefer snake case (e.g. see GTK, etc.). For an example, see the bottom.</p>\n\n<hr>\n\n<p>vkwh.h:</p>\n\n<pre><code>#pragma once\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nVKWFWindow* VKWFCreateWindow(const char* title, int width, int height);\nVKWFBool VKWFWindowShouldClose(VKWFWindow* window);\nvoid VKWFWindowUpdate(VKWFWindow* window);\nvoid VKWFDestroyWindow(VKWFWindow* window);\n\n#ifdef __cplusplus\n}\n#endif\n</code></pre>\n\n<hr>\n\n<p>vkwf.c:</p>\n\n<pre><code>#include \"vkwf.h\"\n\n#ifdef VKWF_PLATFORM_WINDOWS\n#include \"win32_window.c\"\n#elif VKWF_PLATFORM_MACOS\n#include \"macos_window.c\"\n#elif VKWF_PLATFORM_LINUX\n#include \"linux_window.c\"\n#endif\n\nVKWFWindow* VKWFCreateWindow(const char* title, int width, int height)\n{\n return VKWFPlatformCreateWindow(title, width, height);\n}\n\nVKWFBool VKWFWindowShouldClose(VKWFWindow* window)\n{\n return VKWFPlatformWindowShouldClose(window);\n}\n\nvoid VKWFWindowUpdate(VKWFWindow* window)\n{\n VKWFPlatformUpdate(window);\n}\n\nvoid VKWFDestroyWindow(VKWFWindow* window)\n{\n VKWFPlatformDestroyWindow(window);\n}\n</code></pre>\n\n<hr>\n\n<p>win32_window.c:</p>\n\n<pre><code>#include \"vkwf.h\"\n\nstatic VKWFWindow*\nVKWFPlatformCreateWindow(const char* title, int width, int height)\n{\n // ...\n}\n\nstatic VKWFBool\nVKWFPlatformWindowShouldClose(VKWFWindow* window)\n{\n // ...\n}\n\nstatic void\nVKWFPlatformWindowUpdate(VKWFWindow* window)\n{\n // ...\n}\n\nstatic void\nVKWFPlatformDestroyWindow(VKWFWindow* window)\n{\n // ...\n}\n</code></pre>\n\n<hr>\n\n<p>Here's an example of the snake case for the public functions. Note that since the platform specific functions are <code>static</code>, then can use shorter prefixes:</p>\n\n<pre><code>#include \"vkwf.h\"\n\n#ifdef VKWF_PLATFORM_WINDOWS\n#include \"win32_window.c\"\n#elif VKWF_PLATFORM_MACOS\n#include \"macos_window.c\"\n#elif VKWF_PLATFORM_LINUX\n#include \"linux_window.c\"\n#endif\n\nVKWFWindow* VKWF_create_window(const char* title, int width, int height)\n{\n return platform_create_window(title, width, height);\n}\n\nVKWFBool VKWF_window_should_close(VKWFWindow* window)\n{\n return platform_window_should_close(window);\n}\n\nvoid VKWF_window_update(VKWFWindow* window)\n{\n platform_update(window);\n}\n\nvoid VKWF_destroy_window(VKWFWindow* window)\n{\n platform_destroy_window(window);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T23:21:15.567",
"Id": "209328",
"ParentId": "209324",
"Score": "3"
}
},
{
"body": "<h2>Use libraries</h2>\n\n<p>I would suggest a completely different approach. Keeping the common <code>vkwf.h</code> header makes sense because it presents a uniform interface to programmers using it. However, the actual library used is going to be dependent on the platform. That is, there is likely little use in trying to compile the Windows version of the implementation for use on Linux. Instead, what's more likely is that you will be compiling the Windows version using a compiler that emits Windows code, and a Linux version using a compiler that emits Linux code, etc. (Some variations can occur, such as compiling under <a href=\"https://www.cygwin.com/\" rel=\"nofollow noreferrer\">Cygwin</a>.) </p>\n\n<p>So the way to do this is instead to provide separate implementations that each compile into the platform-appropriate static or shared library (e.g. DLLs for Windows and <code>.so</code> files for Linux). </p>\n\n<h2>Don't abuse headers</h2>\n\n<p>Putting code into a <code>.h</code> file is not a good idea. The header should contain the <em>interface</em> only and not produce any object file output. All executable code and memory allocations (e.g. static structures and variables) should be in <code>.c</code> files. There are many reasons for this advice, with the most important one being that if you have multiple files in a project that each need to <code>#include</code> your header, it will fail if you fail to adhere to this guideline. Further, it makes the library brittle and unpredictable, because it can introduce strange header-ordering dependencies that are hard to debug. <strong>Don't do this!</strong></p>\n\n<h2>Study a successful library for ideas</h2>\n\n<p>There are many examples of successful cross-platform libraries. I'd recommend looking at how the very successful <a href=\"https://zlib.net/\" rel=\"nofollow noreferrer\"><code>zlib</code></a> library was written and emulating that. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T15:27:14.200",
"Id": "209369",
"ParentId": "209324",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "209328",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T20:35:31.627",
"Id": "209324",
"Score": "2",
"Tags": [
"c",
"library",
"gui",
"portability"
],
"Title": "Platform-agnostic windowing library"
} | 209324 |
<p>I am doing some projects so I can teach myself programming. The one that I finished states:
"Credit Card Validator - Takes in a credit card number from a common credit card vendor and validates it to make sure that it is a valid number (look into how credit cards use a checksum)."
Would be glad if i can get a constructive feedback on this one.</p>
<pre><code>import sys
cardnumb_input = input('Enter your credit card number: ')
def list_tweak():
try:
cardnumb = [int(i) for i in cardnumb_input]
cardnumb[0::2] = [x * 2 for x in cardnumb[0::2]]
cardnumb = [str(i) for i in cardnumb]
cardnumb = list(''.join(cardnumb))
cardnumb = [int(i) for i in cardnumb]
return cardnumb
except ValueError:
print('Please enter only number in format: xxxxxxxxxxxxxxxx')
sys.exit(1)
def valid_or_not():
total = sum(list_tweak())
if total % 10 != 0:
print('It seems that this credit card number is not valid.')
else:
print('This credit card number is valid. ')
valid_or_not()
</code></pre>
| [] | [
{
"body": "<h1>What should the type signature of these functions be?</h1>\n\n<p>I would really separate the IO from data. In addition, I would display data that you already have. I would not have <code>valid_or_not</code> print stuff out. Instead I would have it <em>return</em> a <em>value</em>. But what value?</p>\n\n<p>Furthermore, don't read global variables. <code>valid_or_not</code> and <code>list_tweak</code> should take paramters.</p>\n\n<p>We'll get to printing stuff in the end.</p>\n\n<h1>What do you want to do with an invalid credit card number?</h1>\n\n<p>You are both throwing an error, and also printing out whether it is a valid card number. I would say there is a couple ways to go, but I prefer this approach:</p>\n\n<blockquote>\n <p>Return an <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"noreferrer\"><code>enum</code></a> that ends up being either: <code>VALID</code>, <code>INVALID_CHECKSUM</code>, or <code>INVALID_FORMAT</code>. Instead of doing printing.</p>\n</blockquote>\n\n<h1>Rework the flow of <code>valid_or_not</code>.</h1>\n\n<p>Consider reworking <code>valid_or_not</code> to do the following:</p>\n\n<ol>\n<li>Check to see if the format is valid, and return <code>INVALID_FORMAT</code> if it is not.</li>\n<li>The run <code>list_tweak</code>, but don't do <code>try</code>-<code>except</code> on it, return either <code>INVALID_CHECKSUM</code> or <code>VALID</code> depending on <code>list_tweak</code>.</li>\n</ol>\n\n<h1>Naming.</h1>\n\n<p>I am not sure what <code>list_tweak</code> means, but I am assuming only because I've seen this problem show up time and time again that it is the Luhn algorithm. Name it something appropriate like <code>luhn_checksum</code>.</p>\n\n<h1>IO</h1>\n\n<p>So what should we really be doing for input? First we should have a <a href=\"https://stackoverflow.com/a/20158605/667648\"><code>main</code> function</a> (see the link for more information why. Thus we get:</p>\n\n<pre><code>def main():\n cardnumber = input('Enter your credit card number: ')\n print(valid_or_not(cardnumber))\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>See all the data is manipulated in <code>valid_or_not</code> which is <em>then</em> displayed, instead of displaying information withing <code>valid_or_not</code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T04:11:10.330",
"Id": "209340",
"ParentId": "209326",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "209340",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T22:39:41.333",
"Id": "209326",
"Score": "1",
"Tags": [
"python",
"beginner",
"python-3.x",
"programming-challenge",
"checksum"
],
"Title": "Credit card validator in Python 3.7.1"
} | 209326 |
<p>I wrote a Twitter scraper using the tweepy so I can scrape user information and tweets. Given that the free API doesn't let me get the number of messages per tweet, I had to rely on BeautifulSoup to do so.</p>
<pre><code>class TweetAPI():
def __init__(self, k1,k2,k3,k4):
self.key = k1
self.secret_key = k2
self.token = k3
self.secret_token = k4
auth = tweepy.OAuthHandler(self.key, self.secret_key)
auth.set_access_token(self.token, self.secret_token)
api = tweepy.API(auth, wait_on_rate_limit=True)
self.api = api
def tweet_getter(self, user_id, n):
api = self.api
tweets = []
try:
for tweet in tweepy.Cursor(self.api.user_timeline, id = user_id).items(n):
url = "https://twitter.com/{}/status/{}".format(user_id, tweet.id_str)
page = requests.get(url)
page = BeautifulSoup(page.content, 'html.parser')
message_count = int(page.find('span',{"class":"ProfileTweet-actionCount"}).text.strip().split()[0])
temp = [user_id, tweet.created_at, tweet.id_str,
tweet.favorite_count, tweet.retweet_count, message_count, tweet.text]
tweets.append(temp)
return tweets
except:
print("Unable to get user @{} tweets".format(user_id))
pass
</code></pre>
<p>I'm worried about two things:</p>
<ol>
<li><p>Does the <code>wait_on_rate_limit=True</code> really prevent the over doing request in terms of limits?</p></li>
<li><p>Should I add an artificial delayer to the in the BeautifulSoup part in order to avoid getting blocked off from the page content of the Twitter website?</p></li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T04:13:35.773",
"Id": "404613",
"Score": "0",
"body": "Why are you using the API but then sending a request to the user-facing page and parsing the HTML for the tweet? This could break if twitter changes that page. You should already have the info you need coming back from the API (or if not, there should be an API endpoint to request it)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T10:13:54.433",
"Id": "404639",
"Score": "0",
"body": "Bailey the free api version does not include the message count. Thats why I had to go a difffetent route to get that info."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T23:14:01.327",
"Id": "209327",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"beautifulsoup",
"twitter"
],
"Title": "Twitter scraper using tweepy"
} | 209327 |
<p>I'm a complete beginner to Java and we have just started learning objects and classes in school. I'm trying to create a very simple text-based Rock Paper Scissors game. I do realise that my code is a mess, so I'm asking for some suggestions on how could I improve it and if I'm even in the right direction with OOP.</p>
<p><strong>Main</strong> class:</p>
<pre><code>public class Main {
public static void main(String[] args) {
new Game();
}
}
</code></pre>
<p><strong>Player</strong> class</p>
<pre><code>public abstract class Player {
private String name;
private String choice;
public Player() {}
public Player(String name) {this.name = name;}
public void setName(String newName) {
name = newName;
}
public String getName() {
return name;
}
public String getChoice() {
return choice;
}
public void setChoice(String newChoice) {
choice = newChoice;
}
public abstract void selectChoice();
}
</code></pre>
<p><strong>User</strong> class</p>
<pre><code>import java.util.Scanner;
public class User extends Player {
private Scanner input;
public User() {
input = new Scanner(System.in);
}
public void selectChoice() {
System.out.println("Enter your choice: R - Rock, P - Paper, S - Scissors");
setChoice(input.nextLine().toUpperCase());
}
}
</code></pre>
<p><strong>Computer</strong> class</p>
<pre><code>import java.util.Random;
public class Computer extends Player {
private Random rand;
private final int MAX_NUMBER = 3;
public Computer() {
setName("Computer");
rand = new Random();
}
public void selectChoice() {
int randomNumber = rand.nextInt(MAX_NUMBER);
switch(randomNumber) {
case 0:
setChoice("ROCK");
break;
case 1:
setChoice("PAPER");
break;
case 2:
setChoice("SCISSORS");
break;
}
}
}
</code></pre>
<p><strong>Game</strong> class</p>
<pre><code>import java.util.Scanner;
public class Game {
private User p;
private Computer com;
private int playerWins;
private int playerLoses;
private int ties;
private boolean isRunning = false;
private Scanner scan;
public Game() {
p = new User();
com = new Computer();
scan = new Scanner(System.in);
start();
}
private void start() {
isRunning = true;
System.out.println("Please, enter your name:");
p.setName(scan.nextLine());
while(isRunning) {
displayScore();
p.selectChoice();
com.selectChoice();
displayChoices();
displayWinner(decideWinner());
updateScore(decideWinner());
playAgain();
}
}
private void displayScore() {
System.out.println(p.getName());
System.out.println("----------");
System.out.println("Wins: " + playerWins);
System.out.println("Loses: " + playerLoses);
System.out.println("Ties: " + ties);
System.out.println("----------");
}
private int decideWinner() {
// 0 - User wins
// 1 - Computer wins
// 2 - tie
if(p.getChoice().equals("ROCK") && com.getChoice().equals("SCISSORS"))
return 0;
else if(p.getChoice().equals("PAPER") && com.getChoice().equals("ROCK"))
return 0;
else if(p.getChoice().equals("SCISSORS") && com.getChoice().equals("PAPER"))
return 0;
else if(com.getChoice().equals("ROCK") && p.getChoice().equals("SCISSORS"))
return 1;
else if(com.getChoice().equals("PAPER") && p.getChoice().equals("ROCK"))
return 1;
else if(com.getChoice().equals("SCISSORS") && p.getChoice().equals("PAPER"))
return 1;
else
return 2;
}
private void displayChoices() {
System.out.println("User has selected: " + p.getChoice());
System.out.println("Computer has selected: " + com.getChoice());
}
private void displayWinner(int winner) {
switch(winner) {
case 0:
System.out.println("User has won!");
break;
case 1:
System.out.println("Computer has won!");
break;
case 2:
System.out.println("It is a tie!");
}
}
private void playAgain() {
String choice;
System.out.println("Do you want to play again? Enter Yes to play again.");
choice = scan.nextLine();
if(!(choice.toUpperCase().equals("YES") ))
isRunning = false;
}
private void updateScore(int winner) {
if(winner == 0)
playerWins++;
else if(winner == 1)
playerLoses++;
else if(winner == 2)
ties++;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T04:15:05.577",
"Id": "404615",
"Score": "3",
"body": "What problem do you expect an OOP approach to solve for you? Design decisions should never be made in a vacuum."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T10:34:38.410",
"Id": "404641",
"Score": "1",
"body": "I suggest you do some validation on the user's input. If the user types anything but the 3 options it always results in a tie now. And you also misleadingly instruct the user to input R, P or S while in fact he needs to type it out"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T02:03:40.943",
"Id": "404721",
"Score": "1",
"body": "@jpmc26 come on, it's a programming assignment. You might as well ask what problem is solved by making computer write \"Hello world\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T02:10:02.063",
"Id": "404722",
"Score": "2",
"body": "@IMil If it's an assignment, that's even more reason to focus on what the tool is best used for rather than apply it blindly. During coursework is the time you're supposed to be learning. Sadly, our discipline does a *very* poor job in the classroom. It teaches platitudes and incorrect absolutes, leaving new recruits a net cost for employers and struggling to learn the basics on the job instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T10:43:38.980",
"Id": "404769",
"Score": "0",
"body": "@jpmc26 I once had a similar assignment. Not in a freshman course, but as part of the hiring process for a senior software developer position that I applied for (with ~20 years of programming experience). You can implement \"rock-paper-scissors\" with maybe 50 LOC. That's not the point. (I'll probably post my code from back then as part of an answer. I didn't want the job anyhow.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T14:35:15.330",
"Id": "404808",
"Score": "0",
"body": "@Marco13 It *is* the point. OO is so mistaught and misapplied that we *must* take every opportunity to teach people to think differently about it. I've only found 2 practical purposes for using objects: grouping data and getting late binding of functions. I've also found that these two should typically not be mixed into a single class. This is far and away from what the OP's code shows they have been taught, who has attempted to use objects to create a *taxonomy*. This is **completely** impractical in real life code. If we want people to be competent, we must start tying practices to problems."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T21:32:04.527",
"Id": "404878",
"Score": "0",
"body": "@jpmc26 We could probably argue for a while here, but a guess: \"taxonomy\" refers to the inheritance in this example? If so: Sure, inheritance is distressingly overused. But it's hard to come up with a \"sensible\" task/assignment where OOP really matters. In any case, in addition to \"grouping data\" and \"late binding\", I'd add **\"abstraction\"** to the list (i.e. defining an *interface*. One could argue that that's also just an instantiation of \"late binding\", but that's why I think the space in the comments will not be enough to sort this all out...)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T21:41:44.047",
"Id": "404879",
"Score": "0",
"body": "@Marco13 \"But it's hard to come up with a 'sensible' task/assignment where OOP really matters.\" **Exactly.** This is **exactly** the point. OOP is usually taught so divorced from the actual practical application that no one knows what situations it's actually useful for. If we, as professional developers with years of experience, can't even articulate the problems it's good at solving, how in the world is an inexperienced student supposed to know how to apply it effectively? We need to emphasize the practical *very early* in education, before students develop habits that cause problems."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T00:51:23.830",
"Id": "404891",
"Score": "0",
"body": "@jpmc26 Then on this level: What's wrong with this (\"artificial\") task where some polymorphism is used via the `Player` class? Again, I think that **abstraction** is something that should be taught (as part of what could more broadly be called \"API design\"). Could you come up with a more suitable example that could convey the relevant ideas **and** be solved with ~4-5 classes and ~<200 LOC?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T01:49:14.417",
"Id": "404899",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/86960/discussion-between-jpmc26-and-marco13)."
}
] | [
{
"body": "<p>This code really isn't a mess! While there are a few relatively minor points I can make, your code is generally easy to read and understand, and there's nothing horribly wrong about it.</p>\n\n<ol>\n<li><p>Watch out for user input! I can enter <code>Z</code> (or anything but rock/paper/scissors) and the result will always be a tie. You should tell the user when they enter something invalid and have them correct it.</p></li>\n<li><p>Both <code>Computer</code> and <code>Player</code> use <code>setName</code> to set their name - once. I would prefer requiring the use of the <code>Player</code> constructor with the <code>name</code> parameter since you could then mark <code>name</code> as <code>final</code>.</p></li>\n<li><p>Why is <code>setChoice</code> <code>public</code>? It is (and should) only used by <code>selectChoice</code>, so mark it <code>protected</code>.</p></li>\n<li><p>What happens when I want to play a game between two computer opponents (or two people)? Right now I can't. It would be nice if <code>Game</code> let me pass the two <code>Player</code> objects in that will be opponents.</p></li>\n<li><p>While I appreciate the <code>MAX_NUMBER</code> constant in the <code>Computer</code> class instead of just including a magic number, it's a better idea to store your choices in an array and then select a random element of the array.</p></li>\n<li><p>Passing around strings for choices isn't so bad when just dealing with Rock/Paper/Scissors, but it will quickly become unmanagable. <a href=\"https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html\" rel=\"noreferrer\">Enum Types</a> were introduced to fix this problem, and generally do a pretty good job of it! It wouldn't hurt to start using them now. Another good spot for an enumeration is in the <code>decideWinner</code> method.</p>\n\n<p>The <code>Choice</code> enum type could also provide a method <code>winsAgainst(Choice other)</code> that can be used to simplify <code>decideWinner</code>.</p></li>\n<li><p>For the most part, your names are great... until we get to <code>Game</code> and see <code>p</code> and <code>com</code>.</p></li>\n<li><p>It would be nice to use the user's name instead of <code>User</code> when displaying the winner and when displaying choices.</p></li>\n</ol>\n\n<p>The following points may directly contradict what your teacher says, as they are more opinion based. Follow whatever your team's (or assignment's) guidelines say.</p>\n\n<ol>\n<li><p>Don't be afraid to include more than one line of code in <code>main</code>. If I wrote this program my <code>main</code> function would look something like this:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>Scanner scanner = new Scanner(System.in);\nSystem.out.println(\"Please enter your name:\");\n\nPlayer user = new User(scanner.nextLine());\nPlayer computer = new Computer();\nGame game = new Game(user, computer);\n\ndo {\n game.play();\n System.out.println(\"Play again? [Yes/No]\");\n} while (scanner.nextLine().toUpperCase().equals(\"YES\"));\n</code></pre></li>\n<li><p>Use braces on all if statements that aren't one line long. I would be fine with <code>if (winner == 0) playerWins++;</code>, but <code>if (winner == 0)\\n playerWins++;</code> is much easier to mess up, especially if you don't have automatic indentation.</p></li>\n<li><p>Don't declare variables before initializing them, if possible. There's no reason to declare <code>choice</code> before printing out instructions in the <code>playAgain</code> method.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T08:44:30.463",
"Id": "404632",
"Score": "0",
"body": "Enums (or constants) avoid spelling errors. You don't get a clear idea of what's wrong from an error message if you just write \"SCISORS\" once."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T01:56:55.477",
"Id": "404720",
"Score": "1",
"body": "BTW this part should be emphasized: *Player* computer = new *Computer()*. The OP had them declared as derived types, which is... ok, but inflexible."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T03:31:40.443",
"Id": "209337",
"ParentId": "209331",
"Score": "9"
}
},
{
"body": "<p>Good job so far!</p>\n\n<p>The previous answers already cover a lot, I just want to add this:</p>\n\n<h2>Don't use String for state!</h2>\n\n<p>Currently you use <code>String</code> to encode the Players <code>Choice</code>. This is hard to refactor and it is difficult to add functionality. Prefer its own <code>Class</code> or <code>Enum</code>.</p>\n\n<p>For example</p>\n\n<pre><code> enum Choice { ROCK, PAPER, SCISSORS}\n</code></pre>\n\n<p>Then, you can have a variable containing the choice, for example:</p>\n\n<pre><code> Choice choice = Choice.ROCK;\n</code></pre>\n\n<p>You can add behaviour to the enum:</p>\n\n<pre><code>enum Choice { \n ROCK, PAPER, SCISSORS\n\n public boolean beats(Choice other)\n {\n switch (this)\n { \n case ROCK:\n return other == SCISSORS;\n case PAPER:\n return other == ROCK;\n case SCISSORS:\n return other == PAPER;\n }\n\n }\n}\n</code></pre>\n\n<p>Now, your other code can just call <code>myChoice.beats(otherChoice)</code>.</p>\n\n<p>Also, you can implement <code>random()</code> in the enum, as well as <code>parseFromUserInput(String s)</code>. If you do this correctly, you can change the enum, adding different choices, without needing to change any other code in your application.</p>\n\n<p>So, if you want to implement <a href=\"https://bigbangtheory.fandom.com/wiki/Rock_Paper_Scissors_Lizard_Spock\" rel=\"nofollow noreferrer\">RockPaperScissorsLizardSpock </a>, you just extend the <code>Enum</code>, and be done!</p>\n\n<p>Also:</p>\n\n<h2>Use Enum instead of magic int values</h2>\n\n<p>Instead of returning <code>int</code> that encodes the result of the round, use a explicit <code>enum</code> as well, replacing the <code>boolean beats()</code> method above:</p>\n\n<pre><code>enum Result { WIN, LOSS, DRAW }\n\npublic Result fights(Choice other)\n {\n switch (this)\n { \n case ROCK:\n if (other == ROCK)\n return Result.DRAW\n return other == SCISSORS ? Result.WIN : Result.LOSS;\n ....\n }\n\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T08:38:14.370",
"Id": "209349",
"ParentId": "209331",
"Score": "19"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T00:57:25.197",
"Id": "209331",
"Score": "12",
"Tags": [
"java",
"beginner",
"rock-paper-scissors"
],
"Title": "Rock Paper Scissors game using OOP"
} | 209331 |
<p>Assuming that the text is tokenized with whitespace for a natural language processing task, the goal is to check the count of the words (regardless of casing) and check them through some conditions. </p>
<p><strong>The current code works as its supposed to but is there a way to optimize and if-else conditions to make it cleaner or more directly?</strong> </p>
<p>First the function has to determine whether : </p>
<ul>
<li><strong>token is an xml tag</strong>, if so ignore it and move to the next token</li>
<li><strong>token is in a list of predefined <code>delayed sentence start</code></strong>, if so ignore it and move to the next token</li>
</ul>
<pre><code># Skip XML tags.
if re.search(r"(<\S[^>]*>)", token):
continue
# Skip if sentence start symbols.
elif token in self.DELAYED_SENT_START:
continue
</code></pre>
<p>Then it checks whether to toggle the <code>is_first_word</code> condition to whether the token is the first word of the sentence; note that there can be many sentences in each line.</p>
<ul>
<li><p>if token in a list of pre-defined sentence ending and the <code>is_first_word</code> condition is False, then set <code>is_first_word</code> to True and then move on to the next token</p></li>
<li><p>if there's nothing to case, since none of the characters falls under the letter regex, then set <code>is_first_word</code> to False and move on to the next token</p></li>
</ul>
<pre><code># Resets the `is_first_word` after seeing sent end symbols.
if not is_first_word and token in self.SENT_END:
is_first_word = True
continue
# Skips words with nothing to case.
if not re.search(r"[{}]".format(ll_lu_lt), token):
is_first_word = False
continue
</code></pre>
<p>Then finally after checking for unweight-able words, and the function continues to finally updates the weight. </p>
<p>First all weights are set to 0, and then set to 1 if it's not <code>is_first_word</code>. </p>
<p>Then if the <code>possibly_use_first_token</code> option is set, then check if the token is lower case, if so use the word. Otherwise, assign a 0.1 weight to it, that's better than setting the weights to 0.</p>
<p>Then finally, update the weights if it's non-zero. And set the <code>is_first_word</code> toggle to False</p>
<pre><code>current_word_weight = 0
if not is_first_word:
current_word_weight = 1
elif possibly_use_first_token:
# Gated special handling of first word of sentence.
# Check if first characer of token is lowercase.
if token[0].is_lower():
current_word_weight = 1
elif i == 1:
current_word_weight = 0.1
if current_word_weight > 0:
casing[token.lower()][token] += current_word_weight
is_first_word = False
</code></pre>
<p>The full code is in the <code>train()</code> function below:</p>
<pre><code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
from collections import defaultdict, Counter
from six import text_type
from sacremoses.corpus import Perluniprops
from sacremoses.corpus import NonbreakingPrefixes
perluniprops = Perluniprops()
class MosesTruecaser(object):
"""
This is a Python port of the Moses Truecaser from
https://github.com/moses-smt/mosesdecoder/blob/master/scripts/recaser/train-truecaser.perl
https://github.com/moses-smt/mosesdecoder/blob/master/scripts/recaser/truecase.perl
"""
# Perl Unicode Properties character sets.
Lowercase_Letter = text_type(''.join(perluniprops.chars('Lowercase_Letter')))
Uppercase_Letter = text_type(''.join(perluniprops.chars('Uppercase_Letter')))
Titlecase_Letter = text_type(''.join(perluniprops.chars('Uppercase_Letter')))
def __init__(self):
# Initialize the object.
super(MosesTruecaser, self).__init__()
# Initialize the language specific nonbreaking prefixes.
self.SKIP_LETTERS_REGEX = r"[{}{}{}]".format(self.Lowercase_Letter,
self.Uppercase_Letter, self.Titlecase_Letter)
self.SENT_END = [".", ":", "?", "!"]
self.DELAYED_SENT_START = ["(", "[", "\"", "'", "&apos;", "&quot;", "&#91;", "&#93;"]
def train(self, filename, possibly_use_first_token=False):
casing = defaultdict(Counter)
with open(filename) as fin:
for line in fin:
# Keep track of first words in the sentence(s) of the line.
is_first_word = True
for i, token in enumerate(line.split()):
# Skip XML tags.
if re.search(r"(<\S[^>]*>)", token):
continue
# Skip if sentence start symbols.
elif token in self.DELAYED_SENT_START:
continue
# Resets the `is_first_word` after seeing sent end symbols.
if not is_first_word and token in self.SENT_END:
is_first_word = True
continue
# Skips words with nothing to case.
if not re.search(self.SKIP_LETTERS_REGEX, token):
is_first_word = False
continue
current_word_weight = 0
if not is_first_word:
current_word_weight = 1
elif possibly_use_first_token:
# Gated special handling of first word of sentence.
# Check if first characer of token is lowercase.
if token[0].is_lower():
current_word_weight = 1
elif i == 1:
current_word_weight = 0.1
if current_word_weight > 0:
casing[token.lower()][token] += current_word_weight
is_first_word = False
return casing
</code></pre>
<p><strong>Sample Input:</strong> <a href="https://gist.github.com/alvations/33799dedc4bab20dd24fb64970451e49" rel="nofollow noreferrer">https://gist.github.com/alvations/33799dedc4bab20dd24fb64970451e49</a></p>
<p><strong>Expected Output of <code>train()</code>:</strong> <a href="https://gist.github.com/alvations/d6d2363bca9a4a9a16e8076f8e8c1e60" rel="nofollow noreferrer">https://gist.github.com/alvations/d6d2363bca9a4a9a16e8076f8e8c1e60</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T02:53:59.637",
"Id": "404607",
"Score": "0",
"body": "Could you provide some example inputs and the corresponding outputs?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T03:44:08.200",
"Id": "404612",
"Score": "0",
"body": "Added the input output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T04:23:26.657",
"Id": "404617",
"Score": "0",
"body": "If anyone is interested, the full code is part of this repo https://github.com/alvations/sacremoses/blob/truecaser/sacremoses/truecase.py"
}
] | [
{
"body": "<p>You aren't doing much heavy lifting here, but there are a few small things that can be improved:</p>\n\n<p><code>self.SENT_END</code> and <code>self.DELAYED_SENT_START</code> are both lists. This means <code>x in self.SENT_END</code> is an <code>O(n)</code> operation. In other words, we must look over the entire list to see if the element is in there. The data structure you want here is a set, which has <code>O(1)</code> lookup time for membership tests. All you have to do is initialize them like so: <code>self.SENT_END = {\".\", \":\", \"?\", \"!\"}</code> (The <code>{}</code> are special syntax for the almost equivalent notation: <code>set([\".\", \":\", \"?\", \"!\"])</code></p>\n\n<p>You use <code>re.search</code> a lot. Regexes are usually rather expensive to run. For example, since you're working on some sort of text corpus, it's a pretty safe assumption that <code><</code> and <code>></code> don't occur unless the word is tag. Furthermore, we may even be able to go as far as to say that the first letter must be a <code><</code>. If you are comfortable making these assumptions, doing <code>word[0] == '<'</code> (or the slightly slower <code>'<' in word</code>) will almost certainly be faster than the regex. That said, if you truly need the regex (maybe your second regex is more complicated, I don't really understand what you're trying to achieve with it), try using precompiled regexes. This way, you don't have to pay the cost of parsing the regex each time you want to use it:</p>\n\n<pre><code>self.SKIP_LETTERS_REGEX = re.compile(r\"[{}{}{}]\".format(self.Lowercase_Letter,\n self.Uppercase_Letter, self.Titlecase_Letter))\n</code></pre>\n\n<p>Then you can use it like <code>self.SKIP_LETTERS_REGEX.search(word)</code>.</p>\n\n<p>This all said, there aren't really many moving parts here. You could try profiling individual bits, but likely you'll hit a wall of \"this is as fast as you can get this to run with cpython.\" If speed is really critical, consider running with <a href=\"https://www.pypy.org/\" rel=\"nofollow noreferrer\">pypy</a>, which is capable of jitting your code and typically is a free performance boost.</p>\n\n<p>If all else fails, you aren't doing too much here, so it wouldn't be hard to port to something lower level like C++ (sans regexes you could accomplish this with <code>iostream</code> and <code>std::unordered_map</code>), but only do that if you identify this as a severe bottleneck via profiling.</p>\n\n<p>Some notes on code style:</p>\n\n<ul>\n<li>You don't need to inherit from <code>(object)</code> in Python 3. You also don't need to call <code>super()</code> either (and <code>super</code> in python 3 is simply <code>super().__init__()</code>)</li>\n<li>Consider making your all caps variables just regular constants and not part of the class</li>\n<li>This doesn't really seem like it needs to be encapsulated in a class. A few top level functions could achieve the last result</li>\n<li>Good comments</li>\n<li><code>train()</code> gets a little bit deep and is hard-ish to follow with all of the continues. Consider breaking it up (although this might affect performance) to make more clear what it actually does</li>\n</ul>\n\n<p>And as a final note on performance, save your code now. Ideally, track it in git. Then, as you make changes, run it with <code>timeit</code>. You can do <code>python3 -m timeit</code> to time your program. Confirm you've measurably improved performance with your changes before committing them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T04:05:23.070",
"Id": "209339",
"ParentId": "209335",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "209339",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T02:46:55.610",
"Id": "209335",
"Score": "2",
"Tags": [
"python",
"regex",
"natural-language-processing"
],
"Title": "Counting lower vs non-lowercase tokens for tokenized text with several conditions"
} | 209335 |
<p>I am trying to see how I can speed up the below script that reports disk usage.</p>
<p>The timed <code>find</code> command towards the end is the problematic line that I am trying to speed up. This script is run on directories that have over 6-7TB of data and it takes 16-18hrs. However I want it to run in under 8hrs. Can someone please suggest alternate ways to modify this script?</p>
<pre><code># -disk_check.csh takes dir name as a mandatory argument and an options <num> or -verbose as a second argument.
# Ex1: disk_check <dir_name> - Reports out the disk usage per user and the total disk consumption
# Ex2: disk_check <dir_name> -verbose -Along with the above, it also lists all files by size in the given directory
# Ex3: disk_check <dir_name> -<num> -Similar to Ex2, But here it reports out the top <num> files by size in the given directory
if ($#argv == 0) then
echo " Error : Dir path missing"
echo " Syntax : disk_check <dir-name> <verbose>"
echo " verbose gives a list of all files per individual sorted by size"
exit 0
endif
set cwd = $argv[1]
if ($cwd =~ "-help") then
echo " Error : Dir path missing"
echo " Syntax : disk_check <dir-name> <-verbose>"
echo " -verbose gives a list of all files per individual sorted by size"
exit 0
endif
if ($#argv > 1) then
set opt = $argv[2]
#echo "opt : $opt"
endif
if ( -d $cwd ) then
set ava = `df -h $cwd | tail -1 | awk '{print $1'}`
set tot = `df -h $cwd | tail -1 | awk '{print $2'}`
set ad = `df -h $cwd | tail -1 | awk '{print $3'}`
set pcu = `df -h $cwd | tail -1 | awk '{print $4'}`
echo ""
echo "Summary for dir ${cwd}: $tot Used (${pcu})"
echo "-----------------------------------------------------------------------------"
echo " Total Volume $ava"
echo " Available on disk $ad "
echo " Percentage used $pcu"
echo ""
echo "Summary by User:"
printf "%sUser%15sSize%10sCount\n" ""
echo "---------------------------------------------"
# This is the command that takes a long time:
time find $cwd -type f -printf "%u %s\n" | awk '{user[$1]+=$2;count[$1]++}; END{ for( i in user) printf "%s%-13s%5s%-0.2f%s%5s%7s\n","", i, "", user[i]/1024**3,"GB", "", count[i]}'| sort -nk2 -r
if ($#argv > 1) then
if ($opt =~ "-verbose") then
echo "\nDetail, Sorted by size"
printf " User%15sFile%15sSize\n" ""
echo "---------------------------------------------------"
find $cwd -type f -not -path '*/\.*' -printf "%-13u | %-50p | %-10s \n" | sort -nk5 -r
endif
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T05:51:40.913",
"Id": "404619",
"Score": "1",
"body": "Have you considered turning on disk quotas? Then the filesystem keeps track of the usage per user, and you can run `quota` to get a report."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T06:48:16.657",
"Id": "404621",
"Score": "0",
"body": "Have you profiled which part of the script is taking such a long time?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T07:47:49.520",
"Id": "404624",
"Score": "0",
"body": "@Mast The specific `find` command has already been identified as a performance problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T08:38:58.760",
"Id": "404628",
"Score": "0",
"body": "@200_success That specific line is the problem, yes. It's also doing most of the heavy lifting of the script, a `find`, `sort` and `awk` call. Given the amount of data it's used on, I'm not sure `find` is the only problem here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T12:07:04.647",
"Id": "404650",
"Score": "0",
"body": "@Mast The time taken by awk and sort are surely insignificant compared to scanning an entire filesystem!"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T05:25:48.170",
"Id": "209342",
"Score": "2",
"Tags": [
"time-limit-exceeded",
"file-system",
"linux",
"unix",
"tcsh"
],
"Title": "Script to report disk usage"
} | 209342 |
<p>I've been writing my code like this for a really long time now, I am wondering if there is a more efficient way to do this. This is especially after a senior developer said my code was very amateurish. </p>
<p>App Purpose: I need to set some data for new employees when they join our organisation. This is a simple command app written in .net that takes an argument, splits it and then assigns the variables. A command might look like this: </p>
<blockquote>
<pre><code>Setdata.exe -Marcus -true -true -false -false.
</code></pre>
</blockquote>
<p>The output is a file that we install on one of our sql servers.</p>
<p>The example below is a small one, but it is not common for the settings to hit 40-50 lines.</p>
<p>Code:</p>
<pre><code> internal static void ExportSolution(SqlService service, string parms)
{
try
{
parms = parms.Replace(" ", "");
string[] args = parms.Split('-');
string solutionName = args[1];
bool managed = Convert.ToBoolean(args[2]);
bool prefix= Convert.ToBoolean(args[3]);
bool profile= Convert.ToBoolean(args[4]);
bool email= Convert.ToBoolean(args[5]);
bool calendar= Convert.ToBoolean(args[6]);
bool appSettings= Convert.ToBoolean(args[7]);
AppSettingsRequestAppSettingsRequest= new AppSettingsRequest();
AppSettingsRequest.SolutionName = solutionName;
AppSettingsRequest.Managed = (managed == true) ? true : false;
AppSettingsRequest.prefix= (prefix== true) ? true : false;
AppSettingsRequest.Managed profile= (profile== true) ? true : false;
AppSettingsRequest.email= (email== true) ? true : false;
AppSettingsRequest.calendar= (calendar== true) ? true : false;
AppSettingsRequest.appSettings= (appSettings== true) ? true : false;
byte[] exportXml = exportSolutionResponse.ExportSolutionFile;
string filename = solutionName + ".zip";
File.WriteAllBytes(filename, exportXml);
Console.WriteLine("Solution exported to {0}.", filename);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
</code></pre>
<p>Initial thoughts are that I could create a new class and then instantiate a new object with these variables, but is there anything to gain from doing this?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T09:10:19.947",
"Id": "404635",
"Score": "3",
"body": "Would you mind posting the entire application?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T09:26:19.997",
"Id": "404636",
"Score": "0",
"body": "`AppSettingsRequest.Managed = (managed == true) ? true : false;` and the following can be written as `AppSettingsRequest.Managed = managed;`"
}
] | [
{
"body": "<p>The code looks good, but I think the code could look more structured, like maybe in the appsetings you could give them one more indentation. This way the code won't just be one long line and it would be much easier to differentiate the code structure.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T09:17:38.947",
"Id": "209352",
"ParentId": "209351",
"Score": "-3"
}
},
{
"body": "<p>Because creating/readings settings and creating the output file are two separate things, consider separating the settings parsing part to different function/class so it can be actually tested without creating files.</p>\n\n<p>Separating the parsing to different file also makes it easier to take the settings from different sources in future if needed (config-files, etc.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T11:10:39.677",
"Id": "209355",
"ParentId": "209351",
"Score": "3"
}
},
{
"body": "<p><strong>Ignored code</strong></p>\n\n<p>From the code sample provided, you're not actually doing anything with the <code>AppSettingsRequest</code> object after you've created it. Why? What is the purpose of this object?</p>\n\n<hr>\n\n<p><strong>Global variables</strong></p>\n\n<pre><code>byte[] exportXml = exportSolutionResponse.ExportSolutionFile;\n</code></pre>\n\n<p>What is <code>exportSolutionResponse</code>? It comes out of nowhere, without being defined anywhere. This seems to be a global variable (I can't otherwise explain its existence).</p>\n\n<p>Global variables are generally a bad idea. They create shortcuts in code that is one of the straws that will eventually break the camel's back (in this case, unmaintainable spaghetti code).</p>\n\n<hr>\n\n<p><strong>Stringly typing</strong></p>\n\n<p>As you seem to be using a console application, the parameters can be parsed an an array of values, not as a single string. Why are you concatenating these values into a string, only to then split the string again?</p>\n\n<p>This can be improved by using explicit method parameters:</p>\n\n<pre><code>internal static void ExportSolution(SqlService service, string name, params bool[] values)\n</code></pre>\n\n<p>This means you no longer have to do the conversion in this method; which is a good separation of concerns.</p>\n\n<p>Given that you are expect a <strong>fixed</strong> amount of booleans, it's better to explicitly name these booleans instead of allowing any array of arbitrary length:</p>\n\n<pre><code>internal static void ExportSolution(SqlService service, string name, bool managed, bool prefix, bool managedprofile, bool email, bool calendar, bool appsettings)\n</code></pre>\n\n<hr>\n\n<p><strong>Vague names</strong></p>\n\n<p>Your variable names leave something to be desired. I can only guess at what these variables mean. Rename them to something clearer. I've <em>guessed</em> at what these booleans are used for:</p>\n\n<pre><code>internal static void ExportSolution(SqlService service, string userName, bool isManaged, bool hasPrefix, bool useManagedProfile, bool importEmail, bool importCalendar, bool overrideAppSettings)\n</code></pre>\n\n<p>Don't get caught up on the names, my interpretations are only a guess. But these examples are much clearer on what the impact of these booleans is.</p>\n\n<hr>\n\n<p><strong>No null checking</strong></p>\n\n<p>This ties into the earlier point. In your original code, you are taking in any string and splitting it into an array, and then <strong>assuming</strong> that this array will contain at least 8 values.</p>\n\n<p>What happens when the array contains less than 8 values? You're going to end up with an <code>IndexOutOfRangeException</code>. While you do catch and display exceptions, it's still better to <strong>avoid exceptions where possible</strong>. It's not that hard to validate the length of the array before you try to access its elements.</p>\n\n<pre><code>if(args.Length < 8)\n{\n Console.WriteLine(\"Insufficient parameters provided\");\n return;\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Pokémon exception handling</strong> (<a href=\"http://wiki.c2.com/?PokemonExceptionHandling\" rel=\"noreferrer\">link</a>)</p>\n\n<pre><code>catch (Exception ex)\n{\n Console.WriteLine(ex);\n}\n</code></pre>\n\n<p>Instead of catching all exceptions, catch the exceptions you're interested in. For example:</p>\n\n<pre><code>catch (IndexOutOfRangeException ex)\n{\n Console.WriteLine(\"Insufficient parameters provided\");\n}\n</code></pre>\n\n<p><em>Note: as mentioned before, it is better to prevent the exception when possible, instead of just catching it afterwards. This only serves as a simple example of how you catch <strong>specific</strong> exceptions instead of all possible exception types.</em></p>\n\n<hr>\n\n<p><strong>Needlessly verbose code</strong></p>\n\n<pre><code>AppSettingsRequest.Managed = (managed == true) ? true : false;\n</code></pre>\n\n<p>this can immediately be refactored to:</p>\n\n<pre><code>AppSettingsRequest.Managed = managed;\n</code></pre>\n\n<p>For two reasons:</p>\n\n<ol>\n<li><code>== true</code> is redundant. If the variable is already a boolean, its \"trueness\" doesn't need to be checked. <code>managed == true</code> will always equal <code>managed</code>.</li>\n<li><code>? true : false</code> is redundant. The evaluation (left of the <code>?</code>) is already a boolean, and what you're doing here is saying \"if this evaluation is true, set this to true; if this evalutation is false, set it to false\". It's much short to just say \"set this to the evaluation's value\". <code>managed ? true : false</code> will always equal <code>managed</code>.</li>\n</ol>\n\n<p><em>Note: if you were using nullable booleans, bullet point 1 wouldn't necessarily be correct (as you're also checking for non-null in that case), but you're not using nullable booleans here.</em></p>\n\n<hr>\n\n<p><strong>Saving some lines of code</strong></p>\n\n<pre><code>bool managed = Convert.ToBoolean(args[2]);\nAppSettingsRequest.Managed = managed;\n</code></pre>\n\n<p>Can be shortened to</p>\n\n<pre><code>AppSettingsRequest.Managed = Convert.ToBoolean(args[2]);\n</code></pre>\n\n<p>In general, I wouldn't advise this. The added clarity from separating the steps makes things easier. However, given that one of your main issues is the amount of settings, combining the two steps will <strong>halve</strong> your line count. At the same time, the combined line is not unreadable by any stretch of the imagination so it's perfectly okay to combine them here.</p>\n\n<hr>\n\n<p><strong>Separating your concerns</strong></p>\n\n<p>In general, your method is taking on too many tasks. It manipulates the input string, converts the values, handles them, writes to storage and updates the UI (console output). This is too many responsibilities for a single method.</p>\n\n<p>However, this seems to be a very small and simple console application, and the overhead cost of implementing some separations may end up costing more effort than it's worth. I would still suggest a basic separation between the following tasks:</p>\n\n<ul>\n<li>Parsing the input values (to their correct string/bool types)</li>\n<li>Instantiating the settings object and settings its properties</li>\n<li>Writing your data to disk</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T11:41:02.177",
"Id": "209358",
"ParentId": "209351",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T09:06:48.587",
"Id": "209351",
"Score": "0",
"Tags": [
"c#",
"beginner",
".net",
"console"
],
"Title": "App that sets configuration data"
} | 209351 |
<p>I found myself working in this coding exercise for a work offer. I tried to apply TDD in the process but I didn't get any feedback from the company and I really would like to know what can be improved (pretty sure there are a lot of things), so any advice or refactor suggestion will be very much appreciated.</p>
<blockquote>
<h3>Background:</h3>
<p>A group event will be created by an user. The group event should run for a whole number of days e.g.. 30 or 60. There should be attributes to set and update the start, end or duration of the event (and calculate the other value). The event also has a name, description (which supports formatting) and location. The event should be draft or published. To publish all of the fields are required, it can be saved with only a subset of fields before it’s published. When the event is deleted/remove it should be kept in the database and marked as such.</p>
<h3>Deliverable:</h3>
<p>Write an AR model, spec and migration for a GroupEvent that would meet the needs of the description above. Then write the API controller and spec to support JSON request/responses to manage these GroupEvents. For the purposes of this exercise, ignore auth. </p>
</blockquote>
<p><strong>app/models/group_event.rb:</strong></p>
<pre><code>class GroupEvent < ApplicationRecord
validates :name, :description, :starts_at, :ends_at, :location, presence: true, if: :published?
validate :duration_range_is_valid?, if: :published?
before_save :set_duration, if: :duration_range_is_valid?
def draft?
!published?
end
def check_duration_range
errors.add(:start_date, "Start date must be before end date") unless duration_range_is_valid?
end
def has_duration_range?
starts_at.present? && ends_at.present?
end
def duration_range_is_valid?
has_duration_range? and starts_at <= ends_at
end
def set_duration
self.duration = ((self.ends_at - self.starts_at) / 1.day).to_i if duration_range_is_valid?
end
def destroy
update_attribute(:deleted, true)
end
end
</code></pre>
<p><strong>app/controllers/api/v1/group_events_controller.rb:</strong></p>
<pre><code> class Api::V1::GroupEventsController < ApplicationController
include Response
include ExceptionHandler
before_action :set_group_event, only: [:show, :update, :destroy]
# GET /api/v1/group_events
def index
@group_events = GroupEvent.all
json_response @group_events
end
# GET /api/v1/group_events/1
def show
json_response @group_event
end
# POST /api/v1/group_events
def create
@group_event = GroupEvent.create!(group_event_params)
json_response(@group_event, :created)
end
# PATCH/PUT /api/v1/group_events/1
def update
if @group_event.update(group_event_params)
json_response @group_event
else
json_response @group_event.errors, :unprocessable_entity
end
end
# DELETE /api/v1/group_events/1
def destroy
@group_event.destroy
end
private
def set_group_event
@group_event = GroupEvent.find(params[:id])
end
def group_event_params
params.permit(:name, :description, :deleted, :published, :location, :starts_at, :ends_at)
end
end
</code></pre>
<p><strong>config/routes.rb:</strong></p>
<pre><code>Rails.application.routes.draw do
namespace :api do
namespace :v1 do
resources :group_events
end
end
end
</code></pre>
<p><strong>spec/models/group_event_spec.rb:</strong></p>
<pre><code>require 'rails_helper'
RSpec.describe GroupEvent, type: :model do
it 'has a valid factory' do
expect(create(:group_event)).to be_valid
end
describe 'validations' do
context 'published' do
before { allow(subject).to receive(:published?).and_return(true) }
it { is_expected.to validate_presence_of :name }
it { is_expected.to validate_presence_of :description }
it { is_expected.to validate_presence_of :starts_at }
it { is_expected.to validate_presence_of :ends_at }
it { is_expected.to validate_presence_of :location }
end
context 'draft' do
before { allow(subject).to receive(:draft?).and_return(true) }
it { is_expected.not_to validate_presence_of :name }
it { is_expected.not_to validate_presence_of :description }
it { is_expected.not_to validate_presence_of :starts_at }
it { is_expected.not_to validate_presence_of :ends_at }
it { is_expected.not_to validate_presence_of :location }
end
end
describe '.draft?' do
context 'published' do
before { allow(subject).to receive(:published?).and_return(true) }
it 'is false' do
expect(subject.draft?).to eq(false)
end
end
context 'draft' do
before { allow(subject).to receive(:published?).and_return(false) }
it 'is true' do
expect(subject.draft?).to eq(true)
end
end
end
describe '.has_duration_range?' do
context 'with both values' do
before { allow(subject).to receive(:starts_at).and_return(DateTime.now) }
before { allow(subject).to receive(:ends_at).and_return(DateTime.tomorrow) }
it 'is true' do
expect(subject.has_duration_range?).to eq(true)
end
end
context 'without both values' do
before { allow(subject).to receive(:starts_at).and_return(nil) }
before { allow(subject).to receive(:ends_at).and_return(nil) }
it 'is false' do
expect(subject.has_duration_range?).to eq(false)
end
end
context 'without only one value' do
before { allow(subject).to receive(:starts_at).and_return(DateTime.now) }
before { allow(subject).to receive(:ends_at).and_return(nil) }
it 'is false' do
expect(subject.has_duration_range?).to eq(false)
end
end
end
describe '.duration_range_is_valid?' do
context 'with valid range' do
before { allow(subject).to receive(:has_duration_range?).and_return(true) }
before { allow(subject).to receive(:starts_at).and_return(DateTime.now) }
before { allow(subject).to receive(:ends_at).and_return(DateTime.tomorrow) }
it 'is true' do
expect(subject.duration_range_is_valid?).to eq(true)
end
end
context 'without invalid range' do
before { allow(subject).to receive(:has_duration_range?).and_return(true) }
before { allow(subject).to receive(:starts_at).and_return(DateTime.tomorrow) }
before { allow(subject).to receive(:ends_at).and_return(DateTime.now) }
it 'is false' do
expect(subject.duration_range_is_valid?).to eq(false)
end
end
end
describe '.set_duration' do
it 'with valid range' do
group_event = GroupEvent.create!(starts_at: DateTime.now, ends_at: DateTime.now + 10.days)
expect(group_event.duration).to eq(10)
end
it 'with invalid range' do
group_event = GroupEvent.create!(starts_at: DateTime.now, ends_at: DateTime.now - 10.days)
expect(group_event.duration).to eq(nil)
end
end
describe '.destroy' do
it 'does not destroy the event' do
group_event = GroupEvent.create!
count = GroupEvent.all.count
group_event.destroy
expect(GroupEvent.unscoped.count).to eq(count)
end
it 'sets deleted' do
group_event = GroupEvent.create!
group_event.destroy
expect(group_event.deleted).to eq(true)
end
end
end
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T13:04:01.807",
"Id": "209360",
"Score": "2",
"Tags": [
"ruby",
"unit-testing",
"ruby-on-rails",
"api"
],
"Title": "TDD for Ruby On Rails API for group event items"
} | 209360 |
<p>I am quite new in Python and I am starting my journey with sorting algorithms, PEP8 and the Zen of Python. I would like to get some feedback about my BubbleSort algorithm which I wrote.
Also, is there a possibility to change the <code>break</code> statement to something else which will stop the loop?</p>
<pre><code>def bubble_sort(structure):
"""
Bubble sort.
Description
----------
Performance cases:
Worst : O(n^2)
Average : O(n^2)
Best case : O(n)
Parameters
----------
structure : Mutable structure with comparable objects.
Returns
-------
structure : return sorted structure.
Examples
----------
>>> bubble_sort([7,1,2,6,4,2,3])
[1, 2, 2, 3, 4, 6, 7]
>>> bubble_sort(['a', 'c', 'b'])
['a', 'b', 'c']
"""
length = len(structure)
while True:
changed = False
for i in range(length - 1):
if structure[i] > structure[i + 1]:
structure[i], structure[i + 1] = structure[i + 1], structure[i]
changed = True
if not changed:
break
return structure
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T13:30:19.553",
"Id": "404654",
"Score": "0",
"body": "You can implement it with 2 for loops, then you can get rid of the `break`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T13:32:31.183",
"Id": "404655",
"Score": "0",
"body": "I get an idea now what if i change the `break` statment to `return structure` and delete the last line `return structure`. Will it harmonize with PEP8?"
}
] | [
{
"body": "<p>Your code looks nice and the documentation is high quality.</p>\n\n<p>Maybe a few things can be improved anyway.</p>\n\n<p><strong>API</strong></p>\n\n<p>It could be a good idea to get inspiration from the Python API functions related to sorting, we have:</p>\n\n<ul>\n<li><a href=\"https://docs.python.org/3/library/functions.html#sorted\" rel=\"nofollow noreferrer\"><code>sorted</code></a> returning a new list from an iterable</li>\n<li><a href=\"https://docs.python.org/3/library/stdtypes.html#list.sort\" rel=\"nofollow noreferrer\"><code>list.sort</code></a> sorts a list in place, returns None</li>\n</ul>\n\n<p>In your case, as <code>structure</code> is sorted in place, I am not sure it makes sense to return it.</p>\n\n<p><strong>Parameter <code>structure</code></strong></p>\n\n<p>This is mostly personal opinion but instead of <code>structure</code>, I'd find <code>container</code> to be a better name.</p>\n\n<p>Also, if you want to be precise in the documentation, you might want to say that it is <code>mutable</code> but also that it implements <code>__len__</code>, <code>__getitem__</code> and <code>__setitem__</code>. These objects are also called <a href=\"https://docs.python.org/3/reference/datamodel.html#objects-values-and-types\" rel=\"nofollow noreferrer\">(mutable) sequences</a>.</p>\n\n<p><strong>The code</strong></p>\n\n<p>Not much to say about the code itself.</p>\n\n<p>Instead of having <code>if not changed: break</code>, you could write a: <code>while changed</code> loop which is very slightly more concise.</p>\n\n<p>Also, you'll find an optimisation suggestion on <a href=\"https://en.wikipedia.org/wiki/Bubble_sort#Optimizing_bubble_sort\" rel=\"nofollow noreferrer\">Wikipedia</a>:</p>\n\n<blockquote>\n <p>The bubble sort algorithm can be easily optimized by observing that the n-th pass finds the n-th largest element and puts it into its final place. So, the inner loop can avoid looking at the last n − 1 items when running for the n-th time</p>\n</blockquote>\n\n<p>Before getting into such a change, I highly recommend writing unit tests.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T15:48:27.423",
"Id": "404666",
"Score": "0",
"body": "I have one more question. How can i make a copy of the `structure` to return it as `sorted` does ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T16:51:47.613",
"Id": "404668",
"Score": "0",
"body": "Changing the struct in place is fine to me. However, if you need, you could use the copy module. Alternatively, you could just also just call list to copy your container as a list."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T14:09:29.013",
"Id": "209362",
"ParentId": "209361",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T13:09:06.057",
"Id": "209361",
"Score": "4",
"Tags": [
"python",
"beginner",
"sorting"
],
"Title": "Bubble sort in Python"
} | 209361 |
<h1>Problem:</h1>
<p>In the following expression <code>1-2+3-4+5-6 ... -98+99-100</code>, print result every 10th (10, 20, 30, ...) calculation.</p>
<h1>My code:</h1>
<pre><code>result = 0
operand = 1
counter = 0
for i in range(1, 101):
result = result + (i * operand)
counter = counter + 1
operand = operand * -1 #Convert between positive and negative number
if counter >= 10:
counter = 0
print(result)
</code></pre>
<h1>My problem:</h1>
<p>I think this code has not good readability. For example, I used * -1 for changing positive and negative number. But it requires math skill(multiplying a negative number) to understand code. </p>
<p>And I don't sure variable name 'counter' and 'operand' is appropriate for this context.</p>
<p>Is there any suggestion?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T15:29:06.040",
"Id": "404663",
"Score": "0",
"body": "Do you need the final `result` of the whole sum and just want to report progress as the summing is going on, or do you want the sum of only every 10th element and also print progress?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T01:35:29.210",
"Id": "404711",
"Score": "1",
"body": "Maybe I'm missing something, but isn't the alternating sum you want $$-\\sum_{n=1}^{m} n (-1)^n \\equiv -\\frac{1}{4}-\\frac{1}{4}(-1)^m (2m+1)$$ And then you can substitute m = 10n or whatever value you need. Far faster than looping."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T01:50:46.623",
"Id": "404718",
"Score": "0",
"body": "@Graipher I want to report progress as the summing is going on. but original question is not clear. So i think it should be interpreted like this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T21:59:59.783",
"Id": "404881",
"Score": "0",
"body": "@esote this seems like the start of an answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T22:12:03.893",
"Id": "404884",
"Score": "0",
"body": "@MathiasEttinger More of a hint. Do you think I should expand it into a full answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T22:20:31.427",
"Id": "404885",
"Score": "1",
"body": "@esote Mathematical analysis of a problem in order to reduce code complexity are usually well received."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T23:05:48.970",
"Id": "404889",
"Score": "0",
"body": "@MathiasEttinger Posted an answer."
}
] | [
{
"body": "<p>You can get rid of your <code>counter</code> and directly use <code>i</code> by using modular arithmetic. <code>i % 10 == 0</code> is true whenever <code>i</code> is divisible by <code>10</code>.</p>\n\n<p>You can get rid of your <code>operand = operand * -1</code> by using <a href=\"https://docs.python.org/3/library/itertools.html#itertools.cycle\" rel=\"noreferrer\"><code>itertools.cycle</code></a>.</p>\n\n<pre><code>from itertools import cycle\n\nresult = 0\nfor i, sign in zip(range(1, 101), cycle([1, -1])):\n result += sign * i\n if i % 10 == 0:\n print(result)\n</code></pre>\n\n<p>The generation of <code>result</code> itself would be a lot more concise with a generator comprehension, but this excludes the progress prints:</p>\n\n<pre><code>result = sum(sign * i for i, sign in zip(range(1, 101), cycle([1, -1])))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T15:25:38.700",
"Id": "404661",
"Score": "0",
"body": "@MathiasEttinger: It seems like MaartenFabre is already going in that direction in [their answer](https://codereview.stackexchange.com/a/209368/98493)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T15:28:06.340",
"Id": "404662",
"Score": "0",
"body": "Yep, saw that after the comment"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T15:12:06.647",
"Id": "209366",
"ParentId": "209364",
"Score": "6"
}
},
{
"body": "<p>The first thing you can do to make the sign change obvious is to use <code>operand = -operand</code>, this way you avoid the need for the multiplication operator. Also changing the <code>operand</code> name to sign can help.</p>\n\n<p>You also don't need <code>counter</code> as it will be equal to <code>i</code> before the test. Just change the test to use the modulo (<code>%</code>) operator instead of reseting <code>counter</code>.</p>\n\n<p>And using augmented assignment for <code>result</code> can lead to a more readable line too:</p>\n\n<pre><code>result = 0\nsign = 1\nfor i in range(1, 101):\n result += sign * i\n sign = -sign\n if i % 10 == 0:\n print(result)\n</code></pre>\n\n<p>Now, this probably need to be made more reusable, this means building a function out of this code and avoiding mixing computation and I/Os:</p>\n\n<pre><code>def alternating_sum(start=1, stop=100, step=10):\n result = 0\n sign = 1\n for i in range(start, stop+1):\n result += sign * i\n sign = -sign\n if i % step == 0:\n yield result\n</code></pre>\n\n<p>Usage being:</p>\n\n<pre><code>for result in alternating_sum(1, 100, 10):\n print(result)\n</code></pre>\n\n<hr>\n\n<p>Also, depending on the problem at hand, you can leverage the fact that every two numbers add-up to <code>-1</code>. So every 10 numbers add-up to <code>-5</code>. If you don't need much genericity, you can simplify the code down to:</p>\n\n<pre><code>def alternating_every_ten(end=100):\n reports = end // 10\n for i in range(1, reports + 1):\n print('After', 10 * i, 'sums, result is', -5 * i)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T18:41:58.043",
"Id": "404677",
"Score": "0",
"body": "I would recommend writing expressions with a sign variable as `sign * value` to match the standard method of writing numbers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T20:11:46.870",
"Id": "404681",
"Score": "0",
"body": "@Apollys Right, fixed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T15:19:15.493",
"Id": "209367",
"ParentId": "209364",
"Score": "12"
}
},
{
"body": "<p>instead of doing the <code>+-</code> by hand, you can use the fact that <code>(-1) ** (i-1) * i for i in range(101)</code> alternates the values</p>\n\n<p>Further on, you can use <code>itertools.accumulate</code> and <code>itertools.islice</code> to take the cumulative sum and select every 10th number</p>\n\n<pre><code>numbers = (int((-1) ** (i-1) * i) for i in range(101))\ncum_sum = itertools.accumulate(numbers)\nnumbers_10 = itertools.islice(cum_sum, 10, None, 10)\n\nfor i in numbers_10:\n print(i)\n</code></pre>\n\n<blockquote>\n<pre><code>-5\n-10\n-15\n-20\n-25\n-30\n-35\n-40\n-45\n-50\n</code></pre>\n</blockquote>\n\n<p>or alternatively, per 200_success' suggestion:</p>\n\n<pre><code>numbers = (sign * i for sign, i in zip(itertools.cycle((1, -1)), itertools.count(1)))\ncum_sum = itertools.accumulate(numbers)\nnumbers_10 = itertools.islice(cum_sum, 9, 100, 10)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T15:24:53.257",
"Id": "404660",
"Score": "0",
"body": "With this you do not get the final result, though. Maybe with a `itertools.tee` of the `numbers`, which you can then `sum`, but then it is no longer reporting on the progress..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T15:37:55.807",
"Id": "404664",
"Score": "0",
"body": "what do you mean with the final result? If needed, you need to do `cum_sum = list(itertools.accumulate(numbers))` or `numbers = [int((-1) ** (i-1) * i) for i in range(101)]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T00:11:41.250",
"Id": "404706",
"Score": "2",
"body": "I like this. Personally, I'd write it as `cum_sum = accumulate(sign * n for sign, n in zip(cycle((+1, -1)), count()))` to more elegantly express the idea of an infinite series, then extract just the relevant partial sums with `for n in islice(cum_sum, 9, 100, 10): print(n)`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T15:19:53.887",
"Id": "209368",
"ParentId": "209364",
"Score": "5"
}
},
{
"body": "<p>I would convert the sign flip into a generator, created via a generator comprehension, recognizing that evens should be negative:</p>\n\n<pre><code># Integers from 1-100, where evens are negative: 1, -2, 3, -4, 5...\nsequence_gen = (i if i % 2 else -i for i in range(1,101))\n</code></pre>\n\n<p>Equivalent to:</p>\n\n<pre><code>def sequence_gen():\n for i in range(1, 101):\n if bool(i % 2): # For our purposes this is i % 2 == 1:\n yield i\n else:\n yield -i\n</code></pre>\n\n<p>Then your code becomes:</p>\n\n<pre><code>result = 0\nfor index, number in enumerate(sequence_gen):\n result += number\n if index % 10 == 9: # Note the comparison change by starting at 0\n print(result)\n</code></pre>\n\n<p>Note this is about half way to what Mathias proposed, and can be used in conjunction, the combination being:</p>\n\n<pre><code>def sequence_sums(start, stop, step):\n result = 0\n seq_gen = (i if i % 2 else -i for i in range(start, stop + 1))\n for index, number in enumerate(seq_gen):\n result += number\n if index % step == step - 1:\n yield result\n</code></pre>\n\n<hr>\n\n<p>You could even go one further step and make the sequence a parameter:</p>\n\n<pre><code># iterates through a sequence, printing every step'th sum\ndef sequence_sums(sequence, step):\n result = 0\n for index, number in enumerate(sequence):\n result += number\n if index % step == step - 1:\n yield result\n</code></pre>\n\n<p>Called via:</p>\n\n<pre><code>sequence = (i if i % 2 else -i for i in range(1, 101))\n\nfor sum in sequence_sums(sequence, 10):\n print(sum)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T08:00:25.290",
"Id": "404742",
"Score": "1",
"body": "`Note the comparison change by starting at 0` => `enumerate` takes a second, optional, argument: `start`. So you can use `enumerate(sequence, 1)` and keep the usual comparison of the modulo to 0."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T23:22:10.387",
"Id": "209396",
"ParentId": "209364",
"Score": "1"
}
},
{
"body": "<p>The other answers are fine. Here is a mathematical analysis of the problem you're trying to solve.</p>\n\n<p>If this code is, for some reason, used in a performance-critical scenario, you can calculate the sum to <span class=\"math-container\">\\$m\\$</span> in <span class=\"math-container\">\\$O(1)\\$</span> time.</p>\n\n<p>Notice that:</p>\n\n<p><span class=\"math-container\">$$\n\\begin{align}\n1-2+3-4+5-6\\dots m &= -\\sum_{n=1}^{m}n(-1)^n \\\\\n&= \\sum_{n=1}^{m}n(-1)^{n-1} \\\\\n&= \\frac{1}{4}-\\frac{1}{4}(-1)^m(2m+1) \\; ^*\n\\end{align}\n$$</span></p>\n\n<p>* There was a typo in my original comment.</p>\n\n<p>Because you only want to see every 10th result, we can substitute <span class=\"math-container\">\\$m=10u\\$</span> where <span class=\"math-container\">\\$u\\in\\mathbb{Z}\\$</span>. This is fortunate because for all integers <span class=\"math-container\">\\$(-1)^{10u} \\equiv 1\\$</span>. Therefore:</p>\n\n<p><span class=\"math-container\">$$\n\\begin{align}\n\\frac{1}{4}-\\frac{1}{4}(-1)^{10u}(20u+1) &= \\frac{1}{4}-\\frac{1}{4}(20u+1) \\\\\n&= \\frac{1}{4}-\\frac{20u+1}{4}\\\\\n&= \\frac{(1-1)-20u}{4} \\\\\n&= -5u\n\\end{align}\n$$</span></p>\n\n<p>Look familiar? It results in <span class=\"math-container\">\\$-5\\$</span>, <span class=\"math-container\">\\$-10\\$</span>, <span class=\"math-container\">\\$-15\\$</span>, ...</p>\n\n<p>This fact is obvious from the output, but now knowing the series that produces it, we can calculate the final result for any such <span class=\"math-container\">\\$m\\$</span> quickly, and every 10th value even easier.</p>\n\n<p>We can avoid computing the exponent <span class=\"math-container\">\\$(-1)^m\\$</span> because <span class=\"math-container\">\\$(-1)^{m} = 1\\$</span> for even values of <span class=\"math-container\">\\$m\\$</span> and <span class=\"math-container\">\\$-1\\$</span> for odd values.</p>\n\n<p>I'm not as familiar with Python, but here's an example:</p>\n\n<pre><code>def series(m):\n alt = 1 if m % 2 == 0 else -1\n return int(1/4 - 1/4 * alt * (2 * m + 1))\n\ndef series_progress(m):\n return -5 * m\n\nm = 134\n\nfor i in range(1, m // 10):\n print(series_progress(i))\n\nprint(series(m))\n</code></pre>\n\n<p>This avoids the costly computation for the final result. If we just needed the result it would be <span class=\"math-container\">\\$O(1)\\$</span>, but because we give \"progress reports\" it is more like <span class=\"math-container\">\\$\\lfloor\\frac{n}{10}\\rfloor\\in O(n)\\$</span>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T23:05:32.587",
"Id": "209482",
"ParentId": "209364",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "209367",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T14:41:14.083",
"Id": "209364",
"Score": "12",
"Tags": [
"python",
"python-3.x"
],
"Title": "Printing every 10th result in an alternating ± series"
} | 209364 |
<h3>Background</h3>
<p>I've come across a puzzle <a href="https://www.analyticsvidhya.com/blog/2016/07/20-challenging-job-interview-puzzles-which-every-analyst-solve-atleast/" rel="nofollow noreferrer">(Problem 10 from this list of sample interview questions)</a>:</p>
<blockquote>
<p>One day, an alien comes to Earth. Every day, each alien does one of four things, each with equal probability to:</p>
<ul>
<li>Kill himself</li>
<li>Do nothing</li>
<li>Split himself into two aliens (while killing himself)</li>
<li>split himself into three aliens (while killing himself)</li>
</ul>
<p>What is the probability that the alien species eventually dies out entirely?</p>
</blockquote>
<p>Unfortunately, I haven't been able to solve the problem theoretically. Then I moved on to simulate it with a basic Markov Chain and Monte Carlo simulation in mind.</p>
<p><em>This was not asked to me in an interview. I learned the problem from a friend, then found the link above while searching for mathematical solutions.</em></p>
<h3>Reinterpreting the question</h3>
<p>We start with the number of aliens <code>n = 1</code>. <code>n</code> has a chance to not change, be decremented by <code>1</code>, be incremented by <code>1</code>, and be incremented by <code>2</code>, %25 for each. If <code>n</code> is incremented, i.e. aliens multiplied, we repeat this procedure for <code>n</code> times again. This corresponds to each alien will do its thing again. I have to put an upper limit though, so that we stop simulating and avoid a crash. <code>n</code> is likely to increase and we're looping <code>n</code> times again and again.</p>
<p>If aliens somehow go extinct, we stop simulating again since there's nothing left to simulate.</p>
<p>After <code>n</code> reaches zero or the upper limit, we also record the population (it will be either zero or some number <code>>= max_pop</code>).</p>
<p>I repeat this many times and record every result. At the end, number of zeros divided by total number of results should give me an approximation.</p>
<h3>The code</h3>
<pre><code>from random import randint
import numpy as np
pop_max = 100
iter_max = 100000
results = np.zeros(iter_max, dtype=int)
for i in range(iter_max):
n = 1
while n > 0 and n < pop_max:
for j in range(n):
x = randint(1, 4)
if x == 1:
n = n - 1
elif x == 2:
continue
elif x == 3:
n = n + 1
elif x == 4:
n = n + 2
results[i] = n
print( np.bincount(results)[0] / iter_max )
</code></pre>
<p><code>iter_max</code> and <code>pop_max</code> can be changed indeed, but I thought if there is 100 aliens, the probability that they go extinct would be negligibly low. This is just a guess though, I haven't done anything to calculate a (more) proper upper limit for population.</p>
<p>This code gives promising results, fairly close to the real answer which is approximately %41.4.</p>
<h3>Some outputs</h3>
<pre><code>> python aliens.py
0.41393
> python aliens.py
0.41808
> python aliens.py
0.41574
> python aliens.py
0.4149
> python aliens.py
0.41505
> python aliens.py
0.41277
> python aliens.py
0.41428
> python aliens.py
0.41407
> python aliens.py
0.41676
</code></pre>
<h3>Aftermath</h3>
<p>I'm okay with the results but I can't say the same for the time this code takes. It takes around 16-17 seconds :)</p>
<p>How can I improve the speed? How can I optimize loops (especially the <code>while</code> loop)? Maybe there's a much better approach or better models?</p>
| [] | [
{
"body": "<p>numpy has a function to generate a random array, this might be faster than generating a random number within the inner loop.\n<a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html\" rel=\"nofollow noreferrer\">https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html</a></p>\n\n<p>You can also try generating a larger 32 or 64-bit number, and shifting and masking the whole time to get 2 random bits. However, this is a bit far-fetched.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T15:58:02.173",
"Id": "404667",
"Score": "0",
"body": "Depending on the platform (and especially in python) working with native machine words is faster even if it seems wasteful to only use 2-3 bits out of 64 or 32."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T15:43:10.180",
"Id": "209372",
"ParentId": "209365",
"Score": "0"
}
},
{
"body": "<p>There are some obvious possible simplifications for elegance, if not necessarily for speed.</p>\n\n<p>The <code>while</code> condition should be written as a double-ended inequality:</p>\n\n<pre><code>while 0 < n < pop_max:\n …\n</code></pre>\n\n<p>The variable <code>j</code> is unused. The convention is to use <code>_</code> as the name of a \"throwaway\" variable.</p>\n\n<p>The <code>if</code>-<code>elif</code> chain can be eliminated with a smarter <code>randint()</code> call:</p>\n\n<pre><code>for j in range(n):\n n += randint(-1, 2)\n</code></pre>\n\n<p>NumPy is overkill here, when all you want to know whether the population went extinct. The built-in <a href=\"https://docs.python.org/3/library/functions.html#sum\" rel=\"nofollow noreferrer\"><code>sum()</code></a> function can do the counting for you.</p>\n\n<p>Each simulation run is independent. I'd put the code in a function for readability.</p>\n\n<pre><code>from random import randint\n\ndef population(pop_max=100):\n n = 1\n while 0 < n < pop_max:\n for _ in range(n):\n n += randint(-1, 2)\n return n\n\niterations = 100000\nprint(sum(population() == 0 for _ in range(iterations)) / iterations)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T18:28:40.463",
"Id": "209383",
"ParentId": "209365",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209383",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T15:11:03.930",
"Id": "209365",
"Score": "3",
"Tags": [
"python",
"programming-challenge",
"numpy",
"simulation",
"markov-chain"
],
"Title": "Simulation of an alien population"
} | 209365 |
<p>Found this project online and looking for some guidance. I'm in the process of developing a Battleship AI that will play against different computer difficulties.</p>
<p>The "barebones" part of the project is already completed. I don't need to develop the game board, create a makefile, write a tester, or anything like that. All I'm doing is creating a single AI that will play against the computer.</p>
<p><strong>The playground is a 10x10 board.</strong></p>
<p><strong>There are :</strong></p>
<ul>
<li><em>3</em> ships of <em>length 5</em></li>
<li><em>2</em> ships of <em>length 4</em></li>
<li><em>1</em> ship of <em>length 3</em></li>
</ul>
<p><strong>There are four different levels of difficulty</strong> (that I'm supposed to beat) :</p>
<ul>
<li><em>Beginner</em></li>
<li><em>Normal Player</em></li>
<li><em>Gambler</em></li>
<li><em>Learning Gambling</em></li>
</ul>
<p>I am unable to see the code for any of these "players". From the names of the difficulties you can guess how they play the game.</p>
<p>So here's the code I developed last night. Everything runs fine and smooth, but I'm only able to defeat the first two difficulties (<em>Beginner</em> and <em>Normal Player</em>). My AI gets absolutely crushed by the later two (I simulated 500 games for each and I maybe won 50 games total).</p>
<p>It would be great is someone could help optimize my code for me. Improving the AI obviously has something to do with the piece placement strategy, but I'm not exactly sure where to go from here. Any help would be greatly appreciated!</p>
<p><strong><em>ourPlayer.h</em></strong></p>
<pre><code>#ifndef DUMBPLAYERV2_H // Double inclusion protection
#define DUMBPLAYERV2_H
using namespace std;
#include "PlayerV2.h"
#include "Message.h"
#include "defines.h"
// DumbPlayer inherits from/extends PlayerV2
class ourPlayer: public PlayerV2 {
public:
ourPlayer( int boardSize );
~ourPlayer();
void newRound();
Message placeShip(int length);
Message getMove();
void update(Message msg);
private:
void initializeBoard();
bool isLegal(Direction dir, int row, int col, int length);
void killFunction();
void markShip(Direction dir, int row, int col, int length);
int dts;
int scanRow;
int scanCol;
int huntRow;
int huntCol;
int numShipsPlaced;
char board[MAX_BOARD_SIZE][MAX_BOARD_SIZE];
char oppBoard[MAX_BOARD_SIZE][MAX_BOARD_SIZE];
};
#endif
</code></pre>
<p><strong><em>ourPlayer.cpp</em></strong> </p>
<pre><code>#include <iostream>
#include <cstdio>
#include<cstdlib>
#include "ourPlayer.h"
ourPlayer::ourPlayer( int boardSize )
:PlayerV2(boardSize)
{
// Could do any initialization of inter-round data structures here.
}
/**
* @brief Destructor placeholder.
* If your code does anything that requires cleanup when the object is
* destroyed, do it here in the destructor.
*/
ourPlayer::~ourPlayer( ) {}
/*
* Private internal function that initializes a MAX_BOARD_SIZE 2D array of char to water.
*/
void ourPlayer::initializeBoard() {
for(int row=0; row<boardSize; row++) {
for(int col=0; col<boardSize; col++) {
this->board[row][col] = WATER;
this->oppBoard[row][col]=WATER;
}
}
}
Message ourPlayer::getMove() {
bool hunting=false;
dts= (rand()%4)+1;
if (scanCol==-3){
scanCol=0;
scanRow=0;
huntRow=0;
huntCol=0;
}
if (oppBoard[scanRow][scanCol]==HIT){
hunting=true;
huntRow=scanRow;
huntCol=scanCol;
}
// Deal with KILL somewhere
if (hunting){
killFunction();
}else {// if (!hunting)
// while (oppBoard[scanRow][scanCol]!=WATER){
scanCol+=3;
if( scanCol >= boardSize ) {
scanRow++;
scanCol= scanRow%3;
}
if( scanRow >= boardSize ) {
scanCol = 0;
scanRow = 0;
}
huntRow = scanRow;
huntCol=scanCol;
// }
}
Message result( SHOT, huntRow, huntCol, "Bang", None, 1 );
return result;
}
void ourPlayer::killFunction(){
// Hunt north
for (int row=huntRow-1;row>-1;row--){
char ch=oppBoard[row][huntCol];
if (ch==WATER){
huntRow=row;
return;
}
else if(ch==MISS||ch==KILL){
break;
}
else{
//HIT=keep going
}
}
//Hunt south
for (int row=huntRow+1;row<boardSize;row++){
char ch=oppBoard[row][huntCol];
if (ch==WATER){
huntRow=row;
return;
}
else if(ch==MISS||ch==KILL){
break;
}
else{
//HIT=keep going
}
}
// Hunt east
for (int col=huntCol+1;col<boardSize;col++){
char ch=oppBoard[huntRow][col];
if (ch==WATER){
huntCol=col;
return;
}
else if(ch==MISS||ch==KILL){
break;
}
else{
//HIT=keep going
}
}
//Hunt west
for (int col=huntCol-1;col>-1;col--){
char ch=oppBoard[huntRow][col];
if (ch==WATER){
huntCol=col;
return;
}
else if(ch==MISS||ch==KILL){
break;
}
else{
//HIT=keep going
}
}
}
void ourPlayer::newRound() {
/* DumbPlayer is too simple to do any inter-round learning. Smarter players
* reinitialize any round-specific data structures here.
*/
this->scanRow = 0;
this->scanCol = -3;
this->numShipsPlaced = 0;
this->initializeBoard();
}
/**
* @brief Gets the AI's ship placement choice. This is then returned to the caller.
* @param length The length of the ship to be placed.
* @return Message The most important parts of the returned message are
* the direction, row, and column values.
*
* The parameters returned via the message are:
* 1. the operation: must be PLACE_SHIP
* 2. ship top row value
* 3. ship top col value
* 4. a string for the ship name
* 5. direction Horizontal/Vertical (see defines.h)
* 6. ship length (should match the length passed to placeShip)
*/
Message ourPlayer::placeShip(int length) {
char shipName[10];
snprintf(shipName, sizeof shipName, "Ship%d", numShipsPlaced);
if (numShipsPlaced==0){
int row=boardSize-1;
int col=boardSize-1-length;
markShip(Horizontal,row,col,length);
Message response(PLACE_SHIP,row,col,shipName,Horizontal,length);
numShipsPlaced++;
return response;
}else{
while(true){
Direction dir=Direction((rand()%2)+1);
int row;
int col;
if(dir==Horizontal) {
row=(rand()%(boardSize));
col=(rand()%(boardSize-length+1));
} else {
row=(rand()%(boardSize-length+1));
col=(rand()%(boardSize));
}
if(isLegal(dir,row,col,length)){
markShip(dir,row,col,length);
Message response( PLACE_SHIP, row, col, shipName, dir, length );
numShipsPlaced++;
return response;
}
}
}
}
void ourPlayer::markShip(Direction dir, int row, int col, int length){
if (dir==Horizontal){
for (int i=0;i<length;i++){
board[row][col+i]=SHIP;
}
}else{
for (int i=0;i<length;i++){
board[row+i][col]=SHIP;
}
}
}
bool ourPlayer::isLegal(Direction dir,int row,int col,int length){
if (dir==Horizontal){
if ((col+length)>boardSize){
return false;
}
for (int i=0;i<length;i++){
if (board[row][col+i]==SHIP/*||
board[row][col+i+1]==SHIP||
board[row][col+i-1]==SHIP||
board[row+1][col+i]==SHIP||
board[row-1][col+i]==SHIP*/){
return false;
}
}
return true;
}else{
if ((row+length)>boardSize){
return false;
}
for(int i=0;i<length;i++){
if (board[row+i][col]==SHIP/*||
board[row+i][col+1]==SHIP||
board[row+i][col-1]==SHIP||
board[row+1+i][col]==SHIP||
board[row-1+i][col]==SHIP*/){
return false;
}
}
return true;
}
}
/**
* @brief Updates the AI with the results of its shots and where the opponent is shooting.
* @param msg Message specifying what happened + row/col as appropriate.
*/
void ourPlayer::update(Message msg) {
switch(msg.getMessageType()) {
case HIT:
case KILL:
case MISS:
oppBoard[msg.getRow()][msg.getCol()] = msg.getMessageType();
break;
case WIN:
break;
case LOSE:
break;
case TIE:
break;
case OPPONENT_SHOT:
// TODO: get rid of the cout, but replace in your AI with code that does something
// useful with the information about where the opponent is shooting.
//cout << gotoRowCol(20, 30) << "DumbPl: opponent shot at "<< msg.getRow() << ", " << msg.getCol() << flush;
break;
}
}
</code></pre>
<p><strong><em>EDITS</em></strong></p>
<ul>
<li><p>Ships are allowed to touch both vertically and horizontally.</p></li>
<li><p>Diagonal ships are not allowed</p></li>
<li><p>You receive confirmation after every move. The AI will known once a ship has sunk.</p></li>
<li><p>Since this is technically AI vs. AI, I have no say over where the specific ships are placed on the board.</p></li>
</ul>
<p>I've already read tons of blogs online talking about similar projects. Problem is I'm a total novice at this stuff so conceptually it's hard for me to actually implement the "strategies" found online.</p>
<p><strong>Here's a sample picture of the AI vs. AI action:</strong></p>
<p><a href="https://i.stack.imgur.com/aALei.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aALei.png" alt="Here's a sample picture of the AI vs. AI action"></a></p>
<p><strong>The final output when the simulations are complete:</strong></p>
<p><a href="https://i.stack.imgur.com/D2loY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D2loY.png" alt="The final output when the simulations are complete"></a></p>
| [] | [
{
"body": "<p>Can you add some rules on ship placement? Can they touch horizontally or vertically? Can they touch diagonally? Do you get a confirmation when you have sunk a ship?</p>\n\n<p>Why do you reset 'hunting' each turn? I would put this as class member.\nDo you use the variable 'dts'?</p>\n\n<p>I see you already implemented the parity strategy, so according to the blog, probability density function are your next best bet.\nThis involves calculating all possible locations for the remaining enemy ships, and calculating the probability of a present ship for each tile.\n<a href=\"http://www.datagenetics.com/blog/december32011/\" rel=\"nofollow noreferrer\">http://www.datagenetics.com/blog/december32011/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T16:37:15.960",
"Id": "209375",
"ParentId": "209373",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T15:47:31.647",
"Id": "209373",
"Score": "3",
"Tags": [
"c++",
"performance",
"ai",
"battleship"
],
"Title": "C++ Battleship player AI"
} | 209373 |
<p>For common users I have 10 queries and for registered users I have 30 queries like this one below, only to print out on the screen the link for the querystrings, a guy said to me that I should escape the values of the menus that use querystrings, I'm having a problem with google insights, my TTFB is at 0,89s on Desktop and 0,24s on Mobile.</p>
<p>This code below is like a "validator". When I create a page I need to insert on my table the <code>title</code>, slug_link and the <code>entry_type</code> that can be <code>item or pagina</code>, otherwise I'm not able to open the page on the browser. It's good. I think I got a bit of security, and this is not a problem. </p>
<p>I'm thinking... maybe I can insert on my table the name/slug_link of my pages and use a variable to the links? Example: <code>$slugHome = ?p=home</code> and on the HTML I would do <code><a href="?p=<?php echo htmlentities($slugHome, \ENT_QUOTES, 'UTF-8', false); ?>">Home</a></code>. This way I don't need to do requests to my database for each item of the menu. I'm not a expert in security, so I want to know what you guys think.</p>
<p>How can I print on the screen the menus without making so many queries?</p>
<p>This is the "validator" code, I also use this global variables. You will see the queries on the other snippet below:</p>
<pre><code>$isItems = !empty($_GET['page']);
$slug = 'home';
if ($isItems) {
$slug = $_GET['page'];
} elseif (!empty($_GET['p'])) {
$slug = $_GET['p'];
}
try {
$stmt = $conn->prepare('SELECT `id`, `title`, `dropmenuGenero`, `epTitle`, `itemName`, `letra`, `data`, `datePublished`, `descricao`, `capa`, `epCapa`, `alt`, `audio`, `qualidade`, `tipo`, `epNum`, `keywords`, `item`, `dateModified`, `slug_url`, `slugForitemPage`, `slug_link`, `entry_type`, `formato`, `status` FROM `table_item` WHERE `slug_link` = :slug_link AND `entry_type` = :entry_type');
$stmt->execute([
':entry_type' => $isItems ? 'item' : 'pagina',
':slug_link' => $slug
]);
if (!$NF = $stmt->fetch(\PDO::FETCH_ASSOC)) {
throw new \InvalidArgumentException('Items title ' . htmlentities($title, \ENT_QUOTES, 'UTF-8', false) . ' not found in database');
}
$id = $NF['id'];
$title = $NF['title'];
$epTitle = $NF['epTitle'];
$itemName = $NF['itemName'];
$letra = $NF['letra'];
$data = $NF['data'];
$datePublished = $NF['datePublished'];
$dateModified = $NF['dateModified'];
$descricao = $NF['descricao'];
$capa = $NF['capa'];
$epCapa = $NF['epCapa'];
$alt = $NF['alt'];
$audio = $NF['audio'];
$qualidade = $NF['qualidade'];
$tipo = $NF['tipo'];
$epNum = $NF['epNum'];
$keywords = $NF['keywords'];
$url = $NF['slug_url'];
$dropmenuGenero = $NF['dropmenuGenero'];
$slug = $NF['slug_link'];
$slugForitemPage = $NF['slugForitemPage'];
$entry_type = $NF['entry_type'];
$formato = $NF['formato'];
$status = $NF['status'];
} catch (\InvalidArgumentException $e) {
header('Location: ?p=home');
exit;
} catch (\Exception $e) {
header('Location: error.php?e=Algo deu errado :/');
throw $e;
}
function sanitize($data, $filter = \FILTER_SANITIZE_STRING) {
if ($data = filter_var(trim($data), $filter)) {
$data = preg_replace('/http(s)?:\/\//', '', $data);
}
return $data;
}
$loadPage = null;
if ($sanitizedName = sanitize($isItem ? $title : $slug)) {
$loadPageSuffix = ($isItem ? '/items/' : '/page_');
$loadPage = __DIR__ . $loadPageSuffix . $sanitizedName . '.php';
}
if (null === $loadPage || !is_file($loadPage)) {
header('HTTP/1.1 404 Not Found');
exit;
}
</code></pre>
<p>This is 3 of 10-30 queries that I use only to print on the screen a list of menus:</p>
<pre><code><?php
titleHome = 'Página Inicial';
$pageHome = $conn->prepare("SELECT `title`, `slug_link` FROM `table_tudo` WHERE `title` = :title");
$pageHome->bindParam(':title', $titleHome, PDO::PARAM_STR);
$pageHome->execute();
?>
<?php foreach($pageHome as list($pageTitle, $pageSlug)) { ?>
<li class="nav-item pr-2 navbarItem">
<a class="nav-link" href="?p=<?php echo htmlentities($pageSlug, \ENT_QUOTES, 'UTF-8', false); ?>"><?php echo htmlentities($pageTitle, \ENT_QUOTES, 'UTF-8', false); ?></a>
</li>
<?php } ?>
<?php
query for dropdows-menus:
$titleListaDropDown = 'Lista de Items';
$pageListDropDown = $conn->prepare("SELECT `title`, `slug_link` FROM `table_tudo` WHERE `title` = :title");
$pageListDropDown->bindParam(':title', $titleListaDropDown, PDO::PARAM_STR);
$pageListDropDown->execute();
$entry_typePageList = 'pagina';
$pageList = $conn->prepare("SELECT `dropmenuList`, `slug_link` FROM `table_tudo` WHERE `entry_type` = :entry_type AND `dropmenuList` IS NOT NULL");
$pageList->bindParam(':entry_type', $entry_typePageList, PDO::PARAM_STR);
$pageList->execute();
?>
<?php foreach($pageListDropDown as list($pageTitleLDD, $pageSlugLDD)) { ?>
<li class="nav-item dropdown pr-2 navbarItem ">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<?php echo htmlentities($pageTitleLDD, \ENT_QUOTES, 'UTF-8', false); ?>
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<?php foreach ($pageList as list($pageTitleL, $pageSlugL)): ?>
<a class="dropdown-item" href="?p=<?php echo htmlentities($pageSlugL, \ENT_QUOTES, 'UTF-8', false); ?>"><?php echo htmlentities($pageTitleL, \ENT_QUOTES, 'UTF-8', false); ?></a>
<?php endforeach; ?>
</div>
</li>
<?php } ?>
</code></pre>
| [] | [
{
"body": "<p>Looking at most of the queries, they appear to be almost the same, except for the values of some parameters. There is nothing wrong with having multiple queries to the database, but you can eliminate the repetitive queries by creating functions or classes for them.</p>\n\n<p>I see two variations of the same basic query:</p>\n\n<ul>\n<li>Find by title</li>\n<li>Find by entry_type</li>\n</ul>\n\n<p>A sample class:</p>\n\n<pre><code>class MenuRepository {\n private $conn;\n\n public function __construct($conn) {\n $this->conn = $conn;\n }\n\n public function findByTitle($title) {\n $query = $this->conn->prepare(\"SELECT `title`, `slug_link` FROM `table_tudo` WHERE `title` = :title\");\n $query->bindParam(':title', $title, PDO::PARAM_STR);\n $query->execute();\n\n return $query;\n }\n\n public function findByEntryType($entryType) {\n $query = $this->conn->prepare(\"SELECT `dropmenuList`, `slug_link` FROM `table_tudo` WHERE `entry_type` = :entry_type AND `dropmenuList` IS NOT NULL\");\n $query->bindParam(':entry_type', $entryType, PDO::PARAM_STR);\n $query->execute();\n\n return $query;\n }\n}\n</code></pre>\n\n<p>Now you eliminate the queries from your code, and just create an instance of your \"menu repository\" and call methods on it when needed:</p>\n\n<p>So there is the abstraction you need to create. Two different functions that each have one copy of the query, and all you need to do is pass in different arguments each time:</p>\n\n<pre><code><?php\n$menuItems = new MenuRepository($conn);\n$pageHome = $menuItems->findByTitle('Página Inicial');\n$pageListDropDown = $menuItems->findByTitle('Lista de Items');\n$pageList = $menuItems->findByEntryType('pagina');\n?>\n\n<?php foreach($pageHome as list($pageTitle, $pageSlug)) { ?>\n <li class=\"nav-item pr-2 navbarItem\">\n <a class=\"nav-link\" href=\"?p=<?php echo htmlentities($pageSlug, \\ENT_QUOTES, 'UTF-8', false); ?>\"><?php echo htmlentities($pageTitle, \\ENT_QUOTES, 'UTF-8', false); ?></a>\n </li>\n<?php } ?>\n\n<?php foreach($pageListDropDown as list($pageTitleLDD, $pageSlugLDD)) { ?>\n<li class=\"nav-item dropdown pr-2 navbarItem \">\n <a class=\"nav-link dropdown-toggle\" href=\"#\" id=\"navbarDropdownMenuLink\" role=\"button\" data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\">\n <?php echo htmlentities($pageTitleLDD, \\ENT_QUOTES, 'UTF-8', false); ?>\n </a>\n <div class=\"dropdown-menu\" aria-labelledby=\"navbarDropdownMenuLink\">\n <?php foreach ($pageList as list($pageTitleL, $pageSlugL)): ?>\n <a class=\"dropdown-item\" href=\"?p=<?php echo htmlentities($pageSlugL, \\ENT_QUOTES, 'UTF-8', false); ?>\"><?php echo htmlentities($pageTitleL, \\ENT_QUOTES, 'UTF-8', false); ?></a>\n <?php endforeach; ?>\n </div>\n</li>\n<?php } ?>\n</code></pre>\n\n<p>It reduces the boiler plate code for each query, and helps to de-clutter the the code that renders the HTML.</p>\n\n<p>There is still some repetition here if the two menu titles and the entry types are need on other pages. Then it's just a matter of parameterizing those three things.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T17:52:19.807",
"Id": "404858",
"Score": "0",
"body": "I don't want to use the database to the menus, can i just set a variable like this? `$home` `<a href=\"?p=<?php echo htmlentities($home, \\ENT_QUOTES, 'UTF-8', false); ?>\">Home</a>` is it safe?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T16:48:31.493",
"Id": "209460",
"ParentId": "209376",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T16:53:06.420",
"Id": "209376",
"Score": "3",
"Tags": [
"beginner",
"php",
"security",
"database",
"pdo"
],
"Title": "Queries to print out on the screen a list of menus"
} | 209376 |
<p>After learning the basics of React-Redux I've made an app to familiarize myself more with the concepts. It's a counter which counts-up the Fibonacci-Number.</p>
<p><a href="https://i.stack.imgur.com/fCt9Q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fCt9Q.png" alt="enter image description here"></a></p>
<p>Here's my code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// -- index.js -----------------------------------
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));</code></pre>
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// ---- App.js -------------------------------------------
import React, { Component } from 'react';
import { Provider } from "react-redux";
import { createStore } from "redux";
import FibonacciCounter from "./FibonacciCounter";
import './App.css';
const init = {
index: 1,
last: 1,
current: 1
}
const reducer = (state = init, action) => {
switch (action.type) {
case "NEXT":
const lastCopy = state.last;
const currentCopy = state.current;
return {
...state,
last: state.current,
current: currentCopy + lastCopy,
index: state.index + 1
};
default:
return state;
}
}
const store = createStore(reducer);
class App extends Component {
render() {
return (
<Provider store={store}>
<div className="wrap">
<FibonacciCounter />
</div>
</Provider>
);
}
}
export default App;</code></pre>
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// -------- FibonacciCounter.js -------------------------------------
import React, { Component } from 'react';
import { connect } from "react-redux";
class FibonacciCounter extends Component {
render() {
return (
<div>
<div className="display">
<span>{("00" + this.props.index).slice(-3)}. Fibonacci Number: </span>
<span className="current-number">{this.props.current}</span>
</div>
<div className="navi">
<a href="#" className="ghost-button" onClick={this.props.onNext}>Increment</a>
</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
current: state.current,
index: state.index
};
}
const mapDispatchToProps = dispatch => {
return {
onNext: () => {
dispatch({
type: "NEXT"
});
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(FibonacciCounter);</code></pre>
</div>
</div>
</p>
<p><strong>Is my implementation of the concepts correct and done in a good way and fashion? What shall / must I change and why?</strong></p>
<p>Looking forward to reading your answers and comments.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T13:47:55.950",
"Id": "405529",
"Score": "0",
"body": "There is nothing wrong at all with the source. Couple of small things -\n\n1) String literals - `<span>{(\\`00${years.length}\\`).slice(-3)}. Fibonacci Number:</span>`\n2) `return {...state, last: state.current, current: currentCopy + lastCopy, index: state.index + 1};` can be just `return {last: state.current, current: currentCopy + lastCopy, index: state.index + 1};` as we completely modifying the previous state."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T13:55:23.737",
"Id": "405530",
"Score": "0",
"body": "@yadav_vi Thanks a lot for your comment. If you like: Make your comment an answer. I'll accept it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T14:05:02.740",
"Id": "405533",
"Score": "0",
"body": "That's alright, maybe you can add `decrement` and some other functionalities (maybe even a GitHub repo), would be fun to modify it.\n\nA small nitpick - I usually keep my `Containers`(`mapStateToProps`, `mapDispatchToProps`) and `Reducers` in a separate file altogether. (Since this is a small project, this is perfectly fine)."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T17:00:36.397",
"Id": "209377",
"Score": "0",
"Tags": [
"javascript",
"react.js",
"redux"
],
"Title": "Fibonacci-Counter implemented with React-Redux"
} | 209377 |
<p>I wanted to write an iterator that would split items up into groups, so I can bulk insert into MySQL without crashing or overwhelming the server.</p>
<p>This is the implementation I came up with.
I am hoping that when yielding from the list it's not creating a copy / clone of the list.</p>
<p>I need more experience with Python internals to be able to debug and profile this function I wrote.</p>
<pre><code>def iter_group(iterable, batch_size:int):
iterable_type = type(iterable)
length = len(iterable)
start = batch_size*-1
end = 0
while(end < length):
start += batch_size
end += batch_size
if iterable_type == list:
yield (iterable[i] for i in range(start,min(length-1,end)))
else:
yield iterable[start:end]
#test data
items = range(0,10001)
for item_group in iter_group(items, 1000):
for item in item_group:
print(item,end=' ')
</code></pre>
| [] | [
{
"body": "<p>Your code cannot work with iterables of unknown length:</p>\n\n<pre><code>def unknown_length():\n i = 0\n while i < 12:\n yield i\n i += 1\n\nitems = iter(unknown_length())\nfor item_group in iter_group(items, 5):\n for item in item_group:\n print(item,end=' ')\n print()\n</code></pre>\n\n<blockquote>\n <p>TypeError: object of type 'generator' has no len()</p>\n</blockquote>\n\n<hr>\n\n<p><strike>\nThis code <code>(iterable[i] for i in range(start,min(length-1,end)))</code> is creating a new tuple containing a shallow copy of each group of <code>batch_size</code> items, although only 1 at a time so you aren't ending up with a complete copy of the iterable all at once, requiring double the memory.\n</strike></p>\n\n<hr>\n\n<p>The <code>range(start,min(length-1,end))</code> omits the your last data item! The end limit is non-inclusive, so the last item you get is <code>iterable[length-2]</code>.</p>\n\n<hr>\n\n<p>The following <code>iter_group</code> yields a nested generator which <code>yield</code> items until <code>batch_size</code> items have been returned. Then, the next nested generator will be yielded, until the list item has been produced.</p>\n\n<pre><code>def iter_group(iterable, batch_size:int):\n it = iter(iterable)\n\n def group(first):\n yield first\n try:\n for _ in range(batch_size - 1):\n yield next(it)\n except StopIteration:\n pass\n\n try:\n while True:\n yield group(next(it))\n except StopIteration:\n pass\n</code></pre>\n\n<p>If you want to try to optimize this for sliceable iterables, you could try:</p>\n\n<pre><code>def iter_group(iterable, batch_size:int):\n\n try:\n # Maybe we can use slices?\n start = 0\n n = len(iterable)\n while start < n:\n yield iterable[start:start+batch_size]\n start += batch_size\n\n except TypeError:\n # Nope! Couldn't get either the length or a slice.\n\n it = iter(iterable)\n\n def group(first):\n yield first\n\n try:\n for _ in range(batch_size - 1):\n yield next(it)\n except StopIteration:\n pass\n\n try:\n while True:\n yield group(next(it))\n except StopIteration:\n pass\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T22:26:55.130",
"Id": "404701",
"Score": "0",
"body": "statement `(iterable[i] for i in range(start,min(length-1,end)))` does not create a new `tuple`, but a [generator expression](https://docs.python.org/3/glossary.html#term-generator-expression)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T22:30:37.397",
"Id": "404702",
"Score": "0",
"body": "@AzatIbrakov You're right - good catch."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T01:16:03.297",
"Id": "404893",
"Score": "0",
"body": "@AzatIbrakov does it return a NEW generator expression, or does it set the state of the existing expression?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T02:07:27.217",
"Id": "404900",
"Score": "1",
"body": "@Ben It will yield a new generator expression each time."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T20:08:07.707",
"Id": "209388",
"ParentId": "209378",
"Score": "2"
}
},
{
"body": "<p>We can improve readability of your code as follows:</p>\n\n<ul>\n<li><p>using type annotations partially looks incomplete, when we can be more descriptive:</p>\n\n<pre><code>from typing import (Iterable, \n TypeVar)\n\nElementType = TypeVar('ElementType')\n\n\ndef iter_group(iterable: Iterable[ElementType],\n batch_size: int) -> Iterable[Iterable[ElementType]]:\n ...\n</code></pre></li>\n<li><p>checking if object has given type should be done using <a href=\"https://docs.python.org/3/library/functions.html#isinstance\" rel=\"noreferrer\"><code>isinstance</code> built-in function</a>, so instead of</p>\n\n<pre><code>iterable_type = type(iterable)\n...\nif iterable_type == list:\n ...\n</code></pre>\n\n<p>we can simply write</p>\n\n<pre><code>if isinstance(iterable, list):\n ...\n</code></pre>\n\n<p>(btw I don't understand why are you treating <code>list</code> as a special case)</p></li>\n<li><p>if you want negate a number then we can use <code>-</code> unary operator, no need to multiply by <code>-1</code>, so instead of</p>\n\n<pre><code>start = batch_size * -1\n</code></pre>\n\n<p>we can write</p>\n\n<pre><code>start = -batch_size\n</code></pre></li>\n<li><p>no need in parentheses for <code>while</code>-loop condition, we are not in <code>C</code>/<code>C++</code>/<code>JAVA</code>, we can simply write:</p>\n\n<pre><code>while end < length:\n ...\n</code></pre></li>\n<li><p>setting <code>start</code> to <code>-batch_size</code> and <code>end</code> to <code>0</code> and change them right after that seems redundant when we can set them to <code>0</code> and <code>batch_size</code> respectfully and increment at the end of the <code>while</code> loop body, so instead</p>\n\n<pre><code>start = batch_size * -1\nend = 0\nwhile end < length:\n start += batch_size\n end += batch_size\n ...\n</code></pre>\n\n<p>we can write</p>\n\n<pre><code>start = 0\nend = batch_size\nwhile end < length:\n ...\n start += batch_size\n end += batch_size\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p>If I understood correctly what you are trying to achieve is to split iterable into evenly sized chunks, which is <a href=\"https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks\">a well-known StackOverflow question</a>, but accepted answer works only for sequences (<code>str</code>/<code>list</code>/<code>tuple</code>) and so does your solution. For example it won't work for potentially infinite sequences like classic Fibonacci numbers generator</p>\n\n<pre><code>>>> def fibonacci():\n a, b = 0, 1\n while True:\n yield a\n a, b = b, a + b\n>>> next(iter_group(fibonacci(), 5))\nTraceback (most recent call last):\n ...\n length = len(iterable)\nTypeError: object of type 'generator' has no len()\n</code></pre>\n\n<p>If you want to work with arbitrary iterables (e.g. <code>generator</code>s), we may use <code>itertools</code> module and <a href=\"https://stackoverflow.com/a/22045226/5997596\">this brilliant solution</a> which uses <a href=\"https://docs.python.org/3/library/functions.html#iter\" rel=\"noreferrer\"><code>iter</code> built-in function</a> form with sentinel value</p>\n\n<pre><code>from itertools import islice\nfrom typing import (Iterable,\n Tuple,\n TypeVar)\n\nElementType = TypeVar('ElementType')\n\n\ndef chunks(iterable: Iterable[ElementType],\n batch_size: int) -> Iterable[Tuple[ElementType, ...]]:\n iterator = iter(iterable)\n return iter(lambda: tuple(islice(iterator, batch_size)), ())\n</code></pre>\n\n<p>but if we make a simple benchmark with</p>\n\n<pre><code>def sequence_chunks(iterable: Sequence[ElementType],\n batch_size: int) -> Iterable[Sequence[ElementType]]:\n for start in range(0, len(iterable), batch_size):\n yield iterable[start:start + batch_size]\n</code></pre>\n\n<p>like</p>\n\n<pre><code>import timeit\n\n...\nprint('original solution',\n min(timeit.repeat('list(iter_group(iterable, 1000))',\n 'from __main__ import iter_group\\n'\n 'iterable = range(0, 10001)',\n number=10000)))\nprint('Ned Batchelder\\'s solution',\n min(timeit.repeat('list(sequence_chunks(iterable, 1000))',\n 'from __main__ import sequence_chunks\\n'\n 'iterable = range(0, 10001)',\n number=10000)))\nprint('senderle\\'s solution',\n min(timeit.repeat('list(chunks(iterable, 1000))',\n 'from __main__ import chunks\\n'\n 'iterable = range(0, 10001)',\n number=10000)))\n</code></pre>\n\n<p>on my laptop with Windows 10 and Python 3.5 we'll have</p>\n\n<pre><code>original solution 0.07320549999999999\nNed Batchelder's solution 0.06249870000000002\nsenderle's solution 2.6072023999999994\n</code></pre>\n\n<p>so how can we have both speed and handle cases with non-sequence iterables?</p>\n\n<p>Here comes <code>functools</code> module with <a href=\"https://docs.python.org/3/library/functools.html#functools.singledispatch\" rel=\"noreferrer\"><code>singledispatch</code> function decorator</a>. We can use it like</p>\n\n<pre><code>import timeit\nfrom collections import abc\nfrom functools import singledispatch\nfrom itertools import islice\nfrom typing import (Iterable,\n Sequence,\n TypeVar)\n\nElementType = TypeVar('ElementType')\n\n\n@singledispatch\ndef chunks(iterable: Iterable[ElementType],\n batch_size: int) -> Iterable[Iterable[ElementType]]:\n iterator = iter(iterable)\n return iter(lambda: tuple(islice(iterator, batch_size)), ())\n\n\n@chunks.register(abc.Sequence)\ndef sequence_chunks(iterable: Sequence[ElementType],\n batch_size: int) -> Iterable[Iterable[ElementType]]:\n for start in range(0, len(iterable), batch_size):\n yield iterable[start:start + batch_size]\n</code></pre>\n\n<p>after that call to <code>chunks</code> will end up in <code>sequence_chunks</code> for sequences and in general <code>chunks</code> for all other cases.</p>\n\n<p>But</p>\n\n<pre><code>print('single-dispatched solution',\n min(timeit.repeat('list(chunks(iterable, 1000))',\n 'from __main__ import chunks\\n'\n 'iterable = range(0, 10001)',\n number=10000)))\n</code></pre>\n\n<p>gives</p>\n\n<pre><code>single-dispatched solution 0.0737681\n</code></pre>\n\n<p>so we lose some time during dispatching, but we can save some time and space if we will use <code>itertools.islice</code> for sequences as well like</p>\n\n<pre><code>@chunks.register(abc.Sequence)\ndef sequence_chunks(iterable: Sequence[ElementType],\n batch_size: int) -> Iterable[Iterable[ElementType]]:\n iterator = iter(iterable)\n for _ in range(ceil_division(len(iterable), batch_size)):\n yield islice(iterator, batch_size)\n\n\ndef ceil_division(left_number: int, right_number: int) -> int:\n \"\"\"\n Divides given numbers with ceiling.\n \"\"\"\n # based on https://stackoverflow.com/a/17511341/5997596\n return -(-left_number // right_number)\n</code></pre>\n\n<p>which gives</p>\n\n<pre><code>complete single-dispatched solution 0.03895900000000002\n</code></pre>\n\n<h1>P.S.</h1>\n\n<p>@AJNeufeld's solution gives </p>\n\n<pre><code>0.0647120000000001\n</code></pre>\n\n<p>on my laptop</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T23:04:01.020",
"Id": "404703",
"Score": "0",
"body": "Note: `list(sequence_chunks(range(0, 10001), 1000))` return `[ <itertools.islice object>, <itertools.islice object>, ..., <itertools.islice object> ]` where `list(iter_group(range(10001), 1000))` returns `[range(0, 1000), range(1000, 2000), ..., range(10000, 10001)]`. And `list(chunks(range(0, 10001), 1000))` returns `[(0, 1, 2, ..., 998, 999), (1000, 1001, ..., 1999), ... , (10000, ) ]`! These are very, very different animals."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T23:21:32.910",
"Id": "404704",
"Score": "0",
"body": "Note: `itertools.islice()` has **not** advanced the iterator (singular) in the returned list of slices. If we assign `x = list(sequence_chunks(range(0, 10001), 1000))`, and then ask for the `next()` values of the third, second and first iterators, `[ next(x[2]), next(x[1]), next(x[0])]` you might expect `[2000, 1000, 0]`, but you will actually get `[0, 1, 2]`!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T08:23:28.880",
"Id": "404744",
"Score": "0",
"body": "@AJNeufeld: I know, but in OP there is a statement `(iterable[i] for i in range(start,min(length-1,end)))`, so I thought `iterator`s are satisfactory choice, especially if author wants to insert records in batches"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T01:21:08.277",
"Id": "404895",
"Score": "0",
"body": "```\nstart = 0\nend = batch_size\nwhile end < length:\n ...\n start += batch_size\n end += batch_size\n```"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T22:16:50.453",
"Id": "209394",
"ParentId": "209378",
"Score": "7"
}
},
{
"body": "<p>Here is a function that will work with any iterable, not just sequences. It does not create any intermediate objects aside from the group iterator, and so should be efficient.</p>\n<pre><code>def grouped(items, size):\n iterator = iter(items)\n more = True\n while more:\n def group():\n nonlocal more\n count = 0\n while count == 0 or count % size != 0:\n try:\n yield next(iterator)\n except StopIteration:\n more = False\n return\n count += 1\n yield group()\n\n \nfor count, group in enumerate(grouped(range(33), 10)):\n print(count)\n print(' ', list(group))\n</code></pre>\n<p>Output:</p>\n<pre><code>0\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n1\n [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]\n2\n [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]\n3\n [30, 31, 32]\n</code></pre>\n<p><code>islice</code> has a decent amount of overhead, and so calling it for each group is going to slow things down a bit if you call it in tight loops. However in practice for the OP's use case, I really doubt that will be significant, and so I think solutions using it are just fine. In fact for doing database operations, the performance of your grouping function is unlikely to be a factor at all unless you're doing something horribly wrong.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-30T07:08:38.973",
"Id": "529571",
"Score": "1",
"body": "Welcome to Code Review! It's usually best to begin your answer with the actual review. Code that implements your suggested improvements is always welcome, but prefer to put that at the end, as it's really just a supplement to the review itself, and not everyone will want to read that far. Please do stay around and continue answering questions here; I think you have a lot to offer!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-30T02:23:23.133",
"Id": "268528",
"ParentId": "209378",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T17:04:00.567",
"Id": "209378",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"iterator",
"pagination"
],
"Title": "Python grouped iterator"
} | 209378 |
<p>I'm new to programming and in front-end.
It's really hard for me to learn good practices.</p>
<p>Right now I'm trying to learn javascript basics and bootstrap in addition.
I did mine first ToDo list with bootstrap (just to train it a bit) and I feel like my JS code and HTML are just bad and should do it much better.</p>
<p>Can you take a look and tell me what should I do better?
It works but I think not as well as it should. </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const divTodo = document.querySelector('#tasks');
const addBtn = document.querySelector('#addTask');
const addInput = document.querySelector('#addTaskText');
const taskList = []
taskList.push({
task: "Make a dinner.",
isDone: true,
});
// Funkcje
//Dodaj Zadanie
const addTask = function (task) {
taskList.push({
task: task,
isDone: false,
})
}
//Zmien status isDone
const changeStatus = function (index) {
taskList[index].isDone = !taskList[index].isDone;
}
const render = function () {
divTodo.textContent = "";
taskList.forEach((el, index) => {
const newRow = document.createElement('div');
const newCheckboxDiv = document.createElement('div');
const newCheckbox = document.createElement('input');
const newTask = document.createElement('div');
const newButtonDiv = document.createElement('div');
const newButton = document.createElement('button');
//row bg-warning m-2 d-flex align-items-center rounded
newRow.classList.add('row')
newRow.classList.add('m-2')
newRow.classList.add('d-flex')
newRow.classList.add('align-items-center')
newRow.classList.add('rounded')
el.isDone == true ? newRow.classList.add('bg-success') : newRow.classList.add('bg-warning');
//col-2 col-md-1
newCheckboxDiv.classList.add('col-2')
newCheckboxDiv.classList.add('col-md-1')
//form-control form-control-lg
newCheckbox.classList.add('form-control');
newCheckbox.classList.add('form-control-lg');
newCheckbox.type = 'checkbox';
el.isDone == true ? newCheckbox.checked = true : newCheckbox.checked = false;
newCheckbox.dataset.key = `${index}`;
newCheckbox.addEventListener('click', () => {
el.isDone = !el.isDone;
render();
})
//col-7 col-md-8 text-justify
newTask.classList.add('col-7');
newTask.classList.add('col-md-8');
newTask.classList.add('text-justify');
newTask.textContent = el.task;
//col-3
newButtonDiv.classList.add('col-3');
//btn btn-danger btn-block p-1 p-md-2
newButton.classList.add('btn');
newButton.classList.add('btn-danger');
newButton.classList.add('btn-block');
newButton.classList.add('p-1');
newButton.classList.add('p-md-2');
newButton.textContent = "Delete";
// newButton.dataset.key = `${index}`;
newButton.addEventListener('click', () => {
taskList.splice(index, 1);
render();
})
newCheckboxDiv.appendChild(newCheckbox);
newButtonDiv.appendChild(newButton);
newRow.appendChild(newCheckboxDiv);
newRow.appendChild(newTask);
newRow.appendChild(newButtonDiv);
divTodo.appendChild(newRow);
})
}
render();
addBtn.addEventListener('click', () => {
if (addInput.value == "") return;
addTask(addInput.value);
render();
addInput.value = "";
})</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ToDo list</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU"
crossorigin="anonymous">
</head>
<body class="bg-info">
<!---
<div class="container mt-md-5">
Three big buttons - doesnt work
<div class="row">
<div class="col-md-12 mr-auto ml-auto text-center">
<div class="row">
<div class="col-12 col-md-4 mr-auto ml-auto mt-3 mt-md-1">
<button class="btn btn-warning btn-block">All</button>
</div>
<div class="col-12 col-md-4 mr-auto ml-auto mt-3 mt-md-1">
<button class="btn btn-warning btn-block">Done</button>
</div>
<div class="col-12 col-md-4 mr-auto ml-auto mt-3 mt-md-1">
<button class="btn btn-warning btn-block">To do</button>
</div>
</div>
</div>
</div>
--->
<!------------------------------>
<!-- Add Tasks-->
<div class="row">
<div class="col-12 col-md-8 mt-2">
<input type="text" class="form-control" placeholder="Add task..." id="addTaskText">
</div>
<div class="col-12 col-md-4 mt-2">
<button class="btn btn-success btn-block" id="addTask">Add Task!</button>
</div>
</div>
<!------------------------------>
<div id="tasks">
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin="anonymous"></script>
<script src="main.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T11:28:45.047",
"Id": "405123",
"Score": "0",
"body": "Looks pretty good actually! Creating DOM elements and adding multiple classes can get a bit verbose, so you might want to write a separate function for that, or you could add multiple classes by using `newButton.className = \"btn btn-danger btn-block p-1 p-md-2 Delete\";`"
}
] | [
{
"body": "<p>Many of the things done are for showing alternatives. There are many ways to do things, each with pros and cons. I have also removed the parts that were not necessary so that there are less distractions.</p>\n\n<p>Used a <code><div></code> with <code>style='display: none'</code> to provide a template of a todo task that I clone when adding a new task.</p>\n\n<p>Instead of redoing the whole list each time you do anything, it now handles the changes that need to be made as they are needed.</p>\n\n<p>Event delegation used so that the whole thing only needs 2 total event handlers as opposed to 1 + 2 times number of tasks.</p>\n\n<p>I added <code>const done</code> and <code>todo</code> for clarifying the classes used to indicate those states.</p>\n\n<p>Hopefully this is helpful in your learning journey, good luck.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const divTodo = document.getElementById('tasks');\nconst addBtn = document.getElementById('addTask');\nconst addInput = document.getElementById('addTaskText');\nconst taskTemplate = document.getElementById('taskTemplate').children[0];\nconst done = 'bg-success';\nconst todo = 'bg-warning';\nlet newIndex = 0;\n\nconst taskList = {};\n\n// event delegation\ndivTodo.addEventListener('click', function(e) {\n const target = e.target;\n const row = target.parentNode.parentNode;\n if (target.type === 'checkbox') {\n const task = taskList[target.dataset.key];\n task.isDone = !task.isDone;\n target.checked = task.isDone;\n row.classList.toggle(done);\n row.classList.toggle(todo);\n } else if (target.type === 'submit') {\n delete taskList[target.dataset.key];\n divTodo.removeChild(row);\n }\n});\n\nconst addTask = function(task, initial) {\n const newTask = {\n task: task,\n isDone: initial || false,\n };\n\n addElement(newTask);\n taskList[newIndex] = newTask;\n newIndex++;\n};\n\nconst addElement = function(el) {\n const index = newIndex;\n const newRow = taskTemplate.cloneNode(true);\n const newCheckbox = newRow.querySelector('input[type=checkbox]');\n const newTask = newRow.children[1];\n const newButton = newRow.querySelector('button');\n\n newRow.classList.add(el.isDone == true ? done : todo);\n\n newCheckbox.checked = el.isDone;\n newCheckbox.dataset.key = `${index}`;\n\n newTask.textContent = el.task;\n\n newButton.dataset.key = `${index}`;\n\n divTodo.appendChild(newRow);\n};\n\naddTask(\"Make a dinner.\", true);\n\naddBtn.addEventListener('click', () => {\n if (addInput.value == \"\")\n return;\n addTask(addInput.value);\n addInput.value = \"\";\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">\n <title>ToDo list</title>\n\n <!-- Bootstrap CSS -->\n <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" integrity=\"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" crossorigin=\"anonymous\">\n <link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.5.0/css/all.css\" integrity=\"sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU\" crossorigin=\"anonymous\">\n\n</head>\n\n<body class=\"bg-info\">\n\n <div class=\"row\">\n <div class=\"col-12 col-md-8 mt-2\">\n <input type=\"text\" class=\"form-control\" placeholder=\"Add task...\" id=\"addTaskText\">\n </div>\n <div class=\"col-12 col-md-4 mt-2\">\n <button class=\"btn btn-success btn-block\" id=\"addTask\">Add Task!</button>\n </div>\n </div>\n\n <div id=\"tasks\"></div>\n\n <div id=\"taskTemplate\" style=\"display : none\">\n <div class=\"row m-2 d-flex align-items-center rounded\">\n <div class=\"col-2 col-md-1\">\n <input class=\"form-control form-control-lg\" type=\"checkbox\">\n </div>\n <div class=\"col-7 col-md-8 text-justify\"></div>\n <div class=\"col-3\">\n <button class=\"btn btn-danger btn-block p-1 p-md-2\">Delete</button>\n </div>\n </div>\n </div>\n\n</body>\n\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-31T21:52:51.700",
"Id": "407253",
"Score": "1",
"body": "You could also consider using a [`<template>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template) tag for the template HTML"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T01:58:41.880",
"Id": "209705",
"ParentId": "209382",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T18:20:53.250",
"Id": "209382",
"Score": "2",
"Tags": [
"javascript",
"beginner",
"dom",
"twitter-bootstrap",
"to-do-list"
],
"Title": "My first ToDo list in JavaScript"
} | 209382 |
<p>We ship large spools of copper wire and pallets of copper rod that have to meet specific chemical and mechanical requirements, this is what must be put on the certifications. I created an SP which builds and then runs a SQL query. This query is pulling in data from several tables and 2 DBs for creating certificates for shipping. Because I don't choose what goes on the certifications I have to pull all the data, even if it ends up not being used. Then someone else actually decides what they want and that is what gets put on the certs. That is why the SP creates a query dynamically. I have tried to limit the amount of data that has to be pulled.</p>
<p>Right now this is taking between 50 to 110 seconds to run. This is too long as we have a lot of shipments that go out and need to run this a lot. I would like to try getting it down to about 15 seconds if that is possible, but I have run out of ideas on what else I can try.</p>
<p>I have played around with Indexes and have added (and removed) clustered and non-clustered indexes on most of the tables involved. I've reorganized that building of the query and created the <code>#TEMP</code> table at the top to help with running faster, but nothing has made a big enough difference.</p>
<p>Here is the SP query:</p>
<pre><code>@PackingSlipId varchar(25) = '',
@PackSales int = 0, -- 0 = Packingslip, 1 = SalesId
@PrintSQL int = 0
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
declare @tsql varchar(max)
declare @SalesName varchar(150)
SELECT ProductionId, Max(ID) AS Id INTO #TEMP
FROM sdiProductionChemistry GROUP BY ProductionId
--Set the SalesName for use in the dynamic sql below
set @SalesName = case when @PackSales = 0 THEN (
select distinct st.SALESNAME
FROM InventTrans AS IT
LEFT OUTER JOIN InventTable AS I ON IT.ItemId = I.ItemId
LEFT OUTER JOIN InventDim AS ID ON IT.INVENTDIMID = ID.InventDimId
LEFT OUTER JOIN SalesTable AS ST ON IT.TransRefId = ST.SalesId
LEFT OUTER JOIN SDICustomerSpecs AS SCS ON ST.CustAccount = SCS.CustomerId AND IT.ItemId = SCS.ItemId
LEFT OUTER JOIN SDIInventory AS SI ON ID.InventBatchId = SI.BatchId
LEFT OUTER JOIN SDIProduction AS P ON SI.ProductionId = P.Id
LEFT OUTER JOIN #Temp ON P.Id = #Temp.PRODUCTIONID
LEFT OUTER JOIN SDIPRODUCTIONCHEMISTRY AS SPC ON #Temp.PRODUCTIONID = SPC.ProductionId AND SPC.Id = #Temp.Id
WHERE IT.PackingSlipId = @PackingSlipId)
when @PackSales = 1 then (
select distinct st.SALESNAME
FROM InventTrans AS IT
LEFT OUTER JOIN InventTable AS I ON IT.ItemId = I.ItemId
LEFT OUTER JOIN InventDim AS ID ON IT.INVENTDIMID = ID.InventDimId
LEFT OUTER JOIN SalesTable AS ST ON IT.TransRefId = ST.SalesId
LEFT OUTER JOIN SDICustomerSpecs AS SCS ON ST.CustAccount = SCS.CustomerId AND IT.ItemId = SCS.ItemId
LEFT OUTER JOIN SDIInventory AS SI ON ID.InventBatchId = SI.BatchId
LEFT OUTER JOIN SDIProduction AS P ON SI.ProductionId = P.Id
LEFT OUTER JOIN #Temp ON P.Id = #Temp.PRODUCTIONID
LEFT OUTER JOIN SDIPRODUCTIONCHEMISTRY AS SPC ON #Temp.PRODUCTIONID = SPC.ProductionId AND SPC.Id = #Temp.Id
WHERE IT.TransRefId = @PackingSlipId) end
set @tsql = '
SELECT DISTINCT P.Id,
ID.InventBatchId AS CoilId, IT.DatePhysical AS DlvDate,'
IF (@PackSales) = 1
SET @tsql = @tsql + '''' + @PackingSlipId + ''' AS SalesOrderId, IT.PackingSlipId As PackingSlipId,'
ELSE
SET @tsql = @tsql + 'IT.TransRefId AS SalesOrderId, ''' + @PackingSlipId + ''' As PackingSlipId,'
SET @tsql = @tsql + '
CASE
WHEN NOT SI.Diameter IS NULL THEN SI.Diameter
ELSE xSI.Diameter END AS Diameter,
SI.Leco, SI.Tensilestrength,
CASE WHEN NOT SI.E200 IS NULL AND SI.E200 > 0 THEN convert(varchar,convert(numeric(10,1),SI.E200))
WHEN NOT xSI.Elongation IS NULL AND xSI.Elongation > 0 THEN convert(varchar,convert(numeric(10,1),xSI.Elongation))
ELSE ''> 35'' END AS E200,
CASE WHEN NOT P.HeatNumber IS NULL THEN P.HeatNumber
ELSE xSI.BreakDownId END AS HeatNumber,
--xSA.Heatnumber as SpectroHeatNumber,
CASE WHEN NOT SI.NetWeight IS NULL THEN SI.NetWeight
ELSE xSI.GrossWeight - xSI.TareWeight END AS NetWeight,
CASE
WHEN SI.CertConductivity = 0 THEN
SI.IACS_REAL
WHEN SI.CertConductivity > 0 THEN
SI.CertConductivity
END AS IACS, (SPC.CU + (SPC.AG / 10000)) AS CUAG,
ST.SalesName, ST.PurchOrderFormNum AS CustomerPO,
xSI.Grm,
-- Customer Spec Min/Max Fields
SCS.CUAGMin, SCS.CUAGMax, SCS.DiameterMin, SCS.DiameterMax, SCS.ElongMin, SCS.ElongMax,
SCS.StrengthMin, SCS.StrengthMax, SCS.OxygenMin, SCS.OxygenMax, SCS.ConductivityMin, SCS.ConductivityMax,
SCS.GrmMin, SCS.GrmMax, SCS.PopMin AS OxideMin, SCS.PopMax AS OxideMax,
SCS.ZnMax, SCS.ZnMin, SCS.PbMax, SCS.PbMin, SCS.SnMax, SCS.SnMin, SCS.PMax, SCS.PMin, SCS.MnMax, SCS.MnMin,
SCS.FeMax, SCS.FeMin, SCS.NiMax, SCS.NiMin, SCS.SiMax, SCS.SiMin, SCS.MgMax, SCS.MgMin, SCS.CrMax, SCS.CrMin,
SCS.TeMax, SCS.TeMin, SCS.AsMax, SCS.AsMin, SCS.SeMax, SCS.SeMin, SCS.SbMax, SCS.SbMin, SCS.CdMax, SCS.CdMin,
SCS.BiMax, SCS.BiMin, SCS.AgMax, SCS.AgMin, SCS.CoMax, SCS.CoMin, SCS.AlMax, SCS.AlMin, SCS.SMax, SCS.SMin,
SCS.BeMax, SCS.BeMin, SCS.HRFMax, SCS.HRFMin,
I.ItemName
-- Element values to show
'
--/*
if(SELECT ZnShow FROM SDICustomerSpecSheets where CustomerName = @SalesName) = -1561783295
SET @tsql = @tsql + ', xSA.Zn'
ELSE
SET @tsql = @tsql + ', 0 Zn'
if(SELECT PbShow FROM SDICustomerSpecSheets where CustomerName = @SalesName) = -1561783295
SET @tsql = @tsql + ', xSA.Pb'
ELSE
SET @tsql = @tsql + ', 0 Pb'
if(SELECT SnShow FROM SDICustomerSpecSheets where CustomerName = @SalesName) = -1561783295
SET @tsql = @tsql + ', xSA.Sn'
ELSE
SET @tsql = @tsql + ', 0 Sn'
if(SELECT PShow FROM SDICustomerSpecSheets where CustomerName = @SalesName) = -1561783295
SET @tsql = @tsql + ', xSA.P'
ELSE
SET @tsql = @tsql + ', 0 P'
if(SELECT MnShow FROM SDICustomerSpecSheets where CustomerName = @SalesName) = -1561783295
SET @tsql = @tsql + ', xSA.Mn'
ELSE
SET @tsql = @tsql + ', 0 Mn'
if(SELECT FeShow FROM SDICustomerSpecSheets where CustomerName = @SalesName) = -1561783295
SET @tsql = @tsql + ', xSA.Fe'
ELSE
SET @tsql = @tsql + ', 0 Fe'
if(SELECT NiShow FROM SDICustomerSpecSheets where CustomerName = @SalesName) = -1561783295
SET @tsql = @tsql + ', xSA.Ni'
ELSE
SET @tsql = @tsql + ', 0 Ni'
if(SELECT SiShow FROM SDICustomerSpecSheets where CustomerName = @SalesName) = -1561783295
SET @tsql = @tsql + ', xSA.Si'
ELSE
SET @tsql = @tsql + ', 0 Si'
if(SELECT MgShow FROM SDICustomerSpecSheets where CustomerName = @SalesName) = -1561783295
SET @tsql = @tsql + ', xSA.Mg'
ELSE
SET @tsql = @tsql + ', 0 Mg'
if(SELECT CrShow FROM SDICustomerSpecSheets where CustomerName = @SalesName) = -1561783295
SET @tsql = @tsql + ', xSA.Cr'
ELSE
SET @tsql = @tsql + ', 0 Cr'
if(SELECT TeShow FROM SDICustomerSpecSheets where CustomerName = @SalesName) = -1561783295
SET @tsql = @tsql + ', xSA.Te'
ELSE
SET @tsql = @tsql + ', 0 Te'
if(SELECT AsShow FROM SDICustomerSpecSheets where CustomerName = @SalesName) = -1561783295
SET @tsql = @tsql + ', xSA.As'
ELSE
SET @tsql = @tsql + ', 0 [As]'
if(SELECT SeShow FROM SDICustomerSpecSheets where CustomerName = @SalesName) = -1561783295
SET @tsql = @tsql + ', xSA.Se'
ELSE
SET @tsql = @tsql + ', 0 Se'
if(SELECT SbShow FROM SDICustomerSpecSheets where CustomerName = @SalesName) = -1561783295
SET @tsql = @tsql + ', xSA.Sb'
ELSE
SET @tsql = @tsql + ', 0 Sb'
if(SELECT CdShow FROM SDICustomerSpecSheets where CustomerName = @SalesName) = -1561783295
SET @tsql = @tsql + ', xSA.Cd'
ELSE
SET @tsql = @tsql + ', 0 Cd'
if(SELECT BiShow FROM SDICustomerSpecSheets where CustomerName = @SalesName) = -1561783295
SET @tsql = @tsql + ', xSA.Bi'
ELSE
SET @tsql = @tsql + ', 0 Bi'
if(SELECT AgShow FROM SDICustomerSpecSheets where CustomerName = @SalesName) = -1561783295
SET @tsql = @tsql + ', xSA.Ag'
ELSE
SET @tsql = @tsql + ', 0 Ag'
if(SELECT CoShow FROM SDICustomerSpecSheets where CustomerName = @SalesName) = -1561783295
SET @tsql = @tsql + ', xSA.Co'
ELSE
SET @tsql = @tsql + ', 0 Co'
if(SELECT AlShow FROM SDICustomerSpecSheets where CustomerName = @SalesName) = -1561783295
SET @tsql = @tsql + ', xSA.Al'
ELSE
SET @tsql = @tsql + ', 0 Al'
if(SELECT SShow FROM SDICustomerSpecSheets where CustomerName = @SalesName) = -1561783295
SET @tsql = @tsql + ', xSA.S'
ELSE
SET @tsql = @tsql + ', 0 S'
if(SELECT BeShow FROM SDICustomerSpecSheets where CustomerName = @SalesName) = -1561783295
SET @tsql = @tsql + ', xSA.Be'
ELSE
SET @tsql = @tsql + ', 0 Be'
if(SELECT HRFShow FROM SDICustomerSpecSheets where CustomerName = @SalesName) = -1561783295
SET @tsql = @tsql + ', 0 HRF'
ELSE
SET @tsql = @tsql + ', 0 HRF'
if(SELECT OxideShow FROM SDICustomerSpecSheets where CustomerName = @SalesName) = -1561783295
SET @tsql = @tsql + ', CASE WHEN SI.POP_EXTERNAL < SI.POP_INTERNAL THEN SI.POP_EXTERNAL
WHEN SI.POP_INTERNAL < SI.POP_EXTERNAL THEN SI.POP_INTERNAL
ELSE 0 END AS SurfaceOxide'
ELSE
SET @tsql = @tsql + ', 0 SurfaceOxide'
set @tsql = @tsql + '
-- What to show
, case SCSS.ZnShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as ZnShow
, case SCSS.PbShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as PbShow
, case SCSS.SnShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as SnShow
, case SCSS.PShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as PShow
, case SCSS.MnShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as MnShow
, case SCSS.FeShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as FeShow
, case SCSS.NiShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as NiShow
, case SCSS.SiShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as SiShow
, case SCSS.MgShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as MgShow
, case SCSS.CrShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as CrShow
, case SCSS.TeShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as TeShow
, case SCSS.AsShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as AsShow
, case SCSS.SeShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as SeShow
, case SCSS.SbShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as SbShow
, case SCSS.CdShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as CdShow
, case SCSS.BiShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as BiShow
, case SCSS.AgShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as AgShow
, case SCSS.CoShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as CoShow
, case SCSS.AlShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as AlShow
, case SCSS.SShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as SShow
, case SCSS.BeShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as BeShow
, case SCSS.HRFShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as HRFShow
, case SCSS.OxideShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as OxideShow
, case SCSS.CuAgShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as CuAgShow
, case SCSS.DiameterShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as DiameterShow
, case SCSS.ElongationShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as ElongationShow
, case SCSS.StrengthShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as StrengthShow
, case SCSS.OxygenShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as OxygenShow
, case SCSS.ConductivityShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as ConductivityShow
, case SCSS.GRMShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as GRMShow'
--*/
set @tsql = @tsql + '
FROM InventTrans AS IT
LEFT OUTER JOIN InventTable AS I ON IT.ItemId = I.ItemId
LEFT OUTER JOIN InventDim AS ID ON IT.INVENTDIMID = ID.InventDimId
LEFT OUTER JOIN SalesTable AS ST ON IT.TransRefId = ST.SalesId
LEFT OUTER JOIN SDICustomerSpecs AS SCS ON ST.CustAccount = SCS.CustomerId AND IT.ItemId = SCS.ItemId
LEFT OUTER JOIN SDIInventory AS SI ON ID.InventBatchId = SI.BatchId
LEFT OUTER JOIN SDICustomerSpecSheets AS SCSS ON SCSS.CustomerName = ST.SalesName
LEFT OUTER JOIN LAFARGA.LaFargaProd.dbo.BreakdownItem AS xSI ON ID.InventBatchId = xSI.BatchId
LEFT OUTER JOIN SDIProduction AS P ON SI.ProductionId = P.Id
LEFT OUTER JOIN #Temp AS T ON P.Id = T.PRODUCTIONID
LEFT OUTER JOIN SDIPRODUCTIONCHEMISTRY AS SPC ON T.PRODUCTIONID = SPC.ProductionId AND SPC.Id = T.Id
LEFT OUTER JOIN LAFARGA.LaFargaProd.dbo.vSpectroAssays AS xSA ON xSA.BatchID = ID.InventBatchId
WHERE '
IF (@PackSales) = 1
SET @tsql = @tsql + 'IT.TransRefId = ''' + @PackingSlipId + ''''
ELSE
SET @tsql = @tsql + 'IT.PackingSlipId = ''' + @PackingSlipId + ''''
SET @tsql = @tsql + '
ORDER BY ID.InventBatchId'
IF (@PrintSQL = 1)
BEGIN
print @tsql
END
IF (@PrintSQL = 0)
BEGIN
execute (@tsql)
END
Drop Table #Temp
END
</code></pre>
<p>Then here is what this creates and runs at the end (<em>or prints if I'm testing</em>):</p>
<pre><code>SELECT DISTINCT P.Id,
ID.InventBatchId AS CoilId, IT.DatePhysical AS DlvDate,IT.TransRefId AS SalesOrderId, 'RPS115898' As PackingSlipId,
CASE
WHEN NOT SI.Diameter IS NULL THEN SI.Diameter
ELSE xSI.Diameter END AS Diameter,
SI.Leco, SI.Tensilestrength,
CASE WHEN NOT SI.E200 IS NULL AND SI.E200 > 0 THEN convert(varchar,convert(numeric(10,1),SI.E200))
WHEN NOT xSI.Elongation IS NULL AND xSI.Elongation > 0 THEN convert(varchar,convert(numeric(10,1),xSI.Elongation))
ELSE '> 35' END AS E200,
CASE WHEN NOT P.HeatNumber IS NULL THEN P.HeatNumber
ELSE xSI.BreakDownId END AS HeatNumber,
--xSA.Heatnumber as SpectroHeatNumber,
CASE WHEN NOT SI.NetWeight IS NULL THEN SI.NetWeight
ELSE xSI.GrossWeight - xSI.TareWeight END AS NetWeight,
CASE
WHEN SI.CertConductivity = 0 THEN
SI.IACS_REAL
WHEN SI.CertConductivity > 0 THEN
SI.CertConductivity
END AS IACS, (SPC.CU + (SPC.AG / 10000)) AS CUAG,
ST.SalesName, ST.PurchOrderFormNum AS CustomerPO,
xSI.Grm,
-- Customer Spec Min/Max Fields
SCS.CUAGMin, SCS.CUAGMax, SCS.DiameterMin, SCS.DiameterMax, SCS.ElongMin, SCS.ElongMax,
SCS.StrengthMin, SCS.StrengthMax, SCS.OxygenMin, SCS.OxygenMax, SCS.ConductivityMin, SCS.ConductivityMax,
SCS.GrmMin, SCS.GrmMax, SCS.PopMin AS OxideMin, SCS.PopMax AS OxideMax,
SCS.ZnMax, SCS.ZnMin, SCS.PbMax, SCS.PbMin, SCS.SnMax, SCS.SnMin, SCS.PMax, SCS.PMin, SCS.MnMax, SCS.MnMin,
SCS.FeMax, SCS.FeMin, SCS.NiMax, SCS.NiMin, SCS.SiMax, SCS.SiMin, SCS.MgMax, SCS.MgMin, SCS.CrMax, SCS.CrMin,
SCS.TeMax, SCS.TeMin, SCS.AsMax, SCS.AsMin, SCS.SeMax, SCS.SeMin, SCS.SbMax, SCS.SbMin, SCS.CdMax, SCS.CdMin,
SCS.BiMax, SCS.BiMin, SCS.AgMax, SCS.AgMin, SCS.CoMax, SCS.CoMin, SCS.AlMax, SCS.AlMin, SCS.SMax, SCS.SMin,
SCS.BeMax, SCS.BeMin, SCS.HRFMax, SCS.HRFMin,
I.ItemName
-- Element values to show
, 0 Zn, xSA.Pb, 0 Sn, 0 P, 0 Mn, 0 Fe, 0 Ni, 0 Si, 0 Mg, 0 Cr, 0 Te, 0 [As], 0 Se, 0 Sb, 0 Cd, 0 Bi, 0 Ag, 0 Co, 0 Al, 0 S, 0 Be, 0 HRF, 0 SurfaceOxide
-- What to show
, case SCSS.ZnShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as ZnShow
, case SCSS.PbShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as PbShow
, case SCSS.SnShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as SnShow
, case SCSS.PShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as PShow
, case SCSS.MnShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as MnShow
, case SCSS.FeShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as FeShow
, case SCSS.NiShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as NiShow
, case SCSS.SiShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as SiShow
, case SCSS.MgShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as MgShow
, case SCSS.CrShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as CrShow
, case SCSS.TeShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as TeShow
, case SCSS.AsShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as AsShow
, case SCSS.SeShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as SeShow
, case SCSS.SbShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as SbShow
, case SCSS.CdShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as CdShow
, case SCSS.BiShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as BiShow
, case SCSS.AgShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as AgShow
, case SCSS.CoShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as CoShow
, case SCSS.AlShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as AlShow
, case SCSS.SShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as SShow
, case SCSS.BeShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as BeShow
, case SCSS.HRFShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as HRFShow
, case SCSS.OxideShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as OxideShow
, case SCSS.CuAgShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as CuAgShow
, case SCSS.DiameterShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as DiameterShow
, case SCSS.ElongationShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as ElongationShow
, case SCSS.StrengthShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as StrengthShow
, case SCSS.OxygenShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as OxygenShow
, case SCSS.ConductivityShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as ConductivityShow
, case SCSS.GRMShow when -1561783295 then 1 when -1561783296 then 0 else 0 end as GRMShow
FROM InventTrans AS IT
LEFT OUTER JOIN InventTable AS I ON IT.ItemId = I.ItemId
LEFT OUTER JOIN InventDim AS ID ON IT.INVENTDIMID = ID.InventDimId
LEFT OUTER JOIN SalesTable AS ST ON IT.TransRefId = ST.SalesId
LEFT OUTER JOIN SDICustomerSpecs AS SCS ON ST.CustAccount = SCS.CustomerId AND IT.ItemId = SCS.ItemId
LEFT OUTER JOIN SDIInventory AS SI ON ID.InventBatchId = SI.BatchId
LEFT OUTER JOIN SDICustomerSpecSheets AS SCSS ON SCSS.CustomerName = ST.SalesName
LEFT OUTER JOIN LAFARGA.LaFargaProd.dbo.BreakdownItem AS xSI ON ID.InventBatchId = xSI.BatchId
LEFT OUTER JOIN SDIProduction AS P ON SI.ProductionId = P.Id
LEFT OUTER JOIN #Temp AS T ON P.Id = T.PRODUCTIONID
LEFT OUTER JOIN SDIPRODUCTIONCHEMISTRY AS SPC ON T.PRODUCTIONID = SPC.ProductionId AND SPC.Id = T.Id
LEFT OUTER JOIN LAFARGA.LaFargaProd.dbo.vSpectroAssays AS xSA ON xSA.BatchID = ID.InventBatchId
WHERE IT.PackingSlipId = 'RPS115898'
ORDER BY ID.InventBatchId
</code></pre>
<p>Any help with making these queries run faster would be appreciated. Here is a link to the query execution plan if that will help: <a href="https://www.brentozar.com/pastetheplan/?id=B1Zn4t61N" rel="nofollow noreferrer">Execution Plan</a></p>
<p><strong>UPDATE</strong></p>
<p>Per the request below here is the <code>vSpectroAssays</code> view:</p>
<pre><code>SELECT DISTINCT sa.ID
, SUBSTRING(sa.SampleName, CHARINDEX('as cast', sa.SampleName) - 5, CHARINDEX('as cast', sa.SampleName) - (CHARINDEX('as cast', sa.SampleName) - 5)) AS HeatNumber
, bdi.BreakdownId
, bdi.BatchId
, bdi.BDHeatNumber
, sa.DATE
, sa.Zn
, sa.Pb
, sa.Sn
, sa.P
, sa.Mn
, sa.Fe
, sa.Ni
, sa.Si
, sa.Mg
, sa.Cr
, sa.Te
, sa.[As]
, sa.Se
, sa.Sb
, sa.Cd
, sa.Bi
, sa.Ag
, sa.Co
, sa.Al
, sa.S
, sa.Be
, sa.TestType
, sa.SampleName
, bdi.HRF
FROM dbo.SpectroAssays AS sa
LEFT JOIN (
SELECT OrderId
, BatchId
, GrossWeight
, NetWeight
, TareWeight
, PeakLoad
, Resistance
, Diameter
, GRM
, Elongation
, PassFail
, CoilId
, CoilId2
, Spec
, Customer
, CreateDate
, BreakdownId
, Line
, HRF
, CASE WHEN SUBSTRING(CoilId, 1, 6) = 'A-Null' THEN '' WHEN CoilId = 'A-000' THEN '' WHEN SUBSTRING(CoilId, 2, 2) = '--' THEN '' WHEN SUBSTRING(CoilId, 1, 2) = 'A-' THEN CONVERT(INT, SUBSTRING(CoilId, 3, (CHARINDEX('-', CoilId, (CHARINDEX('-', CoilId) + 1))) - (CHARINDEX('-', CoilId) + 1))) ELSE '' END AS BDHeatNumber
FROM dbo.BreakdownItem
) AS bdi ON bdi.BDHeatNumber = SUBSTRING(sa.SampleName, CHARINDEX('as cast', sa.SampleName) - 5, CHARINDEX('as cast', sa.SampleName) - (CHARINDEX('as cast', sa.SampleName) - 5))
WHERE (sa.TestType = 'CU-10')
AND (sa.SampleName LIKE '%as cast%')
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-03T02:56:28.527",
"Id": "407455",
"Score": "0",
"body": "What version of SQL Server are you using?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-04T15:17:09.073",
"Id": "407668",
"Score": "0",
"body": "This is running against both SQL 2008 R2 and SQL 2012"
}
] | [
{
"body": "<p>The following are a few suggestions on how I'd write the stored procedure.</p>\n\n<p><strong>Source Control</strong> </p>\n\n<p>If you don't already have a <a href=\"https://docs.microsoft.com/en-us/previous-versions/sql/sql-server-data-tools/hh272677(v=vs.103)\" rel=\"nofollow noreferrer\">database project</a>, create one in <a href=\"https://visualstudio.microsoft.com/\" rel=\"nofollow noreferrer\">Visual Studio</a>. Then check it in to source control. <a href=\"https://azure.microsoft.com/en-au/services/devops/\" rel=\"nofollow noreferrer\">Microsoft Azure DevOps Services</a> is free & private for teams of 5 or less (this is per project, so 5 developers per project). Then you'll be able to track changes you make to your stored procedures, views, tables, etc.</p>\n\n<p><strong>Formatting</strong></p>\n\n<p>I would download the following tool for SSMS and Visual Studio, <a href=\"https://marketplace.visualstudio.com/items?itemName=TaoKlerks.PoorMansT-SqlFormatterSSMSVSExtension\" rel=\"nofollow noreferrer\">Poor Man's T-Sql Formatter</a> and on <a href=\"https://github.com/TaoK/PoorMansTSqlFormatter\" rel=\"nofollow noreferrer\">GitHub</a>. I use it when I have to edit other developer's code. It's a great way to standardize your SQL. I find it does most of the formatting for me, but I'll still make a few changes after.</p>\n\n<p>Here are the settings I used:</p>\n\n<p><a href=\"https://i.stack.imgur.com/aBD8y.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aBD8y.png\" alt=\"screenshot\"></a></p>\n\n<p><strong>Copy & Paste</strong></p>\n\n<p>If you find yourself copying and pasting the same string or number over and over in your query, then you should define it as a variable. <a href=\"https://en.wikipedia.org/wiki/David_Parnas\" rel=\"nofollow noreferrer\"><em>Copy and paste is a design error ~ David Parnas</em></a></p>\n\n<p>e.g. <code>...when -1561783295 then 1 when -1561783296...</code></p>\n\n<p><strong>Commas</strong></p>\n\n<p>I would put the commas in front to clearly define new columns. Versus code wrapped in multiple lines. It also makes trouble-shooting code easier. The only exception in your procedure is that you may want to show the Min and Max for the same Customer Spec field on the same line to edit it a bit easier. </p>\n\n<p>e.g. <code>, SCS.[MnMax], SCS.[MnMin]</code></p>\n\n<p><strong>Where Clause</strong></p>\n\n<p>If you put <code>1=1</code> at the top of a <code>WHERE</code> condition, it enables you to freely change the rest of the conditions when debugging a query. The SQL query engine will end up ignoring the <code>1=1</code> so it should have no performance impact. <a href=\"https://stackoverflow.com/q/242822/9059424\">Reference</a></p>\n\n<p><strong>Common Table Expressions (CTE)</strong></p>\n\n<p><a href=\"https://docs.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql?view=sql-server-2017\" rel=\"nofollow noreferrer\">CTE's</a> in your SQL help with documentation. The expression name can then let other developers know why you used that expression e.g. <code>current_suppliers</code> or <code>active_projects</code>.</p>\n\n<p><strong>Schema Names</strong></p>\n\n<p>Always reference the schema when selecting an object e.g. <code>[dbo].[SalesTable]</code>.</p>\n\n<p><strong>Estimated Execution Plan</strong></p>\n\n<p>It's a good idea to check the <a href=\"https://docs.microsoft.com/en-us/sql/relational-databases/performance/display-the-estimated-execution-plan?view=sql-server-2017\" rel=\"nofollow noreferrer\">Estimated Execution Plan</a>. The shortcut in Microsoft SQL Server Management Studio (SSMS) is <kbd>Ctrl</kbd> + <kbd>L</kbd>. You can even run 2 queries in the same tab to compare the plans.</p>\n\n<p><strong>Keywords</strong></p>\n\n<p>Avoid using keywords as object names. <a href=\"https://docs.microsoft.com/en-us/sql/t-sql/language-elements/reserved-keywords-transact-sql?view=sql-server-2017\" rel=\"nofollow noreferrer\">Microsoft Reference</a></p>\n\n<ul>\n<li>Also check out the book <a href=\"https://rads.stackoverflow.com/amzn/click/0132350882\" rel=\"nofollow noreferrer\"><em>Clean Code</em></a>. It will change the way you think about naming conventions.</li>\n</ul>\n\n<hr>\n\n<p><strong>Revised SQL</strong></p>\n\n<p>Without table definitions and sample records I was unable to test this, but it should give you a good start.</p>\n\n<pre><code>CREATE PROCEDURE [dbo].[Create_Certificate] \n(\n @PackingSlipId VARCHAR(25) = '' -- I would default this to NULL; Also, I would rename it since it references more than one column. e.g. @ReferenceId or @Id\n , @PackSales INT = 0 -- A better naming convention would be @CertificateType and pass in the values either 'Packing' or 'Sales'. Then it becomes self documenting.\n)\nAS\nBEGIN\n\n BEGIN TRY\n\n SET NOCOUNT ON; --Stops the message that shows the count of the number of rows affected\n\n DECLARE @ShowTrue AS INT = -1561783295; --I'm guessing at what column definition is, so you might need to change the data type\n DECLARE @ShowFalse AS INT = -1561783296;\n\n WITH\n max_sdiProductionChemistry\n AS\n (\n SELECT \n [ProductionId]\n , [Id] = MAX([Id])\n FROM \n [dbo].[sdiProductionChemistry] --I'm guessing at the schema name here\n GROUP BY \n [ProductionId]\n )\n SELECT DISTINCT\n P.[Id]\n , [CoilId] = ID.[InventBatchId]\n , [DlvDate] = IT.[DatePhysical]\n , [SalesOrderId] = CASE WHEN @PackSales = 1 THEN @PackingSlipId ELSE IT.[TransRefId] END \n , [PackingSlipId] = CASE WHEN @PackSales = 1 THEN IT.[PackingSlipId] ELSE @PackingSlipId END \n , [Diameter] = CASE WHEN NOT SI.[Diameter] IS NULL THEN SI.[Diameter] ELSE xSI.[Diameter] END \n , SI.[Leco]\n , SI.[Tensilestrength]\n , [E200] = \n CASE \n WHEN NOT SI.[E200] IS NULL AND SI.[E200] > 0 THEN CONVERT(VARCHAR, CONVERT(NUMERIC(10, 1), SI.[E200]))\n WHEN NOT xSI.[Elongation] IS NULL AND xSI.[Elongation] > 0 THEN CONVERT(VARCHAR, CONVERT(NUMERIC(10,1), xSI.[Elongation]))\n ELSE '> 35'\n END\n , [HeatNumber] = CASE WHEN NOT P.[HeatNumber] IS NULL THEN P.[HeatNumber] ELSE xSI.[BreakDownId] END \n --, [SpectroHeatNumber] = xSA.[Heatnumber]\n , [NetWeight] = CASE WHEN NOT SI.[NetWeight] IS NULL THEN SI.[NetWeight] ELSE xSI.[GrossWeight] - xSI.[TareWeight] END \n , [IACS] = CASE WHEN SI.[CertConductivity] = 0 THEN SI.[IACS_REAL] WHEN SI.[CertConductivity] > 0 THEN SI.[CertConductivity] END \n , [CUAG] = (SPC.[CU] + (SPC.[AG] / 10000)) \n , ST.[SalesName]\n , [CustomerPO] = ST.[PurchOrderFormNum]\n , xSI.[Grm]\n -- Customer Spec Min/Max Fields\n , SCS.[CUAGMin] \n , SCS.[CUAGMax]\n , SCS.[DiameterMin]\n , SCS.[DiameterMax]\n , SCS.[ElongMin]\n , SCS.[ElongMax]\n , SCS.[StrengthMin]\n , SCS.[StrengthMax]\n , SCS.[OxygenMin]\n , SCS.[OxygenMax]\n , SCS.[ConductivityMin]\n , SCS.[ConductivityMax]\n , SCS.[GrmMin]\n , SCS.[GrmMax]\n , [OxideMin] = SCS.[PopMin]\n , [OxideMax] = SCS.[PopMax]\n , SCS.[ZnMax], SCS.[ZnMin]\n , SCS.[PbMax], SCS.[PbMin]\n , SCS.[SnMax], SCS.[SnMin]\n , SCS.[PMax], SCS.[PMin]\n , SCS.[MnMax], SCS.[MnMin]\n , SCS.[FeMax], SCS.[FeMin]\n , SCS.[NiMax], SCS.[NiMin]\n , SCS.[SiMax], SCS.[SiMin]\n , SCS.[MgMax], SCS.[MgMin]\n , SCS.[CrMax], SCS.[CrMin]\n , SCS.[TeMax], SCS.[TeMin]\n , SCS.[AsMax], SCS.[AsMin]\n , SCS.[SeMax], SCS.[SeMin]\n , SCS.[SbMax], SCS.[SbMin]\n , SCS.[CdMax], SCS.[CdMin]\n , SCS.[BiMax], SCS.[BiMin]\n , SCS.[AgMax], SCS.[AgMin]\n , SCS.[CoMax], SCS.[CoMin]\n , SCS.[AlMax], SCS.[AlMin]\n , SCS.[SMax], SCS.[SMin]\n , SCS.[BeMax], SCS.[BeMin]\n , SCS.[HRFMax], SCS.[HRFMin]\n , I.[ItemName]\n -- Element values to show\n , [Zn] = CASE WHEN SCSS.[ZnShow] = @ShowTrue THEN xSA.[Zn] ELSE 0 END\n , [Pb] = CASE WHEN SCSS.[PbShow] = @ShowTrue THEN xSA.[Pb] ELSE 0 END\n , [Sn] = CASE WHEN SCSS.[SnShow] = @ShowTrue THEN xSA.[Sn] ELSE 0 END\n , [P] = CASE WHEN SCSS.[PShow] = @ShowTrue THEN xSA.[P] ELSE 0 END\n , [Mn] = CASE WHEN SCSS.[MnShow] = @ShowTrue THEN xSA.[Mn] ELSE 0 END\n , [Fe] = CASE WHEN SCSS.[FeShow] = @ShowTrue THEN xSA.[Fe] ELSE 0 END\n , [Ni] = CASE WHEN SCSS.[NiShow] = @ShowTrue THEN xSA.[Ni] ELSE 0 END\n , [Si] = CASE WHEN SCSS.[SiShow] = @ShowTrue THEN xSA.[Si] ELSE 0 END\n , [Mg] = CASE WHEN SCSS.[MgShow] = @ShowTrue THEN xSA.[Mg] ELSE 0 END\n , [Cr] = CASE WHEN SCSS.[CrShow] = @ShowTrue THEN xSA.[Cr] ELSE 0 END\n , [Te] = CASE WHEN SCSS.[TeShow] = @ShowTrue THEN xSA.[Te] ELSE 0 END\n , [As] = CASE WHEN SCSS.[AsShow] = @ShowTrue THEN xSA.[As] ELSE 0 END\n , [Se] = CASE WHEN SCSS.[SeShow] = @ShowTrue THEN xSA.[Se] ELSE 0 END\n , [Sb] = CASE WHEN SCSS.[SbShow] = @ShowTrue THEN xSA.[Sb] ELSE 0 END\n , [Cd] = CASE WHEN SCSS.[CdShow] = @ShowTrue THEN xSA.[Cd] ELSE 0 END\n , [Bi] = CASE WHEN SCSS.[BiShow] = @ShowTrue THEN xSA.[Bi] ELSE 0 END\n , [Ag] = CASE WHEN SCSS.[AgShow] = @ShowTrue THEN xSA.[Ag] ELSE 0 END\n , [Co] = CASE WHEN SCSS.[CoShow] = @ShowTrue THEN xSA.[Co] ELSE 0 END\n , [Al] = CASE WHEN SCSS.[AlShow] = @ShowTrue THEN xSA.[Al] ELSE 0 END\n , [S] = CASE WHEN SCSS.[SShow] = @ShowTrue THEN xSA.[S] ELSE 0 END\n , [Be] = CASE WHEN SCSS.[BeShow] = @ShowTrue THEN xSA.[Be] ELSE 0 END\n , [HRF] = CASE WHEN SCSS.[HRFShow] = @ShowTrue THEN 0 ELSE 0 END\n , [SurfaceOxide] = CASE WHEN SCSS.[OxideShow] = @ShowTrue THEN \n CASE \n WHEN SI.[POP_EXTERNAL] < SI.[POP_INTERNAL] THEN SI.[POP_EXTERNAL]\n WHEN SI.[POP_INTERNAL] < SI.[POP_EXTERNAL] THEN SI.[POP_INTERNAL]\n ELSE 0 \n END\n ELSE 0 END\n -- What to show\n , [ZnShow] = CASE SCSS.[ZnShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END \n , [PbShow] = CASE SCSS.[PbShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END \n , [SnShow] = CASE SCSS.[SnShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END \n , [PShow] = CASE SCSS.[PShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END \n , [MnShow] = CASE SCSS.[MnShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END \n , [FeShow] = CASE SCSS.[FeShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END \n , [NiShow] = CASE SCSS.[NiShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END \n , [SiShow] = CASE SCSS.[SiShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END \n , [MgShow] = CASE SCSS.[MgShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END \n , [CrShow] = CASE SCSS.[CrShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END\n , [TeShow] = CASE SCSS.[TeShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END\n , [AsShow] = CASE SCSS.[AsShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END\n , [SeShow] = CASE SCSS.[SeShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END\n , [SbShow] = CASE SCSS.[SbShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END \n , [CdShow] = CASE SCSS.[CdShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END\n , [BiShow] = CASE SCSS.[BiShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END \n , [AgShow] = CASE SCSS.[AgShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END \n , [CoShow] = CASE SCSS.[CoShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END \n , [AlShow] = CASE SCSS.[AlShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END\n , [SShow] = CASE SCSS.[SShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END\n , [BeShow] = CASE SCSS.[BeShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END \n , [HRFShow] = CASE SCSS.[HRFShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END\n , [OxideShow] = CASE SCSS.[OxideShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END \n , [CuAgShow] = CASE SCSS.[CuAgShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END \n , [DiameterShow] = CASE SCSS.[DiameterShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END\n , [ElongationShow] = CASE SCSS.[ElongationShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END\n , [StrengthShow] = CASE SCSS.[StrengthShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END\n , [OxygenShow] = CASE SCSS.[OxygenShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END\n , [ConductivityShow] = CASE SCSS.[ConductivityShow]WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END\n , [GRMShow] = CASE SCSS.[GRMShow] WHEN @ShowTrue THEN 1 WHEN @ShowFalse THEN 0 ELSE 0 END\n FROM \n [dbo].[InventTrans] AS IT\n LEFT JOIN [dbo].[InventTable] AS I ON IT.[ItemId] = I.[ItemId]\n LEFT JOIN [dbo].[InventDim] AS ID ON IT.[INVENTDIMID] = ID.[InventDimId]\n LEFT JOIN [dbo].[SalesTable] AS ST ON IT.[TransRefId] = ST.[SalesId]\n LEFT JOIN [dbo].[SDICustomerSpecs] AS SCS ON ST.[CustAccount] = SCS.[CustomerId] AND IT.[ItemId] = SCS.[ItemId]\n LEFT JOIN [dbo].[SDIInventory] AS SI ON ID.[InventBatchId] = SI.[BatchId]\n LEFT JOIN [dbo].[SDICustomerSpecSheets] AS SCSS ON SCSS.[CustomerName] = ST.[SalesName]\n LEFT JOIN [LAFARGA].[LaFargaProd].[dbo].[BreakdownItem] AS xSI ON ID.[InventBatchId] = xSI.[BatchId]\n LEFT JOIN max_sdiProductionChemistry AS mSPC ON P.[Id] = mSPC.[ProductionId] --Should this be an INNER JOIN?\n LEFT JOIN [dbo].[SDIProduction] AS P ON SI.[ProductionId] = P.[Id]\n LEFT JOIN [dbo].[sdiProductionChemistry] AS SPC ON T.[PRODUCTIONID] = SPC.[ProductionId] AND SPC.[Id] = T.[Id]\n LEFT JOIN [LAFARGA].[LaFargaProd].[dbo].[vSpectroAssays] AS xSA ON xSA.[BatchID] = ID.[InventBatchId]\n WHERE \n 1=1\n AND \n (\n (@PackSales = 0 AND IT.[PackingSlipId] = @PackingSlipId)\n OR\n (@PackSales = 1 AND IT.[TransRefId] = @PackingSlipId)\n )\n ORDER BY \n ID.[InventBatchId]\n\n END TRY\n BEGIN CATCH\n SELECT \n [ErrorNumber] = ERROR_NUMBER()\n , [ErrorSeverity] = ERROR_SEVERITY()\n , [ErrorState] = ERROR_STATE()\n , [ErrorProcedure] = ERROR_PROCEDURE()\n , [ErrorLine] = ERROR_LINE()\n , [ErrorMessage] = ERROR_MESSAGE();\n END CATCH\n\nEND\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-04T15:29:06.970",
"Id": "407671",
"Score": "0",
"body": "I will attempt this, but it will take me a little while to get to it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T18:09:30.670",
"Id": "409390",
"Score": "0",
"body": "I only see a few seconds difference with these updates."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T23:06:06.587",
"Id": "409414",
"Score": "0",
"body": "What does the execution plan say? It may be a performance issue with the view `vSpectroAssays`. Is there an index on `BatchID`? Can you post the design of the view?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T23:15:41.607",
"Id": "409415",
"Score": "0",
"body": "Another fast way of checking performance is, commenting out all joins and columns except one then add them back one by one and check the performance. I'd start with only returning the table `InventTrans` and the column `DatePhysical`. Then uncomment one join at a time until you find the performance hit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T20:44:13.753",
"Id": "409544",
"Score": "0",
"body": "An excellent idea, I'll try it and report back. Hopefully, I'll find something worth fixing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T20:45:36.650",
"Id": "409545",
"Score": "0",
"body": "There is a link in my question with the execution plan. I'll pull the design of the view `vSpectroAssays` and add that to my question."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-03T02:41:40.667",
"Id": "210782",
"ParentId": "209384",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T19:13:52.687",
"Id": "209384",
"Score": "3",
"Tags": [
"sql",
"sql-server",
"t-sql",
"stored-procedure"
],
"Title": "SQL SP creating certificates for shipping"
} | 209384 |
<p>So there is this game 2048. You can play it <a href="https://play2048.co/" rel="nofollow noreferrer">here</a></p>
<p>I wrote a python script which "plays" the game on the website by clicking the arrow keys.</p>
<p>I would like to know what can be improved.
Is it a good idea to check the Try again button with exceptions? Is there a better way?</p>
<p>Currently it takes alot of tries to get a high score for the bot. Can the logic be improved?</p>
<p><b> play_2048.py </b></p>
<pre><code>"""
Opens the webpage of the 2048 game and plays it repeadly.
Needs chromedriver in the directory of the script. Download it here:
https://sites.google.com/a/chromium.org/chromedriver/downloads
"""
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
def play_2048():
"""
Main lopp of script. First opens the browser to the game page.
Then pushes the arrow keys to play the game.
If a game over occurs the try again button on the page is klicked
to repeat the game
"""
browser = webdriver.Chrome()
browser.get('https://play2048.co/')
html = browser.find_element_by_tag_name('html')
while True:
html.send_keys(Keys.RIGHT)
html.send_keys(Keys.UP)
html.send_keys(Keys.LEFT)
html.send_keys(Keys.DOWN)
try:
retry = browser.find_element_by_link_text('Try again')
except:
continue
else:
retry.click()
if __name__ == '__main__':
play_2048()
</code></pre>
| [] | [
{
"body": "<p>There isn't really much here to comment on, since there isn't even AI involved.</p>\n\n<p>The only thing that stands out to me is your use of a silent \"catch-all\" <code>try</code> block:</p>\n\n<pre><code>try:\n retry = browser.find_element_by_link_text('Try again')\n\nexcept: # Big problem here\n continue\n\nelse:\n retry.click()\n</code></pre>\n\n<p>You're catching every exception, and simply ignoring them. In this <em>particular</em> case the ramifications aren't huge. Say in the future though you add a second function to do some processing and decide to put it in the <code>try</code> (for whatever reason). Something like:</p>\n\n<pre><code>try:\n retry = browser.find_element_by_link_text('Try again')\n do_something_with_retry(retry) # This throws. Would you ever know that though?\n\nexcept:\n continue\n\nelse:\n retry.click()\n</code></pre>\n\n<p>And lets say that <code>do_something_with_retry</code> is improperly tested, or some unforeseen circumstance comes up, and suddenly <code>do_something_with_retry</code> starts throwing exceptions. Would you ever even know that there was an exception thrown? How would you debug your code failing in that case? It would be <em>much</em> better to be specific about what you need to catch, and deal with that only. As you can see in the <a href=\"https://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webdriver.WebDriver.find_element_by_link_text\" rel=\"nofollow noreferrer\">API\n documentation</a>, <code>find_element_by_link_text</code> is documented to throw a <code>NoSuchElementException</code> if something fails. Catch that instead, so irrelevant errors aren't silently ignored as well: </p>\n\n<pre><code>try:\n retry = browser.find_element_by_link_text('Try again')\n\nexcept NoSuchElementException as e: # Be specific!\n continue\n\nelse:\n retry.click()\n</code></pre>\n\n<p>Now anything other than a <code>NoSuchElementException</code> will cause your program to crash. <em>This is a good thing though</em>. You don't want fundamentally broken code to run.</p>\n\n<p>Don't make your code vulnerable to silly mistakes that may happen in the future. Silly mistakes happen (like improperly tested functions). It's best that they fail catastrophically so they can be detected and fixed.</p>\n\n<p>Of course though, the better option to handling the addition of <code>do_something_with_retry</code> would be, if possible, to just not group it in the <code>try</code> in the first place. Again though, mistakes happen.</p>\n\n<hr>\n\n<p>As for </p>\n\n<blockquote>\n <p>Currently it takes alot of tries to get a high score for the bot. Can the logic be improved?</p>\n</blockquote>\n\n<p>That involves writing up an AI to play the game, and is no small feat. That would be beyond the scope of a Code Review unfortunately.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T16:50:57.740",
"Id": "404850",
"Score": "0",
"body": "if i define `name 'NoSuchElementException' is not defined` it is not defined"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T16:52:49.637",
"Id": "404851",
"Score": "0",
"body": "@Sandro4912 You need to import it from selenium. That's not a standard exception."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T16:54:14.123",
"Id": "404852",
"Score": "0",
"body": "it worked by adding `from selenium.common.exceptions import NoSuchElementException`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T21:21:51.537",
"Id": "209391",
"ParentId": "209386",
"Score": "4"
}
},
{
"body": "<p>A first step towards writing an AI is to give this an interface.</p>\n\n<p>First, let's rewrite the \"AI\" you are currently using as a class:</p>\n\n<pre><code>from itertools import cycle\n\nclass Cycler:\n def __init__(self):\n self.cycle = cycle([Keys.RIGHT, Keys.UP, Keys.LEFT, Keys.DOWN])\n\n def next(self, *args):\n return next(self.cycle)\n</code></pre>\n\n<p>Which you can use like this in your current code:</p>\n\n<pre><code>ai = Cycler()\nwhile True:\n html.send_keys(ai.next())\n try:\n ...\n</code></pre>\n\n<p>In the future you might want to be smarter than that and for that you would need the state of the board to be passed along to the AI.</p>\n\n<pre><code>Class GameStatePrinter(Cycler):\n def next(self, game_state, *args):\n print(game_state)\n return super(self, GameStatePrinter).next(*args)\n</code></pre>\n\n<p>This is not really any smarter, but you can pass it the current game state and it will print it:</p>\n\n<pre><code>ai = GameStatePrinter()\nwhile True:\n current_state = get_current_state(html)\n html.send_keys(ai.next(current_state))\n ...\n</code></pre>\n\n<p>An actual smart bot would then of course act differently according to the information in the board, whereas this one just does the same thing as <code>Cycler</code>, which it inherits from. </p>\n\n<p>This logic is left as an exercise for the reader.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T17:05:50.503",
"Id": "404853",
"Score": "0",
"body": "i tryed adding the first part but in the line `self.cycle = cycle[Keys.RIGHT, Keys.UP, Keys.LEFT, Keys.DOWN]` it throws `'type' object is not subscriptable` so maybe the keys don't work with cycler"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T17:07:02.713",
"Id": "404854",
"Score": "0",
"body": "@Sandro4912: You missed the parenthesis around the list, it should be `self.cycle = cycle([Keys.RIGHT, Keys.UP, Keys.LEFT, Keys.DOWN])`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T13:08:52.110",
"Id": "209441",
"ParentId": "209386",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "209391",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T19:16:32.480",
"Id": "209386",
"Score": "0",
"Tags": [
"python",
"beginner",
"selenium",
"2048"
],
"Title": "2048 Webgame bot"
} | 209386 |
<p>I am quite new in Python and I am starting my journey with sorting algorithms, PEP8 and the Zen of Python. So far i wrote a post <a href="https://codereview.stackexchange.com/questions/209361/bubble-sort-in-python">BubbleSort</a> and I drew conclusions and followed the advices. I implemented two methods with optimatization from <a href="https://en.wikipedia.org/wiki/Bubble_sort#Optimizing_bubble_sort" rel="nofollow noreferrer">Wikipedia</a>. I would ask for information about the current code, tests and directories.</p>
<ol>
<li>Is it possible to write tests more succinctly?</li>
<li>Should i make a docummentation with tests? ( or the specific name of the function is enough )</li>
<li>Is the code compatible with PEP8 and Zen of Python?</li>
<li>Is the code compatible with Python-style coding?</li>
<li>What should i change to avoid future problems with my code?</li>
<li>Should i add more options to functions for example: reverse, default options, exceptions? ( or its unnecessary in algorithms )</li>
<li>Should i add comparator? Should it be a class then? Can you give some advice?</li>
<li>Is my directory layout correct?</li>
<li>If you found something else in the text, try to give me this information.</li>
</ol>
<p>My directory looks like:</p>
<pre><code>Python:.
│
├───algorithms
│ └───sorting
│ bubble_sort.py
│ __init__.py
│
└───tests
└───algorithms
└───sorting
bubble_sort_test.py
__init__.py
</code></pre>
<p>bubble_sort.py</p>
<pre><code>import copy
def bubble_sort_v_one(container: object) -> object:
"""
Bubble sort with first optimization.
Description
----------
From wikipedia: inner loop can avoid looking
at the last (length − 1) items when running for the n-th time.
Performance cases:
Worst : O(n^2)
Average : O(n^2)
Best case : O(n)
Parameters
----------
container : Mutable container with comparable objects and structure
which has implemented __len__, __getitem__ and __setitem__.
Returns
-------
container : Sorted container
Examples
----------
>>> bubble_sort_v_one([7,1,2,6,4,2,3])
[1, 2, 2, 3, 4, 6, 7]
>>> bubble_sort_v_one(['a', 'c', 'b'])
['a', 'b', 'c']
"""
# setting up variables
container = copy.copy(container)
length = len(container)
changed = True
while changed:
changed = False
for i in range(length - 1):
if container[i] > container[i + 1]:
container[i], container[i + 1] = container[i + 1], container[i]
changed = True
length -= 1
return container
def bubble_sort_v_two(container: object) -> object:
"""
Bubble sort with second optimization.
Description
----------
From wikipedia: This allows us to skip over a lot of the elements,
resulting in about a worst case 50% improvement in comparison count.
Performance cases:
Worst : O(n^2) - 50%
Average : O(n^2)
Best case : O(n)
Parameters
----------
container : Mutable container with comparable objects and structure
which has implemented __len__, __getitem__ and __setitem__.
Returns
-------
container : Sorted container
Examples
----------
>>> bubble_sort_v_two([7,1,2,6,4,2,3])
[1, 2, 2, 3, 4, 6, 7]
>>> bubble_sort_v_two(['a', 'c', 'b'])
['a', 'b', 'c']
"""
# setting up variables
container = copy.copy(container)
length = len(container)
while length >= 1:
changed_times = 0
for i in range(1, length):
if container[i - 1] > container[i]:
container[i - 1], container[i] = container[i], container[i - 1]
changed_times = i
length = changed_times
return container
</code></pre>
<p>bubble_sort_test.py</p>
<pre><code>import unittest
from Algorithms.Sorting.bubble_sort import bubble_sort_v_one as bubble_one
from Algorithms.Sorting.bubble_sort import bubble_sort_v_two as bubble_two
class TestBubbleSortVOneAlgorithm(unittest.TestCase):
def test_bubble_sort_with_positive_numbers(self):
self.assertEqual(bubble_one([5, 5, 7, 8, 2, 4, 1]),
[1, 2, 4, 5, 5, 7, 8])
def test_bubble_sort_negative_numbers_only(self):
self.assertEqual(bubble_one([-1, -3, -5, -7, -9, -5]),
[-9, -7, -5, -5, -3, -1])
def test_bubble_sort_with_negative_and_positive_numbers(self):
self.assertEqual(bubble_one([-6, -5, -4, 0, 5, 5, 7, 8, 2, 4, 1]),
[-6, -5, -4, 0, 1, 2, 4, 5, 5, 7, 8])
def test_bubble_sort_same_numbers(self):
self.assertEqual(bubble_one([1, 1, 1, 1]), [1, 1, 1, 1])
def test_bubble_sort_empty_list(self):
self.assertEqual(bubble_one([]), [])
class TestBubbleSortVTwoAlgorithm(unittest.TestCase):
def test_bubble_sort_with_positive_numbers(self):
self.assertEqual(bubble_two([5, 5, 7, 8, 2, 4, 1]),
[1, 2, 4, 5, 5, 7, 8])
def test_bubble_sort_negative_numbers_only(self):
self.assertEqual(bubble_two([-1, -3, -5, -7, -9, -5]),
[-9, -7, -5, -5, -3, -1])
def test_bubble_sort_with_negative_and_positive_numbers(self):
self.assertEqual(bubble_two([-6, -5, -4, 0, 5, 5, 7, 8, 2, 4, 1]),
[-6, -5, -4, 0, 1, 2, 4, 5, 5, 7, 8])
def test_bubble_sort_same_numbers(self):
self.assertEqual(bubble_two([1, 1, 1, 1]), [1, 1, 1, 1])
def test_bubble_sort_empty_list(self):
self.assertEqual(bubble_two([]), [])
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>Should i add <code>bubble_sort</code> function so user can choose which version want to run easier?</p>
<pre><code>def bubble_sort(container: object, version : int = 1) -> object:
if version == 1:
bubble_sort_v_one(container)
elif version == 2:
bubble_sort_v_two(container)
else:
raise ValueError
</code></pre>
<p>What do you think about comparator and editing the function head to:</p>
<pre><code>def comparator(a: object, b: object) -> object:
return a - b
def bubble_sort_v_one(container: object, comparator=comparator) -> object:
</code></pre>
<p>and for sure the line for comparating the 2 variables should like like that:</p>
<pre><code>if comparator(container[i] , container[i + 1]) > 0:
</code></pre>
<p>Of course, the questions are not only about this code. I would like to know if this methodology in the future will help me write correct and clean code and will increase its functionality.</p>
<p>So my <code>bubble_sort.py</code> will look like:</p>
<pre><code>import copy
def comparator(a, b):
return a - b
def bubble_sort(container, version: int = 1, cmp=comparator):
if version == 1:
return bubble_sort_v_one(container, cmp)
elif version == 2:
return bubble_sort_v_two(container, cmp)
else:
raise ValueError
def bubble_sort_v_one(container, cmp):
"""
Bubble sort with first optimization.
Description
----------
From wikipedia : inner loop can avoid looking
at the last (length − 1) items when running for the n-th time.
Performance cases:
Worst : O(n^2)
Average : O(n^2)
Best : O(n)
Parameters
----------
container : Mutable container with comparable objects and structure
which has implemented __len__, __getitem__ and __setitem__.
cmp : Comparator default a - b > 0
Returns
-------
container : New sorted container,
Examples
----------
>>> bubble_sort_v_one([7,1,2,6,4,2,3])
[1, 2, 2, 3, 4, 6, 7]
>>> bubble_sort_v_one(['a', 'c', 'b'])
['a', 'b', 'c']
"""
# setting up variables
container = copy.copy(container)
length = len(container)
changed = True
while changed:
changed = False
for i in range(length - 1):
if cmp(container[i], container[i + 1]) > 0:
container[i], container[i + 1] = container[i + 1], container[i]
changed = True
length -= 1
return container
def bubble_sort_v_two(container, cmp):
"""
Bubble sort with second optimization.
Description
----------
From wikipedia: This allows us to skip over a lot of the elements,
resulting in about a worst case 50% improvement in comparison count.
Performance cases:
Worst : O(n^2) - 50%
Average : O(n^2)
Best : O(n)
Parameters
----------
container : Mutable container with comparable objects and structure
which has implemented __len__, __getitem__ and __setitem__.
cmp : Comparator default a - b > 0
Returns
-------
container : New sorted container,
Examples
----------
>>> bubble_sort_v_two([7,1,2,6,4,2,3])
[1, 2, 2, 3, 4, 6, 7]
>>> bubble_sort_v_two(['a', 'c', 'b'])
['a', 'b', 'c']
"""
# setting up variables
container = copy.copy(container)
length = len(container)
while length >= 1:
changed_times = 0
for i in range(1, length):
if cmp(container[i - 1], container[i]) > 0:
container[i - 1], container[i] = container[i], container[i - 1]
changed_times = i
length = changed_times
return container
</code></pre>
<p>and <code>bubble_sort_test.py</code></p>
<pre><code>import unittest
from Algorithms.Sorting.bubble_sort import bubble_sort
class TestBubbleSortVOneAlgorithm(unittest.TestCase):
def test_bubble_sort_with_positive_numbers(self):
self.assertEqual(bubble_sort([5, 5, 7, 8, 2, 4, 1]),
[1, 2, 4, 5, 5, 7, 8])
def test_bubble_sort_negative_numbers_only(self):
self.assertEqual(bubble_sort([-1, -3, -5, -7, -9, -5]),
[-9, -7, -5, -5, -3, -1])
def test_bubble_sort_with_negative_and_positive_numbers(self):
self.assertEqual(bubble_sort([-6, -5, -4, 0, 5, 5, 7, 8, 2, 4, 1]),
[-6, -5, -4, 0, 1, 2, 4, 5, 5, 7, 8])
def test_bubble_sort_with_positive_numbers_reverse(self):
self.assertEqual(bubble_sort([5, 5, 7, 8, 2, 4, 1],
cmp=lambda x, y: y - x),
[8, 7, 5, 5, 4, 2, 1])
def test_bubble_sort_negative_numbers_only_reverse(self):
self.assertEqual(bubble_sort([-1, -3, -5, -7, -9, -5],
cmp=lambda x, y: y - x),
[-1, -3, -5, -5, -7, -9])
def test_bubble_sort_with_negative_and_positive_numbers_reverse(self):
self.assertEqual(bubble_sort([-6, -5, -4, 0, 5, 5, 7, 8, 2, 4, 1],
cmp=lambda x, y: y - x),
[8, 7, 5, 5, 4, 2, 1, 0, -4, -5, -6])
def test_bubble_sort_same_numbers(self):
self.assertEqual(bubble_sort([1, 1, 1, 1]), [1, 1, 1, 1])
def test_bubble_sort_empty_list(self):
self.assertEqual(bubble_sort([]), [])
class TestBubbleSortVTwoAlgorithm(unittest.TestCase):
def test_bubble_sort_with_positive_numbers(self):
self.assertEqual(bubble_sort([5, 5, 7, 8, 2, 4, 1], version=2),
[1, 2, 4, 5, 5, 7, 8])
def test_bubble_sort_negative_numbers_only(self):
self.assertEqual(bubble_sort([-1, -3, -5, -7, -9, -5], version=2),
[-9, -7, -5, -5, -3, -1])
def test_bubble_sort_with_negative_and_positive_numbers(self):
self.assertEqual(bubble_sort([-6, -5, -4, 0, 5, 5, 7, 8, 2, 4, 1], version=2),
[-6, -5, -4, 0, 1, 2, 4, 5, 5, 7, 8])
def test_bubble_sort_with_positive_numbers_reverse(self):
self.assertEqual(bubble_sort([5, 5, 7, 8, 2, 4, 1], version=2,
cmp=lambda x, y: y - x),
[8, 7, 5, 5, 4, 2, 1])
def test_bubble_sort_negative_numbers_only_reverse(self):
self.assertEqual(bubble_sort([-1, -3, -5, -7, -9, -5], version=2,
cmp=lambda x, y: y - x),
[-1, -3, -5, -5, -7, -9])
def test_bubble_sort_with_negative_and_positive_numbers_reverse(self):
self.assertEqual(bubble_sort([-6, -5, -4, 0, 5, 5, 7, 8, 2, 4, 1],
version=2, cmp=lambda x, y: y - x),
[8, 7, 5, 5, 4, 2, 1, 0, -4, -5, -6])
def test_bubble_sort_same_numbers(self):
self.assertEqual(bubble_sort([1, 1, 1, 1], version=2), [1, 1, 1, 1])
def test_bubble_sort_empty_list(self):
self.assertEqual(bubble_sort([], version=2), [])
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>Which one is better and why? Of course I will accept all the imperfections on the chest.</p>
| [] | [
{
"body": "<p>Various things with no precise order:</p>\n\n<p><strong>Function names</strong></p>\n\n<p>Numbers are accepted in <a href=\"https://docs.python.org/3/reference/lexical_analysis.html#identifiers\" rel=\"nofollow noreferrer\">identifier</a> such as function names. Instead of having <code>my_func_v_one</code>, you could go for <code>my_func_v1</code>.</p>\n\n<p><strong>Less verbose tests</strong></p>\n\n<p>These comments are to be taken with a pinch of salt: some prefer their unit test to be as simple as possible, some prefer to consider them as code and apply the usual principles such as Don't repeat yourself.</p>\n\n<p>In order to make the tests more concise and easier to write, you could consider adding an helper method.</p>\n\n<p>Also, you could have a single class like this:</p>\n\n<pre><code>class TestBubbleSortAlgorithm(unittest.TestCase):\n\n def _test_sort(self, sorting_func, input_list, expected_list):\n self.assertEqual(sorting_func(input_list), expected_list)\n\n def test_bubble_sort_v1_with_positive_numbers(self):\n self._test_sort(bubble_sort_v1, [5, 5, 7, 8, 2, 4, 1], [1, 2, 4, 5, 5, 7, 8])\n\n def test_bubble_sort_v1_negative_numbers_only(self):\n self._test_sort(bubble_sort_v1, [-1, -3, -5, -7, -9, -5], [-9, -7, -5, -5, -3, -1])\n\n def test_bubble_sort_v1_with_negative_and_positive_numbers(self):\n self._test_sort(bubble_sort_v1, [-6, -5, -4, 0, 5, 5, 7, 8, 2, 4, 1], [-6, -5, -4, 0, 1, 2, 4, 5, 5, 7, 8])\n\n def test_bubble_sort_v1_same_numbers(self):\n self._test_sort(bubble_sort_v1, [1, 1, 1, 1], [1, 1, 1, 1])\n\n def test_bubble_sort_v1_empty_list(self):\n self._test_sort(bubble_sort_v1, [], [])\n\n def test_bubble_sort_v2_with_positive_numbers(self):\n self._test_sort(bubble_sort_v2, [5, 5, 7, 8, 2, 4, 1], [1, 2, 4, 5, 5, 7, 8])\n\n def test_bubble_sort_v2_negative_numbers_only(self):\n self._test_sort(bubble_sort_v2, [-1, -3, -5, -7, -9, -5], [-9, -7, -5, -5, -3, -1])\n\n def test_bubble_sort_v2_with_negative_and_positive_numbers(self):\n self._test_sort(bubble_sort_v2, [-6, -5, -4, 0, 5, 5, 7, 8, 2, 4, 1], [-6, -5, -4, 0, 1, 2, 4, 5, 5, 7, 8])\n\n def test_bubble_sort_v2_same_numbers(self):\n self._test_sort(bubble_sort_v2, [1, 1, 1, 1], [1, 1, 1, 1])\n\n def test_bubble_sort_v2_empty_list(self):\n self._test_sort(bubble_sort_v2, [], [])\n</code></pre>\n\n<p>Then you can use the fact that we have a sorting function we can trust to use it as a <a href=\"https://en.wikipedia.org/wiki/Test_oracle\" rel=\"nofollow noreferrer\">Test Oracle</a>.</p>\n\n<p>Then you can write something like:</p>\n\n<pre><code>class TestBubbleSortAlgorithm(unittest.TestCase):\n\n def _test_sort(self, sorting_func, input_list):\n expected_list = sorted(input_list)\n self.assertEqual(sorting_func(input_list), expected_list)\n\n def test_bubble_sort_with_positive_numbers(self):\n input_list = [5, 5, 7, 8, 2, 4, 1]\n self._test_sort(bubble_sort_v1, input_list)\n self._test_sort(bubble_sort_v2, input_list)\n\n def test_bubble_sort_negative_numbers_only(self):\n input_list = [-1, -3, -5, -7, -9, -5]\n self._test_sort(bubble_sort_v1, input_list)\n self._test_sort(bubble_sort_v2, input_list)\n\n def test_bubble_sort_with_negative_and_positive_numbers(self):\n input_list = [-6, -5, -4, 0, 5, 5, 7, 8, 2, 4, 1]\n self._test_sort(bubble_sort_v1, input_list)\n self._test_sort(bubble_sort_v2, input_list)\n\n def test_bubble_sort_same_numbers(self):\n input_list = [1, 1, 1, 1]\n self._test_sort(bubble_sort_v1, input_list)\n self._test_sort(bubble_sort_v2, input_list)\n\n def test_bubble_sort_empty_list(self):\n input_list = []\n self._test_sort(bubble_sort_v1, input_list)\n self._test_sort(bubble_sort_v2, input_list)\n</code></pre>\n\n<p>Or even:</p>\n\n<pre><code>class TestBubbleSortAlgorithm(unittest.TestCase):\n\n def _test_sort_single_func(self, sorting_func, input_list):\n expected_list = sorted(input_list)\n self.assertEqual(sorting_func(input_list), expected_list)\n\n def _test_sort_all_funcs(self, input_list):\n self._test_sort_single_func(bubble_sort_v1, input_list)\n self._test_sort_single_func(bubble_sort_v2, input_list)\n\n def test_bubble_sort_with_positive_numbers(self):\n input_list = [5, 5, 7, 8, 2, 4, 1]\n self._test_sort_all_funcs(input_list)\n\n def test_bubble_sort_negative_numbers_only(self):\n input_list = [-1, -3, -5, -7, -9, -5]\n self._test_sort_all_funcs(input_list)\n\n def test_bubble_sort_with_negative_and_positive_numbers(self):\n input_list = [-6, -5, -4, 0, 5, 5, 7, 8, 2, 4, 1]\n self._test_sort_all_funcs(input_list)\n\n def test_bubble_sort_same_numbers(self):\n input_list = [1, 1, 1, 1]\n self._test_sort_all_funcs(input_list)\n\n def test_bubble_sort_empty_list(self):\n input_list = []\n self._test_sort_all_funcs(input_list)\n</code></pre>\n\n<p>Also, as for the tests themselves, I wouldn't base my tests on type of numbers you have (positive, negative, etc) other criteria. For instance, I'd write the following tests:</p>\n\n<pre><code>class TestBubbleSortAlgorithm(unittest.TestCase):\n\n def _test_sort_single_func(self, sorting_func, input_list):\n expected_list = sorted(input_list)\n self.assertEqual(sorting_func(input_list), expected_list)\n\n def _test_sort_all_funcs(self, input_list):\n self._test_sort_single_func(bubble_sort_v1, input_list)\n self._test_sort_single_func(bubble_sort_v2, input_list)\n\n def test_bubble_sort_empty_list(self):\n input_list = []\n self._test_sort_all_funcs(input_list)\n\n def test_bubble_sort_one_element(self):\n input_list = [0]\n self._test_sort_all_funcs(input_list)\n\n def test_bubble_sort_same_numbers(self):\n input_list = [1, 1, 1, 1]\n self._test_sort_all_funcs(input_list)\n\n def test_bubble_sort_already_sorted(self):\n input_list = [1, 2, 3, 4]\n self._test_sort_all_funcs(input_list)\n\n def test_bubble_sort_reversed(self):\n input_list = [4, 3, 2, 1]\n self._test_sort_all_funcs(input_list)\n\n def test_bubble_sort_disorder_with_repetitions(self):\n input_list = [3, 5, 3, 2, 4, 2, 1, 1]\n self._test_sort_all_funcs(input_list)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T14:14:00.123",
"Id": "209527",
"ParentId": "209387",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T19:38:16.143",
"Id": "209387",
"Score": "6",
"Tags": [
"python",
"beginner",
"sorting",
"unit-testing",
"comparative-review"
],
"Title": "Bubble sort algorithms and unittest in Python"
} | 209387 |
<p>I created a 2 player Snake game from my original one player version. I am looking for some feedback on how I made it. I think I could use improvement when handling input (<code>Snake.handle</code>). Sometimes it feels like the input is not being read when I hit keys really fast.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Block {
constructor(x, y, w, h, col) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.col = col;
}
draw() {
ctx.fillStyle = "rgb" + this.col;
ctx.fillRect(this.x, this.y, this.w, this.h);
ctx.strokeRect(this.x, this.y, this.w, this.h);
}
}
class Snake {
constructor(x, y, w, h, col, col2, name, ins) {
this.bod = [];
this.h = h;
this.w = w;
this.name = name;
this.killed = false;
this.spd = 25;
this.vel = [0, 0];
this.col = col;
this.col2 = col2;
this.bod.push(new Block(x, y, w, h, col))
this.ins = ins;
}
win() {
ctx.textAlign = "center";
ctx.clearRect(0, 0, width, height);
ctx.font = "100px Oswald";
ctx.fillStyle = "rgb" + this.col;
ctx.fillText(this.name + " WINS!", width / 2, height / 2);
setTimeout(() => {
location.reload();
}, 1000)
}
draw() {
for (var x = 0; x < this.bod.length; x++) {
this.bod[x].draw();
}
}
move(tx, ty) {
this.bod[0].x += tx
this.bod[0].y += ty;
}
isBack(tx, ty) {
return this.bod[0].x + tx == this.bod[1].x && this.bod[0].y + ty == this.bod[1].y
}
grow(pos_x, pos_y) {
this.bod.push(new Block(pos_x, pos_y, this.w, this.h, this.col2));
}
handle(inp, ins) {
ins = ins || this.ins;
var old_vel = this.vel;
switch(inp) {
case ins[0]:
this.vel = [-this.spd, 0];
break;
case ins[1]:
this.vel = [0, -this.spd];
break;
case ins[2]:
this.vel = [this.spd, 0];
break;
case ins[3]:
this.vel = [0, this.spd]
break
default:
this.vel = old_vel;
}
if (this.bod.length > 2) {
if (this.isBack(this.vel[0], this.vel[1])) {
this.vel = old_vel
}
}
}
update() {
if (this.bod[0].x == food.x && this.bod[0].y == food.y) {
this.grow(food.x, food.y);
food.x = Math.floor(Math.random() * 19) * 25;
food.y = Math.floor(Math.random() * 19) * 25
}
for (var i = this.bod.length - 1; i > 0; i--){
this.bod[i].x = this.bod[i - 1].x;
this.bod[i].y = this.bod[i - 1].y;
}
this.move(this.vel[0], this.vel[1]);
if (this.bod[0].x > width - this.bod[0].w || this.bod[0].x < 0 || this.bod[0].y > height - this.bod[0].h || this.bod[0].y < 0 || this.isInside(this.bod[0])) {
this.killed = true;
}
}
isInside(obj) {
for (var i = 1; i < this.bod.length; i++) {
if (obj.x == this.bod[i].x && obj.y == this.bod[i].y) {
return true;
}
}
return false;
}
}
function init() {
canvas = document.getElementById("display");
ctx = canvas.getContext('2d');
width = canvas.width;
height = canvas.height;
time = 30;
key_state = [];
key_stat2 = [];
start = false;
ply1 = new Snake(Math.floor(Math.random() * 19) * 25, Math.floor(Math.random() * 19) * 25, 25, 25, "(25, 150, 25)", "(0, 255, 0)", "GREEN",[37, 38, 39, 40])
ply2 = new Snake(Math.floor(Math.random() * 19) * 25, Math.floor(Math.random() * 19) * 25, 25, 25, "(25, 25, 150)", "(0, 0, 255)", "BLUE", [65, 87, 68, 83]);
food = new Block(Math.floor(Math.random() * 19) * 25, Math.floor(Math.random() * 19) * 25, 25, 25, "(255, 0, 0)");
addEventListener("keydown", (e) => {
if (e.keyCode == 32) {
start = true;
}
else if (e.keyCode == 72) {
location.replace("/")
} else if ([37, 38, 39, 40].includes(e.keyCode)) {
key_state.push(e.keyCode);
} else if ([87, 65, 83, 68].includes(e.keyCode)) {
key_stat2.push(e.keyCode);
}
})
loop = setInterval(menu);
}
function showWinner(winner) {
clearInterval(frames);
setTimeout(() => {
winner.win();
}, 1000);
}
function parseSecs(t) {
if (isNaN(t)) {
return t;
}
var mins = Math.floor(t/60).toString();
var secs = (t%60).toString();
if (secs.length < 2) {
secs = "0" + secs;
}
if (mins.length < 2) {
mins = "0" + mins;
}
return mins + ":" + secs;
}
function menu() {
ctx.clearRect(0, 0, width, height);
ctx.font = "75px Oswald"
ctx.textAlign = "center";
ctx.fillStyle = "rgb(0, 0, 255)";
ctx.fillText("Basically Snake", width/2, height * 1/3);
ctx.font = "25px Oswald";
ctx.fillText("wasd for blue | arrow keys for green", width / 2, height * 2/4);
ctx.fillText("space to start", width/2, height * 2/3)
if (start) {
clearInterval(loop);
timing = setInterval(() => {
time -= 1;
}, 1000)
frames = setInterval(frame, 100);
}
}
function drawAll() {
ctx.clearRect(0, 0, width, height);
ctx.font = "25px Oswald";
ctx.fillStyle = "rgb" + ply1.col;
ctx.textAlign = "left";
ctx.fillText(ply1.name + ": " + ply1.bod.length, 25, 25);
ctx.textAlign = "center";
ctx.fillStyle = "rgb(0, 255, 0)";
ctx.fillText("Time: " + parseSecs(time), width / 2, 25)
ctx.fillStyle = "rgb" + ply2.col;
ctx.textAlign = "right";
ctx.font = "25px Oswald";
ctx.fillText(ply2.name + ": " + ply2.bod.length, width - 25, 25);
ply1.draw();
ply2.draw();
food.draw();
}
function frame() {
ply1.update();
ply2.update();
ply1.handle(key_state[0])
key_state.pop();
ply2.handle(key_stat2[0]);
key_stat2.pop();
ply2.handle()
drawAll();
if (ply2.killed) {
showWinner(ply1);
} else if (ply1.killed) {
showWinner(ply2);
}
if (time < 1) {
clearInterval(timing);
time = "OVERTIME";
if (ply1.bod.length > ply2.bod.length) {
showWinner(ply1);
} else if (ply2.bod.length > ply1.bod.length) {
showWinner(ply2);
}
}
}
window.onload = init;</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css?family=Oswald');
html {
height: 100%;
display: grid;
}
body {
color: #0f0;
margin: auto;
background-color: black
}
#display {
border: 3px solid white;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="display" width="500" height="500"></canvas></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<h2>General Feedback</h2>\n\n<p>This code looks quite decent. Most of the functions and methods aren’t excessively long. Some lines are terminated with a semi-colon but others aren’t. It is best to be consistent. </p>\n\n<p>The code uses some <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged 'ecmascript-6'\" rel=\"tag\">ecmascript-6</a> AKA ES-6 features like classes and arrow functions so other ES-6 features could be used as well. See below for more details. </p>\n\n<h2>Targeted Feedback</h2>\n\n<p>The two lines in the snake constructor that setup the array of property <code>bod</code> and push a block into it could be combined into a single statement. </p>\n\n<p>An ES-6 <code>for...of</code> loop could be used to simplify <code>Snake::draw()</code></p>\n\n<blockquote>\n<pre><code>for (var x = 0; x < this.bod.length; x++) {\n this.bod[x].draw();\n}\n</code></pre>\n</blockquote>\n\n<p>To this:</p>\n\n<pre><code>for (const segment of this.bod) {\n segment.draw();\n}\n</code></pre>\n\n<p>It seems a bit beyond the scope of the Snake class to set a timer to call<code>window.reload</code> from the <code>win</code> method. It seems more appropriate to have that handled by the <code>showWinner()</code> function. </p>\n\n<p>For a small SPA it likely doesn’t matter but some variables are referenced globally- e.g. <code>start</code>, <code>loop</code>, <code>frames</code>, <code>ctx</code>, etc. In a larger application it would be wise to at least declare them with the <code>var</code> or <code>let</code> keyword and wrap everything in an IIFE or module. </p>\n\n<p>The arrow function below could be simplified to a single line:</p>\n\n<blockquote>\n<pre><code>timing = setInterval(() => {\n time -= 1;\n}, 1000)\n</code></pre>\n</blockquote>\n\n<p>To the following:</p>\n\n<pre><code>timing = setInterval(_ => time -= 1, 1000);\n</code></pre>\n\n<p>Notice that the empty parameters list was replaced by a single unused parameter i.e. <code>_</code> </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-27T15:58:20.857",
"Id": "225041",
"ParentId": "209392",
"Score": "3"
}
},
{
"body": "<p>I first played a few rounds of the game and I immediately liked it.</p>\n\n<p>The screen motion is smooth, the colors have a nice contrast, and I liked that it is even possible to play snake in single-player mode.</p>\n\n<p>On the start screen, the icing on the cake would be if the wasd text would be in blue, the arrow keys would be in green and the neutral text would be in a neutral color. This would emphasize the player colors even more.</p>\n\n<p>When I played and my snake was 2 cells long, I could make a u-turn, which is not possible with larger snakes. This feels a little inconsistent, and traditional snake games don't allow u-turns at all.</p>\n\n<p>The initial positions of the snakes can be in the very top row where the status is displayed. This is confusing since there is a conflict about what to show on top. The snakes should not be allowed to be in the very top row at all.</p>\n\n<p>As the green player, I can run over the blue snake in its starting position without getting penalized. Is that intentional? I had expected that my snake would die whenever it runs into an obstacle, or anything else that is not the red apple.</p>\n\n<p>When the snake currently goes to the right, and I press Up, Right very quickly, I expect that the snake goes one step up and then turns right. Depending on the exact timing of when the next step is taken, this either works as expected, or the Right key is silently swallowed. This inconsistency makes the game a bit unpleasant.</p>\n\n<p>So much for the game play. All in all, what you have right now already feels good, and the fine points that I mentioned above can probably added without investing too much time and effort.</p>\n\n<p>Regarding your code, I will go from the top to the bottom and just add remarks to everything that I find:</p>\n\n<pre><code>class Block {\n constructor(x, y, w, h, col) {\n</code></pre>\n\n<p>The meaning of the first variables was immediately clear to me. I thought that <code>col</code> would mean <code>column</code>, but that was wrong. Therefore, whenever an abbreviation is ambiguous, it's better to use the full name instead, in this case <code>color</code>.</p>\n\n<pre><code> ctx.fillStyle = \"rgb\" + this.col;\n</code></pre>\n\n<p>From this line I infer that <code>col</code> should be something like <code>(0,0,255)</code>, including the parentheses. That's not the standard form of a color that most programmers would expect. It would be more flexible if the color were specified as <code>rgb(0,0,255)</code> instead. This would allow the color to be specified as <code>#0000ff</code> or <code>#00f</code> or <code>blue</code>, or even with alpha channel.</p>\n\n<pre><code>class Snake {\n constructor(x, y, w, h, col, col2, name, ins) {\n</code></pre>\n\n<p>What is <code>col</code> and <code>col2</code>? It would be better to name them <code>headColor</code> and <code>tailColor</code>. Then I would not have to guess anything. Same for <code>ins</code>. My first guess is that it means <code>insert</code>, but that doesn't make sense here.</p>\n\n<pre><code> this.bod = [];\n</code></pre>\n\n<p>This should be <code>body</code> instead.</p>\n\n<pre><code> this.spd = 25;\n</code></pre>\n\n<p>This should be <code>speed</code> instead, or whatever you mean by <code>spd</code>.</p>\n\n<pre><code> this.vel = [0, 0];\n</code></pre>\n\n<p>This should be <code>velocity</code>.</p>\n\n<pre><code> win() {\n ctx.textAlign = \"center\";\n</code></pre>\n\n<p>The abbreviation <code>ctx</code> usually means <code>context</code>. This is a very abstract term. You can probably find a more concrete term, like <code>field</code>.</p>\n\n<pre><code> ctx.clearRect(0, 0, width, height);\n</code></pre>\n\n<p>Compared to your other variable names, <code>width</code> and <code>height</code> are really long. But they are immediately understandable, therefore they are not <em>too</em> long, but exactly right.</p>\n\n<pre><code> move(tx, ty) {\n</code></pre>\n\n<p>What does the <code>t</code> mean here? I usually call these variables <code>dx</code> and <code>dy</code>, and they are pronounced delta-x and delta-y.</p>\n\n<pre><code> update() {\n if (this.bod[0].x == food.x && this.bod[0].y == food.y) {\n this.grow(food.x, food.y);\n food.x = Math.floor(Math.random() * 19) * 25;\n food.y = Math.floor(Math.random() * 19) * 25\n }\n</code></pre>\n\n<p>The food should not appear on either of the snakes. Therefore you need to generate a food position, see if the space is empty, and if it is not, try again and again, until you succeed.</p>\n\n<pre><code> ctx = canvas.getContext('2d');\n</code></pre>\n\n<p>Ah, ok, since <code>ctx</code> is called <code>Context</code> by the Canvas, that name is perfect. I didn't know that when I did read the code further above.</p>\n\n<pre><code> ply1 = new Snake(Math.floor(Math.random() * 19) * 25, Math.floor(Math.random() * 19) * 25, 25, 25, \"(25, 150, 25)\", \"(0, 255, 0)\", \"GREEN\",[37, 38, 39, 40])\n ply2 = new Snake(Math.floor(Math.random() * 19) * 25, Math.floor(Math.random() * 19) * 25, 25, 25, \"(25, 25, 150)\", \"(0, 0, 255)\", \"BLUE\", [65, 87, 68, 83]);\n food = new Block(Math.floor(Math.random() * 19) * 25, Math.floor(Math.random() * 19) * 25, 25, 25, \"(255, 0, 0)\");\n</code></pre>\n\n<p>The expression <code>Math.floor(Math.random() * 19)</code> appears so often and always means the same, therefore you should write a new function called <code>randomX()</code> or <code>randomY()</code>.</p>\n\n<pre><code> ctx.fillStyle = \"rgb\" + ply1.col;\n</code></pre>\n\n<p>In chess, a <em>ply</em> is a half-move. You should rather write <code>player</code> instead.</p>\n\n<p>All in all, you structured your code quite well.</p>\n\n<p>One other thing that I noticed is that you use the number 25 excessively. It is usually a good idea to have two separate coordinate systems: one for the game field (0..18, 0..18), and one for the screen. The 25 should only appear in the screen coordinates since they have nothing to do with the game by itself. If you do this correctly, you can scale the game by just changing a single number in the code. There should be these constants and conversion functions:</p>\n\n<pre><code>// Game coordinates\nconst fieldWidth = 19;\nconst fieldHeight = 19;\n\n// Screen coordinates\nconst cellWidth = 25;\nconst cellHeight = 25;\n\nfunction fieldToScreenX(fieldX) {\n return fieldX * cellWidth;\n}\n\nfunction screenToFieldX(screenX) {\n return Math.floor(screenX / cellWidth);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-27T21:11:33.887",
"Id": "225062",
"ParentId": "209392",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "225062",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T21:51:22.190",
"Id": "209392",
"Score": "8",
"Tags": [
"javascript",
"object-oriented",
"ecmascript-6",
"canvas",
"snake-game"
],
"Title": "Two player snake game"
} | 209392 |
<p>This is pretty much one of my first programs that I have created in Java and I just wanted to ask if anyone sees some obvious errors or mistakes I made.</p>
<p>The purpose of this program is to sort numbers given by a user using an algorithm.</p>
<p>First off, the program gets an input in form of <code>int</code>s from the user, I have used a popup here, and than creates an array <code>arr1</code> with that size.
After that, another popup opens that asks the user for the 1st number he wants to sort. Then the 2nd, 3rd, etc, until the array has been filled with <code>int</code>s.</p>
<p>The array gets transferred into the sorting algorithm which, surprise, sorts the numbers into a different array <code>arr2</code>.</p>
<p>This array then gets passed into a method that takes a static frame and puts a text field with the numbers (in correct order) onto it. [+ 1 close and 1 repeat button]</p>
<p>If the repeat method (<code>buttonRetry.addActionListener.actionPerformed</code>) is called / the button is pressed, the frame gets "cleaned" (<code>main_frame.getContentPane().removeAll();</code>) and the main() method is called again.</p>
<p>Is it possible to make the process of this happening (getting input from the user and sorting that input) faster and do you have any additional advice about what and how I did this (Noob errors, graphical tips, etc.).</p>
<p>Here is the code :</p>
<pre><code>import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class AWTCounter extends JFrame {
public static int[] arr1;
public static JFrame frame = new JFrame("Super Simple Sorting Program");
public static JFrame main_frame = new JFrame("Super Simple Sorting Program");
public void main()
{
String input_1 = JOptionPane.showInputDialog(frame, "How many numers do you want to sort with SSSP ?");
if (input_1 == null) {dispose(); System.exit(0);}
int checksum = Integer.parseInt(input_1);
arr1 = new int[checksum];
int logNumber = 0;
int debug = checksum;
checksum = 0;
while (checksum <= debug-1)
{
logNumber++;
String input_2 = JOptionPane.showInputDialog(frame, "Please enter your " + logNumber + " . number.");
int member = Integer.parseInt(input_2);
arr1 [checksum] = member ;
checksum++;
}
int[] arr2 = doSelect(arr1);
print(arr2);
}
public int[] doSelect(int[] arr)
{
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
if (arr[j] < arr[index])
index = j;
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
return arr;
}
public void print(int[] arr2)
{
JTextField t2;
t2 = new JTextField("Here are your sorted numbers : " + Arrays.toString(arr2));
main_frame.add(t2, BorderLayout.NORTH);
JButton buttonEnd = new JButton("Close apllication");
main_frame.add(buttonEnd, BorderLayout.CENTER);
JButton buttonRetry = new JButton("Try again !");
main_frame.add(buttonRetry, BorderLayout.SOUTH);
main_frame.setLayout(new FlowLayout());
main_frame.setSize(600,300);
main_frame.setVisible(true);
buttonEnd.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
dispose();
System.exit(0);
}
});
buttonRetry.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
main_frame.getContentPane().removeAll();
main();
}
});
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T20:22:10.647",
"Id": "456635",
"Score": "2",
"body": "For your first program this is fine. However as you learn more about Java you'll find that [Swing is not thread safe.](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html) You should be using the EDT to update GUI components, and you'll need to learn multi-threading for that. I recommend [Brian Goetz's book, Java Concurrency in Practice.](https://jcip.net/)"
}
] | [
{
"body": "<p>Im impressed that you used selection sort. The standard bubble sort method would be slower. Have a look at the bubble sort method anyway.</p>\n\n<pre><code>int n = arr.length, r;\nfor (int i = 0; i < n; i++) \n{\n for (int (j = i + 1); j < n; j++) \n {\n if (arr[i] > arr[j]) \n {\n r = arr[i];\n arr[i] = arr[j];\n arr[j] = r;\n }\n }\n}\n</code></pre>\n\n<p>You could also have used the default <code>Arrays.sort</code> method</p>\n\n<pre><code>Arrays.sort(arr);\n</code></pre>\n\n<p>You are creating an applet. In this case, it would probably be good to declare the main method as <code>static</code></p>\n\n<p>When you are importing the packages, why have you imported the individual classes <em>after</em> importing them by wildcard character '*'; There is no need for it.\nThat is redundant and the computer wastes time re-importing and garbage-collecting. Just do:</p>\n\n<pre><code>import java.util.*;\nimport java.awt.*;\nimport java.awt.event.*; \nimport javax.swing.*;\n</code></pre>\n\n<p>Also, printing mistake here:</p>\n\n<pre><code>String input_1 = JOptionPane.showInputDialog(frame, \"How many numbers do you want to sort with SSSP ?\");\n</code></pre>\n\n<p>Consider setting bounds to the buttons and text boxes in your mainframes, to make the locations more exact. That way, it will be easier to add a new GUI component to the window when you want to add it. \nThe command goes:\n<code><name of object>.setBounds(//x-axis from left, //y-axis from top, //width, //height)</code>\nFor example:</p>\n\n<pre><code>t2 = new JTextField(\"Here are your sorted numbers : \" + Arrays.toString(arr2));\nt2.setBounds(20, 40, 75, 10);\nmain_frame.add(t2);\n\nJButton buttonEnd = new JButton(\"Close application\");\nt2.setBounds(95, 40, 75, 10);\nmain_frame.add(buttonEnd);\n\nJButton buttonRetry = new JButton(\"Try again !\");\nt2.setBounds(180, 40, 75, 10);\nmain_frame.add(buttonRetry);\n</code></pre>\n\n<p>WHY have you named your class <code>AWTCounter</code>? That makes me think you are counting numbers with certain properties or words in a sentence. Won't <code>AWTSorter</code> be better?</p>\n\n<p>Great program though, especially if it's your first!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T12:18:35.527",
"Id": "456676",
"Score": "0",
"body": "@greybeard yelp looks like I've done a mistake."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T13:29:05.573",
"Id": "233542",
"ParentId": "209397",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "233542",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T23:32:44.833",
"Id": "209397",
"Score": "3",
"Tags": [
"java",
"beginner",
"algorithm",
"sorting",
"swing"
],
"Title": "Sorting an array of numbers in Java with an algorithm"
} | 209397 |
<p>I just completed <a href="https://projecteuler.net/problem=81" rel="nofollow noreferrer">Project Euler Problem 81</a> in Haskell:</p>
<blockquote>
<p>In the 5 by 5 matrix below,</p>
<pre><code>131 673 234 103 18
201 96 342 965 150
630 803 746 422 111
537 699 497 121 956
805 732 524 37 331
</code></pre>
<p>the minimal path sum from the top left to
the bottom right, by only moving to the right and down, is </p>
<pre><code>131 → 201 → 96 → 342 → 746 → 422 → 121 → 37 → 331
</code></pre>
<p>and is equal to 2427.</p>
<p>Find the minimal path sum, in <a href="https://projecteuler.net/project/resources/p081_matrix.txt" rel="nofollow noreferrer"><code>matrix.txt</code></a>, a 31K text file containing a 80 by 80 matrix,
from the top left to the bottom right by only moving right and down.</p>
</blockquote>
<p>I'm looking for feedback on a few specific aspects, but I appreciate general feedback and style suggestions as well. The raw code is available <a href="https://gitlab.com/snippets/1788791/raw" rel="nofollow noreferrer">here</a>. The program input is available <a href="https://projecteuler.net/project/resources/p081_matrix.txt" rel="nofollow noreferrer">here</a>; the program needs to be run in the same folder as the input file.</p>
<p>The solution has two main parts:</p>
<ol>
<li>Reading a CSV file containing an 80x80 grid of integers into an array</li>
<li>Traversing the array to accumulate the minimal path sum</li>
</ol>
<hr />
<pre><code>{-|
file: p081.hs
title: Path sum: two ways
date: December 9, 2018
link: <https://projecteuler.net/problem=81>
-}
{-# LANGUAGE OverloadedStrings #-}
import Control.Arrow (first, (&&&), (***))
import Control.Monad (join, liftM, mapM)
import Data.Array (Array, Ix, array, bounds, (!))
import Data.Function (on)
import Data.Ix (inRange)
import Data.List (groupBy)
import Data.Maybe (fromJust)
import Data.Text (Text)
import qualified Data.Text as Text (lines, null, splitOn)
import qualified Data.Text.IO as TextIO (readFile)
import Data.Text.Read (decimal)
type Matrix a = Array (Int, Int) a
-- the shape of a matrix stored in a space-separated text file
textMatrixShape :: Text -> (Int, Int)
textMatrixShape = (length &&& length . Text.splitOn "," . head) . Text.lines
-- map over a monomorphic 2-tuple
mapTuple :: (a -> b) -> (a, a) -> (b, b)
mapTuple = join (***)
textMatrixBounds :: Text -> ((Int, Int), (Int, Int))
textMatrixBounds = (,) (0,0) . mapTuple (subtract 1) . textMatrixShape
-- from <https://hackage.haskell.org/package/either-5.0.1>
rightToMaybe :: Either a b -> Maybe b
rightToMaybe = either (const Nothing) Just
textMatrixElements :: Text -> Maybe [Int]
textMatrixElements = rightToMaybe
. fmap (map fst)
. mapM decimal
. concatMap (Text.splitOn ",")
. Text.lines
grid :: (Int, Int) -> [(Int, Int)]
grid (m, n) = [(i, j) | i <- [0..m - 1], j <- [0..n - 1]]
-- textMatrixAssocs :: Text -> Maybe [((Int, Int), Int)]
-- textMatrixAssocs t = liftM (zip ((grid . textMatrixShape) t)) (textMatrixElements t)
textMatrixAssocs :: Text -> Maybe [((Int, Int), Int)]
textMatrixAssocs = uncurry fmap . first zip
. (grid . textMatrixShape &&& textMatrixElements)
-- textMatrix :: Text -> Maybe (Matrix Int)
-- textMatrix t = liftM (array (textMatrixBounds t)) (textMatrixAssocs t)
textMatrix :: Text -> Maybe (Matrix Int)
textMatrix = uncurry fmap . first array . (textMatrixBounds &&& textMatrixAssocs)
rightAndDown :: Num a => Matrix a -> ((Int, Int), a) -> [((Int, Int), a)]
rightAndDown m (i, s) = [(i', s + m ! i')
| i' <- [fmap (+ 1) i, first (+ 1) i]
, inRange (bounds m) i']
-- | Blackbird combinator
(...) :: (c -> d) -> (a -> b -> c) -> a -> b -> d
(...) = (.) . (.)
infix 8 ...
updateFrontier :: (Num a, Ord a) => Matrix a -> [((Int, Int), a)] -> [((Int, Int), a)]
updateFrontier = map minimum . groupBy ((==) `on` fst) ... concatMap . rightAndDown
minimalPathSum :: (Num a, Ord a) => Matrix a -> a
minimalPathSum m = go [((0, 0), m ! (0, 0))]
where
go f = case f' of
[] -> (minimum . map snd) f
_ -> go f'
where
f' = updateFrontier m f
p081 :: IO Int
p081 = do
t <- TextIO.readFile "p081_matrix.txt"
return (minimalPathSum . fromJust . textMatrix $ t)
main :: IO ()
main = do
print =<< p081
</code></pre>
<h1>Questions</h1>
<p>I tried to use a point-free style wherever I could. Are there more elegant ways to do this? Is it too obscure?</p>
<p>I used <code>Text</code> and <code>Array</code> for performance reasons. Are there any ways that I could further improve performance without re-writing the program?</p>
<p>In the first part, the file is read using <code>Data.Text.IO.readFile</code>. The shape of the text matrix is estimated using <code>TextMatrixShape</code>, which is used to determine the bounds of the array in <code>TextMatrixBounds</code>. This is not safe, as the number of elements in each line of the text file is not guaranteed to be the same in every line in general. Is there a better way to get the shape of the array?</p>
<p>The elements are extracted from the text file using <code>textMatrixElements</code> and converted into an association list in <code>textMatrixAssocs</code>. I'm worried that this might be an inefficient way to build an array, as the array appears to me to be traversed multiple times. I would greatly appreciate it if someone could shed some light on this.</p>
<p>What of my use of <code>Maybe</code> in my <code>text*</code> functions? Is this appropriate?</p>
<p>In <code>textMatrixElements</code>, I use the decimal reader from <code>Data.Text.Read</code> to convert text values into integers. Is there a nice way to make this function more polymorphic?</p>
<p>In the second part, I accumulate the minimum path sum to each point in a frontier, which is an association list of array indices and path sums. In <code>rightAndDown</code>, I construct a list of next moves from a frontier element. For every next move, I'm checking whether the index is in the bounds of the matrix <code>m</code>. Is this wasterful?</p>
<p>Note that I try to solve Project Euler problems without external dependencies, and I'm interested in learning how to do things in the general case, not just to solve this particular problem. I want to hardcode as little as possible.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T07:17:03.777",
"Id": "404741",
"Score": "2",
"body": "Point free is cute, but only when it adds clarity. `updateFrontier` pushes that boundary."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T23:51:56.713",
"Id": "209398",
"Score": "2",
"Tags": [
"programming-challenge",
"array",
"haskell",
"graph",
"pathfinding"
],
"Title": "Project Euler #81 in Haskell: minimal path sum through a matrix"
} | 209398 |
<p>I have a too large <code>data.txt</code> file containing data as follows:</p>
<pre><code>a = line0
line1
line2
€
b = line0
line1
line2
€
...
z = line0
line1
</code></pre>
<p>I am still beginner with java, I wrote this code to split the <code>data.txt</code> into multiple <code>.txt</code> files named <code>a.txt , b.txt etc...</code> it splits the <code>data.txt</code> at each <code>€\n</code> character.</p>
<p>It works perfectly, but it is so slow, I noticed, as if it reads everything at once and makes its mission, then at once the result .txt files are created and showed at once in the destination folder.</p>
<p>How could I make my code faster, for example when it is finished with the first part then it should create the result a.txt file immediatly then the second, third and so on...
Thank in advance</p>
<pre><code>import java.util.*;
import java.io.File;
import java.io.IOException;
import java.io.*;
public class Main
{
public static void main(String[] args)
{
File file = new File("/path/path2/file.txt");
try{
Scanner scanner = new Scanner(file);
String str = "";
while(scanner.hasNext()){
str+=scanner.nextLine()+"\n";
}
String charac = "€";
String end = "end of file";
for(int i = 0; i < (str.split(charac).length)-1; i++){
String name = str.split(charac)[i].split(" = ")[0];
String out= "/path/path2/path3/Folder/"+name+".txt";
FileWriter fw = new FileWriter(out);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(str.split(charac)[i]+"\n"+end);
bw.close();
}
System.out.println("Splitting is finished");
}
catch(Exception e){}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T08:38:35.757",
"Id": "404746",
"Score": "0",
"body": "Your program is slow because it load the full file in memory before splitting it (`str+=scanner.nextLine()+\"\\n\";`).\n\nYou can do the split inside the first loop (where your are reading the file)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T10:38:34.557",
"Id": "404768",
"Score": "0",
"body": "What do you mean exactly, should I move the while block with its statement str+=scanner.nextLine()+\"\\n\"; into the for-loop as first statement?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T11:18:29.873",
"Id": "404770",
"Score": "0",
"body": "you should move the whole splitting logic inside the first loop `while(scanner.hasNext())`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T23:06:10.407",
"Id": "405923",
"Score": "0",
"body": "and use a StringBuilder object rather than string concatenation"
}
] | [
{
"body": "<p>As said in the comment, you program is slow because you load the full file in memory. To change that you should keep only your first loop where you read but also write and split into files.</p>\n\n<pre><code>while(scanner.hasNext()){\n str+=scanner.nextLine()+\"\\n\";\n if ( mustSplit(str) ) {\n writeToAnotherFile(str); \n str = \"\";\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T11:20:40.753",
"Id": "209429",
"ParentId": "209399",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-10T23:56:56.263",
"Id": "209399",
"Score": "1",
"Tags": [
"java",
"performance",
"file"
],
"Title": "Java splitting too large text file enhance performance"
} | 209399 |
<p>Can somebody review the code and provide suggestions on where I can improve on the code like use of better data structure etc.</p>
<p>Input: {1,7,2,8,3,6}, 9</p>
<p>Output: [0, 3] [1, 2] [4, 5]</p>
<pre><code>public class TwoSumExactAll {
public static void main(String[] args) {
int[] nums1 = {1,7,2,8,3,6};
for (List<Integer> list : twoSumExactWithList(nums1,9)) {
System.out.println(list);
}
}
public static ArrayList<List<Integer>> twoSumExactWithList(int[] nums,int target) {
HashMap<Integer,Integer> map = new HashMap<Integer, Integer>();
ArrayList<List<Integer>> outerList = new ArrayList<List<Integer>>();
ArrayList<Integer> innerList=null;
int complement;
for(int i=0;i<nums.length;i++) {
complement = target-nums[i];
if(map.containsKey(complement)) {
innerList = new ArrayList<Integer>();
innerList.add(map.get(complement));
innerList.add(i);
outerList.add(innerList);
}else {
map.put(nums[i], i);
}
}
return outerList;
}
}
</code></pre>
| [] | [
{
"body": "<p>I guess that the relevant piece of code is the <code>twoSumExactWithList</code> method and for now I will ignore the rest... </p>\n\n<p>I think that depending on the context, e.g. the principles used in the project that you intent to use, this code you could either fully embrace collections or stick to arrays... but your code does a combo of both where the arguments are naked arrays and the returns uses collections... so please choose between the two. </p>\n\n<p>If you choose arrays a possible return type is <code>int[][]</code> where one of the two dimensions is 2. representing first vs second index of the pair. In practice <code>int[2][]</code> is potentially more efficient than <code>int[][2]</code> but perhaps the Jit may make it irrelevant. Perhaps you could have a IntPair[] where <code>IntPair</code> is a pair of ints struct-like class.</p>\n\n<p>If you choose collections... then the arguments should be <code>List<Integer> nums, int target</code>. The result is kind-of fine... but don't commit to return an <code>ArrayList</code> but rather a <code>List</code>; don't give any details on the implementation that are not necessary. To encode the index pair, consider the use of a custom class <code>IntPair</code> again... List is correct but seems a bit overkill considering that we know is always two and exactly two elements.</p>\n\n<p>As for the method body... The varible types should be a general as they can be... so <code>map</code>'s type should be <code>Map<Integer, Integer></code> rather than <code>HashMap<...></code>, <code>outerList</code>'s should be <code>List</code> rather than <code>ArrayList</code> and so forth...</p>\n\n<p>I would declare <code>complement</code> within the loop as it is not used outside of it and is rewritten at every iteration. <code>innerList</code> would go within the if within the for.</p>\n\n<p>Whenever possible I would declare variables as <code>final</code> to give an extra hint to the compiler/optimizer that indeed these are not going to be changed... eg. <code>final int[] nums, final int target</code>, <code>final Map<Integer, Integer> map</code>, <code>final int complement</code>.</p>\n\n<p>I would rename <code>map</code> to something a bit more informative as to what it contains...\nso perhaps <code>indexByNumValue</code>?</p>\n\n<p>I think your code would read and look much better with some additional spaces e.g.:</p>\n\n<p><code>List<Integer> innerList=null;</code> to <code>List<Integer> innerList = null;</code>.</p>\n\n<p><code>for(int i=0;i<nums.length;i++) {</code> to <code>for (int i = 0; i < nums.length; i++) {</code>.</p>\n\n<p><code>}else {</code> to <code>} else {</code>.</p>\n\n<p><code>if(</code> to <code>if (</code>.</p>\n\n<p><code>nums,int</code> to <code>nums, int</code>.</p>\n\n<p>etc...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T05:34:05.973",
"Id": "209414",
"ParentId": "209400",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T00:12:27.437",
"Id": "209400",
"Score": "3",
"Tags": [
"java",
"k-sum"
],
"Title": "Printing all the combination of indexes for 2 sum exact outcome"
} | 209400 |
<p>This implementation seems to work. I would love to get any suggestions / comments on how this code could be improved. Are there any potential memory management issues? Any additional methods that would be useful (also, from educational point of view) to implement? Thank you!</p>
<p><strong>Stack.hpp</strong></p>
<pre><code>#ifndef STACK_H
#define STACK_H
#include <iostream>
#include <memory>
#include <vector>
#include <stdexcept>
class Stack {
private:
struct Node {
int val;
// To get min and max value of stack in O(1):
int maxVal = std::numeric_limits<int>::min();
int minVal = std::numeric_limits<int>::max();
};
std::vector<Node> currStack;
public:
int size() const { return currStack.size(); }
bool empty() const { return currStack.empty(); }
void pop() { currStack.pop_back(); }
void push(int val);
int top() const; // O(1)
int min() const; // O(1)
int max() const; // O(1)
};
#endif /* STACK_H */
</code></pre>
<p><strong>Stack.cpp</strong></p>
<pre><code>#include "Stack.hpp"
void Stack::push(int val) {
Node tempNode;
tempNode.val = val;
if (this->empty()) {
tempNode.minVal = val;
tempNode.maxVal = val;
} else {
tempNode.minVal = std::min(currStack.back().minVal, val);
tempNode.maxVal = std::max(currStack.back().maxVal, val);
}
currStack.push_back(tempNode);
}
int Stack::top() const {
if (currStack.empty()) {
throw std::out_of_range ("Stack is empty");
}
return currStack.back().val;
}
int Stack::min() const {
if (currStack.empty()) {
throw std::out_of_range ("Stack is empty");
}
return currStack.back().minVal;
}
int Stack::max() const {
if (currStack.empty()) {
throw std::out_of_range ("Stack is empty");
}
return currStack.back().maxVal;
}
</code></pre>
<p><strong>main.cpp</strong></p>
<pre><code>#include "Stack.hpp"
int main() {
// Stack init
Stack myStack;
std::cout << "Empty? " << myStack.empty() << "\n";
std::cout << "Size: " << myStack.size() << "\n";
try {
std::cout << "Top: " << myStack.top() << "\n";
std::cout << "Min: " << myStack.min() << "\n";
std::cout << "Max: " << myStack.max() << "\n";
}
catch (const std::out_of_range& e) {
std::cout << "Out of range error. " << e.what() << "\n";
}
std::cout << "Push some integers: \n";
myStack.push(5);
myStack.push(3);
myStack.push(7);
std::cout << "Empty? " << myStack.empty() << "\n";
std::cout << "Size: " << myStack.size() << "\n";
try {
std::cout << "Top: " << myStack.top() << "\n";
std::cout << "Min: " << myStack.min() << "\n";
std::cout << "Max: " << myStack.max() << "\n";
}
catch (const std::out_of_range& e) {
std::cout << "Out of range error. " << e.what() << "\n";
}
std::cout << "Pop some integers: \n";
myStack.pop();
std::cout << "Empty? " << myStack.empty() << "\n";
std::cout << "Size: " << myStack.size() << "\n";
try {
std::cout << "Top: " << myStack.top() << "\n";
std::cout << "Min: " << myStack.min() << "\n";
std::cout << "Max: " << myStack.max() << "\n";
}
catch (const std::out_of_range& e) {
std::cout << "Out of range error. " << e.what() << "\n";
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T01:49:40.303",
"Id": "404716",
"Score": "1",
"body": "Could you explain the purpose for your code, maybe provide a use case? I fail to see the purpose of adding a max and min query to a stack, but I’m sure it’s useful to you. Please share! :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T04:18:06.277",
"Id": "404724",
"Score": "1",
"body": "It doesn't have any particular purpose, except educational :) This is just a common interview question to implement a stack that supports min() / max() in constant time."
}
] | [
{
"body": "<p>I'm going to answer your direct questions first.</p>\n\n<blockquote>\n <p>Are there any potential memory management issues?</p>\n</blockquote>\n\n<p>No. You don't do any manual memory management (using <code>new</code> and <code>delete</code>) so there are no issues.</p>\n\n<blockquote>\n <p>Any additional methods that would be useful (also, from educational\n point of view) to implement?</p>\n</blockquote>\n\n<p><a href=\"https://en.cppreference.com/w/cpp/container/stack\" rel=\"nofollow noreferrer\">Here is the reference page for <code>std::stack</code></a>. This is the standard library documentation. You may not be able to do them all right now but those are all possible functions and members you could implement for a stack. (I recommend only trying a little bit at a time.</p>\n\n<p>I'd like to point out that your code is very clean and easy to read. I also appreciate good use of const correctness.</p>\n\n<hr>\n\n<h2>Use unique include guards</h2>\n\n<pre><code>#ifndef STACK_H\n#define STACK_H\n</code></pre>\n\n<p>This is a very basic name. It would be easy for others to use a very similar name. Make your includes unique. Add a namespace name, a project name, a library name and possibly a GUID or all of the above to eliminate the risk of clashes.</p>\n\n<hr>\n\n<h2>Use the right headers</h2>\n\n<pre><code>#include <iostream>\n#include <memory>\n#include <vector>\n#include <stdexcept>\n</code></pre>\n\n<p>You don't use <code><memory></code> or <code><iostream></code> in your class. You don't use <code><stdexcept></code> until the cpp file. declare the header there.</p>\n\n<p>You are missing <code><limits></code> for <code>:std::numeric_limits<></code></p>\n\n<hr>\n\n<h2>List <code>public</code> members first</h2>\n\n<p>Anyone using your stack is only going to be able to use the public member functions. It is common practice therefor to list these first. </p>\n\n<hr>\n\n<h2>Avoid the use of <code>this-></code></h2>\n\n<p>It is almost always wrong to have <code>this-></code> in your code in C++. For example this:</p>\n\n<pre><code>if (this->empty())\n</code></pre>\n\n<p>can simply be written:</p>\n\n<pre><code>if (empty()) \n</code></pre>\n\n<p>The exception to this rule is with variable shadowing (which you don't have) which is also typically solved with a name change.</p>\n\n<hr>\n\n<h2>Always ask: What does this feature serve?</h2>\n\n<p>So you implemented a <code>min()</code> and <code>max()</code>. You did it with an O(1) lookup by having every single element keep track of the current min and max value of the entire stack. This is a problem on two levels:</p>\n\n<ul>\n<li>Your nodes should not contain information on other nodes. That breaks encapsulation. This is the job of the Container.</li>\n<li>And its also useless information. There is one accessible node. What value do you gain by knowing what the min and max values beneath that one are? how can you even act on that even if you knew?</li>\n</ul>\n\n<p>If you have your heart content on keeping the <code>min()</code> <code>max()</code> then at least store the value in the container. In addition to being good practice it will also take significantly less memory.</p>\n\n<hr>\n\n<p>Lastly When you are ready you should look into Template Metaprogramming. A Container / Data Structure like this needs to be usable with any type, including user defined types, in order to be truly useful/robust. </p>\n\n<hr>\n\n<p><strong>Edit: to answer point brought up in comments</strong></p>\n\n<p>The problem as I see it is the fact that you need to store state, which a stack is great for. If I needed to maintain current, min, and max values like you are, I would put them all into a struct like so:</p>\n\n<pre><code>struct State\n{\n int current_value;\n int min_value;\n int max_value;\n}\n</code></pre>\n\n<p>Then I would use a stack that supports user-defined types. <code>std::stack<State> state_machine</code>. </p>\n\n<p>Furthermore by maintaining <code>min()</code> and <code>max()</code>, in the node or in the container, if you do decide to extend your container to support user-defined types you will force your users to overload the comparison operators for their type even if there is no logical way to do so and it isn't otherwise needed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T06:51:05.997",
"Id": "404739",
"Score": "0",
"body": "Damn you! You talk about almost all topic I reviewed but you posted first. Now I have to rework all my review to avoid repetitions. Very nice review BTW ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T14:19:42.410",
"Id": "404805",
"Score": "1",
"body": "I don't see how keeping min/max in the node breaks encapsulation. The node is private to the stack and the consumer can't access it in any way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T14:22:02.057",
"Id": "404806",
"Score": "2",
"body": "The stack could be a piece of an algorithm where the time complexity is way more important than the space requirement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T14:57:12.573",
"Id": "404816",
"Score": "0",
"body": "@Johnbot if the container maintains the values then the lookup remains O(1). You arent sacrificing space for speed here. You're just sacrificing space. And I still hold Nodes shouldn't know about each other."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T14:59:58.060",
"Id": "404819",
"Score": "2",
"body": "If you have [7, 1, 7], min=1, max=7 and you pop the last element how would you propose we calculate the new min and max values from min=1, max=7 and popped=7?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T18:48:00.917",
"Id": "404866",
"Score": "1",
"body": "@Johnbot You're right. When popping a value equal to min or max recalculating will be done at O(n). However this is all still the wrong approach. See my addition to the answer for more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T03:57:30.980",
"Id": "404905",
"Score": "0",
"body": "Thank you so much, very helpful review. I also like your suggestion regarding std::stack of States. I have one question regarding \"Your nodes should not contain information on other nodes.\" I feel like this sentence is based on some very important concept, which I do not quite know. I read about encapsulation, but what you say about a node containing information about another node is still not intuitive for me. Do you, by any chance, know of some good resources, which talk more about it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T04:50:45.017",
"Id": "404907",
"Score": "1",
"body": "@user_185051 I don't have a great source no. Just look at Wikipedia or here on SO/SE for Encapsulation, Data Hiding, and Abstraction. I will also note that I don't agree fully with Johnbot's point but it isn't entirely invalid. The container would still maintain protection from outside manipulation. Think of each Node as a file and the container as a filing cabinet. It's okay if the filing cabinet knows about the files. After all it needs to sort the files by alphabet, or date, or size or whatever. But I don't want information from my file to end up in yours."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T07:13:00.977",
"Id": "404915",
"Score": "1",
"body": "The `min` and `max` values must be kept on the stack. Your edit at the bottom suggests exactly what OP has implement (except using the default `std::stack` which doesn't really help with the exercise of implementing a stack)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T13:36:49.513",
"Id": "404958",
"Score": "0",
"body": "@CrisLuengo My point was that taking state and implementing a stack are unique problems that should be handled separately. My solution isn't the same. It factors out the state from the rest of the stack."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T06:05:04.770",
"Id": "209417",
"ParentId": "209401",
"Score": "4"
}
},
{
"body": "<p>I'll add to what @bruglesco says.</p>\n\n<h1>Storing the running <code>min</code> and <code>max</code></h1>\n\n<p>If I understand correctly your goal is to have a stack where you can <code>pop()</code> and still access <code>min()</code> and <code>max()</code> in constant time.</p>\n\n<p>Then it's indeed not sufficient to have a single <code>max_</code> and <code>min_</code> member in your class and your approach of storing the current <code>min</code> and <code>max</code> values in the stack is fine.</p>\n\n<p>Alternatively you could store the values in a simple <code>std::vector<int></code> and have two additional <code>std::vector<int></code> instances <code>currMax</code> and <code>currMin</code>. Then <code>push(val)</code> would append <code>val</code> to <code>currMax</code> iff <code>val</code> is greater or equal to <code>currMax.back()</code>, and <code>pop()</code> would pop the last item from <code>currMax</code> if the popped item is equal to <code>currMax.back()</code>. (Similarly for <code>currMin</code>)</p>\n\n<h1>Member initialization</h1>\n\n<p>Remove the default member initialization from <code>Stack::Node::maxVal</code> and <code>Stack::Node::minVal</code>.<br>\n<code>push()</code> always sets these values.</p>\n\n<h1>Exception style</h1>\n\n<p><code>top()</code>, <code>min()</code> and <code>max()</code> throw an exception if the stack is empty. <code>pop()</code> just calls <code>currStack.pop()</code> which is UB if the stack is empty. Both approaches are valid, you should just be consistent.</p>\n\n<h1>DRY</h1>\n\n<p>You have the same <code>if (currStack.empty()) { throw std::out_of_range (\"Stack is empty\"); }</code> in three functions. Make it a private function of its own, say <code>void throwIfEmpty() const</code> and call that.</p>\n\n<h1><code>empty()</code> / <code>clear()</code></h1>\n\n<p>From a practical view you could add a <code>clear()</code> method that clears the stack.<br>\nSome people complain about <code>empty()</code> because it's unclear it it's used as an attribute (\"Is this instance empty?\") or a command (\"Empty this instance!\"). In C++17 you could add a <a href=\"https://en.cppreference.com/w/cpp/language/attributes/nodiscard\" rel=\"nofollow noreferrer\"><code>[[nodiscard]]</code></a> attribute to issue warnings if <code>empty()</code> is used as a command.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T07:28:11.290",
"Id": "404919",
"Score": "0",
"body": "Good point! I missed that!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T09:45:07.330",
"Id": "404933",
"Score": "1",
"body": "Having three vectors to store the value, min and max is a bad idea, it causes unnecessary memory fragmentation, it will cause more cache usage on your CPU to iterate through getting min and max, it's easy to create a bug where they de-sync, it's more code and slower because of more memory allocations and instructions to grow/shrink three vectors. Please don't do this."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T06:51:04.293",
"Id": "209501",
"ParentId": "209401",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "209417",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T00:12:59.303",
"Id": "209401",
"Score": "3",
"Tags": [
"c++",
"algorithm",
"stack"
],
"Title": "Stack implementation in C++ including min(), max() functions in O(1)"
} | 209401 |
<p>I've implemented a factorial function in a more "Ruby" way. I would like to get feedback on the algorithm.</p>
<pre><code>def factorial_of n
(1..n).inject :*
end
factorial_of 5
=> 120
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T00:35:24.347",
"Id": "404708",
"Score": "1",
"body": "`factorial_of 5` gives 15, not 120... Maybe you had another function and didn't paste in the correct one?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T00:36:06.733",
"Id": "404709",
"Score": "0",
"body": "So sorry! Just edited. I pasted it wrong."
}
] | [
{
"body": "<p>The \"of\" in the name <code>factorial_of</code> is redundant and unconventional.</p>\n\n<p><code>factorial_of 0</code> returns <code>nil</code> instead of <a href=\"https://en.wikipedia.org/wiki/Factorial#Factorial_of_zero\" rel=\"nofollow noreferrer\">the correct answer, which is <code>1</code></a>.</p>\n\n<pre><code>def factorial(n)\n (1..n).inject(1, :*)\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T01:26:02.033",
"Id": "209406",
"ParentId": "209402",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "209406",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T00:27:47.733",
"Id": "209402",
"Score": "0",
"Tags": [
"ruby",
"functional-programming"
],
"Title": "Non-recursive factorial in Ruby"
} | 209402 |
<p>I have limited experience with both making REST APIs and implementing security features, so I figured it'd be worth running this code through some other people's eyes before making it live.</p>
<p>My main questions are around the use of REST - e.g. are there better ways to implement my methods that return <code>bool</code>s?</p>
<p>(Assume the "drivers" are keyed in the DB by Name)</p>
<pre><code>public class Driver
{
public string Name { get; set; }
public string Pass { get; set; }
}
[HttpPost]
[RequireHttps]
[ActionName( "GetPasswordExists" )]
public HttpResponseMessage GetPasswordExists([FromBody] Driver driver)
{
HttpResponseMessage response;
try
{
bool passExists = false;
// db operations
response = Request.CreateResponse(HttpStatusCode.OK, passExists);
}
catch (Exception)
{
response = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return response;
}
[HttpPost]
[RequireHttps]
[ActionName("SetPassword")]
public HttpResponseMessage SetPassword([FromBody] Driver driver)
{
HttpResponseMessage response;
try
{
string hash = System.Web.Helpers.Crypto.HashPassword(driver.Pass);
// db operations
response = Request.CreateResponse(HttpStatusCode.OK);
}
catch (Exception)
{
response = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return response;
}
[HttpPost]
[RequireHttps]
[ActionName("VerifyPassword")]
public HttpResponseMessage VerifyPassword([FromBody] Driver driver)
{
HttpResponseMessage response;
try
{
bool valid = false;
string hash = null;
// db operations
valid = System.Web.Helpers.Crypto.VerifyHashedPassword(hash, driver.Pass);
response = Request.CreateResponse(HttpStatusCode.OK, valid);
}
catch (Exception)
{
response = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return response;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T01:40:42.910",
"Id": "404714",
"Score": "0",
"body": "Not quite an answer, but just your prose paragraph makes me nervous. Are you a team of security researchers, each with decades of experience in the field? No? Don't roll your own crypto algorithms (stuff like hashing and encryption). It _looks_ like you're not, but I'm not familiar enough with C#, and I just wanted to make sure you're not committing the cardinal sin of infosec."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T01:55:19.370",
"Id": "404719",
"Score": "0",
"body": "I'm definitely not in a team like that, so I'm doing my very best to avoid any in-house nonsense. The algorithm used (in `System.Web.Helpers.Crypto`) appears to be the recommended one by others on SO who also use C# to encrypt passwords. If anyone else who is more familiar with C# wants to point out that this is not the case, or suggest an alternative, I'm all ears!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T08:53:35.490",
"Id": "404747",
"Score": "0",
"body": "Fair enough. Like I said, I'm not familiar enough with C# to tell here. I just wanted to reiterate that if you find yourself writing a custom cryptographic hash or encryption, you're probably doing something wrong :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T12:47:20.653",
"Id": "404789",
"Score": "1",
"body": "(@BCdotWEB: Valid observations. Then, even a single valid point presented well makes a good answer.)"
}
] | [
{
"body": "<p>Some quick remarks:</p>\n\n<ul>\n<li><p>Keep your controllers lean and mean:</p>\n\n<ul>\n<li>Move all of the processing (that you seem to have removed by using the comment <code>// db stuff</code>) to dedicated classes, </li>\n<li>bind it all together using <a href=\"https://github.com/jbogard/MediatR\" rel=\"nofollow noreferrer\">MediatR</a>, </li>\n<li>validate incoming data with <a href=\"https://github.com/JeremySkinner/FluentValidation\" rel=\"nofollow noreferrer\">FluentValidation</a>.</li>\n</ul>\n\n<p>There are plenty of examples that show you how to combine these two, e.g. <a href=\"https://stackoverflow.com/questions/42283011/add-validation-to-a-mediatr-behavior-pipeline\">this Stack Overflow question</a>. Jimmy Bogard also has plenty of examples on his own blog, e.g. <a href=\"https://lostechies.com/jimmybogard/2014/09/09/tackling-cross-cutting-concerns-with-a-mediator-pipeline/\" rel=\"nofollow noreferrer\">this post</a>.</p>\n\n<p>Microsoft also promotes this kind of structure:<a href=\"https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/microservice-ddd-cqrs-patterns/microservice-application-layer-implementation-web-api#implement-the-command-and-command-handler-patterns\" rel=\"nofollow noreferrer\">\"Implement the Command and Command Handler patterns\"</a>. (In this case in the context of CQRS, which is something that you also could look into.)</p></li>\n<li><p>Don't needlessly abbreviate (why \"pass\" instead of \"password\"?).</p></li>\n<li><p>Don't use exceptions to control your logic. An invalid password should IMHO not throw an exception, it's an expected result. Even worse it that you seem to be \"eating\" your exceptions and don't even log them.</p></li>\n<li><p>WRT your app's logic, you might want to look at the logic in similar applications, e.g. <a href=\"http://jasonwatmore.com/post/2018/06/26/aspnet-core-21-simple-api-for-authentication-registration-and-user-management\" rel=\"nofollow noreferrer\">\"Simple API for Authentication, Registration and User Management\"</a>. Also think about things like \"how many times can a user try to log in and fail before his account gets locked?\" in order to avoid hackers who'll try to access the system by going through large lists of often-used passwords.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T14:24:27.790",
"Id": "209443",
"ParentId": "209404",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T00:49:09.327",
"Id": "209404",
"Score": "1",
"Tags": [
"c#",
".net",
"rest"
],
"Title": "Set / verify password using REST API"
} | 209404 |
<p>I'm rewriting <a href="https://github.com/collection-json/collection-json.js" rel="nofollow noreferrer">collection-json.js</a>, a client for Collection+JSON. (Collection+JSON is a HATEAOS API media type built on top of JSON.)</p>
<p>My Goals:</p>
<ul>
<li>Remove CoffeeScript</li>
<li>webpack</li>
<li>UMD so it can be used via node and via <code><script ...></code> (not there yet.)</li>
</ul>
<p>I'm more comfortable in Ruby, though I do know JS. Still, I wouldn't say it's my native tongue.</p>
<p>The current challenge is the 'http' file. I have the actual HTTP calls in one module, and then the HTTP library in another. We use different abstraction patters but I believe the original author's intent was to allow the insertion of other network layers into the HTTP client, which would then allow for things like using jquery's methods or, perhaps more importantly, for inserting test-related stubs.</p>
<p>Here's my <a href="https://github.com/mustmodify/collection-json.js/blob/eeb7de8a93b513f7d697bdbbfe49f7272d3613e3/src/http.js" rel="nofollow noreferrer">current code</a>:</p>
<pre><code>import fetch from 'node-fetch';
let content_type = "application/vnd.collection+json";
class HttpImplementation {
// http_callback is used by each of the verb-methods below.
// It should call `done` with (error_string_or_null, body_as_text,
// response_headers)
//
http_callback(response, done) {
if(response.status < 400) {
// strangely, response.text() returns a promise...
response.text().then((actual_response) => {
done(null, actual_response, response.headers)
})
}
else { done(response.status); }
}
get(href, options, done) {
fetch(href).then((response) => {this.http_callback(response, done)}).
catch(error => done(error));
};
post(href, options, done) {
http_options = Object.assign({}, options,
{
method: "POST", body: JSON.stringify(options.body),
headers: options.headers,
redirect: "follow", mode: "CORS",
credentials: "same-origin", referrer: "client",
})
return(fetch(href, http_options).then(this.http_callback, done));
};
put(href, options, done) {
http_options = Object.assign({}, options,
{
method: "PUT", body: JSON.stringify(options.body),
headers: headers,
redirect: "follow", mode: "CORS",
credentials: "same-origin", referrer: "client",
})
return(fetch(href, http_options).then(this.http_callback, done));
}
delete(href, options, done){
http_options = Object.assign({}, options,
{
method: "DELETE", body: JSON.stringify(options.body),
headers: headers,
redirect: "follow", mode: "CORS",
credentials: "same-origin", referrer: "client",
})
return(fetch(href, http_options).then(http_callback, done));
};
}
class InterfaceLayer {
constructor( network_layer )
{
if( network_layer == null || network_layer == undefined )
{ this.source = new HttpImplementation(); }
else
{ this.source = network_layer ; }
}
get(href, options, done) {
if(!options.headers) { options.headers = {} }
options.headers["accept"] = content_type;
this.source.get(href, options, function(error, collection, headers) {
// the previous implementation of this was async, so
// it might bear reworking once figured out
// seems like you could add a layer that would try each one
// and, on failure, try the next.
if( error || collection )
{
// if a collection is returned, the source should handle caching
// though in the original code...
// https://github.com/collection-json/collection-json.js/blob/master/lib/http.coffee#L49
return(done(error, collection, headers));
}
else
{
return(false);
}
})
}
post(href, options, done) {
if (options == null) { options = {}; }
if (!options.headers) { options.headers = {}; }
options.headers = Object.assign({}, options.headers, {
"accept": content_type,
"content-type": content_type,
"Content-Type": "application/collection+json; charset=utf-8"
})
this.source.post(href, options, function(error, collection, headers)
{
if( error || collection )
{
// if a collection is returned, the source should handle caching
// though in the original code...
// https://github.com/collection-json/collection-json.js/blob/master/lib/http.coffee#L49
return(done(error, collection, headers));
}
else
{
return(false);
}
})
}
put(href, options, done) {
if (options == null) { options = {}; }
if (!options.headers) { options.headers = {}; }
options.headers = Object.assign({}, options.headers, {
"accept": content_type,
"content-type": content_type,
"Content-Type": "application/collection+json; charset=utf-8"
})
this.source.put(href, options, function(error, collection, headers)
{
if( error || collection )
{
// if a collection is returned, the source should handle caching
// though in the original code...
// https://github.com/collection-json/collection-json.js/blob/master/lib/http.coffee#L49
return(done(error, collection, headers));
}
else
{
return(false);
}
})
}
delete(href, options, done) {
if (options == null) { options = {}; }
if (!options.headers) { options.headers = {}; }
options.headers = Object.assign({}, options.headers, {
"accept": content_type,
"content-type": content_type,
"Content-Type": "application/collection+json; charset=utf-8"
})
this.source.delete(href, options, function(error, collection, headers)
{
if( error || collection )
{
// if a collection is returned, the source should handle caching
// though in the original code...
// https://github.com/collection-json/collection-json.js/blob/master/lib/http.coffee#L49
return(done(error, collection, headers));
}
else
{
return(false);
}
})
}
}
export default (new InterfaceLayer())
</code></pre>
<p>Sample usage in the form of a 'live test':</p>
<pre><code>import Client from '../src/client.js'
describe("LIVE test from ACTUAL API", () => {
test("it gets an error when calling an invalid path", () => {
new Client('http://todo-collection-json.herokuapp.com/invalid',
(error, collection) => {
expect(error).toBe(404);
expect(collection).toBeUndefined();
});
})
test('it works with a real-life-ish example', () => {
expect.assertions();
new Client('http://todo-collection-json.herokuapp.com/collection/tasks/',
(error, collection) => {
expect(collection).not.toBeDefined();
console.log(collection);
expect(error).toBeNull();
});
})
})
</code></pre>
<hr>
<p><a href="https://github.com/mustmodify/collection-json.js/blob/0fa3190842a86cdb7e8bba76ce5f46764032b168/lib/http.coffee" rel="nofollow noreferrer">Original <code>http.coffee</code></a>:</p>
<blockquote>
<pre><code>module.exports = defaults =
_get: (href, options, done=()->)->
done new Error "'GET' not implemented"
_post: (href, options, done=()->)->
done new Error "'POST' not implemented"
_put: (href, options, done=()->)->
done new Error "'PUT' not implemented"
_del: (href, options, done=()->)->
done new Error "'DELETE' not implemented"
cache:
# This is a fake cache. You should probably add a real one...
put: (key, value, time, done=()->)->
if typeof time is 'function'
done = time
time = null
done()
del: (key, done=()->)->
done()
clear: (done=()->)->
done()
get: (key, done=()->)->
done()
size: (done=()->)->
done 0
memsize: (done=()->)->
done 0
debug: ()->
true
module.exports["content-type"] = "application/vnd.collection+json"
module.exports.get = (href, options, done)->
defaults.cache.get href, (error, collection)->
# Give them the cached stuff if we have it
return done error, collection if error or collection
options.headers ||= {}
options.headers["accept"] = module.exports["content-type"]
module.exports.setOptions href, options
defaults._get href, options, (error, collection, headers)->
return done error if error
performCache collection, headers
done error, collection
module.exports.post = (href, options={}, done)->
options.headers ||= {}
options.headers["accept"] = module.exports["content-type"]
options.headers["content-type"] = module.exports["content-type"]
module.exports.setOptions href, options
defaults._post href, options, (error, collection, headers)->
# Do we cache this?
done error, collection
# Should be overridden by the client
module.exports.setOptions = (href, options)->
performCache = (collection, headers)->
# Expires
# expires = response.headers.expires
# # TODO convert to time-from-now
# # Cache-Control
# # TODO implement
# defaults.cache.put response.request.href, response.body, new Date(expires).getTime() if expires
</code></pre>
</blockquote>
<p><a href="https://github.com/mustmodify/collection-json.js/blob/0fa3190842a86cdb7e8bba76ce5f46764032b168/lib/index.coffee" rel="nofollow noreferrer">Original <code>index.coffee</code></a>:</p>
<blockquote>
<pre><code>request = require "request"
http = require "./http"
http._get = (href, options, done)->
options.url = href
request options, (error, response, body)->
done error, body, response?.headers
http._post = (href, options, done)->
options.url = href
options.body = JSON.stringify options.body
options.method = "POST"
request options, (error, response, body)->
done error, body, response?.headers
http._put = (href, options, done)->
options.url = href
options.body = JSON.stringify options.body
request.put options, (error, response)->
done error, response
http._del = (href, options, done)->
options.url = href
request.del options, (error, response)->
done error, response
module.exports = require "./client"
</code></pre>
</blockquote>
<h1>Questions</h1>
<ul>
<li>Is this a good way to separate these two concerns?</li>
<li>Is there a much cleaner/simpler way to express all this?</li>
</ul>
<p>I'm open to input on any part of the code, but especially this http aspect.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T18:41:27.683",
"Id": "405021",
"Score": "0",
"body": "We've just taken it off hold."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T03:59:28.830",
"Id": "209409",
"Score": "3",
"Tags": [
"javascript",
"json",
"client"
],
"Title": "Network abstraction layer for a JavaScript JSON API client"
} | 209409 |
<p>I wrote a solution to <a href="https://leetcode.com/problems/4sum/" rel="nofollow noreferrer">find all combinations of 4 elements from a list whose sum of elements equals some target</a></p>
<blockquote>
<p>Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.</p>
</blockquote>
<p>If there is better way for me to do it? it seems like the performace for the following code is too bad.</p>
<pre><code>def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
from itertools import combinations
if len(nums) <= 3:return []
res, col = [], []
for i in combinations(nums, 4):
check = set(i)
if sum(i) == target and check not in col:
res.append(list(i))
col.append(check)
return res
</code></pre>
| [] | [
{
"body": "<p>Lists are pretty inefficient for this type of thing. The majority of the complexity is from iterating over the lists and comparing contents. Sets use a hash for their content, reducing complexity.</p>\n\n<p>When using sets, most of the complexity comes from the combinations function.</p>\n\n<p><strong>Here are the results of a time test on your code</strong></p>\n\n<pre><code>res1 = Solution().fourSum([-5,5,4,-3,0,0,4,-2],4)\nprint(time.time() - start)\n# 0.0001342296600341797\n</code></pre>\n\n<p><strong>The results of a method using only sets</strong></p>\n\n<pre><code>res = Solution().fourSum([-5,5,4,-3,0,0,4,-2],4)\nprint(time.time() - start)\n# 9.918212890625e-05\n</code></pre>\n\n<p><strong>Code for the second function</strong>\n(updated to prevent 3-number outputs)</p>\n\n<pre><code>class Solution:\n def fourSum(self, nums, target):\n from itertools import combinations\n res = set()\n # Create all possible combinations\n\n for i in combinations(nums, 4):\n if sum(i) == target:\n # Turns the tuple of numbers into list of strings\n # Then joins them into a single string\n # This allows hashing for the set\n res.add(\" \".join(sorted(list([str(x) for x in i]))))\n # Splits the strings into lists of ints\n return list([ [int(z) for z in x.split()] for x in res])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T12:42:19.510",
"Id": "404787",
"Score": "2",
"body": "(Never trust sub-second timing results without in-depth knowledge of and trust in the measurement mechanism. There are tools for micro-benchmarking.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T16:03:41.910",
"Id": "404840",
"Score": "0",
"body": "great information about using `frozenset` however, if it code correct? `frozenset(i)` will also filter the duplicated number? like `i, target = (-5, 5, 0 ,0), 0 ` after `frozenset(i)` {-5,5 0} add into res?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T01:15:25.617",
"Id": "404892",
"Score": "0",
"body": "You're absolutely right, maybe someone has a better solution. In the meantime, I'll brainstorm."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T06:21:17.673",
"Id": "209418",
"ParentId": "209410",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T04:55:25.333",
"Id": "209410",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"k-sum"
],
"Title": "Find all combinations of 4 elements whose sum equals a target in Python"
} | 209410 |
<p>I am learning Android with Udacity nanodegree (having no support) and this is my assignment of music app. It is just an interface and no music I have to add. So far so the app is running without any error but I wold like to get expert feedback to write code in better and optimized way to achieve the same result.</p>
<p>My entire project is in my <a href="https://bitbucket.org/q2amarket/musicmasti/src/8175fe3e76d8613eb0fb3906eb75190ce99c29fb" rel="nofollow noreferrer">Bitbucket repo</a>.</p>
<h1>SongAdapter.java</h1>
<pre><code>public class SongAdapter extends ArrayAdapter<Song> {
int playingIndex = -1;
boolean currentTrack = false;
public SongAdapter(@NonNull Context context, int resource, @NonNull List<Song> objects) {
super(context, resource, objects);
}
@NonNull
@Override
public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View playlistItemView = convertView;
final ViewHolder holder;
if (playlistItemView == null) {
playlistItemView = LayoutInflater.from(getContext()).inflate(R.layout.playlist_item, parent, false);
holder = new ViewHolder();
holder.albumCoverThumbnail = playlistItemView.findViewById(R.id.playlist_album_thumbnail);
holder.songTitle = playlistItemView.findViewById(R.id.playlist_song_title);
holder.songAlbumTitle = playlistItemView.findViewById(R.id.playlist_song_album_title);
holder.songArtist = playlistItemView.findViewById(R.id.playlist_song_artist);
holder.songPlayButton = playlistItemView.findViewById(R.id.playlist_play_button);
playlistItemView.setTag(holder);
} else {
holder = (ViewHolder) playlistItemView.getTag();
}
final Song currentSong = getItem(position);
// set data to the list item
assert currentSong != null;
holder.albumCoverThumbnail.setImageResource(currentSong.getSongAlbumCoverId());
holder.songTitle.setText(currentSong.getSongTitle());
holder.songAlbumTitle.setText(currentSong.getSongAlbumTitle());
holder.songArtist.setText(currentSong.getSongSingers());
// check the play status of the song item
if (playingIndex == position) {
holder.songPlayButton.setImageResource(R.drawable.ic_pause_black_24dp);
} else {
holder.songPlayButton.setImageResource(R.drawable.ic_play_arrow_black_24dp);
}
// set song button action
holder.songPlayButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
holder.songPlayButton.setImageResource(R.drawable.ic_pause_black_24dp);
// pause current song on other click
if (position == playingIndex) {
playingIndex = -1;
} else {
playingIndex = position;
notifyDataSetChanged();
}
// pause play current track
if (currentTrack) {
holder.songPlayButton.setImageResource(R.drawable.ic_play_arrow_black_24dp);
currentTrack = !currentTrack;
} else {
holder.songPlayButton.setImageResource(R.drawable.ic_pause_black_24dp);
}
currentTrack = !currentTrack;
}
});
return playlistItemView;
}
static class ViewHolder {
ImageView albumCoverThumbnail;
TextView songTitle;
TextView songAlbumTitle;
TextView songArtist;
ImageButton songPlayButton;
}
}
</code></pre>
| [] | [
{
"body": "<p><code>ListView</code> has been deprecated, a better practice would be to use <code>RecyclerView</code> and <code>RecyclerView.Adapter</code>, for more information: <a href=\"https://developer.android.com/guide/topics/ui/layout/recyclerview\" rel=\"nofollow noreferrer\">Android RecyclerView</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T16:20:30.590",
"Id": "405000",
"Score": "2",
"body": "ListView is not deprecated class or widget, you can still use it, a lot of app does. RecyclerView is usually recommended approach because better performance and clear API."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T14:10:44.863",
"Id": "209526",
"ParentId": "209412",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T05:09:38.647",
"Id": "209412",
"Score": "1",
"Tags": [
"java",
"android"
],
"Title": "Adapter class to display songs in an Android ListView"
} | 209412 |
<p>I recently worked on a module, in which I implemented the functionality of downloading the CSV files.</p>
<pre><code>@RequestMapping(value = "/export_data")
public void downloadDataInCsv(
@RequestParam("type") String type,
@RequestParam("tID") String tableId,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
if (type.equals("csv")) {
List<UserInfo> list = userInfoDao.findById(tableId);
ExportCsvUtil.downloadCsv(request, response, list);
}
}
private void downloadCsv(HttpServletRequest request, HttpServletResponse response, List<UserInfo> list) throws IOException {
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=Table_Data.csv");
response.setContentType("text/csv");
response.setHeader(headerKey, headerValue);
try (final CSVWriter writer = new CSVWriter(response.getWriter(), ",")) {
writer.writeNext(new String[]{"User Id", "First Name", "Last Name", "Roll No", "Email ID", "Gender"});
for (UserInfo entry: list) {
// cast/convert to String where needed
writer.writeNext(new String[]{entry.getUserId()+"", entry.getFirstName(), entry.getLastName(),entry.getRollNo(),entry.getEmail(),entry.getGender()});
}
writer.close();
}
}
</code></pre>
<p>I am using OpenCSV library for reading and writing the CSV files, in addition, one thing should be note down here is, the function <code>writeNext()</code> accepts <code>String[]</code> .</p>
<p>I initialized the <code>String[]</code> inside <code>writeNext()</code>. I want to know the better way to do the same, so the readability enhanced.</p>
<p>Please review my code and suggest me the best practice.</p>
| [] | [
{
"body": "<p>First of all, please don't take what I am writting personnaly. Also, I am sure there would be something to argue with my proposals so feel free to tell me!</p>\n\n<p>Let's begin with:</p>\n\n<pre><code>@RequestMapping(value = \"/export_data\")\npublic void downloadDataInCsv(\n @RequestParam(\"type\") String type,\n @RequestParam(\"tID\") String tableId,\n HttpServletRequest request,\n HttpServletResponse response) throws IOException {\n if (type.equals(\"csv\")) {\n List<UserInfo> list = userInfoDao.findById(tableId);\n ExportCsvUtil.downloadCsv(request, response, list);\n }\n}\n</code></pre>\n\n<p>I hate using plain strings when doing some comparison especially when it looks like a real constant like <code>csv</code></p>\n\n<p>In order to remove the plain String, I usually use <code>enum</code> to do that.</p>\n\n<p>Why not replace <code>type.equals(\"csv\")</code> by something like <code>type.equals(FileType.CSV.name())</code></p>\n\n<p>Next, if we are looking here at this chunk:</p>\n\n<pre><code>List<UserInfo> list = userInfoDao.findById(tableId);\nExportCsvUtil.downloadCsv(request, response, list);\n</code></pre>\n\n<p>we see that your are proceding with <code>ExportCsvUtil.downloadCsv()</code> even if the list is empty. Should this be a normal behaviour of your application ? Maybe you should send a message telling the user that they were no data to retrieve ?</p>\n\n<p>Last thing for <code>downloadDataInCsv()</code> method is that if your <code>type</code> isn't a <code>csv</code> file, it will return a HTTP code 200 with nothing. I think the client would be kind of confused with that. Maybe try to send a different message like I said before. (e.g: only CSV export is available at the moment)</p>\n\n<p>Next chunk! :)</p>\n\n<pre><code>private void downloadCsv(HttpServletRequest request, HttpServletResponse response, List<UserInfo> list) throws IOException {\n String headerKey = \"Content-Disposition\";\n String headerValue = String.format(\"attachment; filename=Table_Data.csv\");\n response.setContentType(\"text/csv\");\n response.setHeader(headerKey, headerValue);\n\n try (final CSVWriter writer = new CSVWriter(response.getWriter(), \",\")) {\n\n writer.writeNext(new String[]{\"User Id\", \"First Name\", \"Last Name\", \"Roll No\", \"Email ID\", \"Gender\"});\n\n for (UserInfo entry: list) {\n // cast/convert to String where needed\n writer.writeNext(new String[]{entry.getUserId()+\"\", entry.getFirstName(), entry.getLastName(),entry.getRollNo(),entry.getEmail(),entry.getGender()});\n }\n writer.close();\n }\n}\n</code></pre>\n\n<p>If you look at <code>String headerValue = String.format(\"attachment; filename=Table_Data.csv\");</code>, you don't use <code>String.format()</code> capabilities at all! (if I am not mistaken)</p>\n\n<p><code>String.format()</code> allows you to do things like <code>String.format(\"Hello %s\", name)</code></p>\n\n<p>You can replace this with an old plain <code>String</code> then.</p>\n\n<p><code>response.setContentType(\"text/csv\");</code>, if you are using the <code>enum</code> like I said before, you could add a property <code>contentType</code> that allows you to do <code>FileType.CSV.getContentType()</code> in order to remove the hardcoded string.</p>\n\n<p><code>writer.writeNext(new String[]{\"User Id\", \"First Name\", \"Last Name\", \"Roll No\", \"Email ID\", \"Gender\"});</code>, since you know the header of the file, why not store is as a constant so it is not recreated every time you call the endpoint ?</p>\n\n<p>Like so:</p>\n\n<p><code>private static final String[] CSV_HEADER = new String[]{\"User Id\", \"First Name\", \"Last Name\", \"Roll No\", \"Email ID\", \"Gender\"});</code></p>\n\n<p>I think you could do something about the <code>for</code> loop with some of Java 8 fanciness but I am not confident enough to write this without tools for testing.</p>\n\n<p>Lastly, you don't have to do <code>writer.close()</code> since you are opening your file with a <code>try with resource</code></p>\n\n<p>Basically, <code>CSVWriter</code> class should implement <code>AutoCloseable</code> wich call <code>close()</code> method for you at the end of the <code>try</code> statement so you do not have to worry about this.</p>\n\n<p>Documentation about this is <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">here</a> </p>\n\n<p>Hope my answer helps !</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T05:37:45.687",
"Id": "405082",
"Score": "0",
"body": "Really appreciate MadJlzz, I have one question regardign this, I am looking a way to make it universal, so i can pass only the list of object, and it will parse the data and write to csv"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T08:23:01.897",
"Id": "405089",
"Score": "0",
"body": "It's gonna be hard to do this universal without getting uneasy to read because you have to know what you want to write before actually writting. The headers won't be the same for example plus you'd have something different for `UserInfo` attributes. Seems complicated. Plus this is a feature for your frontend so you can't add too much technicals informations in your endpoints to help you with that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T16:29:05.620",
"Id": "209539",
"ParentId": "209413",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T05:22:06.803",
"Id": "209413",
"Score": "2",
"Tags": [
"java",
"csv",
"spring",
"spring-mvc"
],
"Title": "CSV file download in Spring"
} | 209413 |
<p>I began implementing Game of Life for fun, then I challenged myself to implement the game with no loops. I only used STL Algorithms. I don't know how to make pretty GUI's yet but this will print the coordinates of each alive cell. I also do not know if I made a good hashing function. I think it's sufficient for the game but I don't know any theory behind good hashing functions. I glanced through the top questions with <a href="/questions/tagged/c%2b%2b" class="post-tag" title="show questions tagged 'c++'" rel="tag">c++</a> and <a href="/questions/tagged/game-of-life" class="post-tag" title="show questions tagged 'game-of-life'" rel="tag">game-of-life</a> and noticed everyone used a 2d array. I figured a hashing container would be more efficient.</p>
<pre><code>#include <unordered_set>
#include <iostream>
#include <vector>
#include <functional>
#include <array>
#include <iterator>
#include <cstddef>
#include <algorithm>
#include <utility>
using Cell = std::pair<int, int>;
namespace std {
template<>
struct hash<Cell> {
std::size_t operator()(const Cell& cell) const {
const std::hash<int> hasher;
return hasher(cell.first) & hasher(cell.second);
}
};
}
std::ostream& operator<<(std::ostream& out, const Cell& cell) {
out << '(' << cell.first << ',' << cell.second << ')';
return out;
}
class Life {
public:
template<typename InputIt>
Life(InputIt begin, InputIt end);
void tick();
friend std::ostream& operator<<(std::ostream& out, const Life& life);
private:
std::unordered_set<Cell> grid;
std::array<Cell, 8> neighbors_of(const Cell& cell) const;
int n_alive_neighbors(const std::array<Cell, 8>& neighbors) const;
};
template<typename InputIt>
Life::Life(InputIt begin, InputIt end)
: grid(begin, end) {}
void Life::tick() {
std::vector<Cell> to_die;
std::vector<Cell> to_create;
std::vector<Cell> all_neighbors;
// find cells that will die
std::copy_if(grid.begin(), grid.end(), std::back_inserter(to_die),
[&](const auto& cell){
const auto neighbors = neighbors_of(cell);
const auto alive_neighbors = n_alive_neighbors(neighbors);
return alive_neighbors < 2 || alive_neighbors > 3;
});
// collect neighbors of all cells
std::for_each(grid.begin(), grid.end(),
[&](const auto& cell){
const auto neighbors = neighbors_of(cell);
std::copy(neighbors.begin(), neighbors.end(), std::back_inserter(all_neighbors));
});
// find cells that will be created
std::copy_if(all_neighbors.begin(), all_neighbors.end(), std::back_inserter(to_create),
[&](const auto& cell) {
if (grid.find(cell) != grid.end()) return false;
const auto neighbors = neighbors_of(cell);
const auto alive_neighbors = n_alive_neighbors(neighbors);
return alive_neighbors == 3;
});
// kill cells
std::for_each(to_die.begin(), to_die.end(), [&](const auto& cell){ grid.erase(cell); });
// reproduce cells
grid.insert(to_create.begin(), to_create.end());
}
std::array<Cell, 8> Life::neighbors_of(const Cell& cell) const {
return { Cell(cell.first - 1, cell.second + 1),
Cell(cell.first, cell.second + 1),
Cell(cell.first + 1, cell.second + 1),
Cell(cell.first + 1, cell.second),
Cell(cell.first + 1, cell.second - 1),
Cell(cell.first, cell.second - 1),
Cell(cell.first - 1, cell.second - 1),
Cell(cell.first - 1, cell.second) };
}
int Life::n_alive_neighbors(const std::array<Cell, 8>& neighbors) const {
return std::count_if(neighbors.begin(), neighbors.end(),
[&](const auto& cell){ return grid.find(cell) != grid.end(); });
}
std::ostream& operator<<(std::ostream& out, const Life& life) {
if (life.grid.empty()) return out;
out << *life.grid.begin();
std::for_each(std::next(life.grid.begin()), life.grid.end(),
[&](const auto& cell){
out << '\n' << cell;
});
return out;
}
int main() {
std::array<Cell, 3> blinker {Cell(-1, 0), Cell(0, 0), Cell(1, 0)};
std::array<Cell, 6> toad {Cell(0, 0), Cell(1, 0), Cell(2, 0),
Cell(1, 1), Cell(2, 1), Cell(3, 1)};
Life life(toad.begin(), toad.end());
std::cout << life << '\n';
for (int i = 0; i < 6; ++i) {
life.tick();
std::cout << '\n' << life << '\n';
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T07:07:11.597",
"Id": "404740",
"Score": "3",
"body": "When a contiguous array suffices, a hash table is _never_ better. Think of it this way: your 2D array has simple index arithmetic as a perfect, no collisions hash function. You have no guarantee of sparsity, so your storage is optimally compact. With a hashtable you sacrifice speed both on lookups but also memory fragmentation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T18:54:59.253",
"Id": "404867",
"Score": "0",
"body": "@AlexReinking this does not allow for an infinite grid. I think an unordered_set is the efficient way to get an infinite grid."
}
] | [
{
"body": "<blockquote>\n <p>I challenged myself to implement the game with no loops</p>\n</blockquote>\n\n<p>However I like your set of mind, I wouldn't advise to renounce raw loops in this kind of program. There is no equivalent to <code>for (int i = 0; i < n; ++i)</code> in the algorithm standard library if you only want the <code>i</code> (as opposed to as an offset in a container, or as a value to fill a container with, or anything related to a container), and you'll need it to efficiently compute the cell's neighbors for instance. What you could do though is to rely on Eric Niebler's range library, which will be partially standardized in C++20; that would give something like <code>for (auto i : view::iota(0) | view::take(n)) // do something with i)</code></p>\n\n<blockquote>\n <p></p>\n</blockquote>\n\n<p>The thing I don't like about your program is that it is too complex. The whole program could fit into two core functions and a display function: one function would compute the number of alive neighbors for each cell of the grid (so the return value would be a grid of the same size as the input), and one function would compute the grid's next state from the grid of alive neighbors by cell. You don't even have to create a <code>Grid</code> class, as a <code>std::vector</code> or yet better a <code>std::array</code> has every functionality you need and more (such as compile-time size and bounds for a <code>std::array</code>).</p>\n\n<pre><code>#include <unordered_set>\n#include <iostream>\n#include <vector>\n#include <functional>\n#include <array>\n#include <iterator>\n#include <cstddef>\n#include <algorithm>\n#include <utility>\n</code></pre>\n\n<p>There is I think a bit too many headers here: for instance, is <code><functional></code> really used?</p>\n\n<pre><code>using Cell = std::pair<int, int>;\n\nnamespace std {\n template<>\n struct hash<Cell> {\n std::size_t operator()(const Cell& cell) const {\n const std::hash<int> hasher;\n return hasher(cell.first) & hasher(cell.second);\n }\n };\n}\n</code></pre>\n\n<p>As @AlexReinking said, a hash map isn't more efficient here, or rather: a simple 2d array is the most efficient hash map you could devise.</p>\n\n<pre><code>std::ostream& operator<<(std::ostream& out, const Cell& cell) {\n out << '(' << cell.first << ',' << cell.second << ')';\n return out;\n}\n\nclass Life {\npublic:\n template<typename InputIt>\n Life(InputIt begin, InputIt end);\n\n void tick();\n friend std::ostream& operator<<(std::ostream& out, const Life& life);\n\nprivate:\n std::unordered_set<Cell> grid;\n std::array<Cell, 8> neighbors_of(const Cell& cell) const;\n int n_alive_neighbors(const std::array<Cell, 8>& neighbors) const;\n};\n\ntemplate<typename InputIt>\nLife::Life(InputIt begin, InputIt end)\n : grid(begin, end) {}\n\nvoid Life::tick() {\n std::vector<Cell> to_die;\n std::vector<Cell> to_create;\n std::vector<Cell> all_neighbors;\n</code></pre>\n\n<p>That looks like a lot of intermediary vectors.</p>\n\n<pre><code> // find cells that will die\n std::copy_if(grid.begin(), grid.end(), std::back_inserter(to_die),\n [&](const auto& cell){\n</code></pre>\n\n<p>It is a bad idea to capture the whole context, and even worse when you do it by reference, because it's a source of silent bugs: one or two wrong keystrokes and you can refer to a variable outside of the lambda while thinking you refer to a variable inside</p>\n\n<pre><code> const auto neighbors = neighbors_of(cell);\n const auto alive_neighbors = n_alive_neighbors(neighbors);\n return alive_neighbors < 2 || alive_neighbors > 3;\n });\n\n // collect neighbors of all cells\n std::for_each(grid.begin(), grid.end(),\n</code></pre>\n\n<p>No raw loops is a nice goal, but <code>for_each</code> shouldn't be used instead of <code>for (const auto& elem : container)</code>: it's more convoluted, less readable, etc.</p>\n\n<pre><code> [&](const auto& cell){\n const auto neighbors = neighbors_of(cell);\n std::copy(neighbors.begin(), neighbors.end(), std::back_inserter(all_neighbors));\n</code></pre>\n\n<p>I don't understand why you have the <code>neighbors</code> intermediary array, if the only thing you do with it is copy it into <code>all_neighbors</code>. It's just a waste.</p>\n\n<pre><code> });\n\n // find cells that will be created\n std::copy_if(all_neighbors.begin(), all_neighbors.end(), std::back_inserter(to_create),\n [&](const auto& cell) {\n if (grid.find(cell) != grid.end()) return false;\n const auto neighbors = neighbors_of(cell);\n const auto alive_neighbors = n_alive_neighbors(neighbors);\n return alive_neighbors == 3;\n });\n\n // kill cells\n std::for_each(to_die.begin(), to_die.end(), [&](const auto& cell){ grid.erase(cell); });\n // reproduce cells\n grid.insert(to_create.begin(), to_create.end());\n}\n\nstd::array<Cell, 8> Life::neighbors_of(const Cell& cell) const {\n return { Cell(cell.first - 1, cell.second + 1),\n Cell(cell.first, cell.second + 1),\n Cell(cell.first + 1, cell.second + 1),\n Cell(cell.first + 1, cell.second),\n Cell(cell.first + 1, cell.second - 1),\n Cell(cell.first, cell.second - 1),\n Cell(cell.first - 1, cell.second - 1),\n Cell(cell.first - 1, cell.second) };\n}\n</code></pre>\n\n<p>This doesn't take into account the fact that some cells are at the border of the grid: those don't have 8 neighbors, but between 3 (angles) and 7. </p>\n\n<pre><code>int Life::n_alive_neighbors(const std::array<Cell, 8>& neighbors) const {\n return std::count_if(neighbors.begin(), neighbors.end(),\n [&](const auto& cell){ return grid.find(cell) != grid.end(); });\n}\n\nstd::ostream& operator<<(std::ostream& out, const Life& life) {\n if (life.grid.empty()) return out;\n out << *life.grid.begin();\n std::for_each(std::next(life.grid.begin()), life.grid.end(),\n [&](const auto& cell){\n out << '\\n' << cell;\n });\n return out;\n}\n</code></pre>\n\n<p>You don't have to master GUIs in order to do better than that: just output your grid as a grid, not as a list of cells (for instance <code>for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (grid.find(cell(i, j)) != grid.end()) std::cout << 'O' else std::cout ' '; } std::cout << std::endl; }</code>).</p>\n\n<pre><code>int main() {\n std::array<Cell, 3> blinker {Cell(-1, 0), Cell(0, 0), Cell(1, 0)};\n std::array<Cell, 6> toad {Cell(0, 0), Cell(1, 0), Cell(2, 0),\n Cell(1, 1), Cell(2, 1), Cell(3, 1)};\n\n Life life(toad.begin(), toad.end());\n\n std::cout << life << '\\n';\n for (int i = 0; i < 6; ++i) {\n life.tick();\n std::cout << '\\n' << life << '\\n';\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T11:15:39.693",
"Id": "209427",
"ParentId": "209415",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "209427",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T05:40:09.087",
"Id": "209415",
"Score": "5",
"Tags": [
"c++",
"game-of-life"
],
"Title": "Game of Life implementation with no loops"
} | 209415 |
<p>I've been told few days ago that using <code>is</code> is a code smell and anti-pattern.</p>
<p>I used it in an game to filter some elements of a collection (the inventory of the player).</p>
<hr>
<p><strong>Classes structure</strong></p>
<p>The base class of an element of the collection is <code>Item</code> :</p>
<pre><code>public abstract class Item
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
</code></pre>
<p>From that class are derived 3 classes, <code>Potion</code>, <code>Armor</code> and <code>Weapon</code></p>
<p>A potion is <code>IUsable</code></p>
<pre><code>public interface IUsable
{
void Use(Character target);
}
</code></pre>
<p>And <code>IStackable</code></p>
<pre><code>public interface IStackable
{
int Quantity { get; set; }
int MaxQuantity { get; set; }
}
</code></pre>
<p>The class <code>Potion</code> is, in example, defined that way :</p>
<pre><code>public class Potion : Item, IUsable, IStackable
{
//Some properties and implementations of interfaces
}
</code></pre>
<p>The weapons and armors are <code>IEquipable</code></p>
<pre><code>public interface IEquipable
{
void TakeOn(Character target);
void TakeOff(Character target);
}
</code></pre>
<p>Here is a shortened example of <code>Armor</code></p>
<pre><code>public class Armor : Item, IEquipable
{
//Some properties and implementations of interfaces
}
</code></pre>
<p>And one for <code>Weapon</code></p>
<pre><code>public class Weapon : Item, IEquipable
{
//Some properties and implementations of interfaces
}
</code></pre>
<hr>
<p><strong>Collection access</strong></p>
<p>Now, the part that smells, considering what was told to me :</p>
<p>To access some specific items in the collection, I'm using a generic method <code>SpecificInventoryItems<T>()</code>, which contains this part to get the expected <code>T</code> items :</p>
<pre><code>foreach (Item item in player.Inventory)
{
if (item is T)
{
string stack = "";
if (item is IStackable)
{
var stackable = item as IStackable;
stack = "(" + stackable.Quantity + "/" + stackable.MaxAmount + ") ";
}
options += "[" + i++ + "] - " + item.Name + " " + stack + ": " + item.Description;
if (item is Armor)
options += " " + ArmorDetail(item as Armor);
else if (item is Weapon)
options += " " + WeaponDetail(item as Weapon);
options += "\n";
items.Add(item as T); //items is List<T>
}
}
</code></pre>
<p>What's wrong with it? How could (should) I redesign this structure ? I though using separates lists such as <code>List<IUsable></code> and so on, instead of just a <code>List<Item> Inventory</code></p>
<p>Another example, after displayed the specific elements of the inventory, the user can select an item, and depending of its type, the item will be either used or taken on :</p>
<pre><code>switch (selected) //selected type is T
{
case IEquipable eq:
eq.TakeOn(player);
break;
case IUsable us:
us.Use(player);
//Manage the deletion of the IUsable if not IStackable, or IStackable and quantity = 0
break;
default:
break;
}
}
</code></pre>
<hr>
<p><strong>Testable code</strong></p>
<p>The code below can be copied/pasted in VS as is, to be used for testing purposes</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace SOTests
{
public abstract class Item
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public interface IUsable
{
void Use(Character target);
}
public class Character
{
public List<Item> Inventory { get; set; }
public Character()
{
Inventory = new List<Item>
{
new Potion
{
Id = 1,
Name = "Lesser HP potion",
Description = "Heals 42 HP",
HPRestored = 42,
MaxQuantity = 20,
Quantity = 10
},
new Potion
{
Id = 2,
Name = "Greater HP potion",
Description = "Heals 100 HP",
HPRestored = 100,
MaxQuantity = 20,
Quantity = 10
},
new Armor
{
Id = 3,
Name = "Lesser Armor",
Description = "A basic armor",
Defense = 10
},
new Armor
{
Id = 4,
Name = "Regular Armor",
Description = "An armor",
Defense = 25
},
new Armor
{
Id = 5,
Name = "Superbe Armor",
Description = "A nice shiny armor",
Defense = 50
},
new Weapon
{
Id = 42,
Name = "Lesser Sword",
Description = "A basic sword",
Attack = 50
},
new Weapon
{
Id = 43,
Name = "Regular Sword",
Description = "A sword",
Attack = 75
},
new Weapon
{
Id = 44,
Name = "Superbe Sword",
Description = "A nice shiny sword",
Attack = 100
}
};
}
}
public class Potion : Item, IUsable, IStackable
{
public int HPRestored { get; set; }
public int Quantity { get; set; }
public int MaxQuantity { get; set; }
//This is not exactly how I implemented it, but it's sufficient for testing purpose
public void Use(Character target)
{
--Quantity;
Console.WriteLine("Used " + Name);
}
}
public interface IStackable
{
int Quantity { get; set; }
int MaxQuantity { get; set; }
}
public interface IEquipable
{
void TakeOn(Character target);
void TakeOff(Character target);
}
public class Armor : Item, IEquipable
{
public int Defense { get; set; }
//This is not how I implemented it, but it's sufficient for testing purpose
public void TakeOn(Character target)
{
Console.WriteLine("Wearing armor : " + Name);
}
public void TakeOff(Character target) { }
}
public class Weapon : Item, IEquipable
{
public int Attack { get; set; }
//This is not how I implemented it, but it's sufficient for testing purpose
public void TakeOn(Character target)
{
Console.WriteLine("Wearing weapon : " + Name);
}
public void TakeOff(Character target) { }
}
public class AbsentFromInventory : Item
{
}
class Program
{
static Character player = new Character();
static string ArmorDetail(Armor armor)
{
return (armor.Name + " : " + armor.Description + " -> Defense : " + armor.Defense);
}
static string WeaponDetail(Weapon weapon)
{
return (weapon.Name + " : " + weapon.Description + " -> Attack : " + weapon.Attack);
}
/// <summary>
/// Displays some elements of the inventory depending of its type
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="type">This is only for friendly display purpose</param>
static void SpecificInventoryItems<T>(string type) where T : class
{
string error = "";
string input;
List<T> items;
bool back = false;
do
{
do
{
items = null;
items = new List<T>();
string options = type + " :\n";
int i = 1;
if (player.Inventory.Count > 0)
{
foreach (Item item in player.Inventory)
{
if (item is T)
{
string stack = "";
if (item is IStackable)
{
var stackable = item as IStackable;
stack = "(" + stackable.Quantity + "/" + stackable.MaxQuantity + ") ";
}
options += "[" + i++ + "] - " + item.Name + " " + stack + ": " + item.Description;
if (item is Armor)
options += " " + ArmorDetail(item as Armor);
else if (item is Weapon)
options += " " + WeaponDetail(item as Weapon);
options += "\n";
items.Add(item as T);
}
}
if (i > 1)
{
Console.WriteLine(options);
if (error != "")
Console.WriteLine(error);
Console.WriteLine("Please select an item or go [[B]ack]");
}
else
Console.WriteLine("No " + type.ToLower() + " found. Please go [[B]ack]");
}
else
Console.WriteLine("No item in inventory. Please go [[B]ack]");
input = Console.ReadLine();
error = "";
} while (!Regex.IsMatch(input, "^(([0-9]+)|(b(ack)?))$", RegexOptions.IgnoreCase));
if (int.TryParse(input, out int result))
{
if (result > 0 && result <= items.Count)
{
var selected = items[--result];
switch (selected)
{
case IEquipable eq:
eq.TakeOn(player);
back = true;
break;
case IUsable us:
us.Use(player);
if (us is IStackable)
{
var stackable = us as IStackable;
if (stackable.Quantity <= 0)
player.Inventory.Remove(stackable as Item);
}
else
player.Inventory.Remove(us as Item);
back = true;
break;
default:
break;
}
}
else
error = "Invalid number.";
}
else
back = true;
} while (!back);
}
static void Main(string[] args)
{
do
{
SpecificInventoryItems<Potion>("Potion");
SpecificInventoryItems<Weapon>("Weapon");
SpecificInventoryItems<Armor>("Armor");
SpecificInventoryItems<AbsentFromInventory>("Super item");
Console.WriteLine("Again? Y/N");
} while (Console.ReadKey().Key != ConsoleKey.N);
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T09:22:58.443",
"Id": "404752",
"Score": "0",
"body": "I find your question lacks a lot of details and context and that you should provide more code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T09:54:15.490",
"Id": "404760",
"Score": "0",
"body": "@t3chb0t sure, but there can be a lot of code that can be added. What part do you like to see? The whole function `SpecificInventoryItems<T>()` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T10:15:56.657",
"Id": "404763",
"Score": "0",
"body": "Yes, for example. It's always easier if you can copy/paste the code into an IDE and don't have to create variables yourself like `items.Add(item as T); //items is List<T>`, this one isn't defined anywhere. It'd be great if you could make it copy/pasteable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T11:37:18.940",
"Id": "404774",
"Score": "3",
"body": "@t3chb0t I edited my question with testable code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T15:14:38.737",
"Id": "404823",
"Score": "0",
"body": "One more thing, could you clarify which parts for the code are exactly as you implemented them and which ones are just for demonstration purposes. I see there are a couple of such commens already. How about the `SpecificInventoryItems`? I suppose this is what you want us to review, right? So how real is it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T20:20:57.183",
"Id": "404873",
"Score": "1",
"body": "`is` is NOT a code smell OR an anti-pattern. Whoever told you that needs to leave the industry."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T20:40:01.677",
"Id": "404876",
"Score": "0",
"body": "@t3chb0t the `SpecificInventoryItems` is actually almost as it is in my project. I just removed 2 lines of codes that shows the player's stats which are irrevelant for the question. About the one that told me that `is` is anti-pattern and code smell, that was as comment about an [answer](https://stackoverflow.com/a/53651915/8398549) I wrote in SO."
}
] | [
{
"body": "<h3>About 'is'</h3>\n\n<p>I see four different uses of <code>is</code> in your code:</p>\n\n<ol>\n<li><code>item is T</code>, for filtering on item type, such as weapons-only or potions-only.</li>\n<li><code>item is Armor</code> and <code>item is Weapon</code>, for creating type-specific effect descriptions.</li>\n<li><code>item is IStackable</code>, for descriptions and special inventory handling of stackable items.</li>\n<li><code>case IEquipable eq</code> and <code>case IUsable us</code>, for handling of equipment and consumption logic that applies to certain item 'categories' (both weapons and armors are equippable, only potions are consumable).</li>\n</ol>\n\n<hr>\n\n<p>Number 1, selecting items of a specific type from a collection of different types (which is a very natural way to represent a player's inventory) seems fine. Note that this can be simplified by using Linq's <code>OfType<T></code> extension method. An alternative such as using separate lists will likely introduce more problems than that they solve.</p>\n\n<hr>\n\n<p>Number 2 is problematic. You can easily end up with several checks like these in multiple places, which makes updating description or other item-specific logic more difficult and error-prone than it needs to be. A better solution is to add a virtual <code>EffectsDescription</code> property to <code>Item</code>, so each item type can generate its own effects description, using actual effect values. Adding a new item type no longer requires changes in various other parts of the code, because type-specific description logic is kept in a single place, the item class itself.</p>\n\n<hr>\n\n<p>Number 3, stackable item handling, looks ok at first sight, but it's not very flexible. A class either implements an interface or it does not, so each item type is either stackable or it's not. A two-handed broadsword isn't stackable, but what about a set of throwing knives? The current design does not allow for special cases like that. I would use a data-driven approach here instead of encoding this in C#'s type system. The easiest solution would be to make all items stackable, with a max stack size of 1 for unstackable items.</p>\n\n<hr>\n\n<p>Number 4, equippable and consumable item handling, can sometimes be useful, but in this case I think it indicates a suboptimal design choice. A call like <code>SpecificInventoryItems<Weapon></code> is intended to let the player select a weapon, but because <code>SpecificInventoryItems</code> is a generic method it has to resort to type-checks to determine how to use the selected item - something that could easily (and unambiguously) have been decided by the caller. I would split this up into a generic <code>SelectItem<T></code> method and several type-specific methods such as <code>EquipWeapon</code>.</p>\n\n<hr>\n\n<h3>Other notes</h3>\n\n<ul>\n<li>Pattern matching isn't limited to <code>switch</code> statements: <code>if (item is Armor) ...item as Armor</code> can be rewritten as <code>if (item is Armor armor) ...armor</code>. That also reduces the number of type checks to one.</li>\n<li><code>SpecificInventoryItems</code> is doing too many things. Splitting it up into smaller functions that each perform a single task not only makes the code easier to understand, it also enables you to reuse functionality in different contexts.</li>\n<li><code>Item.Description</code> is used inconsistently: potions use it to describe their effects, but weapons and armor do not. Note how potion descriptions can easily become incorrect if you change the value of <code>HPRestored</code> but forget to update <code>Description</code> accordingly.</li>\n<li>The <code>T : class</code> constraint does not prevent unrelated interfaces and types. A top-level <code>IItem</code> interface that is implemented by both <code>Item</code> and the various equippable/usable interfaces allows for a more specific constraint, which makes the intent of the method more clear. Renaming <code>T</code> to <code>TItem</code> would also help.</li>\n<li>If you're using <code>options</code> the way you do to reduce the number of <code>Console.WriteLine</code> calls, and if that's because of a concern for performance, then you should know that using a <code>StringBuilder</code> is more efficient than concatenating lots of strings. Not that I'm expecting performance problems here, but just in case you didn't know.</li>\n<li>All <code>Item</code> properties have public setters. This allows any code to modify them, with the risk of putting an item in an invalid state, with the result that a modification in one part of the program can cause another unrelated part to break.</li>\n</ul>\n\n<hr>\n\n<h3>Alternative implementation</h3>\n\n<p>Here's what the code could look like after applying some of the above suggestions:</p>\n\n<pre><code>// Top-level item-specific methods:\nstatic void EquipWeapon(Character player)\n{\n var selectedWeapon = AskUserToSelectItem<Weapon>(player, \"weapon\");\n if (selectedWeapon == null)\n return;\n\n // NOTE: Unequipping current weapon left out.\n selectedWeapon.TakeOn(player);\n Console.WriteLine($\"{selectedWeapon.Name} has been equipped.\");\n}\n\nstatic void EquipArmor(Character player)\n{\n var selectedArmor = AskUserToSelectItem<Weapon>(player, \"armor\");\n if (selectedArmor == null)\n return;\n\n // NOTE: Unequipping current armor left out.\n selectedArmor.TakeOn(player);\n Console.WriteLine($\"{selectedArmor.Name} has been equipped.\");\n}\n\nstatic void ConsumeUsableItem(Character player)\n{\n var selectedUsableItem = AskUserToSelectItem<IUsable>(player, \"consumable\");\n if (selectedUsableItem == null)\n return;\n\n RemoveFromInventory(player, selectedUsableItem, 1);\n selectedUsableItem.Use(player);\n Console.WriteLine($\"{selectedUsableItem.Name} has been consumed.\");\n}\n\n// Displays all items of the specified type.\n// Returns the selected item, or null if no item was selected.\nstatic TItem AskUserToSelectItem<TItem>(Character player, string itemDisplayName) where TItem : IItem\n{\n var items = player.Inventory.OfType<TItem>().ToArray();\n if (items.Length == 0)\n {\n Console.WriteLine($\"Your inventory contains no {itemDisplayName}.\");\n return default;\n }\n\n Console.WriteLine($\"{itemDisplayName}:\");\n for (int i = 0; i < items.Length; i++)\n {\n Console.WriteLine($\"[{i}] - {FullItemDescription(items[i])}\");\n }\n var selectedIndex = AskUserForIntegerInRange($\"Please select an item or go [[B]ack]:\", 0, items.Length - 1);\n return selectedIndex.HasValue ? items[selectedIndex.Value] : default;\n}\n\nstatic void RemoveFromInventory(Character player, IItem item, int quantity)\n{\n // NOTE: Ownership and quantity sanity check left out for brevity's sake:\n if (item.Quantity > quantity)\n item.Quantity -= quantity;\n else\n player.Inventory.Remove(item);\n}\n\nstatic string FullItemDescription(IItem item)\n{\n var description = new StringBuilder();\n description.Append(item.Name);\n\n if (item.StackSize > 1)\n description.Append($\" ({item.Quantity}/{item.StackSize})\");\n\n description.Append($\": {item.Description} -> {item.EffectsDescription}\");\n return description.ToString();\n}\n\n// Asks the user to enter a number within the given range.\n// Returns null if the user entered 'b' or 'back'.\nstatic int? AskUserForIntegerInRange(string prompt, int minValue, int maxValue)\n{\n while (true)\n {\n Console.WriteLine(prompt);\n var input = Console.ReadLine().ToLower();\n if (input == \"b\" || input == \"back\")\n {\n return null;\n }\n else if (int.TryParse(input, out var index))\n {\n if (index >= minValue && index <= maxValue)\n return index;\n\n Console.WriteLine($\"Please enter a number between {minValue} and {maxValue}.\");\n }\n else\n {\n Console.WriteLine(\"Please enter a valid number, or 'b' or 'back'.\");\n }\n }\n}\n</code></pre>\n\n<p>With the following changes to the <code>Item</code> class hierarchy (not including everything, but the rest should be obvious):</p>\n\n<pre><code>public interface IItem\n{\n int Id { get; }\n string Name { get; }\n string Description { get; }\n string EffectsDescription { get; }\n int Quantity { get; set; }\n int StackSize { get; }\n}\n\npublic abstract class Item : IItem\n{\n ...\n public virtual string EffectsDescription { get; }\n}\n\npublic interface IEquippable : IItem { ... }\n\npublic class Weapon : Item, IEquippable\n{\n ...\n public override string EffectsDescription => $\"Attack: {Attack}\";\n}\n</code></pre>\n\n<p>Perhaps not all of these changes will make sense for what you have in mind with your game, but I hope you'll find some of this useful.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T09:53:54.023",
"Id": "405484",
"Score": "0",
"body": "Thank you for your great answer, I'll study it carefully. As you mentionned, there's some parts I can't use, in example, the case 2. I'm developping the game using a 3-tiers architecture and I don't want to use only strings for the details of an `Item` (later, I plan to give up the console and use something more visual, like Unity 3D)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T10:09:40.510",
"Id": "405702",
"Score": "0",
"body": "That makes sense - normally you wouldn't store display-strings at this level, you'd provide information that can be translated or visualized by the UI layer. I'd probably add an `Effect` property to `IItem`, with an effect-type enum (damage/armor/healing/etc.) and a value. That could be extended to an `Effects` array if items can have multiple effects, or the value could be replaced by a range, for weapons with randomized damage, and so on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T10:18:18.867",
"Id": "405703",
"Score": "0",
"body": "This is already the case, I have an `Status` base class that is derived for `Buff` (that is used for debuff too) `OverTime` (derived to `Dot` - Damage Over Time - and planned to `Hot` - Healing Over Time). This can be used in buff/debuff/poison potions and in skills. This is actually a 5000 lines project available on GitHub :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T10:33:17.523",
"Id": "405704",
"Score": "0",
"body": "Armors have 2 main attributes, the `Defense` and the type (which is an enum). If you have a breastplate (chest armor) having 3 in `Defense` of type Plate. You've been hit on the chest by an attack dealing 10 damage. Your armor has 3 in defense, and the damages are reduced to 7. The plate type reduce the damage by 40%, the damage is 4.2 (rounded to 4). Depending of the type of the weapon (pierce, blunt or slash), the damage are increased or decreased"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T19:47:03.373",
"Id": "209633",
"ParentId": "209419",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "209633",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T08:18:01.253",
"Id": "209419",
"Score": "4",
"Tags": [
"c#",
"design-patterns",
"collections"
],
"Title": "Collections management with many derived elements"
} | 209419 |
<p>I have a method that takes as parameter an array of several depth (<code>group</code>) and a name as a string (<code>currentFilterName</code>)</p>
<pre><code>checkFilterValue(group, currentFilterName) {
group.forEach((element, index) => {
if (element.children) {
if (element.name === currentFilterName) {
this.returnedValue = element.value
} else {
this.checkFilterValue(element.children || this.filtersConfig[index + 1], currentFilterName)
}
} else {
if (element.name === currentFilterName) {
this.returnedValue = element.value
}
}
})
}
</code></pre>
<p>The depth levels are the <code>element.children</code> , being the goal is to return the <code>element.value</code>, at each turn if the element has a depth level I first check if <code>element.name === currentFilterName</code> if it is the case I would like returned the <code>element.value</code> if it is not the case I return the method evening with the next <code>element.children</code> if there is otherwise the original tables with the next index <code>this.filtersConfig [index + 1]</code>, if the element has no depth I simply check if <code>element.name === currentFilterName</code> and I return to <code>element.value</code></p>
<p>The problem I have is that the method is a little verbose, how can we simplify it with an elegant writing?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T09:41:02.183",
"Id": "404758",
"Score": "1",
"body": "What other code is in this object's definition? Is it in `strict` mode? Why do you want to set `returnedValue` this way?"
}
] | [
{
"body": "<p>I think your code has an issue:</p>\n\n<pre><code>this.checkFilterValue(element.children || this.filtersConfig[index + 1], currentFilterName)\n</code></pre>\n\n<p>The <code>this.filtersConfig[index + 1]</code> is never called as you check <code>element.children</code> first:</p>\n\n<pre><code>if (element.children) {\n ...\n}\n</code></pre>\n\n<p>Your code doesn't need a <code>forEach</code> as a for loop will be better:</p>\n\n<pre><code>checkFilterValue(group, currentFilterName) {\n for (let key in group) {\n const { name, value, children } = group[key]\n if (name === currentFilterName) {\n return value\n }\n\n if (children) {\n let found = this.checkFilterValue(children, currentFilterName)\n if (found) return found\n }\n }\n\n return null\n}\n</code></pre>\n\n<p>By using a for loop you are able to directly return the value if found.</p>\n\n<p>Another issue of your code is you missed to reset <code>this.returnedValue</code> doing so you have a bug if you call 2 different searches and the second one doesn't find anything.</p>\n\n<p>Although you didn't share other code, maybe you should do this in another method.</p>\n\n<p>You can see I use the spread operator to make the code much more concise:</p>\n\n<pre><code>const { name, value, children } = group[key]\n</code></pre>\n\n<p>and get rid of <code>element.something</code>.</p>\n\n<p>Not sure how to handle the part where you call the function with a different set of data, but maybe inside this method is not the right place of doing it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T11:32:22.817",
"Id": "209431",
"ParentId": "209420",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "209431",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T08:21:37.867",
"Id": "209420",
"Score": "-1",
"Tags": [
"javascript",
"recursion"
],
"Title": "Recursive loop which returns a value according to a single condition"
} | 209420 |
<p>I have created a query that populates a datapoint with random values.
The logic is simple: Iterate between the START and END dates and INSERT random values. </p>
<p>I want from this query to be very perfomant. For example populate every second of a year with values (what with this code will last ages). I am new to SQL statements of this complexity and I dont know the pitfalls and of it.</p>
<p>Are there some hidden areas in my code that can be improved? If I replace the random function with just a hardcoded value will it cause much boost?
Is a loop with a lot of <code>INSERT INTO</code> time consuming; Is there a better way to Insert (some kind of batch insert)?</p>
<pre><code>DO $$
DECLARE --Variables
NODE_ID bigint := 11; -- The node id of the datapoint
TIMESTAMP_START TIMESTAMP := '2018-12-06 22:00:00';
TIMESTAMP_END TIMESTAMP := '2018-12-10 00:00:00';
TS_STEP INTERVAL := '30 minute';
MAX_VALUE integer := 100;
BEGIN
LOOP
EXIT WHEN TIMESTAMP_START > TIMESTAMP_END;
INSERT INTO datapoint_values (dp_id, ts, datatype, source, int_value, float_value)
VALUES (NODE_ID, TIMESTAMP_START, 2, 0, floor(random()*(MAX_VALUE+1)), 0);
TIMESTAMP_START := TIMESTAMP_START + TS_STEP;
END LOOP;
END $$;
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T09:33:27.717",
"Id": "404754",
"Score": "0",
"body": "Do you care about the quality of the randomness, or do you just want some arbitrary values?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T09:38:32.447",
"Id": "404756",
"Score": "0",
"body": "@200_success If I had I would choose performance, so quality of randomness is a background feature. I want maximum perfomance that coulbe be pressed out of this code."
}
] | [
{
"body": "<p>Instead of a loop which inserts one row after the other you should use <code>generate_series</code> to create all timestamps at once.</p>\n\n<p>Untested:</p>\n\n<pre><code>DO $$\nDECLARE --Variables\n NODE_ID bigint := 11; -- The node id of the datapoint\n TIMESTAMP_START TIMESTAMP := '2018-12-06 22:00:00';\n TIMESTAMP_END TIMESTAMP := '2018-12-10 00:00:00';\n TS_STEP INTERVAL := '30 minute'; \n\n MAX_VALUE integer := 100;\n\nBEGIN \n INSERT INTO datapoint_values (dp_id, ts, datatype, source, int_value, float_value)\n SELECT (NODE_ID, x, 2, 0, floor(random()*(MAX_VALUE+1)), 0)\n FROM generate_series(TIMESTAMP_START, TIMESTAMP_END, TS_STEP) t(x);\nEND $$;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-08T10:12:50.463",
"Id": "408095",
"Score": "0",
"body": "Would be great if it worked, but im getting errors"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-08T10:26:57.227",
"Id": "408096",
"Score": "1",
"body": "*getting errors* is not very helpful. The Select itself works fine, see https://dbfiddle.uk/?rdbms=postgres_9.6&fiddle=12cb948566055213ec4a58efcde91b3f I just noticed that I used the start timestamp in both places, fixed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-08T10:37:11.880",
"Id": "408097",
"Score": "0",
"body": "I didn't know about generate_series. Nice solution."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T23:02:28.137",
"Id": "210331",
"ParentId": "209422",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T09:25:14.820",
"Id": "209422",
"Score": "3",
"Tags": [
"performance",
"sql",
"datetime",
"postgresql",
"plpgsql"
],
"Title": "Iterate between dates and INSERT values in a performant way"
} | 209422 |
<p>Just a simple script that puts a user's currently playing track(on Spotify) to his account's status on vk.com. And printing info about the track in the console. </p>
<pre><code>import requests
import os
import json
URL_TRACK = 'https://api.spotify.com/v1/me/player/currently-playing'
URL_STATUS = "https://api.vk.com/method/status.set"
VK_TOKEN = os.environ.get('VK_TOKEN')
SP_TOKEN = os.environ.get('SP_TOKEN')
def set_status():
params = {
'user_id': 8573490,
'v': 5.92,
'access_token': VK_TOKEN,
'text': current_track()
}
status = requests.get(url=URL_STATUS, params=params)
def track_data():
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': f'Bearer {SP_TOKEN}',
}
return requests.get(url=URL_TRACK, headers=headers)
def track_is_playing():
return track_data().status_code == 200
def current_track():
data = track_data().json()
artist_path = data["item"]['artists'][0]['name']
track_path = data["item"]['name']
return(f'{artist_path} - {track_path}')
def run_script():
if track_is_playing():
set_status()
print(current_track())
else:
print('Not playing')
if __name__ == "__main__":
run_script()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T13:05:40.837",
"Id": "404795",
"Score": "0",
"body": "I'm also wondering what are the options to make this thing used by many users so they don't have to deal with command-line, manual input of tokens etc. Now I could think only of web-app, written in Django for example."
}
] | [
{
"body": "<p>Rather than <code>os.environ.get</code> you can do <code>getenv</code>.</p>\n\n<p>In <code>track_data</code>, don't pass <code>Content-Type</code>, because you aren't passing any body with your request.</p>\n\n<p>Otherwise, it's quite reasonable. You may want to expand error checking and reporting, particularly for <code>track_data</code>, since you aren't currently checking the status. <code>raise_for_status</code> is often a good thing to do.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T15:57:50.590",
"Id": "209452",
"ParentId": "209423",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "209452",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T09:56:33.367",
"Id": "209423",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Spotify API data to vk.com user's status"
} | 209423 |
<p>I was failed at coding challenge for my interview with the following reasons given by the interviewer: deep use of mutation and a not that well thought up internal API. </p>
<p>I understand that my code and design have so many flaws and I genuinely want to get your opinion so I could improve my code. </p>
<p>The challenge is about asking me to build a quote processor to calculate a premium for different products, based on different rule sets.</p>
<p>Since the requirements are very lengthy, I try to summarize it below:</p>
<h2>Data model</h2>
<ul>
<li>A user (with an id, an address, and a risk value)</li>
<li>An address (with an id and a location risk value)</li>
<li>A product (with an id and a price value)</li>
</ul>
<p>(Risk values are in our patented Universal Risk Value Scale [tm])</p>
<p>For products we have modelled in our system the following types:
- Houses (with address and size in square meters)
- Bananas (with number of black spots)
- Bicycles (with number of gears)</p>
<p>Asides from above, the premium quote would need to take in rules, base surcharge, universal risk value for each product and each user to quote a premium for user.</p>
<h2>Rules</h2>
<p>We want to build a quote processor that will receive a user and a set of products, and return whether we reject the user or not, and if not, for how much premium will we insure the products in euros per year.</p>
<p>To ensure this, we have a set of rules to follow.</p>
<p>Each product will have a base premium value, that multiplied by the product value will give a subtotal for the product's premium. To this subtotal, we must add a surcharge that depends on the product type and maybe on other rules. Each surcharge is multiplied to the base value.</p>
<p>Then, for all the products, if for one the rules say that it is un-insurable, then the final result given is that we won't offer an insurance. If no product is un-insurable, then we add all the premiums and that is the quote we return to the user.</p>
<p><strong>EDIT - ADD MORE INFORMATION</strong></p>
<h3>Base Premium surcharge value per product</h3>
<p>Banana: 1.15
House: 0.03</p>
<h3>Surcharges</h3>
<ul>
<li>User</li>
</ul>
<p>Depending on our estimation of the risk value of the user, we apply the following surcharges:
<a href="https://i.stack.imgur.com/ZGqnW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZGqnW.jpg" alt="enter image description here"></a></p>
<ul>
<li><p>Banana</p>
<ul>
<li>We won't offer insurance for bananas unless their number of black spots is between 3 and 12 (inclusive).</li>
<li>We also won't offer banana insurance to users with a risk value of more than 200 (our investigations show they tend to lose them)</li>
</ul></li>
</ul>
<h3>EXAMPLES 1:</h3>
<ul>
<li>1,000,000 * // house value</li>
<li>0.03 * // house base premium value</li>
<li>0.7 * // house risk surcharge</li>
<li>0.3 // user risk surcharge</li>
<li>= 6300 € per year as premium quote (=1000000 * 0.03 * 0.7 * 0.3)</li>
</ul>
<h3>EXAMPLES 2: BANANA</h3>
<ul>
<li>10 * // banana value</li>
<li>4 * // number of black spots (inclusive = no additional base premium value to be calculated)</li>
<li>1 // user risk surcharge (user's risk value between 21 and 200)</li>
<li>= 10 € per year as premium quote (=10 * 1)</li>
</ul>
<p>Below are my classes, I am putting here one or two model classes just to present my design.</p>
<p>Interfaces:</p>
<pre><code>public interface Product {
BigDecimal getProductValue();
BigDecimal getBasePremium();
BigDecimal getSubTotalPremium();
}
public interface Risk {
void setRiskValue(int riskValue);
BigDecimal getRiskSurcharge();
static BigDecimal getUnIdentifiedRiskSurcharge()
{
return new BigDecimal(-1);
}
static BigDecimal getDefaultRiskSurcharge()
{
return new BigDecimal(0);
}
static boolean isWithinRange(int riskValue, int minValue, int maxValue)
{
return riskValue >= minValue && riskValue <= maxValue;
}
}
</code></pre>
<p>Model classes:
- Base class InsuredProduct implements above interfaces.</p>
<pre><code>public abstract class InsuredProduct implements Product, Risk {
private int id;
private BigDecimal productValue;
private int riskValue;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public InsuredProduct(int id, BigDecimal productValue)
{
this.id = id;
this.productValue =productValue;
}
public BigDecimal getProductValue() {
return productValue;
}
public void setProductValue(BigDecimal productValue) {
this.productValue = productValue;
}
@Override
public BigDecimal getSubTotalPremium()
{
return getProductValue().multiply(getBasePremium());
}
@Override
public void setRiskValue(int riskValue) {
this.riskValue = riskValue;
}
public int getRiskValue() {
return this.riskValue;
}
}
</code></pre>
<p>Then Banana class as insured product extends from base class:</p>
<pre><code>public class Banana extends InsuredProduct {
private static BigDecimal BASE_PREMIUM = new BigDecimal(1.15);
private int noOfBlackSpots;
private int userRiskValue;
public Banana(int id, BigDecimal productValue) {
super(id, productValue);
}
public int getNoOfBlackSpots() {
return noOfBlackSpots;
}
public void setNoOfBlackSpots(int noOfBlackSpots) {
this.noOfBlackSpots = noOfBlackSpots;
}
@Override
public BigDecimal getBasePremium() {
return BASE_PREMIUM;
}
@Override
public BigDecimal getRiskSurcharge() {
if(this.userRiskValue > 200)
return Risk.getUnIdentifiedRiskSurcharge();
final int minAcceptableBlackSpots = 3;
final int maxAcceptableBlackSpots = 12;
if(Risk.isWithinRange(this.noOfBlackSpots, minAcceptableBlackSpots, maxAcceptableBlackSpots))
return Risk.getDefaultRiskSurcharge();
return Risk.getUnIdentifiedRiskSurcharge();
}
@Override
public void setRiskValue(int riskValue) {
this.userRiskValue = riskValue;
}
}
</code></pre>
<p>A User class (with Address) as an insured person. User's address is also part of risk surcharge to determine the quote calculation.</p>
<pre><code>public class User implements Risk {
private static final BigDecimal MAXIMUM_USER_RISK_SURCHARGE = new BigDecimal(3.0);
private static final BigDecimal MEDIUM_USER_RISK_SURCHARGE = new BigDecimal(1.0);
private static final BigDecimal MINIMUM_USER_RISK_SURCHARGE = new BigDecimal(0.3);
private int id;
private Address address;
private int riskValue;
public User(int id, Address address)
{
this.setId(id);
this.setAddress(address);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public int getRiskValue() {
return riskValue;
}
@Override
public void setRiskValue(int riskValue) {
this.riskValue = riskValue;
}
@Override
public BigDecimal getRiskSurcharge() {
final int unsupportedRiskValue = 501;
final int startMinimumRiskValue = 20;
final int endMinimumRangeRiskValue = 200;
final int startMaximumRiskValue = 201;
final int endMaximumRangeRiskValue = 500;
if(this.getRiskValue() >= unsupportedRiskValue)
return Risk.getUnIdentifiedRiskSurcharge();
if(this.getRiskValue() < startMinimumRiskValue)
return MINIMUM_USER_RISK_SURCHARGE;
if(Risk.isWithinRange(this.getRiskValue(), startMinimumRiskValue, endMinimumRangeRiskValue))
return MEDIUM_USER_RISK_SURCHARGE;
if(Risk.isWithinRange(this.getRiskValue(), startMaximumRiskValue, endMaximumRangeRiskValue))
return MAXIMUM_USER_RISK_SURCHARGE;
return Risk.getDefaultRiskSurcharge();
}
}
public class Address implements Risk{
private static final BigDecimal MAXIMUM_LOCATION_RISK_SURCHARGE = new BigDecimal(2.5);
private static final BigDecimal MEDIUM_LOCATION_RISK_SURCHARGE = new BigDecimal(1.0);
private static final BigDecimal MINIMUM_LOCATION_RISK_SURCHARGE = new BigDecimal(0.7);
private int id;
private int locationRisk;
public Address(int id)
{
this.id = id;
}
public int getRiskValue() {
return locationRisk;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public void setRiskValue(int riskValue) {
this.locationRisk = riskValue;
}
@Override
public BigDecimal getRiskSurcharge() {
final int unsupportedLocationRisk = 502;
final int startMinimumLocationRisk = 100;
final int endMinimumRangeLocationRisk = 299;
final int startMaximumLocationRisk = 300;
final int endMaximumRangeLocationRisk = 501;
if(this.getRiskValue() >= unsupportedLocationRisk)
return Risk.getUnIdentifiedRiskSurcharge();
if(this.getRiskValue() < startMinimumLocationRisk)
return MINIMUM_LOCATION_RISK_SURCHARGE;
if(Risk.isWithinRange(this.getRiskValue(), startMinimumLocationRisk, endMinimumRangeLocationRisk))
return MEDIUM_LOCATION_RISK_SURCHARGE;
if(Risk.isWithinRange(this.getRiskValue(), startMaximumLocationRisk, endMaximumRangeLocationRisk))
return MAXIMUM_LOCATION_RISK_SURCHARGE;
return Risk.getDefaultRiskSurcharge();
}
}
</code></pre>
<p>Processor: To calculate the premium quote or to determine if it's is insurable.</p>
<pre><code>public class UserPremiumBuilder<T extends InsuredProduct> {
private User user;
T product;
private UserPremiumBuilder(User user){
this.user = user;
}
public static <T extends InsuredProduct> UserPremiumBuilder<T> createProfile(User user){
UserPremiumBuilder<T> builder = new UserPremiumBuilder<T>(user);
return builder;
}
public UserPremiumBuilder <T> setProduct(T product) {
this.product = product;
return this;
}
public BigDecimal calculateSingleProductPremiumForUser() {
BigDecimal userRiskSurcharge = user.getRiskSurcharge();
if(Risk.getUnIdentifiedRiskSurcharge().compareTo(userRiskSurcharge)==0)
return Risk.getUnIdentifiedRiskSurcharge();
this.product.setRiskValue(this.user.getRiskValue());
BigDecimal productRiskSurcharge =this.product.getRiskSurcharge();
if(Risk.getUnIdentifiedRiskSurcharge().compareTo(productRiskSurcharge)==0)
return Risk.getUnIdentifiedRiskSurcharge();
if(Risk.getDefaultRiskSurcharge().compareTo(productRiskSurcharge)==0)
return this.product.getSubTotalPremium();
BigDecimal totalPremium = this.product.getSubTotalPremium().multiply(this.product.getRiskSurcharge()).multiply(user.getRiskSurcharge());
return totalPremium;
}
}
</code></pre>
<p>A sample unit test class:</p>
<pre><code>public class UserPremiumBuilderBananaTest {
Banana banana;
@Before
public void initBanana()
{
banana = new Banana(1, new BigDecimal(10));
}
@Test
public void testUnInsurableBananaRiskSurchargeWithUserRiskValueLargerThan200() {
User user = initUser(10);
user.setRiskValue(201);
banana.setRiskValue(user.getRiskValue());
banana.setNoOfBlackSpots(4);
BigDecimal totalPremium = createProfile(user).setProduct(banana).calculateSingleProductPremiumForUser();
assertEquals(Risk.getUnIdentifiedRiskSurcharge(), totalPremium);
}
@Test
public void testInsurableBananaRiskSurchargeWithUserRiskNotGreaterThan200() {
User user = initUser(10);
user.setRiskValue(200);
banana.setRiskValue(user.getRiskValue());
banana.setNoOfBlackSpots(3);
UserPremiumBuilder<Banana> builder = createProfile(user);
BigDecimal totalPremium = builder.setProduct(banana).calculateSingleProductPremiumForUser();
totalPremium = totalPremium.setScale(2, BigDecimal.ROUND_HALF_EVEN);
BigDecimal productPremium = banana.getSubTotalPremium().setScale(2, BigDecimal.ROUND_HALF_EVEN);
assertEquals(productPremium, totalPremium);
user.setRiskValue(199);
totalPremium = builder.setProduct(banana).calculateSingleProductPremiumForUser();
totalPremium = totalPremium.setScale(2, BigDecimal.ROUND_HALF_EVEN);
assertEquals(productPremium, totalPremium);
}
private static UserPremiumBuilder<Banana> createProfile(User user)
{
return UserPremiumBuilder.createProfile(user);
}
private User initUser(int addressRiskValue)
{
Address address = new Address(1);
address.setRiskValue(addressRiskValue);
User user = new User(1, address);
return user;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T15:22:09.107",
"Id": "404825",
"Score": "0",
"body": "At a first glance, try to avoid instantiating BigDecimals when you can reuse existing instances. Thus, instead of `new BigDecimal(0)` use `BigDecimal.ZERO`. Similar instances exists for `ONE` and `TEN` as well. Also, don't use the `double` constructor of BigDecimal, because double can be imprecise and your 3.0 could become 3.0000000001. Use either `new BigDecimal(\"3.0\")` or `BigDecimal.valueOf(3.0)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T15:45:12.193",
"Id": "404831",
"Score": "0",
"body": "@Tom: Thank you, definitely very useful advice! If you could also shed some light on the interviewer's feedback to my code: \"deep use of mutation and a not that well thought up internal API.\", I really appreciate that!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T15:50:24.840",
"Id": "404832",
"Score": "0",
"body": "I'm sorry, I don't have the time for further inspections of the code, but I'm sure someone else will gladly help you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T14:30:42.113",
"Id": "404962",
"Score": "1",
"body": "What is risk value? It's making the question nearly unanswerable"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T15:05:19.387",
"Id": "404974",
"Score": "0",
"body": "@Pimgd: Risk value is given differently per product and user, as part of premium quote calculation. More information has been added."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T10:49:17.770",
"Id": "405114",
"Score": "0",
"body": "@Anna thanks for updating your question. I've answered it."
}
] | [
{
"body": "<p>Your model classes are also doing the calculating and that hurts.</p>\n\n<p>I've been trying to understand the code for a while now and that's the main point I keep coming up with.</p>\n\n<pre><code>@Override\npublic BigDecimal getRiskSurcharge() {\n if(this.userRiskValue > 200)\n return Risk.getUnIdentifiedRiskSurcharge();\n\n final int minAcceptableBlackSpots = 3;\n final int maxAcceptableBlackSpots = 12;\n\n if(Risk.isWithinRange(this.noOfBlackSpots, minAcceptableBlackSpots, maxAcceptableBlackSpots))\n return Risk.getDefaultRiskSurcharge(); \n\n return Risk.getUnIdentifiedRiskSurcharge();\n}\n</code></pre>\n\n<p>This does not belong in a Banana.</p>\n\n<p>This is your business logic. It goes in the processor or parts thereof.</p>\n\n<p>When I look at the Processor itself, then I also see something strange: </p>\n\n<pre><code>public BigDecimal calculateSingleProductPremiumForUser() {\n BigDecimal userRiskSurcharge = user.getRiskSurcharge();\n if(Risk.getUnIdentifiedRiskSurcharge().compareTo(userRiskSurcharge)==0)\n return Risk.getUnIdentifiedRiskSurcharge();\n\n this.product.setRiskValue(this.user.getRiskValue());\n BigDecimal productRiskSurcharge =this.product.getRiskSurcharge();\n if(Risk.getUnIdentifiedRiskSurcharge().compareTo(productRiskSurcharge)==0)\n return Risk.getUnIdentifiedRiskSurcharge();\n\n if(Risk.getDefaultRiskSurcharge().compareTo(productRiskSurcharge)==0)\n return this.product.getSubTotalPremium();\n\n BigDecimal totalPremium = this.product.getSubTotalPremium().multiply(this.product.getRiskSurcharge()).multiply(user.getRiskSurcharge());\n return totalPremium;\n}\n</code></pre>\n\n<p>Given a User (which was provided via the constructor) and a Product (which may be null)...</p>\n\n<p>Actually, let's stop there for a moment.</p>\n\n<p>Why can product be null?</p>\n\n<p>Here's one of your tests, with the code of functions inlined.</p>\n\n<pre><code>@Test\npublic void testUnInsurableBananaRiskSurchargeWithUserRiskValueLargerThan200() {\n Banana banana = new Banana(1, new BigDecimal(10));\n Address address = new Address(1);\n address.setRiskValue(10);\n User user = new User(1, address);\n user.setRiskValue(201);\n\n banana.setRiskValue(user.getRiskValue());\n banana.setNoOfBlackSpots(4);\n\n BigDecimal totalPremium = UserPremiumBuilder\n .createProfile(user)\n .setProduct(banana)\n .calculateSingleProductPremiumForUser();\n assertEquals(Risk.getUnIdentifiedRiskSurcharge(), totalPremium);\n}\n</code></pre>\n\n<p>Let's look at it from this perspective.</p>\n\n<p>The Banana constructor takes an id and a product value.</p>\n\n<p>We need a User with an id and address, and the address also has an id and a risk value.</p>\n\n<p>Then we set the user's risk value, which is something like a credit score but for insurances.</p>\n\n<p>Next, we place the risk value of the user in the banana.</p>\n\n<p>That part makes no sense to me.</p>\n\n<p>Next, set amount of black spots for the banana (which is just part of test setup again).</p>\n\n<p>Then, using the UserPremiumBuilder, create a profile, set a product, and calculate the product premium.</p>\n\n<hr>\n\n<p>I'll describe the issues I have with the ideas presented in the unit test, and then draft my own interface. Afterward, I'll explain to you why I think they are a better fit for the problem domain.</p>\n\n<p>I can imagine there's an insurance company that has statistics for things. Given an address, it can find how much \"bonus\" it should apply. Furthermore, given some kind of history, people have scores, and these scores also define some sort of bonus. Lastly, depending on the type, different restrictions and calculations may apply. For instance, refusing to insure any car older than 40 years, or any house which has not been inspected.</p>\n\n<p>It's with that imagination that I'll build my model classes and interfaces.</p>\n\n<p>A customer rings up the company. They provide their customer id. Their score is retrieved from some database. Also retrieved from the database is their address, which has been given a score by our automatic scoring system.</p>\n\n<pre><code>Address address = new Address(1, 10); //ID, Risk value\nUser user = new User(1, address, 201); //ID, address, risk value\n</code></pre>\n\n<p>Since we can't service customers properly if we don't know their scores or where they live (or what the score is for where they live), all of this is required in the constructor.</p>\n\n<p>The customer says they have a banana they wish to insure (it's very important to them). We ask them for some of the details and register the banana in our database. However, if that's the logic we follow, I'd expect a product to have a reference to a user (namely the \"owner\" of the product). We'll ignore that for now, I guess a Banana requires an id for SOME reason, if only due to business requirements.</p>\n\n<pre><code>Banana banana = new Banana(1, new BigDecimal(10), 4); //ID, value, black spots\n</code></pre>\n\n<p>The customer says they'd only want to insure this one banana and if we could provide them with a quote.</p>\n\n<p>So, we enter into the calculator - our user (with their address) and our banana.</p>\n\n<pre><code>BigDecimal totalPremium = PremiumCalculator.calculateFor(user, banana); //User user, Product[] products...\n</code></pre>\n\n<p>We now have a total premium which we can use.</p>\n\n<p>The full code for this section:</p>\n\n<pre><code>Address address = new Address(1, 10); //ID, Risk value\nUser user = new User(1, address, 201); //ID, address, risk value\nBanana banana = new Banana(1, new BigDecimal(10), 4); //ID, value, black spots\n\nBigDecimal totalPremium = PremiumCalculator.calculateFor(user, banana); //User user, InsurableProduct[] products...\n</code></pre>\n\n<hr>\n\n<p>I did hide some of the details, though.</p>\n\n<p>I'm sure it's fine if I skip over the part where I redefined constructors for Address, User and Banana.</p>\n\n<p>I think I should explain at least part of the interfaces:</p>\n\n<pre><code>public interface InsurableProduct {\n BigDecimal getProductValue();\n default BigDecimal getBasePremiumMultiplier() {\n return BigDecimal.ONE;\n }\n default BigDecimal getRiskSurchargeMultiplier() {\n return BigDecimal.ONE;\n }\n boolean canBeInsuredFor(User user);\n}\n</code></pre>\n\n<p>This is an insurable product. It has a base value, which you can multiply by the premium multiplier to get a sub total premium, which you can multiply by the risk surcharge multiplier to get the final price.</p>\n\n<p>It also has a \"canBeInsuredFor\" method; this is to specify logic like \"don't insure bananas that have a million black spots\". It also takes a user, since for some products, we might say \"If the user is living in a high risk area, we'll refuse to insure your $100k car\".</p>\n\n<p>Okay, so how does this \"PremiumCalculator\" work?</p>\n\n<pre><code>public class PremiumCalculator {\n private PremiumCalculator() { \n //No instantiation required/allowed\n }\n public static BigDecimal calculateFor(User user, InsurableProduct[] products...) {\n BigDecimal total = BigDecimal.ZERO;\n for (InsurableProduct product : products) {\n if (!product.canBeInsuredFor(user)) { \n return Risk.getUnIdentifiedRiskSurcharge(); //Left this in for now\n }\n BigDecimal productValue = product.getProductValue();\n BigDecimal productSubtotal = productValue.multiply(product.getBasePremiumMultiplier());\n BigDecimal productPremium = productSubtotal.multiply(product.getRiskSurchargeMultiplier());\n total = total.add(productPremium);\n }\n return total.multiply(user.getRiskSurcharge());\n }\n}\n</code></pre>\n\n<p>It takes the user and products, and if any of them in uninsurable, it returns the unidentified risk surcharge value - your \"error\" value. I don't like how it's handled, but I don't have a better solution yet.</p>\n\n<p>Start the total off at zero, and then, for each product, calculate the productPremium via value * basePremiumMultiplier * riskSurchargeMultiplier. Then add to the total.</p>\n\n<p>Finally, multiply the total by the users's risk surcharge.</p>\n\n<p>This places your calculations in a single class.</p>\n\n<p>As for the implementation of your Banana:</p>\n\n<pre><code>public class Banana implements InsurableProduct {\n private static BigDecimal BASE_PREMIUM = new BigDecimal(1.15);\n\n private final int id;\n private final BigDecimal productValue;\n private final int noOfBlackSpots;\n\n public Banana(int id, BigDecimal productValue, int noOfBlackSpots) {\n this.id = id;\n this.productValue = productValue;\n this.noOfBlackSpots = noOfBlackSpots;\n }\n\n public int getId() {\n return id;\n }\n\n public int getNoOfBlackSpots() {\n return noOfBlackSpots;\n }\n\n @Override\n public BigDecimal getProductValue() {\n return productValue;\n }\n\n @Override\n public BigDecimal getBasePremiumMultiplier() {\n return BASE_PREMIUM;\n }\n\n @Override\n public boolean canBeInsuredFor(User user) {\n final int minAcceptableBlackSpots = 3;\n final int maxAcceptableBlackSpots = 12;\n\n return Risk.isWithinRange(noOfBlackSpots, minAcceptableBlackSpots, maxAcceptableBlackSpots) && user.getRiskValue() <= 200;\n }\n\n @Override\n public BigDecimal getRiskSurchargeMultiplier() {\n return Risk.getDefaultRiskSurcharge(); \n }\n}\n</code></pre>\n\n<p>Some of this might be extractable to a base class; I don't care about that right now.</p>\n\n<hr>\n\n<p>What I have done is decouple \"can be insured\" and \"can be insured for\", for products. I have also migrated the User's risk value to be part of the user, and not individually set, first.</p>\n\n<p>By relocating the calculations to the calculator, the only thing the products still contain are the actual rules. If we remove the getters and setters from the Banana, we're left with this:</p>\n\n<pre><code>public class Banana implements InsurableProduct {\n public final int id;\n public final BigDecimal productValue;\n public final int noOfBlackSpots;\n\n public Banana(int id, BigDecimal productValue, int noOfBlackSpots) {\n this.id = id;\n this.productValue = productValue;\n this.noOfBlackSpots = noOfBlackSpots;\n }\n\n @Override\n public BigDecimal getProductValue() {\n return productValue;\n }\n\n @Override\n public BigDecimal getBasePremiumMultiplier() {\n return new BigDecimal(1.15);\n }\n\n @Override\n public boolean canBeInsuredFor(User user) {\n final int minAcceptableBlackSpots = 3;\n final int maxAcceptableBlackSpots = 12;\n\n return Risk.isWithinRange(noOfBlackSpots, minAcceptableBlackSpots, maxAcceptableBlackSpots) && user.getRiskValue() <= 200;\n }\n\n @Override\n public BigDecimal getRiskSurchargeMultiplier() {\n return Risk.getDefaultRiskSurcharge(); \n }\n}\n</code></pre>\n\n<p>(I've made the variables public so you could still retrieve them).</p>\n\n<p>In essence, this is all the real coding required. Three of these methods are simple getters still, the last one contains your business logic, and even then it's small and to the point.</p>\n\n<p>Further more, you'll notice that the whole use of \"mutation\" is gone. There are no setters. A Banana is immutable. You want to change something? Get a new Banana. Whether that meets the business needs remains to be seen. But for a quote-creating application, if you don't need to be able to modify it, then you can't modify it.</p>\n\n<p>I believe this should showcase enough on how to create a better API (you must provide all values, you can't forget something) and how to reduce mutation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T08:48:40.650",
"Id": "405691",
"Score": "0",
"body": "Thank you! Your design looks much better than mine. One question: you said it’s not good to put logic in model; so where should I put the calculation logic for each type of product in this example that you could suggest? And do we always avoid putting (business) logic in the models? If so, could you share the reason why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T09:47:08.937",
"Id": "405699",
"Score": "0",
"body": "@Anna It's not good to put logic in the model because if you have another model that you want to apply the same (or mostly the same) logic too, you now have to duplicate the logic, which is not ideal. Basically, you're trying to separate concerns (google separation of concerns). If you later have to deal with persistence to a database, or transformation of entities to a DTO, or other manipulations, you want the smallest models you can get away with, because it reduces your complexity and test setup."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T14:29:51.233",
"Id": "209529",
"ParentId": "209439",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T13:00:36.233",
"Id": "209439",
"Score": "4",
"Tags": [
"java"
],
"Title": "Insurance Premium Quote Challenge"
} | 209439 |
<p>I have below working code with <code>pandas</code> and <code>python</code>, i'm looking if there is an improvement or simplification which can be done.</p>
<p>Can we Just wrap this up into a definition.</p>
<pre><code>$ cat getcbk_srvlist_1.py
#!/python/v3.6.1/bin/python3
from __future__ import print_function
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE,SIG_DFL)
import pandas as pd
import os
##### Python pandas, widen output display to see more columns. ####
pd.set_option('display.height', None)
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('expand_frame_repr', True)
##################### END OF THE Display Settings ###################
################# PANDAS Extraction ###########
df_csv = pd.read_csv(input("Please input the CSV File Name: "), usecols=['Platform ID', 'Target system address']).dropna()
hostData = df_csv[df_csv['Platform ID'].str.startswith("CDS-Unix")]['Target system address']
hostData.to_csv('host_file1', header=None, index=None, sep=' ', mode='a')
with open('host_file1') as f1, open('host_file2') as f2:
dataset1 = set(f1)
dataset2 = set(f2)
for i, item in enumerate(sorted(dataset2 - dataset1)):
print(str(item).strip())
os.unlink("host_file1")
</code></pre>
<p>The above code just compares the two files one is processed through pandas ie <code>host_file1</code> and another is already existing <code>host_file2</code>.</p>
| [] | [
{
"body": "<h1>main guard</h1>\n\n<p>It is common to put the code you want to run behind an <code>if __name__ == \"__main__\":</code>, so you can later import the functions that might be reused in a different module</p>\n\n<h1>naming</h1>\n\n<p>You use both <code>snake_case</code> and <code>CamelCase</code>. Try to stick to 1 naming convention. PEP-8 advised <code>snake_case</code> for variables and functions, <code>CamelCase</code> for classes</p>\n\n<h1>functions</h1>\n\n<p>split the code in logical parts</p>\n\n<h2>pandas settings</h2>\n\n<pre><code>def settings_pandas():\n pd.set_option(\"display.height\", None)\n pd.set_option(\"display.max_rows\", None)\n pd.set_option(\"display.max_columns\", None)\n pd.set_option(\"display.width\", None)\n pd.set_option(\"expand_frame_repr\", True)\n</code></pre>\n\n<h2>filename input</h2>\n\n<p>The way you ask the filename is very fragile. A more robust way would be to ask the filename in a different function, and then validate it</p>\n\n<pre><code>from pathlib import Path\ndef ask_filename(validate=True):\n \"\"\"\n Asks the user for a filename.\n If `validate` is True, it checks whether the file exists and it is a file\n \"\"\"\n while True:\n file = Path(input(\"Please input the CSV File Name: (CTRL+C to abort)\"))\n if validate:\n if not file.exists() and file.is_file():\n print(\"Filename is invalid\")\n continue\n return file\n</code></pre>\n\n<h1>IO</h1>\n\n<pre><code>def read_host_data(filename):\n \"\"\"reads `filename`, filters the unix platforms, and returns the `Target system address`\"\"\"\n df = pd.read_csv(filename, usecols=[\"Platform ID\", 'Target system address']).dropna()\n unix_platforms = df['Platform ID'].str.startswith(\"CDS-Unix\")\n return df.loc[unix_platforms, \"Target system address\"]\n</code></pre>\n\n<p>There is no need to save the intermediary data to a file. You could use a <code>io.StringIO</code>. An alternative if you need a temporary file is <a href=\"https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryFile\" rel=\"nofollow noreferrer\"><code>tempfile</code></a>.</p>\n\n<p>But in this case, where you just need the set of the values of a <code>pd.Series</code>, you can do just <code>set(host_data)</code>, without the intermediary file.</p>\n\n<h1>putting it together:</h1>\n\n<pre><code>if __name__ == \"__main__\":\n settings_pandas() # needed?\n filename = ask_filename()\n host_data = set(read_host_data(filename))\n with open(\"hostfile2\") as hostfile2:\n host_data2 = set(hostfile2)\n for item in sorted(host_data2 - host_data):\n print(item.strip())\n</code></pre>\n\n<p>since the <code>i</code> is not used, I dropped the <code>enumerate</code>. Since <code>host_data2</code> is directly read from a file, there are no conversions, and it are all <code>str</code>s, so the conversion to <code>str</code> is dropped too.</p>\n\n<p>Since I don't see any printing of <code>pandas</code> data, This part can be dropped apparently.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T15:15:03.443",
"Id": "404981",
"Score": "0",
"body": "@.Maarten, thnx for the elaborated and explicit explanation."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T08:52:46.620",
"Id": "209504",
"ParentId": "209440",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209504",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T13:05:36.733",
"Id": "209440",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"pandas"
],
"Title": "How to better process csv file with pandas and further dealing with set"
} | 209440 |
<p>I have created my first Java app. I am very familiar with C++ and thus without reading any books (just introduction, googling and IntelliJ auto-completion) I directly jumped into Java.
So I made a calculator.</p>
<p>Main.java:</p>
<pre><code>import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.*;
import javax.swing.text.PlainDocument;
import java.awt.*;
import java.awt.event.KeyEvent;
class Main extends JFrame {
public static void main(String[] args) throws AWTException {
System.out.println("init");
var app = new Main();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setVisible(true);
}
private JButton numButtons[] = new JButton[10];
private JButton opeButtons[] = new JButton[5];
private JButton lb = new JButton("(");
private JButton rb = new JButton(")");
private JButton cb = new JButton("C");
private JButton decb = new JButton(".");
private JTextField text = new JTextField();
private Robot keyboard = new Robot();
private ScriptEngine jsEng;
public Main() throws AWTException {
super();
jsEng = (new ScriptEngineManager()).getEngineByName("js");
var textDoc = (PlainDocument)text.getDocument();
textDoc.setDocumentFilter(new EquationFilter());
initGui();
for(JButton i : numButtons) {
i.addActionListener(e -> simKey(i.getText().charAt(0)));
}
for(int i = 0;i<4;i++) {
int finalI = i;
opeButtons[i].addActionListener(e -> simKey(opeButtons[finalI].getText().charAt(0)));
}
decb.addActionListener(e -> simKey(decb.getText().charAt(0)));
rb.addActionListener(e -> simKey(rb.getText().charAt(0)));
lb.addActionListener(e -> simKey(lb.getText().charAt(0)));
cb.addActionListener(e-> text.setText(""));
opeButtons[4].addActionListener(e -> {
try {
text.setText(jsEng.eval(text.getText()).toString());
} catch (ScriptException e1) {
e1.printStackTrace();
}
});
}
private void simKey(char code){
text.requestFocus();
keyboard.keyPress(KeyEvent.VK_SHIFT);
switch (code) {
case '+':
keyboard.keyPress(KeyEvent.VK_EQUALS);
keyboard.keyRelease(KeyEvent.VK_EQUALS);
break;
case '(':
keyboard.keyPress(KeyEvent.VK_LEFT_PARENTHESIS);
keyboard.keyRelease(KeyEvent.VK_LEFT_PARENTHESIS);
break;
case ')':
keyboard.keyPress(KeyEvent.VK_RIGHT_PARENTHESIS);
keyboard.keyRelease(KeyEvent.VK_RIGHT_PARENTHESIS);
break;
case '*':
keyboard.keyPress('8');
keyboard.keyRelease('8');
break;
default:
keyboard.keyRelease(KeyEvent.VK_SHIFT);
keyboard.keyPress(code);
keyboard.keyRelease(code);
return;
}
keyboard.keyRelease(KeyEvent.VK_SHIFT);
}
private void initGui(){
setTitle("Calculator");
setSize(400,500);
var grid = new GridBagLayout();
setLayout(grid);
GridBagConstraints gridCon = new GridBagConstraints();
gridCon.weightx = gridCon.weighty = 1.0;
gridCon.gridy = 0;
gridCon.gridx = 0;
gridCon.gridwidth = 4;
gridCon.fill = gridCon.BOTH;
add(text,gridCon);
gridCon.gridwidth = 1 ;
String names[] = {"+","-","/","*","="};
for(int i = 0;i < 5; i++){
opeButtons[i] = new JButton(names[i]);
}
gridCon.gridx = 3;
for( int y = 1; y < 6; y++ ){
gridCon.gridy = y;
add(opeButtons[y-1],gridCon);
}
for(int y = 2, i = 1; y < 5; y++ ){
for(int x = 0 ; x < 3; x++,i++) {
gridCon.gridx = x;
gridCon.gridy = y;
numButtons[i] = new JButton(Integer.toString(i));
add(numButtons[i],gridCon);
}
}
gridCon.gridx = 0;
gridCon.gridy = 1;
add(lb,gridCon);
gridCon.gridx = 1;
add(rb,gridCon);
gridCon.gridx = 2;
add(cb,gridCon);
numButtons[0] = new JButton("0");
gridCon.gridx = 0;
gridCon.gridy = 5;
gridCon.gridwidth = 2;
add(numButtons[0],gridCon);
gridCon.gridwidth = 1;
gridCon.gridx = 2;
add(decb,gridCon);
}
}
</code></pre>
<p>EquationFilter.java:</p>
<pre><code>import javax.swing.text.AttributeSet;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.BadLocationException;
import java.awt.event.KeyEvent;
import java.security.Key;
public class EquationFilter extends DocumentFilter {
@Override
public void insertString(FilterBypass fb, int offset, String string,
AttributeSet attr) throws BadLocationException {
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.insert(offset, string);
if (test(sb.toString())) {
super.insertString(fb, offset, string, attr);
}
}
private boolean test(String text) {
char validInput[] = {'1','2','3','4','5','6','7','8','9','0','.','/','*','-','+','(',')',' ','\0','\b'};
if(text.isEmpty())
return true;
for(char i : validInput){
if(i == text.charAt(text.length()-1))
return true;
}
return false;
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text,
AttributeSet attrs) throws BadLocationException {
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.replace(offset, offset + length, text);
if (test(sb.toString())) {
super.replace(fb, offset, length, text, attrs);
}
}
@Override
public void remove(FilterBypass fb, int offset, int length)
throws BadLocationException {
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.delete(offset, offset + length);
try {
if (test(sb.toString())) {
super.remove(fb, offset, length);
}
}
catch (StringIndexOutOfBoundsException e) {
super.remove(fb,0,1);
}
}
}
</code></pre>
<p><a href="https://gitlab.com/SmitTheTux/javacalculator/tree/937a0300d55bd25afef7c419439643e8628238fb" rel="nofollow noreferrer">https://gitlab.com/SmitTheTux/javacalculator</a></p>
<p>Please suggest me improvments.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T15:42:37.227",
"Id": "404829",
"Score": "0",
"body": "It looks to me that the `test` method doesn't do what one might expect. As it is, it only checks if the last character of the input string is valid. It seems to me that one would want to check that all the characters of the input string are valid. Is the current behavior what you expected?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T15:26:27.060",
"Id": "209449",
"Score": "2",
"Tags": [
"java",
"beginner",
"calculator",
"swing"
],
"Title": "My first Java app: a calculator in Swing"
} | 209449 |
<p>I repeated a lot of code here and I'm trying to use more ES6 but I'm not sure where I should have used it in my code. I'd appreciate any input on where I could improve.</p>
<p><a href="https://github.com/aioy/calendar/tree/e3245533f938a4a2e64ab66d11ecb949d1c96a20" rel="nofollow noreferrer">GitHub</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>"use strict";
//Calendar
let today = new Date();
let currentMonth = today.getMonth();
let currentYear = today.getFullYear();
let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
//JSON event data
let eventData = {
"events": [
{
"description": 'es',
"year": '2018',
"month": 'Nov',
"day": '28'
}
]
};
let headerMonths = document.getElementsByClassName('month')[0];
let headerYears = document.getElementsByClassName('year')[0];
let next = document.getElementById('next');
let prev = document.getElementById('prev');
let selectYear = document.getElementById('year');
let selectMonth = document.getElementById('month');
selectYear.value=currentYear;
selectMonth.value=currentMonth;
next.addEventListener('click', nextMonth);
prev.addEventListener('click', previousMonth);
selectYear.addEventListener('input', (event)=> {
if(event.keyCode == 13) {
event.preventDefault();
return false;
} else {
jump();
}
})
selectMonth.addEventListener('change', jump);
showCalendar(currentMonth,currentYear);
showEvents();
function showCalendar(month, year) {
let firstDay = (new Date(year, month)).getDay();
let tbl = document.getElementsByClassName("calendar-days")[0]; // body of the calendar
// clearing all previous cells
tbl.innerHTML = "";
// filing data about month and in the page via DOM.
headerMonths.innerHTML = months[month];
headerYears.innerHTML = year;
// creating all cells
let date = 1;
for (let i = 0; i < 6; i++) {
// creates a table row
let row = document.createElement("tr");
//creating individual cells, filing them up with data.
for (let j = 0; j < 7; j++) {
if (i === 0 && j < firstDay) {
let cell = document.createElement("td");
let cellText = document.createTextNode("");
cell.appendChild(cellText);
row.appendChild(cell);
}
else if (date > daysInMonth(month, year)) {
break;
}
else {
let cell = document.createElement("td");
let cellText = document.createTextNode(date);
if (date === today.getDate() && year === today.getFullYear() && month === today.getMonth()) {
cell.classList.add("active"); // color today's date
}
cell.classList.add('day');
cell.appendChild(cellText);
row.appendChild(cell);
date++;
}
}
tbl.appendChild(row); // appending each row into calendar body.
}
}
function nextMonth() {
currentYear = (currentMonth === 11) ? currentYear + 1 : currentYear;
currentMonth = (currentMonth + 1) % 12;
showCalendar(currentMonth, currentYear);
showEvents();
}
function previousMonth() {
currentYear = (currentMonth === 0) ? currentYear - 1 : currentYear;
currentMonth = (currentMonth === 0) ? 11 : currentMonth - 1;
showCalendar(currentMonth, currentYear);
showEvents();
}
function jump() {
currentYear = parseInt(selectYear.value);
currentMonth = parseInt(selectMonth.value);
showCalendar(currentMonth, currentYear);
showEvents();
}
function daysInMonth (month, year) {
return new Date(year, month+1, 0).getDate();
}
// Events
//https://stackoverflow.com/questions/34896106/attach-event-to-dynamic-elements-in-javascript Event Delegation for new elements
document.addEventListener('click',function(e){
if(!e.target.classList.contains('active') && e.target.classList.contains('day')){
if(document.getElementsByClassName('active')[0] === undefined){
e.target.classList.add('active');
}
document.getElementsByClassName('active')[0].classList.remove('active');
if(document.getElementsByClassName('active')[0] === undefined){
e.target.classList.add('active');
}
e.target.classList.add('active');
} else if(e.target.classList.contains('active')===null && e.target.classList.contains('day')){
e.target.classList.add('active');
}
});
//handles new Event form
let newEvent = {
// day: parseInt(event.innerHTML),
desc: document.querySelector('#new-event-desc'),
month: headerMonths,
year: headerYears,
active: document.getElementsByClassName('active'),
submit: ()=>{
if(newEvent.desc.value.length===0) {
newEvent.desc.classList.add('error');
newEvent.desc.style.border='4px solid red';
} else {
newEventJson(newEvent.desc.value, newEvent.month.innerHTML, newEvent.year.innerHTML, newEvent.active[0].innerHTML);
hideShowEventsDiv();
showEventText(newEvent.desc.value);
newEvent.desc.classList.remove('error');
newEvent.desc.style.border='none';
newEvent.clear();
}
},
clear: ()=>{
newEvent.desc.value='';
}
};
const hideShowEventsDiv = ()=> {
let eventsDiv = document.querySelector('.events');
let newEventForm = document.querySelector('.new-event-form');
let saveEventButton = document.querySelector('.submit-event');
let showEventForm = document.querySelector('.show-event-form');
if(eventsDiv.classList.contains('hidden')){
//show Events
newEventForm.classList.add('hidden');
newEventForm.classList.remove('visible');
eventsDiv.classList.remove('hidden');
eventsDiv.classList.add('visible');
showEvents();
//change rotate class for Event listener
saveEventButton.classList.remove('rotate');
showEventForm.classList.add('rotate');
} else {
//show new Event Form
eventsDiv.classList.remove('visible');
eventsDiv.classList.add('hidden');
newEventForm.classList.remove('hidden');
newEventForm.classList.add('visible');
showEventForm.classList.remove('rotate');
saveEventButton.classList.add('rotate');
}
}
//Submit form and show event or new event form
document.addEventListener('click', (e)=>{
e.preventDefault();
if(e.target.classList.contains('rotate') && e.target.classList.contains('submit-event')){
newEvent.submit();
} else if(e.target.classList.contains('rotate')) {
hideShowEventsDiv();
}
});
//color the events on the calendar
function showEvents () {
let days = document.getElementsByClassName('day');
let events = [];
[...eventData['events']].forEach((event)=>{
[...days].forEach((day)=>{
if(event['day']===day.innerHTML && event['month']===headerMonths.innerHTML && event['year']===headerYears.innerHTML){
day.classList.add('active-event');
events.push(event)
}
});
});
return events;
}
//clears previous event Text
function clearEventText() {
if(document.getElementsByClassName('event-desc')){
[...document.getElementsByClassName('event-desc')].forEach((event)=>{
event.outerHTML='';
});
}
}
//shows eventText
function showEventText(desc) {
let noEvents = document.getElementsByClassName('no-Events')[0];
let eventsDescContainer = document.querySelector('.events');
//span element to put Event text into
const span = document.createElement('span');
let EventText = document.createTextNode(desc);;
//delete button for span
const remove = document.createElement('div');
let x = document.createTextNode('x');
remove.appendChild(x);
remove.classList.add('remove');
//clear previous events message
noEvents.classList.remove('show');
noEvents.style.display='none';
//append to container
span.appendChild(EventText)
span.appendChild(remove);
span.classList.add('event-desc', 'event-message');
eventsDescContainer.appendChild(span);
}
//compares eventData array values to date of day clicked on
const checkEvents = (obj, date)=>{
let isInArray = eventData['events'].find(event => event[obj]===date)
return isInArray;
}
// //handler to show text from eventData array
document.addEventListener('click', (e)=> {
let noEvents = document.getElementsByClassName('no-Events')[0];
if(e.target.classList.contains('day')){
//Clear previous event Text
clearEventText();
if(eventData.events.length===0){
noEvents.style.display='initial';
noEvents.innerHTML = `There are no events on ${headerMonths.innerHTML} ${e.target.innerHTML} ${headerYears.innerHTML}`;
} else {
[...eventData['events']].forEach((event)=>{
if(event['day']===e.target.innerHTML && event['month']===headerMonths.innerHTML && event['year']===headerYears.innerHTML){
//show event Text
showEventText(event['description']);
} else if(!checkEvents('year',headerYears.innerHTML) || !checkEvents('month', headerMonths.innerHTML) || !checkEvents('day', e.target.innerHTML)) {
clearEventText();
noEvents.style.display='initial';
noEvents.innerHTML = `There are no events on ${headerMonths.innerHTML} ${e.target.innerHTML} ${headerYears.innerHTML}`;
}
});
}
}
});
//click on x to remove event
document.addEventListener('click', (x)=>{
//day clicked on
let day = document.getElementsByClassName('active')[0];
let noEvents = document.getElementsByClassName('no-Events')[0];
if(x.target.classList.contains('remove')){
let eventText = x.target.parentNode.textContent.slice(0,-1);
for(var i = eventData.events.length-1; i >= 0; --i) {
if(eventData.events[i]['day']===day.innerHTML && eventData.events[i]['month']===headerMonths.innerHTML && eventData.events[i]['year']===headerYears.innerHTML && eventData.events[i]['description']===eventText){
eventData.events.splice(i,1);
//remove event clicked on from view
x.target.parentNode.classList.add('swingHide');
setInterval(()=>{
x.target.parentNode.outerHTML='';
},500);
//if no events on day selected show message
if(!checkEvents('year',headerYears.innerHTML) || !checkEvents('month', headerMonths.innerHTML) || !checkEvents('day', day.innerHTML)){
setTimeout(()=>{
noEvents.style.display='initial';
},600)
noEvents.innerHTML = `There are no events on ${headerMonths.innerHTML} ${day.innerHTML} ${headerYears.innerHTML}`;
day.classList.remove('active-event');
}
//if events on day selected show them
if(checkEvents('year',headerYears.innerHTML) && checkEvents('month', headerMonths.innerHTML) & checkEvents('day', day.innerHTML)){
showEventText(eventData.events[i].description);
}
}
}
}
});
//adds json to eventData
function newEventJson(description, month, year, day){
let event = {
"description": description,
"year": year,
"month": month,
"day": day
};
eventData.events.push(event);
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css?family=Muli');
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
font-family: 'Muli', sans-serif;
background-image: linear-gradient(to right, #649173, #dbd5a4 );
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
/***** Container- calendar- Events ******/
.container {
display: flex;
flex-direction: row;
margin: 40px auto;
padding: 20px;
align-items: stretch;
justify-content: center;
}
.calendar {
align-self:center;
display: flex;
flex-direction: column;
align-items: center;
border: 2px solid black;
min-height: 425px;
}
/***** Calender Header *****/
.date-header{
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
background-image: linear-gradient(to right, #649173, #dbd5a4 );
height:2em;
box-shadow: 0 3px 6px rgba(0,0,0,0.16),
0 3px 6px rgba(0,0,0,0.23);
}
.date-header .time-skip{
height:100%;
line-height: 2em;
padding: 0 .2em 0 .2em;
}
.date-header .time-skip:hover {
background-color: rgba(0,0,0,0.30);
cursor: pointer;
}
/***** Calendar Body *****/
.days-body thead .days-row th {
padding: 1em;
cursor: default;
border: 2px solid black;
font-weight: bold;
}
.days-body thead .days-row th:hover{
color:yellow;
transition: .5s;
}
.calendar-days td {
padding: 1em;
cursor: default;
border: 2px solid black;
text-align:center;
transition: all 600ms;
}
.calendar-days td:hover {
background: #dd9756;
}
/******** Select Date *********/
.select-date {
border: 2px solid black;
border-right:none;
border-bottom: 1px;
width: 100%;
display: flex;
flex-direction: row;
justify-content: space-evenly;
margin-top: auto;
}
#month {
margin-right: 40px;
}
#year {
-moz-appearance:textfield;
height:100%;
padding:0%;
border: none;
color: white;
background: black;
}
#year::-webkit-outer-spin-button,
#year::-webkit-inner-spin-button {
-webkit-appearance: none;
}
.select-date label {
margin-left: 40px;
align-self: center;
}
/****** Events ********/
.event-container{
background: linear-gradient(to bottom left, #f2fcef, #eff7f1);
border-left:none;
display: flex;
width:433px;
height: 425px;
border: 2px solid black;
overflow:hidden;
overflow-y: auto
}
.events{
height: 100%;
display:flex;
flex-direction: column;
align-items: center; /*center children horizontally*/
overflow-y: auto;
justify-content: start;
padding: 10px auto;
}
.events .event-message{
align-items: center;
width: 80%;
text-align: center;
margin: 20px auto 0px auto;
padding: 15px 5px;
background-image: linear-gradient(to right, #649173, #dbd5a4 );
border-radius: 3px;
box-shadow: 3px 6px 10px #393a39;
transition: all 0.5s cubic-bezier(.36,-0.64,.34,1.76);
}
.event-desc {
align-self: flex-start;
word-wrap: break-word;
flex-shrink: 0;
order: -1;
font-weight: bold;
position: relative;
}
.remove {
display: block;
padding: 2px;
-moz-border-radius: 7.5px;
-webkit-border-radius: 7.5px;
border-radius: 7.5px;
line-height:12px;
background-color: #69b6d5;
position:absolute;
right:0;
top:0;
font-weight:100;
font-size:14px;
cursor:pointer;
}
.hasEvent {
background: #dd9756;
}
.active {
background: blue;
}
.active-event {
background: pink;
}
.error {
color: red;
}
.show-event-form {
margin-top: 20px;
padding: 10px;
flex-shrink: 0;
border: none;
position:relative;
font-weight:600;
border-radius: 23px;
-webkit-transition: all .2s ease-in;
transition: all .2s ease-in;
color:gray;
box-shadow: 5px 8px 14px #393a39;
background-color: #dbd5a4;
outline:none;
cursor:pointer;
}
.show-event-form:hover{
transform: scale(1.2);
}
.show-event-form::after{
content:'';
display:block;
position: absolute;
height:10px;
width:10px;
top:100%;
}
/******** new Event Form **********/
.new-event-form{
width: 100%;
display:flex;
flex-direction: column;
justify-content: space-evenly;
text-align: center;
}
.new-event-form legend{
font-size: 30px;
}
#new-event-desc{
border:none;
background-color:white;
width: 40%;
align-self: center;
-webkit-transition: all .2s ease-in;
transition: all .2s ease-in;
border-radius: 23px;
padding:20px;
outline:none;
}
#new-event-desc:focus{
width:60%;
}
.submit-event{
border: none;
font-weight:600;
border-radius: 23px;
-webkit-transition: all .2s ease-in;
transition: all .2s ease-in;
color:gray;
box-shadow: 5px 8px 14px #393a39;
background-color: #dbd5a4;
width:60%;
align-self:center;
padding:14px;
outline:none;
cursor:pointer;
}
.submit-event:hover{
transform: scale(1.2);
}
/****animations*******/
.hidden {
height: 0; opacity: 0; width: 0;
overflow: hidden;
transition: height 0ms 400ms, opacity 200ms 0ms, width 0ms 0ms;
}
.visible {
height: 100%; opacity: 1; width: 100%;
transition: height 200ms 0ms, opacity 600ms 200ms, width 0ms 0ms;
}
.swingHide {
opacity: 0;
transform: rotateY(-90deg);
transition: all 0.5s cubic-bezier(.36,-0.64,.34,1.76);
}
.show {
opacity: 1;
transform: none;
transition: all 0.5s cubic-bezier(.36,-0.64,.34,1.76);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Calendar</title>
<link rel='stylesheet' href='resources/styles/main.css'>
</head>
<body>
<div class='container'>
<div class='calendar'>
<div class='date-header'>
<span id='prev' class='time-skip'>prev</span>
<div class='year-month'>
<span class='month'></span>
<span class='year'></span>
</div>
<span id='next' class='time-skip'>next</span>
</div>
<table class='days-body'>
<thead>
<tr class='days-row'>
<th>Sun</th>
<th>Mon</th>
<th>Tue</th>
<th>Wed</th>
<th>Thu</th>
<th>Fri</th>
<th>Sat</th>
</tr>
</thead>
<tbody class='calendar-days'></tbody>
</table>
<form class='select-date'>
<label for='month'>Go To: </label>
<select name='month' id='month'>
<option value=0>Jan</option>
<option value=1>Feb</option>
<option value=2>Mar</option>
<option value=3>Apr</option>
<option value=4>May</option>
<option value=5>Jun</option>
<option value=6>Jul</option>
<option value=7>Aug</option>
<option value=8>Sep</option>
<option value=9>Oct</option>
<option value=10>Nov</option>
<option value=11>Dec</option>
</select>
<input type='number' min='1' id='year'>
</form>
</div>
<div class='event-container'>
<div class='events visible'>
<span class='no-Events event-message'>There are no events today</span>
<button class='show-event-form rotate'>Add new event</button>
</div>
<form class='new-event-form hidden'>
<legend>Submit New Event</legend>
<input id='new-event-desc' type='text' name='desc' placeholder='desc'>
<input type='submit' class='submit-event rotate' value='submit'>
</form>
</div>
</div>
<script type='text/javascript' src='resources/js/calendar.js' async></script>
</body>
</html></code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T16:33:59.033",
"Id": "404845",
"Score": "0",
"body": "What code are you specifically referring to that you consider to be repeated?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T16:37:33.577",
"Id": "404846",
"Score": "0",
"body": "I made the noEvents variable several times to set the display to hide or show it. I could have made a function for this, and there are a lot of if statements in my eventHandlers that could have been put into seperate function because I'm repeating a lot of the same things, especially if I want to add more features to this like editing events."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T16:41:12.983",
"Id": "404847",
"Score": "0",
"body": "Yes, `let noEvents = document.getElementsByClassName('no-Events')[0]` appears to be able to be defined once. The `if..else` statements are unique within each function body, correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T16:48:09.360",
"Id": "404849",
"Score": "0",
"body": "The if statements are unique but in some functions like the hideShowEventsDiv() I repeat a lot of adding and removing classes and this makes my code harder to read. I've seen a .toggle class in jquery to do the same thing but there is no equivalent in ECMAScript that I know of. Other functions like showEventText do several different things that I could have separated into several functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T17:56:24.160",
"Id": "404860",
"Score": "0",
"body": "See [`toggle( String [, force] )`](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList)"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T16:24:31.287",
"Id": "209456",
"Score": "2",
"Tags": [
"javascript",
"html",
"datetime",
"css",
"dom"
],
"Title": "Event Calendar in JS, CSS, and HTML"
} | 209456 |
<p>Follow-up Code: <a href="https://codereview.stackexchange.com/questions/209472/2-bartender-project-with-c-exporting-printer-code-templates">BarTender project - exporting printer code templates - Follow-up</a></p>
<p>Second Revision: <a href="https://codereview.stackexchange.com/questions/209695/bartender-project-exporting-printer-code-templates-follow-up-2">Bartender Project - exporting printer code templates - Follow-up-2</a></p>
<p>as stated in the question I've got a working C# project.</p>
<p>The project's goal is to open up the application BarTender and export printer code templates (a way of getting information from databases connected to BarTender). I would like to make improvements (i.e. syntax or build quality/speed).</p>
<p>Any general tips or practices would be awesome!</p>
<pre><code>using System;
namespace BarTender
{
class btExport
{
// Dummy Variable
private const string DataExportPath = "";
static void Main(string[] args)
{
///////////////////////////////////////////////
/* VARIABLE DECLARATION */
//////////////////////////////////////////////
// Declare a BarTender application variable
BarTender.Application btApp;
// Declare a BarTender document variable
BarTender.Format btFormat;
// Declare a BarTender printer code template variable
BarTender.PrinterCodeTemplate btPCT;
// Declare a BarTender verification variable
BarTender.Verification btVerification;
// Declare a BarTender messages variable to hold all messages
BarTender.Messages btMessages;
// Declare a variable to hold message text
string btMessageText = "";
// Declare a success variable
bool ExportSuccess = true;
// Declare an object variable
System.Object obj = null;
// Used for manual input
string input = null;
string output = null;
///////////////////////////////////////////
/* START OF BARTENDER SIDE */
///////////////////////////////////////////
// Only start BarTender when needed, otherwise use old instances
try
{
// Store this instance as an object variable in C#
object btObject = System.Runtime.InteropServices.Marshal.GetActiveObject("BarTender.Application");
// Convert the object variable to a BarTender application variable
btApp = btObject as BarTender.Application;
}
catch
{
btApp = new BarTender.Application();
}
// Set the BarTender application visible
btApp.Visible = true;
////////////////////////////////////////
/* START LOGIC */
////////////////////////////////////////
// If run without parameters this 'if' is triggered for manual entry
if (args.Length == 0)
{
Console.WriteLine("No parameters specified. \n Enter manually or try again.");
Console.Write("Input: ");
input = Console.ReadLine();
int start = input.Length - 4;
output = input.Remove(start, 4);
output = output += "prn\"";
Console.WriteLine(output);
}
// Taking parameters from Main
else
{
input = args[0];
Console.WriteLine("Input File Path:" + input);
output = args[1];
Console.WriteLine("Output File Path:" + output);
}
// Open a BarTender document
try
{
btFormat = btApp.Formats.Open("\"" + input + "\"", false, "");
// Specify the password to remove print-only protection from the application
btApp.SpecifyPrintOnlyPassword("#Betsy");
// Set the printer code template variable
btPCT = btFormat.PrinterCodeTemplate;
// Export the printer code template
btPCT.Export("SAPscript-ITF", BarTender.BtPctExportType.btPctExportCombined, output, DataExportPath, ref obj);
}
catch { Console.WriteLine("Input or Export file does not exist."); Console.ReadLine(); return; }
// Set the messages variable to the object
btMessages = obj as BarTender.Messages;
// Check to see if there is an error message
if (ExportSuccess == false)
{
// Loop through the messages
for (int i = 1; i <= btMessages.Count; i++)
{
// Get the error message
btVerification = btMessages.GetMessage(1).Verification;
// Populate the error messages into a string
btMessageText = btMessageText + btVerification.Problem + "\r\n" + btVerification.Fields + " " + btVerification.AutoFix + "\r\n" + btVerification.Result;
}
}
else
{
// Loop through the messages
foreach (BarTender.Message btMsg in btMessages)
{
// Get the error message
btVerification = btMessages.GetMessage(1).Verification;
// Populate warning messages into a string
btMessageText = btMessageText + btVerification.Problem + "\r\n" + btVerification.Fields + " " + btVerification.AutoFix + "\r\n" + btVerification.Result;
}
}
// End the BarTender process
btApp.Quit(BarTender.BtSaveOptions.btDoNotSaveChanges);
Console.WriteLine("Complete");
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T20:06:04.227",
"Id": "404871",
"Score": "0",
"body": "Welcome to Code Review! I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T20:43:32.213",
"Id": "405299",
"Score": "0",
"body": "Having section headers like that indicates you should be making functions where the name of those functions are the section headers. I used to do the same thing, I thought it aesthetically looked better, but in reality it made my code harder to read for others (and myself later-on). It makes it harder to get \"the big picture\" of what the main function is doing when you have to scroll that much."
}
] | [
{
"body": "<ol>\n<li>dont prefix your code, <code>bt</code> looks like button... you can just name <code>Format format</code> and be all set. (Clean Code - Uncle Bob)...</li>\n<li>Break down your ideas into smaller functions (Single Responsibility Principle). like <code>btFormat = btApp.Formats.Open(\"\\\"\" + input + \"\\\"\", false, \"\");</code> can be in its own method with a <a href=\"https://medium.com/coding-skills/clean-code-101-meaningful-names-and-functions-bf450456d90c\" rel=\"nofollow noreferrer\"><em>meaningful name</em></a>. Your <code>btMessageText</code>, can be set from private function called <code>CreateVerificationMessage</code>... </li>\n<li>what exactly are you going to do with <code>btMessageText</code>? Were you supposed to write that to the console?</li>\n</ol>\n\n<p>Look for \"intent\" and separate those ideas into functions, methods and classes instead of creating a <a href=\"https://sourcemaking.com/antipatterns/the-blob\" rel=\"nofollow noreferrer\">God Class</a> to do everything...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T19:55:09.910",
"Id": "404869",
"Score": "0",
"body": "I've taken what you said to consideration, I am going to edit the code up top please let me know if you think it looks better!\n\nAlso: btMessageText was going to display in the console a list of errors that Bartender was generating but seeing as I can't fully figure out how to automate it I can see the errors while running through the program as opposed to reading them in the console."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T16:57:24.917",
"Id": "209461",
"ParentId": "209457",
"Score": "1"
}
},
{
"body": "<h3>Bugs and problems:</h3>\n\n<ul>\n<li><code>input.Remove(start, 4)</code> will throw an exception if <code>start</code> is less than 0, which happens when <code>input.Length</code> is less than 4. You should check for that, or otherwise catch exceptions at that point. This output path logic also seems to be written with very specific inputs in mind - it looks fairly brittle.</li>\n<li>Similarly, <code>args[1]</code> will fail if <code>args.Length</code> is less than 2, but you've only made sure that <code>args.Length</code> isn't 0, so this will throw if only one argument is provided. This too will cause a crash because you're not catching exceptions here.</li>\n<li>Always check for <code>null</code> whenever you use <code>as</code>. You're not doing that with <code>btObject</code> and <code>btMessages</code>, so using them might result in <code>NullReferenceExceptions</code>.</li>\n<li>The final <code>for</code> and <code>foreach</code> loop both seem to do the exact same thing, just in a slightly different way, so one of them can probably be removed. Since <code>ExportSuccess</code> is always true, the <code>for</code> loop is never executed anyway. Either way, both loops always get the same message (index or id 1), which is probably not correct.</li>\n</ul>\n\n<h3>Readability:</h3>\n\n<ul>\n<li>There are a lot of unnecessary comments. Things like 'delare a TypeName variable' aren't useful, and there are better ways to get an overview of what code is doing than using 'shouty' headers. Try using comments to explain <em>why</em> code does what it does - <em>what</em> it's doing should be obvious by looking at the code itself.</li>\n<li>As Andy already mentioned, try splitting your Main method up into several methods, each with a specific purpose. <code>GetApplication</code>, <code>GetInputOutputPaths</code>, <code>ExportCodeTemplate</code> and <code>ShowErrorMessages</code> seems like a reasonable way to do it. This keeps <code>Main</code> short and simple, and quickly gives you a high-level overview of what the application is actually doing - without needing any comments.</li>\n<li>Why are all variables declared up-front? I'd move them as close to where each variable is actually used. Preferably in as small a scope as possible, and immediately initialized whenever possible. That keeps related things together, which should make the code easier to understand.</li>\n<li>There's a <code>catch</code> statement body with several statements, including a <code>return</code>, all on a single line. That sort of inconsistencies makes code more difficult to read. Put each of those statements on a separate line.</li>\n</ul>\n\n<h3>Other notes:</h3>\n\n<ul>\n<li><code>btMessageText</code> is not used anywhere. In any case, successive concatenation of strings is more efficiently done by appending to a <code>StringBuilder</code>.</li>\n<li>Things like <code>variable1 + \"small string\" + variable2</code> can be written more succinctly with interpolated strings: <code>$\"{variable1}small string{variable2}\"</code>.</li>\n<li><code>variable == false</code>, where <code>variable</code> is a boolean instead of a nullable boolean, is normally written as <code>!variable</code>.</li>\n<li>Try using more descriptive names. <code>input</code> and <code>output</code> are ok, but <code>inputFilePath</code> and <code>outputFilePath</code> are better. <code>obj</code> and <code>btObject</code> are poor names - <code>messages</code> (or even <code>exportErrorMessages</code>) and <code>application</code> are better. In most cases there is no need to abbreviate things (<code>printerCodeTemplate</code> instead of <code>PCT</code>), and the <code>bt</code> prefix doesn't add any real value and is easily confused with <code>button</code>, as Andy already pointed out.</li>\n<li><code>btPCT</code> isn't necessary: you can call <code>btFormat.PrinterCodeTemplate.Export(...)</code> directly.</li>\n<li>I'd use <code>using System.Runtime.InteropServices</code> instead of writing <code>Marshal</code>'s name out full.</li>\n<li>Why is that password hardcoded instead of passed in as an argument or via user input?</li>\n<li>Why is only one part of the code inside a try-catch statement?</li>\n<li>Personally I would make a lot more use of C#'s type inference (<code>var</code>), especially because in most assignments the type is obvious from both the left and right-hand side.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T20:46:11.137",
"Id": "405300",
"Score": "0",
"body": "Couldn't agree more on readability #3. I'm tired of going through legacy code and having to find out 20 minutes later than the only place this variable is used in on the last line. Just declare it when you use it unless you have a reason not to do so."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T20:20:07.023",
"Id": "209471",
"ParentId": "209457",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "209461",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T16:31:14.037",
"Id": "209457",
"Score": "1",
"Tags": [
"c#",
"beginner",
"console"
],
"Title": "BarTender project - exporting printer code templates"
} | 209457 |
<p>As an old dog (age 73) learning new (Excel VBA) tricks, I am reasonably happy with putting together the code below. But I think it could be cleaner. How would you have coded it?</p>
<pre><code>Private Sub Workbook_Open()
Dim lastRow As Long 'last row with data
Dim thisDate As Double 'start timestamp
thisDate = Now()
With Sheets("Pressure Log")
lastRow = .Range("B" & .Rows.Count).End(xlUp).Row 'populate next row with date/time
.Range("B" & lastRow + 1 & ":G" & lastRow + 1).Borders.LineStyle = xlContinuous
.Range("B" & lastRow).Offset(1) = Format(thisDate, "dddd")
.Range("B" & lastRow).Offset(1, 1) = Format(thisDate, "mm/dd/yyyy")
.Range("B" & lastRow).Offset(1, 2) = Format(thisDate, "hh:mm AM/PM")
.Range("B" & lastRow).Offset(1, 3).Select 'position for data
End With
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T16:42:30.633",
"Id": "404848",
"Score": "2",
"body": "Cross post from: https://stackoverflow.com/questions/53683704/excel-range-less-clumsy"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T08:43:32.817",
"Id": "404929",
"Score": "0",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T15:02:45.293",
"Id": "404971",
"Score": "0",
"body": "@Toby Speight okay. I did receive terrific responses so I am fine with removing this. How is that done?"
}
] | [
{
"body": "<p>Properly formatting and indenting code is always a good start.</p>\n\n<p>Using <code>Option Explicit</code> at the top of every module is a must. You may already do this, just thought I would mention it.</p>\n\n<p>You declare <code>thisDate</code> as a <code>Double</code> but you use it as a <code>Date</code>. Declare it as a <code>Date</code>.</p>\n\n<p>Make your life a little easier and set a range to the start of your new row instead of calling a calculated range. Example below:</p>\n\n<pre><code>Private Sub Workbook_Open() \n Dim lastRow As Long 'last row with data \n Dim thisDate As Date 'start timestamp \n Dim entryRange as Range\n thisDate = Now() \n With Sheets(\"Pressure Log\") \n lastRow = .Range(\"B\" & .Rows.Count).End(xlUp).Row 'populate next row with date/time \n Set entryRange = .Range(\"B\" & lastRow+1) ` There are other ways of doing this too. \n End With \n entryRange.resize(1, 6).Borders.LineStyle = xlContinuous ' Yes, could do this in a With block as well.\n entryRange.Value = Format(thisDate, \"dddd\") \n entryRange.Offset(, 1).Value = Format(thisDate, \"mm/dd/yyyy\") \n entryRange.Offset(, 2) = Format(thisDate, \"hh:mm AM/PM\") \n entryRange.Offset(, 3).Select 'position for data \nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T21:51:59.510",
"Id": "404880",
"Score": "0",
"body": "thank you AJD \"Properly formatting and indenting code is always a good start .\" Agreed. My script code is indented but I have trouble with this forum's code block."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T22:00:25.537",
"Id": "404882",
"Score": "0",
"body": "thank you @AJD \"Properly formatting and indenting code is always a good start .\" Agreed. My script code is indented but I have trouble with this forum's code block. (as is trying to line break in this comment) \"Using Option Explicit at the top of every module is a must. \" I understood the concept, but thought that Option Explicit was once for the entire workbook so I did not know where to put it. Now I know. Thank you. \"You declare thisDate as a Double but you use it as a Date. Declare it as a Date.\" I thought Date was a method, not a type as well. Will make the change"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T22:03:18.893",
"Id": "404883",
"Score": "0",
"body": "\" Set entryRange = .Range(\"B\" & lastRow+1) ` There are other ways of doing this too.\" I gather you recommend this as the better alternative. What might be some of the other ways?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T06:20:22.683",
"Id": "404909",
"Score": "0",
"body": "@grNadpa: `Set entryRange = .Range(\"B\" & lastRow).Offset(1,0)` is an easy alternative. You could also use `.Cells(lastRow+1,2)` (not preferable because `Cells` is relative to a range and which cells are selected can be confused if you change the base range). In some cases, just comes down to personal preferences."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T19:14:53.597",
"Id": "209465",
"ParentId": "209459",
"Score": "1"
}
},
{
"body": "<p>Another <code>With</code> statement would make the code easier to read.</p>\n\n<blockquote>\n<pre><code>With Sheets(\"Pressure Log\")\n lastRow = .Range(\"B\" & .Rows.Count).End(xlUp).Row 'populate next row with date/time\n .Range(\"B\" & lastRow + 1 & \":G\" & lastRow + 1).Borders.LineStyle = xlContinuous\n With .Range(\"B\" & lastRow)\n .Offset(1) = Format(thisDate, \"dddd\")\n .Offset(1, 1) = Format(thisDate, \"mm/dd/yyyy\")\n .Offset(1, 2) = Format(thisDate, \"hh:mm AM/PM\")\n .Offset(1, 3).Select 'position for data\n End With\nEnd With\n</code></pre>\n</blockquote>\n\n<p>It is better to format entire columns and rows. These reduces the file size by combining multiple css rules.</p>\n\n<p>There are many way to skin this cat. For variety I set a range variable ( newRow ) to the next empty row. This allows me to uses ranges relative to the new row.</p>\n\n<pre><code>Dim newRow As Range\nWith Worksheets(\"Pressure Log\")\n Set newRow = .Range(\"B\" & .Rows.Count).End(xlUp).Offset(1).EntireRow\n newRow.Range(\"B1:G1\").Borders.LineStyle = xlContinuous\n newRow.Range(\"B1:D1\").Value = Now\n .Columns(\"C\").NumberFormat = \"ddd\"\n .Columns(\"D\").NumberFormat = \"mm/dd/yyyy\"\n .Columns(\"E\").NumberFormat = \"hh:mm AM/PM\"\n .Columns(\"C:G\").AutoFit\n newRow.Columns(\"E\").Select\nEnd With\n</code></pre>\n\n<p>With this setup we can copy all the formats from the row above except NumberFormats by using <code>Range().FillDown</code>. </p>\n\n<blockquote>\n<pre><code> newRow.FillDown\n</code></pre>\n</blockquote>\n\n<p>Alternately, we could copy all the formats from the row above like this:</p>\n\n<blockquote>\n<pre><code>newRow.Offset(-1).Copy\nnewRow.PasteSpecial Paste:=xlPasteFormats\nApplication.CutCopyMode = False\n</code></pre>\n</blockquote>\n\n<p>Your code is pretty solid but if you truly want to learn Excel VBA I would start by watching this series: <a href=\"https://www.youtube.com//watch?v=KHO5NIcZAc4&index=1&list=PLNIs-AWhQzckr8Dgmgb3akx_gFMnpxTN5\" rel=\"nofollow noreferrer\">Excel VBA Introduction</a>. </p>\n\n<p>You should also use <a href=\"http://rubberduckvba.com/\" rel=\"nofollow noreferrer\">Rubberduck VBA</a>. It is a free add-in with many features to help you write better code. The code formatter alone is invaluable.</p>\n\n<p>Last but not least start answering questions on <a href=\"https://stackoverflow.com\">StackOverflow</a>. This will give you exposure to questions that you would never think to ask and solutions that you didn't know where possible. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T06:22:53.287",
"Id": "404910",
"Score": "1",
"body": "Advice on the last suggestion (\"Last but not least start answering questions on StackOverflow.\") - while providing good exposure it will also open you up to criticism, especially as you learn how to provide a good answer. A thick skin and not taking anything as personal helps weather the early attempts!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T06:52:40.310",
"Id": "404913",
"Score": "0",
"body": "@AJD I agree. I have my share of callouses. But I improved more in the 2 years of SO than I did in the previous 6 years."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T14:58:44.160",
"Id": "404970",
"Score": "0",
"body": "@TinMan This is precisely the thorough comment I was hoping for. Thank you. As far as answering questions, I think that may be a bit premature. But I certainly intend to make the effort to read the responses to other questions in this forum"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T19:55:30.537",
"Id": "405037",
"Score": "0",
"body": "@grNadpa, Since you're new to Code Review: It's customary to \"thank\" someone for a contribution that answers your question by clicking the checkmark to the left of the Answer. This also lets others with a similar question know when something helped/worked. Later, when you've accumulated reputation (site points) you'll also be able to upvote questions, comments and proposed answers you find useful/helpful. Enjoy!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T20:13:11.727",
"Id": "405038",
"Score": "0",
"body": "@grNadpa I'm glad that it helps."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T05:11:36.193",
"Id": "209495",
"ParentId": "209459",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "209465",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T16:38:41.687",
"Id": "209459",
"Score": "-1",
"Tags": [
"vba",
"excel"
],
"Title": "Excel Range less clumsy"
} | 209459 |
<p>This is a Django tag with 2 classes, but can be viewed as a module:</p>
<p><strong>What does the module do?</strong> it loads a database, performs some transformations on the data, returns the output as a dictionary of json strings for the frontend of django to represent in slickgrid tables</p>
<p>It's all working fine, but my class is too abstract and ended using a lot of static methods because there is actually no state that I need. </p>
<p>This first class shouldn't be important, don't think there is something here to improve. I basically have 4 types in 3 categories and want to go from 4 pandas dataframes to 12 json strings that are passed to django frontend:</p>
<pre><code>class RenderTag:
@staticmethod
def get_context_data():
annotations = Annotations()
df_type_1_category_1, df_type_1_category_2, df_type_1_category_3 = annotations.filter_categories(annotations.df_type_1)
df_type_2_category_1, df_type_2_category_2, df_type_2_category_3 = annotations.filter_categories(annotations.df_type_2)
df_type_3_category_1, df_type_3_category_2, df_type_3_category_3 = annotations.filter_categories(annotations.df_type_3)
df_type_4_category_1, df_type_4_category_2, df_type_4_category_3 = annotations.filter_categories(annotations.df_type_4)
# json data for js tables
json_for_category_1_1 = df_type_1_category_1.apply(lambda x: x.to_json(), axis=1)
json_for_category_1_2 = df_type_2_category_1.apply(lambda x: x.to_json(), axis=1)
json_for_category_1_3 = df_type_3_category_1.apply(lambda x: x.to_json(), axis=1)
json_for_category_1_4 = df_type_4_category_1.apply(lambda x: x.to_json(), axis=1)
json_for_category_2_1 = df_type_1_category_2.apply(lambda x: x.to_json(), axis=1)
json_for_category_2_2 = df_type_2_category_2.apply(lambda x: x.to_json(), axis=1)
json_for_category_2_3 = df_type_3_category_2.apply(lambda x: x.to_json(), axis=1)
json_for_category_2_4 = df_type_4_category_2.apply(lambda x: x.to_json(), axis=1)
json_for_category_3_1 = df_type_1_category_3.apply(lambda x: x.to_json(), axis=1)
json_for_category_3_2 = df_type_2_category_3.apply(lambda x: x.to_json(), axis=1)
json_for_category_3_3 = df_type_3_category_3.apply(lambda x: x.to_json(), axis=1)
json_for_category_3_4 = df_type_4_category_3.apply(lambda x: x.to_json(), axis=1)
context = {
"json_1_1": json_for_category_1_1.to_json(orient='split'),
"json_1_2": json_for_category_1_2.to_json(orient='split'),
"json_1_3": json_for_category_1_3.to_json(orient='split'),
"json_1_4": json_for_category_1_4.to_json(orient='split'),
"json_2_1": json_for_category_2_1.to_json(orient='split'),
"json_2_2": json_for_category_2_2.to_json(orient='split'),
"json_2_3": json_for_category_2_3.to_json(orient='split'),
"json_2_4": json_for_category_2_4.to_json(orient='split'),
"json_3_1": json_for_category_3_1.to_json(orient='split'),
"json_3_2": json_for_category_3_2.to_json(orient='split'),
"json_3_3": json_for_category_3_3.to_json(orient='split'),
"json_3_4": json_for_category_3_4.to_json(orient='split'),
}
return context
</code></pre>
<p>This class I think needs a lot of improvement:</p>
<pre><code>class Annotations:
def __init__(self):
# loading data
self.df_type_2 = helpers.load_database("type_2").round(2)
self.df_type_3 = helpers.load_database("type_3").round(2)
self.df_type_1 = helpers.load_database("type_1").round(2)
# main transformations
# type_2 and 4
self.df_type_2, self.df_type_4 = self.split_2_into_2_and_4(self.df_type_2)
self.df_type_4 = self.do_transformations_for_4(self.df_type_4)
self.df_type_2 = self.do_transformations_for_2(self.df_type_2)
# type_1
self.df_type_1 = self.do_transformations_for_1(self.df_type_1)
# type_3
self.df_type_3 = self.do_transformations_for_3(self.df_type_3)
# and I have 4 methods that call a lot of static functions
def do_transformations_for_1(self, df):
"""
This is the main function that edits the data for type 1
We take the main df and then we run a series of manipulations
Args:
df(pd.DataFrame): the df that we want to process
Returns:
df(pd.DataFrame): the end dataframe that will be transferred to the js file
"""
df["id"] = df.index
df = df.pipe(self.do_something)\
.pipe(self.do_something_1)\
.pipe(self.do_something_2)\
.pipe(self.do_something_3)\
.pipe(self.do_something_4)\
.pipe(self.do_something_5)\
.pipe(self.add_colors_log2foldchange)\
.pipe(self.fill_na_with_empty_strings)\
.pipe(helpers.sort_df_by_columns, self.columns_to_sort_snv)
return df
def do_transformations_for_2(self, df):
"""
This is a function that runs only for type 2
We take the main df and then we run a series of manipulations
Args:
df(pd.DataFrame): the df that we want to process
Returns:
df(pd.DataFrame): the end dataframe that will be transferred to the js file
"""
df = df.pipe(self.do_something) \
.pipe(self.add_colors_log2foldchange) \
.pipe(self.do_something_7)\
.pipe(helpers.sort_df_by_columns, self.columns_to_sort_type_4)\
return df
def do_transformations_for_3(self, df):
"""
This is a function that runs only for type 3. We take the main df and then we run a series of manipulations
Args:
df(pd.DataFrame): the df that we want to process
Returns:
df(pd.DataFrame): the end dataframe that will be transferred to the js file
"""
df = df.pipe(self.do_something, False) \
.pipe(self.do_something_9) \
.pipe(self.add_colors_log2foldchange) \
.pipe(helpers.sort_df_by_columns, self.columns_to_sort_type_3)
return df
def do_transformations_for_4(self, df):
"""
This is a function that runs only for the type_4
We take the main df and then we run a series of manipulations
Args:
df(pd.DataFrame): the df that we want to process
Returns:
df(pd.DataFrame): the end dataframe that will be transferred to the js file
"""
df = df.pipe(self.do_something, True) \
.pipe(self.do_something_9) \
.pipe(self.add_colors_log2foldchange) \
.pipe(helpers.sort_df_by_columns, self.columns_to_sort_type_2)
return df
# many static methods that are only used once or twice, deleted many of them
@staticmethod
def unicode_lists_to_string(df, columns):
for column in columns:
df[column] = df[column].str.strip("[]").str.replace("u'|'",'').str.replace(",",";")
return df
@staticmethod
def transform_type_4_position(df: pd.DataFrame):
"""
Remove copy number from position in type_4 table and also add chr in front
Args:
df(pd.DataFrame):
Returns:
pd.DataFrame: with position modified
"""
df["vid_position"] = "chr" + df["vid"].str.split(":").str[:3].str.join(":")
return df
@staticmethod
def filter_categories(df):
"""
Split the df by categories because we want them in separate tables
Args:
df: main df
Returns:
Tuple[pd.DataFrame]: a tuple of 3 dataframes from categories 1,2,3
"""
df_1 = df[df["category"] == 1]
df_2 = df[df["category"] == 2]
df_3 = df[df["category"] == 3]
return df_1, df_2, df_3
@staticmethod
def add_colors_log2foldchange(df: pd.DataFrame):
"""
We want to add background colors to log2foldchange values, fron blue to red
Args:
df(pd.DataFrame): df with log2foldchange values
Returns:
df(pd.DataFrame): df with a new hex_color column
"""
df_new = helpers.add_colors_to_df(df, helpers.get_colors(), "log2_fold_change")
df_new["hex_color"] = df_new["hex_color"].str.replace("#", "")
return df_new
@staticmethod
def edit_support_alt_ref(df: pd.DataFrame) -> pd.DataFrame:
"""
Args:
df(pd.DataFrame):
Returns:
pd.DataFrame:
"""
def strip_germline_from_alt_ref(row):
if pd.notna(row):
if "]," in row:
row = row.split("],")
row = row[1]
row = row.replace("[", "").replace("]", "").replace(",", "|").replace(" ", "")
return row
df["paired_end_reads"] = df["paired_end_reads"].apply(strip_germline_from_alt_ref)
df["split_end_reads"] = df["split_end_reads"].apply(strip_germline_from_alt_ref)
return df
</code></pre>
<p>As you can see I do modifications for all 4 types in 4 methods. </p>
<p>I think I can go along with not using a class here, but sort of want to use a class here to be inline with the whole project... I use static methods because they are obviously easier to unit test. Pass a df and return a df, easy unit test. </p>
| [] | [
{
"body": "<blockquote>\n <p>This first class shouldn't be important, don't think there is something here to improve.</p>\n</blockquote>\n\n<p>You're wrong :)</p>\n\n<p>There's a sea of repeated code here. You need to seriously DRY it up. I don't have enough of your system to test this myself, so you need to; but you should do something like</p>\n\n<pre><code>class RenderTag:\n @staticmethod\n def get_context_data():\n annotations = Annotations()\n\n def to_json(x):\n return x.to_json()\n\n context = {}\n for i in range(1, 5):\n df_type = getattr(annotations, f'df_type_{i}')\n categories = annotations.filter_categories(df_type)\n for j, category in enumerate(categories, 1):\n js = category.apply(to_json, axis=1).to_json(orient='split')\n context[f'json{j}_{i}'] = js\n\n return context\n</code></pre>\n\n<p>That assumes that <code>Annotations</code> cannot change. You can make it even simpler if <code>Annotations.df_type</code> is stored as a 3-tuple, instead of three separate attributes. Elsewhere in your code, you really should carry this philosophy forward - instead of hard-coding three or four variables with numbers in the name, just maintain one tuple (if immutable) or list (if mutable).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T22:22:38.343",
"Id": "209479",
"ParentId": "209462",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T17:23:53.243",
"Id": "209462",
"Score": "3",
"Tags": [
"python",
"pandas",
"django"
],
"Title": "Django module to transform data from database to be displayed in Slickgrid tables"
} | 209462 |
<p>My program automates the process of creating and publishing 152 blog posts quarterly. The blogging platform HubSpot has a series of <a href="https://developers.hubspot.com/docs/overview" rel="nofollow noreferrer">APIs</a> that allow developers to access account data from a CLI in Terminal. First step is creating an excel file (must save as CSV) and importing the file for use as a new HubDB table in HubSpot (basically a google sheet built into HS). The HubDB contains all of the content for a single post in a single row.</p>
<p>Not all of the functions defined are used, however I expect the scope to expand and to use this program to automate content creation for other blogs on HubSpot. Therefore, my goal is to make the process agnostic so that it may be applied broadly.</p>
<pre><code>import requests
import json
import time
from urllib.request import urlopen
from pprint import pprint
"""
CRUD (Create, Retrieve, Update, And Delete) HTTP methods for the
ManpowerGroup Employment Outlook Survey hosted in HubSpot
"""
# Set the API endpoint
APIKEY_VALUE = "XXX-X-X-XXX"
APIKEY = "?hapikey=" + APIKEY_VALUE
HS_API_URL = "http://api.hubapi.com"
PORTAL_ID = XXXXXXX
# Define content group IDs as global variables
TEMPLATE_ID = 5548244265 # HubSpot Templates
MANPOWERGROUP_ID = 5548244265 # ManpowerGroup
MEOS_ID = 5664168304 # ManpowerGroup Employment Outlook Survey
WEF_ID = 5505585256 # World Economic Forum
# List all HubDB table IDs as global variables
MEOS_Q1_2019 = 1029596 # table ID
MEOS_Q2_2018 = 679969
MEOS_Q3_2018 = 700276
MEOS_Q4_2018 = 850049
# Define JSON Actions
PUBLISH = {"action": "schedule-publish"}
CANCEL = {"action": "cancel-publish"}
# Define publication details
PUBLISH_NOW = str(time.time())
DRAFT = 'draft'
LIVE = 'publish'
LIMIT = 152 # Number of rows in table to publish as posts
# CREATE BLOG POSTS
def create_batch_posts(table_id):
"""Get table by row
GET /hubdb/api/v2/tables/:tableId/rows
"""
xurl = "/hubdb/api/v2/tables/" + str(table_id) + "/rows?portalId=" + str(PORTAL_ID)
url = HS_API_URL + xurl
response = urlopen(url).read()
table_data = json.loads(response)
for row in table_data['objects']:
name = row["values"]["1"]
embed = row["values"]["2"]
title = row["values"]["3"]
state = row["values"]["4"]
date = row["values"]["5"]
year = row["values"]["6"]
quarter = row["values"]["7"]
country = row["values"]["9"]
forecast = row["values"]["10"]
blog_author_id = row["values"]["11"]
campaign_id = row["values"]["12"]
campaign_name = row["values"]["13"]
content_group_id = row["values"]["14"]
featured_image = row["values"]["15"]
year_id = row["values"]["19"]
quarter_id = row["values"]["20"]
market_id = row["values"]["21"]
state_id = row["values"]["22"]
epoch_date = row["values"]["23"]
embed_pdf = "<embed src='https://drive.google.com/viewerng/viewer?embedded=true&amp;url=https://go.manpowergroup.com/hubfs/MEOS/2019_Q1/" + str(embed) + ".pdf' width='500' height='675'>"
POST = {
"blog_author_id": blog_author_id,
"campaign": campaign_id,
"campaign_name": campaign_name,
"content_group_id": content_group_id,
"featured_image": featured_image,
"topic_ids": [year_id, quarter_id, market_id, state_id],
"meta_description": str(quarter) + " ~ " + str(year) + " ~ " + str(date) + " | " + str(forecast) + " " + str(title) + " " + str(name) + " | " + str(state) + ", " + str(country),
"name": str(date) + " | " + str(forecast) + " " + str(title) + " " + str(name),
"post_body": embed_pdf,
"publish_date": str(epoch_date),
"publish_immediately": False,
"slug": str(year) + "_" + str(quarter) + "/" + str(embed),
"use_featured_image": True
}
xurl = "/content/api/v2/blog-posts"
url = HS_API_URL + xurl + APIKEY
headers = { "content-type" : "application/json" }
response = requests.post(url, headers=headers, data=json.dumps(POST))
pprint(response.status_code, response.content, response)
# RETRIEVE CONTENT FROM HubDB
def get_single_row(table_id):
"""Get table by row
GET /hubdb/api/v2/tables/:tableId/rows
"""
xurl = "/hubdb/api/v2/tables/" + str(table_id) + "/rows?portalId=" + str(PORTAL_ID)
url = HS_API_URL + xurl
response = urlopen(url).read()
table_data = json.loads(response)
return(table_data)
def get_all_rows(table_id):
"""Get table by row
GET /hubdb/api/v2/tables/:tableId/rows
"""
xurl = "/hubdb/api/v2/tables/" + str(table_id) + "/rows?portalId=" + str(PORTAL_ID)
url = HS_API_URL + xurl
response = urlopen(url).read()
table_data = json.loads(response)
return(table_data)
def get_all_tables():
"""Get the tables
GET /hubdb/api/v2/tables
"""
xurl = "/hubdb/api/v2/tables"
url = HS_API_URL + xurl + APIKEY
response = urlopen(url).read()
all_tables = json.loads(response)
return all_tables
def get_table_by_id(table_id):
"""Get the tables
GET /hubdb/api/v2/tables/:tableId
"""
xurl = "/hubdb/api/v2/tables/" + str(table_id) + "?portalId=" + str(PORTAL_ID)
url = HS_API_URL + xurl
response = urlopen(url).read()
table = json.loads(response)
return table
# RETRIEVE BLOG POST ID
def list_all_posts():
"""List blog posts
Hit this URL with a HTTP method of
GET /content/api/v2/blog-posts
"""
xurl = "/content/api/v2/blog-posts/"
url = HS_API_URL + xurl + APIKEY
blog_list = urlopen(url).read()
# print(blog_list)
return blog_list
def list_blog_posts(blog_id):
"""List blog posts
Hit this URL with a HTTP method of
GET /content/api/v2/blog-posts
"""
xurl = "/content/api/v2/blog-posts/" + str(blog_id)
url = HS_API_URL + xurl + APIKEY
blog_list = urlopen(url).read()
# print(blog_list)
return blog_list
# PUBLISH BLOG POSTS
def publish_blog_post_by_id(blog_post_id):
"""
Publish, schedule or unpublish a blog post
POST /content/api/v2/blog-posts/:blog_post_id/publish-action
"""
xurl = "/content/api/v2/blog-posts/" + str(blog_post_id) + "/publish-action"
url = HS_API_URL + xurl + APIKEY
response = requests.post(url)
headers = { "content-type" : "application/json" }
response = requests.post(url, headers=headers, data=json.dumps(PUBLISH))
# pprint(response.status_code, response.content, response)
return response
def publish_post():
"""Get the blog post by ID
GET /content/api/v2/blog-posts/
"""
xurl = "/content/api/v2/blog-posts/"
url = HS_API_URL + xurl + APIKEY
response = urlopen(url).read()
blog_data = json.loads(response)
for blog_post in blog_data['objects']:
draft_id = blog_post['id']
# print(draft_id)
publish_blog_post_by_id(draft_id) # req. publish_post function
def publish_draft_posts(content_group_id, limit, draft):
"""Get the blog post by ID
GET /content/api/v2/blog-posts/
"""
xurl = "/content/api/v2/blog-posts/"
url = HS_API_URL + xurl + APIKEY
+ '&content_group_id=' + str(content_group_id) # Blog ID
+ '&state=' + str(DRAFT) # DRAFT vs. LIVE
+ '&limit=' + str(LIMIT) # LIMIT TOTAL RESPONSES to ROW NUM
response = urlopen(url).read()
blog_data = json.loads(response)
for blog_post in blog_data['objects']:
print(blog_post['id'])
def get_blog_post_by_id(post_id):
"""Get the blog by ID
GET /content/api/v2/blogs/:blog_id
"""
xurl = "/content/api/v2/blogs/" + str(post_id)
url = HS_API_URL + xurl + APIKEY
response = urlopen(url).read()
blog_info = json.loads(response)
return blog_info
def cancel_post(blog_post_id):
"""
Publish, schedule or unpublish a blog post
POST /content/api/v2/blog-posts/:blog_post_id/publish-action
"""
xurl = "/content/api/v2/blog-posts/" + str(blog_post_id) + "/publish-action"
url = HS_API_URL + xurl + APIKEY
# bin = "http://requestbin.fullcontact.com/1iiiiyo1"
headers = { "content-type" : "application/json" }
response = requests.post(url, headers=headers, data=json.dumps(CANCEL))
# pprint(response.status_code, response.content, response)
return response
# AUTOMATION FOR MANPOWERGROUP EMPLOYMENT OUTLOOK SURVEY (HUBSPOT)
def main():
# Create a draft version of the blog posts
create_batch_posts(1029596)
# Publish the drafts
publish_draft_posts(TEMPLATE_ID, 2, DRAFT)
print("Published")
main()
</code></pre>
<p><a href="https://gist.github.com/flyspaceage/8755c80880eb66c7cba41ff0658c464e" rel="nofollow noreferrer">Please check out my gist for easier reading...</a>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T18:02:45.790",
"Id": "404861",
"Score": "0",
"body": "@200_success I have added the entire program to the post."
}
] | [
{
"body": "<p>At the top, add a shebang:</p>\n\n<pre><code>#!/usr/bin/env python3\n</code></pre>\n\n<p>For this line:</p>\n\n<pre><code>APIKEY = \"?hapikey=\" + APIKEY_VALUE\n</code></pre>\n\n<p>You're doing string concatenation when the nicer thing to do is pass a dict to the <code>params</code> kwarg of requests. This also applies to the following lines:</p>\n\n<pre><code>xurl = \"/hubdb/api/v2/tables/\" + str(table_id) + \"/rows?portalId=\" + str(PORTAL_ID)\nurl = HS_API_URL + xurl\n</code></pre>\n\n<p>The alternative is:</p>\n\n<pre><code>url = f'{HS_API_URL}/hubdb/api/v2/tables/{table_id}/rows'\nresponse = requests.get(url, params={'portalId': PORTAL_ID})\n</code></pre>\n\n<p>And for this line:</p>\n\n<pre><code>urlopen(url).read()\n</code></pre>\n\n<p>Why, if you have requests? Use requests instead.</p>\n\n<pre><code>table_data = json.loads(response)\n</code></pre>\n\n<p>For this, use requests; then you can write</p>\n\n<pre><code>table_data = response.json()\n</code></pre>\n\n<p>For this line:</p>\n\n<pre><code>\"meta_description\": str(quarter) + \" ~ \" + str(year) + \" ~ \" + str(date) + \" | \" + str(forecast) + \" \" + str(title) + \" \" + str(name) + \" | \" + str(state) + \", \" + str(country),\n</code></pre>\n\n<p>Stop doing so much string concatenation. Use f-string interpolation like I did above. The same applies to <code>slug</code> and others.</p>\n\n<pre><code>headers = { \"content-type\" : \"application/json\" }\n</code></pre>\n\n<p>You don't need to do that if you use requests and pass the <code>json</code> kwarg with your dict.</p>\n\n<p>For this line:</p>\n\n<pre><code>main()\n</code></pre>\n\n<p>If someone else imports your file, you should give them the option of not running main. The standard way to do this is <code>if __name__ == '__main__':</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T18:34:53.640",
"Id": "405609",
"Score": "0",
"body": "Thanks for hitting on these points, in particular using f string interpolation. Is this for both readability and speed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T19:27:33.647",
"Id": "405624",
"Score": "0",
"body": "Speed is dubious; that would have to be tested. It's more for legibility and ease of maintenance."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T21:15:27.453",
"Id": "209477",
"ParentId": "209463",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209477",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T17:45:42.527",
"Id": "209463",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"rest"
],
"Title": "Create, update, and publish a batch of blog posts"
} | 209463 |
<p>How can I reduce the amount of if statements in this program to make it more robust and any other tips for improvement would be grateful.</p>
<pre><code># importing pickle
import pickle
# defining variables
create_username = 0
create_password = 0
password = 0
username = 0
# this variable allows the user or denies the user to the rest of the program (will only run if access is 1)
access = 0
# creates a users dictionary
with open('users.pickle', 'rb') as f:
users = pickle.load(f)
print(users)
# sign up (creating new account)
while username not in users and username != 'signup':
username = input("enter username(type signup to create an account): ")
# add new user to dictionary
if username == "signup" or username == "Signup":
create_username = input("enter a new username: ")
create_password = input("enter a new password (Your password cannot be the same as your username !!!!!!!): ")
if create_password in users:
create_password = input("password taken re-enter: ")
# then adds the new username to the users dictionary
if username == 'signup':
users[create_username] = create_password
if username in users:
password = input("enter password: ")
if password in users:
print("access granted")
access = 1
if username not in users and username != 'signup':
username = input("enter username: ")
if username in users:
password = input("enter password")
if password in users:
print("access granted")
access = 1
if password not in users:
print("access denied")
with open('users.pickle', 'wb') as f:
# Pickle the 'data' dictionary using the highest protocol available.
pickle.dump(users, f, pickle.HIGHEST_PROTOCOL)
print(users)
</code></pre>
| [] | [
{
"body": "<pre><code># importing pickle\n</code></pre>\n\n<p>Obviously. Don't clutter your code with comments unless they add something we don't already know.</p>\n\n<pre><code># defining variables\ncreate_username = 0\ncreate_password = 0\npassword = 0\nusername = 0\n</code></pre>\n\n<p>This is generally a bad idea, and you aren't in mid-1990s C. Don't predeclare your variables. Initialize them where they're actually used.</p>\n\n<pre><code>print(users)\n</code></pre>\n\n<p>If <code>users</code> is a plain-old dictionary, I recommend the use of <code>pprint</code> instead of <code>print</code>.</p>\n\n<pre><code>\"enter username(type signup to create an account): \"\n</code></pre>\n\n<p>This is called in-band control, and is a bad idea. What if someone's username is called \"signup\"? You want out-of-band control. Ask explicitly whether the user wants to sign up or log in.</p>\n\n<pre><code>if username == \"signup\" or username == \"Signup\":\n</code></pre>\n\n<p>Don't do two comparisons. Convert <code>username</code> to lowercase and compare with <code>'signup'</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T06:52:13.547",
"Id": "404912",
"Score": "0",
"body": "Can you please explain why predeclaring variables is a bad idea, and something to avoid?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T15:31:44.243",
"Id": "404987",
"Score": "1",
"body": "@vanderZonStef It's a habit from pre-99 C. It's not necessary in nearly all languages, now. Programs read easier if the variables aren't introduced until they're actually used. Plus, Python doesn't really have the concept of variable declaration at all; only variable assignment with implicit declaration."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T21:01:46.433",
"Id": "209474",
"ParentId": "209464",
"Score": "2"
}
},
{
"body": "<h2>Bugs</h2>\n\n<p>Both your check for an existing user and checking if the user entered the correct password are not working correctly:</p>\n\n<pre><code>if create_password in users:\n create_password = input(\"password taken re-enter: \")\n</code></pre>\n\n<p>This just checks if the just entered password is also a username already in use. <code>in</code> for dictionaries checks only if a value is present in the keys of the dictionary, not the values.</p>\n\n<p>But even if this would be working like you intended (checking if this is the password of another user), <strong>checking if another user has the same password is very dangerous</strong>. First of all it gives away the fact that you are saving your passwords in clear text, which you shouldn't, anyway. In the best case the user will not want to use your system for that reason alone, in the worst case they will want to crack it.</p>\n\n<p>And for this second case there is even more information now, because now they know the password of one other user! They just don't know which one, but if they keep on trying passwords and save them whenever they are already taken, they get a nice dictionary of passwords, where they know that each one is some users password. If they want to crack some specific users account, they just try all of them.</p>\n\n<pre><code>if username in users:\n password = input(\"enter password\")\n\nif password in users:\n print(\"access granted\")\n access = 1\n</code></pre>\n\n<p>This checks if the user exists (good) and if another user with the username of the just entered password also exists, but not if the password is the password of the user who wants to login (bad).</p>\n\n<p><strong>This means that you can login to your system by knowing a single username!</strong> Just enter the username as both the username and the password and you are guaranteed access.</p>\n\n<p>Instead, you want to check if the password is <em>that</em> users password:</p>\n\n<pre><code>if username in users:\n password = input(\"enter password: \")\n if password == users[username]:\n print(\"access granted\")\n access = 1\n</code></pre>\n\n<p>This also makes sure that the check for the password is only performed if the user actually entered a password. Otherwise it will check if the user <code>0</code> exists in users (in your current version) or it will raise a <code>KeyError</code>, since <code>user[username]</code> does not exist (in this version where the <code>if</code> is not nested).</p>\n\n<h2>Style</h2>\n\n<p>Using <code>1</code> and <code>0</code> for logged-in and not logged-in, respectively, sounds like you will mess this up at least once. Instead used <code>logged_in = False</code> in the beginning and then later set it to <code>logged_in = True</code> if the login is successful.</p>\n\n<p>Indeed, you should probably move all of your code to separate functions, one of which, the <code>login</code> function, returns <code>True</code> or <code>False</code> depending on whether or not the login was successful.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T19:41:13.517",
"Id": "405036",
"Score": "1",
"body": "Thanks didn't know about the bug with the user just needing to enter the username twice! quite a big bug actually come to think of it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T11:00:49.487",
"Id": "209513",
"ParentId": "209464",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209513",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T18:13:31.397",
"Id": "209464",
"Score": "3",
"Tags": [
"python"
],
"Title": "Python - username and password authentication"
} | 209464 |
<p>I would like to find the find the distance transform of a binary image in the fastest way possible without using the scipy function <a href="http://scipy.github.io/devdocs/generated/scipy.ndimage.distance_transform_edt.html" rel="nofollow noreferrer"><code>distance_transform_edt()</code></a>. The image is 256 by 256. The reason I don't want to use scipy is because using it is difficult in Tensorflow. Every time I want to use this package I need to start a new session and this takes a lot of time. So I would like to make a custom function that only utilizes NumPy.</p>
<p>My approach is as follows: Find the coordinated for all the ones and all the zeros in the image. Find the euclidian distance between each of the zero pixels (a) and the one pixels (b) and then the value at each (a) position is the minimum distance to a (b) pixel. I do this for each 0 pixel. The resultant image has the same dimensions as the original binary map. My attempt at doing this is shown below.</p>
<p>I tried to do this as fast as possible using no loops and only vectorization. But my function still can't work as fast as the scipy package can. When I timed the code it looks like the assignment to the variable "a" is taking the longest time. But I do not know if there is a way to speed this up.</p>
<p>If anyone has any other suggestions for different algorithms to solve this problem of distance transforms or can direct me to other implementations in python, it would be very appreciated.</p>
<pre><code>def get_dst_transform_img(og): #og is a numpy array of original image
ones_loc = np.where(og == 1)
ones = np.asarray(ones_loc).T # coords of all ones in og
zeros_loc = np.where(og == 0)
zeros = np.asarray(zeros_loc).T # coords of all zeros in og
a = -2 * np.dot(zeros, ones.T)
b = np.sum(np.square(ones), axis=1)
c = np.sum(np.square(zeros), axis=1)[:,np.newaxis]
dists = a + b + c
dists = np.sqrt(dists.min(axis=1)) # min dist of each zero pixel to one pixel
x = og.shape[0]
y = og.shape[1]
dist_transform = np.zeros((x,y))
dist_transform[zeros[:,0], zeros[:,1]] = dists
plt.figure()
plt.imshow(dist_transform)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T05:55:26.140",
"Id": "404908",
"Score": "3",
"body": "This post is [double-posted on SO](https://stackoverflow.com/q/53678520/7328782), and answered there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T10:45:51.923",
"Id": "404942",
"Score": "0",
"body": "You could just try to copy the code from the [`scipy` function](https://github.com/scipy/scipy/blob/6d0eade/scipy/ndimage/morphology.py#L2059-L2223). There are two imports used as far as I can tell, one is a normal Python file in the same folder, the other one is written in C and needs to be compiled, though."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T19:19:02.320",
"Id": "209466",
"Score": "4",
"Tags": [
"python",
"performance",
"algorithm",
"image",
"numpy"
],
"Title": "Distance transform on image using NumPy"
} | 209466 |
<p>When checking a python dict for a key, which is the better way here:
(I can't figure how to use <code>dict.get()</code> to make this cleaner)</p>
<pre><code>if 'y' in self.axes:
ax = self.axes['y'].ax
coord1[ax] = x0
coord2[ax] = (y1) - height[ax]
coord3[ax] = x0 + width[ax]
coord4[ax] = y1
</code></pre>
<p>or:</p>
<pre><code>try:
ax = self.axes['y'].ax
except KeyError:
pass
else:
coord1[ax] = x0
coord2[ax] = (y1) - height[ax]
coord3[ax] = x0 + width[ax]
coord4[ax] = y1
</code></pre>
<p>The latter way is closer to EAFP but former seems clearer, especially for new code contributors who are scientists first & coders second.</p>
| [] | [
{
"body": "<p>Sort of neither, but closer to the first.</p>\n\n<pre><code>y = self.axes.get('y')\nif y is not None:\n ax = y.ax\n coord1[ax] = x0\n coord2[ax] = y1 - height[ax]\n coord3[ax] = x0 + width[ax]\n coord4[ax] = y1\n</code></pre>\n\n<p><code>get</code> is a best-effort function that will (by default) return <code>None</code> if the key doesn't exist. This approach means you only ever need to do one key lookup.</p>\n\n<p>One of the reasons to prefer this method is that it can be faster than exceptions, depending on your data. To demonstrate,</p>\n\n<pre><code>#!/usr/bin/env python3\n\nfrom contextlib import suppress\nfrom sys import version\nfrom timeit import timeit\n\n\ndef exception_method(axes, coord):\n try:\n ax = axes['y']\n except KeyError:\n pass\n else:\n coord[ax] = 0\n\n\ndef suppress_method(axes, coord):\n with suppress(KeyError):\n ax = axes['y']\n coord[ax] = 0\n\n\ndef get_method(axes, coord):\n ax = axes.get('y')\n if ax is not None:\n coord[ax] = 0\n\n\nmethods = ((suppress_method, 'contextlib.suppress'),\n (exception_method, 'exception swallowing'),\n (get_method, 'dict.get'))\n\n\ndef trial(method_index, is_present):\n coord = {}\n axes = {'y': 0} if is_present else {}\n method, desc = methods[method_index]\n\n def run():\n method(axes, coord)\n\n REPS = 200000\n t = timeit(run, number=REPS)/REPS * 1e6\n\n print(f'Method: {desc:20}, '\n f'Key pre-exists: {str(is_present):5}, '\n f'Avg time (us): {t:.2f}')\n\n\ndef main():\n print(version)\n\n for method in range(3):\n for present in (False, True):\n trial(method, present)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>The output is:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]\nMethod: contextlib.suppress , Key pre-exists: False, Avg time (us): 8.86\nMethod: contextlib.suppress , Key pre-exists: True , Avg time (us): 7.71\nMethod: exception swallowing, Key pre-exists: False, Avg time (us): 3.70\nMethod: exception swallowing, Key pre-exists: True , Avg time (us): 2.93\nMethod: dict.get , Key pre-exists: False, Avg time (us): 2.90\nMethod: dict.get , Key pre-exists: True , Avg time (us): 3.00\n</code></pre>\n\n<p>If you can guarantee that in most cases the key will pre-exist, then the exception-swallowing method is marginally fastest. Otherwise, <code>get</code> is fastest.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T17:36:33.830",
"Id": "405012",
"Score": "2",
"body": "I wonder if the upcoming syntax `if ax := axis.get('y') is not None: coord[ax] = 0` will bring improvements."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T20:55:51.687",
"Id": "209473",
"ParentId": "209468",
"Score": "4"
}
},
{
"body": "<p>Both ways are valid and have their own advantages. Checking upfront using an <code>if</code> statement involve a bit of overheard for each usage, using EAFP involve greater overheads but only for the \"wrong\" case.</p>\n\n<p>So if you mostly have cases where <code>'y'</code> <strong>is</strong> in <code>self.axes</code> then EAFP is better, otherwise LBYL is fine.</p>\n\n<p>But if you only are calling this pattern a handful of times, then either will do; or no, use the third approach <a href=\"https://docs.python.org/3/library/contextlib.html#contextlib.suppress\" rel=\"nofollow noreferrer\"><code>contextlib.suppress</code></a> because this <code>except: pass</code> is ugly:</p>\n\n<pre><code>from contextlib import suppress\n\n\nwith suppress(KeyError):\n ax = self.axes['y'].ax\n coord1[ax] = x0\n coord2[ax] = (y1) - height[ax]\n coord3[ax] = x0 + width[ax]\n coord4[ax] = y1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T16:28:20.293",
"Id": "405001",
"Score": "0",
"body": "I know that it's considered Pythonic to do \"logic by exception\", but in every other language it's discouraged, and it creeps me out."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T22:33:59.217",
"Id": "209480",
"ParentId": "209468",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "209473",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T19:48:11.340",
"Id": "209468",
"Score": "2",
"Tags": [
"python",
"hash-map"
],
"Title": "Pythonic way of checking for dict keys"
} | 209468 |
<p>I have a small angular project, where I have an Article component to list articles with pagination system.</p>
<ol>
<li><p>The default page<img src="https://previews.dropbox.com/p/thumb/AAR0-EYTjb_s0v3f4WcNHzQ8dcdE5AlsDXphkUVEdwYB4WA8HrWmSgr5gDyRAJg5cY1gFUdt3UUjj9Isfm3Ho4ZuIRO53BJHDtjrXLP90Y-ugWzwOjbta4S9BWBE57ugaoJ47eQdXO58aVC6iZsjFrgyMLS_ecktIcsqXwTqzdW5fSjls2aF7UEN8jSZ6V5pMncm-W-IPjXvhsIoWgpJhYo83dUKnYoqJG_5z1X_l6q1Yg/p.png?size=1600x1200&size_mode=3"></p></li>
<li><p>The placeholder loader page<img src="https://previews.dropbox.com/p/thumb/AAQbSwuL7X2wRnBYzELgb9iwGw97OG-PSea6clcPJ5aq6AGrOwn-Vec-Nq7BluN-cWA7PVaSs8VPcUlaJTqwPhYjBI8nAhXJWkJDjKC8XNhaJv1WFUI7IYi9K4MZLfEEMIB4mahJ6VLv1usVS3zlhcl49vD4oOzZCRviHNYOK0k_ij0hjw0ayc2UaZqykokzRdhN58iMfcEW5kfNW0f9tMTm3gH_5Q8Aa8gw6e6vCKXvXQ/p.png?size=1600x1200&size_mode=3"></p></li>
</ol>
<p>The main objectives are:</p>
<ul>
<li> Display the articles after consuming a GET API ressource.</li>
<li> Paginating the articles with <a href="https://ng-bootstrap.github.io/#/components/pagination/examples" rel="nofollow noreferrer">ngb-pagination</a>.</li>
<li> Display a placeholder loader in case the response is not ready yet.</li>
</ul>
<p>My code works perfectly, except that I notice a little refresh of the page each time I paginate to another page. I'm sure that my code need a lot of improvements.</p>
<p>I'm gonna show you my code, and I ask you to help me to improve it. (you can find <a href="https://github.com/ahmed-bhs/angular6-demo/tree/74157f865af32ff5d916027e6db2e26e22276b00" rel="nofollow noreferrer">here on GitHub</a>.</p>
<p>This my <code>article.compononent.ts</code></p>
<pre><code>export class ArticleComponent implements OnInit {
itemsPerPage: any;
totalItems: any;
page: any;
previousPage: any;
public observable$: Observable<any>;
private _articlesUrl = `${environment.apiUrl}` + '/articles';
public articles: any;
readonly imagePath = `${environment.apiUrl}` + '/..';
constructor(
private http: HttpClient,
) { }
ngOnInit() {
this.observable$ = this.http.get(this._articlesUrl).pipe(map((res: Response) => {
this.page = res['page'];
this.totalItems = res['total'];
this.itemsPerPage = res['limit'];
return res['_embedded']['items'];
}));
this.observable$.subscribe(
(res) => this.articles = res
);
}
loadPage(page: number) {
if (page !== this.previousPage) {
this.previousPage = page;
this.loadData();
}
}
loadData() {
this.http.get(this._articlesUrl, {
params: new HttpParams()
.set('page', this.page)
.set('per_page', this.itemsPerPage)
}).pipe(map((res) => res['_embedded']['items'])).subscribe(
(res: any[]) => this.articles = res
);
}
trackElement(index: number, element: any) {
return element ? element.id : null;
}
createRange(len= 20) {
const arr = [];
for (let i = 0; i < len ; i++) {
arr.push(i);
}
return arr;
}
}
</code></pre>
<p><br>
This is the <code>article.component.html</code></p>
<pre><code> <div class="col-xs-12" *ngIf="articles">
<div class="blog-grids">
<div class="grid" *ngFor="let article of (articles); trackBy: trackElement">
<div class="entry-media" >
<img [src]="imagePath + article.image" alt="">
</div>
<div class="entry-body">
<span class="cat">{{article.title}}</span>
<h3><a [routerLink]="['/article/', article.id]">Visit {{article.title}}</a></h3>
<p>Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut..</p>
<div class="read-more-date">
<a href="#">Read More..</a>
<span class="date">3 Hours ago</span>
</div>
</div>
</div>
</div>
<ngb-pagination [collectionSize]="totalItems" [pageSize]="itemsPerPage" [(page)]="page" [maxSize]="2" [rotate]="true" (pageChange)="loadPage($event)"></ngb-pagination>
</div>
<masonry class="row mt-5" *ngIf="!(observable$ | async)">
<masonry-brick class="col-md-4 mb-3" *ngFor="let item of createRange(6)">
<div class="timeline-item">
<div class="animated-background">
<div class="background-masker image"></div>
<div class="background-masker header-bottom"></div>
...
</div>
</div>
</masonry-brick>
</masonry>
</code></pre>
<p>Any code review, improvement, refactoring, recommendation, advices, pull-request would be appreciated and <strong>voted</strong>.</p>
<p><strong>EDIT</strong>
This is what my api return as a result:</p>
<pre><code>{
"_embedded": {
"items": [
{
"categoryLabel": "category_label",
"id": 275,
"title": "Miss",
"image": "/images/articles/9f9d5128ba85f715d5bf0c72d9609b89.jpg"
},
{
"categoryLabel": "category_label",
"id": 276,
"title": "Dr.",
"image": "/images/articles/79f58611ecfe946bc41a5aba403c2c3c.jpg"
},
{
"categoryLabel": "category_label",
"id": 277,
"title": "Mr.",
"image": "/images/articles/920574ee7bcf374e2b68eb7d698a64a4.jpg"
},
{
"categoryLabel": "category_label",
"id": 278,
"title": "Prof.",
"image": "/images/articles/b5d6da63fa2db61ac4e4e8ca01568a0d.jpg"
},
{
"categoryLabel": "category_label",
"id": 279,
"title": "Prof.",
"image": "/images/articles/940d7dcbd80f8ff8f3fd707bd92f681d.jpg"
}
]
},
"route": "api_get_articles",
"parameters": [],
"absolute": false,
"limit": 5,
"total": 250,
"limitparametername": "per_page",
"page": 1,
"pages": 50,
"pageparametername": "page",
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T18:09:13.797",
"Id": "405017",
"Score": "1",
"body": "Welcome to Code Review! After getting an answer you should not change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T18:30:23.800",
"Id": "405019",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. I've rolled back to revision 5."
}
] | [
{
"body": "<p>The purpose of the request made in <code>ngOnInit</code> seemed unclear to me. \nI presume if any pagination info is not provided, then the result contains the default pagination values such as <code>page</code>, <code>total</code>, <code>limit</code> or does it return all items? </p>\n\n<p>Just in case, it is good practice to provide explicit default values such as <code>page: 0</code>, <code>limit: 20</code>etc. After setting the default values, <code>ngOnInit</code>should use <code>loadData</code> to fetch the items.</p>\n\n<p><strike>As far as i see, <code>observable$</code> variable is not used anywhere except <code>ngOnInit</code>, so i would remove it.</strike></p>\n\n<p>For fetching data or another possible operations on item(s) such as update, fetch, delete etc, i would create a <code>ItemService</code>. You can prefer it to be inject to your component.</p>\n\n<p>Since typescript is a typed language i would define types for response and item.\nSuch as</p>\n\n<pre><code>interface Item {\n\n}\n\ninterface ItemResponse {\n page: number;\n total: number;\n limit: number;\n items: Item[];\n}\n</code></pre>\n\n<p>So from <code>ItemService</code> you may return observable of the proper type.</p>\n\n<p>Edit: updated comment about <code>observable$</code> variable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T10:11:33.900",
"Id": "209509",
"ParentId": "209470",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T20:16:36.023",
"Id": "209470",
"Score": "2",
"Tags": [
"typescript",
"pagination",
"angular-2+",
"rxjs"
],
"Title": "List component using RXJS Angular"
} | 209470 |
<p>I did the following exercise from <a href="https://automatetheboringstuff.com/chapter12/" rel="nofollow noreferrer">here</a> to try out the <a href="https://openpyxl.readthedocs.io/en/stable/" rel="nofollow noreferrer">openpyxl</a> module for generating excel files:</p>
<blockquote>
<p>Create a program that takes a number N from the command line and creates an NxN multiplication table in an Excel spreadsheet.</p>
<p>Row 1 and column A should be used for labels and should be in bold</p>
</blockquote>
<p>Here is the code:</p>
<p><b> multiplication_table.py </b></p>
<pre><code>"""
Makes a Excel mulitplication table with user input.
e.g. input = 4
Output in Excel should look like this:
A B C D E -> column
1 1 2 3 4 -> titel column in bold (same for row)
2 1 1 2 3 4
3 2 2 4 6 8
4 3 3 6 9 12
5 4 4 8 12 16
r
o
w
"""
import sys
import openpyxl
from openpyxl.utils import get_column_letter
from openpyxl.styles import Font
def valid_input(input_string: str) -> bool:
"""Checks if input is valid to use for the excel file"""
return input_string.isdigit() and int(input_string) >= 1
def get_number_from_user() -> int:
"""Asks user until he puts a valid input string."""
while True:
input_string: str = input("Enter positive number to make"
" Excel chart\n")
if valid_input(input_string):
return int(input_string)
def get_max_number() -> int:
"""
Asks from the command line or the user to get the max number for
the excel file
"""
if len(sys.argv) > 1:
input_string: str = sys.argv[1]
if valid_input(input_string):
return int(input_string)
return get_number_from_user()
def make_label_column(sheet, max_number: int, font: Font):
"""Make label column containing enumeration until max_number and
variable font"""
for number in range(1, max_number + 1):
sheet['A' + str(number+1)].font = font
sheet['A' + str(number+1)] = number
def make_label_row(sheet, max_number: int, font: Font):
"""Make label row containing enumeration until max_number and
variable font"""
for number in range(1, max_number + 1):
sheet[get_column_letter(number+1) + "1"].font = font
sheet[get_column_letter(number+1) + "1"] = number
def make_multiplication_field(sheet, max_number: int):
"""Make a field in excel with max_number*max_number elements"""
for num_x in range(1, max_number + 1):
for num_y in range(1, max_number + 1):
sheet[get_column_letter(num_x + 1)
+ str(num_y+1)] = num_x*num_y
def save_workbook_excel_file(workbook):
"""Trys to save created data to excel file"""
try:
workbook.save('result.xlsx')
except PermissionError:
print("No permission to save file.")
def make_excel_table():
"""Main loop to generate excel multiplication file"""
workbook = openpyxl.Workbook()
sheet = workbook['Sheet']
max_number: int = get_max_number()
font_with_bold = Font(name='Times New Roman', bold=True)
make_label_column(sheet, max_number, font_with_bold)
make_label_column(sheet, max_number, font_with_bold)
make_multiplication_field(sheet, max_number)
save_workbook_excel_file(workbook)
if __name__ == "__main__":
make_excel_table()
</code></pre>
<p>Let me know what you think about the code. Is it good to read? What would you improve?</p>
<p>I tried the program with big numbers and it gets rather slow. Is there a way to fill the rows more efficiently?</p>
| [] | [
{
"body": "<p>Run your comments and any UI text through spellcheck. In particular, your problem statement had a few errors in it.</p>\n\n<pre><code>for number in range(1, max_number + 1):\n sheet['A' + str(number+1)].font = font\n sheet['A' + str(number+1)] = number\n</code></pre>\n\n<p>Is this not equivalent to:</p>\n\n<pre><code>for col in range(1, max_number + 1):\n ind = f'A{col+1}'\n sheet[ind].font = font\n sheet[ind] = col\n</code></pre>\n\n<p>Note that you should never call something \"number\". Call it what it actually does (it's a column index). Also, factor out common expressions to a variable. The same applies in your code elsewhere.</p>\n\n<p>I browsed through the <code>openpyxl.utils.cell</code> package and couldn't find anything like this: I suggest that you write a utility function that accepts two zero-based coordinate integers and outputs a ready-to-use row/column cell reference.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T18:31:54.970",
"Id": "405020",
"Score": "0",
"body": "In youre corrected example it should be `sheet[ind] = col - 1`. And thanks i didnt know about the `f-strings`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T18:41:53.710",
"Id": "405022",
"Score": "0",
"body": "@Sandro4912 ish. I've updated the loop. Thanks."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T22:01:15.070",
"Id": "209478",
"ParentId": "209475",
"Score": "4"
}
},
{
"body": "<p>Theres a bug which hides in the make_excel_table function. During refactoring I called by accident 2 times the column method and not the row method. </p>\n\n<p>it should be:</p>\n\n<pre><code>def make_excel_table():\n ...\n font_with_bold = Font(name='Times New Roman', bold=True)\n make_label_column(sheet, max_number, font_with_bold)\n make_label_row(sheet, max_number, font_with_bold)\n make_multiplication_field(sheet, max_number)\n save_workbook_excel_file(workbook)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T18:20:05.727",
"Id": "209550",
"ParentId": "209475",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "209478",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T21:03:35.843",
"Id": "209475",
"Score": "3",
"Tags": [
"python",
"beginner",
"excel"
],
"Title": "Excel Multiplication Table Maker"
} | 209475 |
<p>I have written a little program that calculates the time by given strings.</p>
<p>A time string in the context of this program consists of a number and a following letter that can be s, m, h, or d.</p>
<p>You can enter something like this:</p>
<pre><code>java TimeCalculator 443432s 34234m 34323m 32344234s 8h 23d 12h
</code></pre>
<p>It than calculates the time and prints it out in an readable format:</p>
<pre><code>450 days 22 hours 18 minutes 6 seconds
</code></pre>
<p>I want to ask you, how I can improve the readability and maybe also the performance. I dont tried to design the program object oriented because I think the program is to small for that. But if you have another opinion on that, please let me know!</p>
<pre><code>public class TimeCalculator {
private static final int MINUTE_IN_SECONDS = 60;
private static final int HOUR_IN_SECONDS = 3600;
private static final int DAY_IN_SECONDS = 86400;
private static int seconds = 0;
public static void main(String[] args) {
if (args.length == 0 || args[0].contains("help")) {
showHelp();
return;
}
for (String arg : args) {
timeStringToSeconds(arg);
}
printNewTimeString();
}
private static void timeStringToSeconds(String timeString) {
if (timeString.contains("s")) {
timeString = timeString.replace("s", "");
seconds += Integer.parseInt(timeString);
} else if (timeString.contains("m")) {
timeString = timeString.replace("m", "");
seconds += Integer.parseInt(timeString) * MINUTE_IN_SECONDS;
} else if (timeString.contains("h")) {
timeString = timeString.replace("h", "");
seconds += Integer.parseInt(timeString) * HOUR_IN_SECONDS;
} else if (timeString.contains("d")) {
timeString = timeString.replace("d", "");
seconds += Integer.parseInt(timeString) * DAY_IN_SECONDS;
}
}
private static void printNewTimeString() {
String newTimeString = new String();
// calculate days
int days = 0;
while (seconds >= DAY_IN_SECONDS) {
days++;
seconds -= DAY_IN_SECONDS;
}
if (days > 0) {
newTimeString += days + " days ";
}
// calculate hours
int hours = 0;
while(seconds >= HOUR_IN_SECONDS) {
hours++;
seconds -= HOUR_IN_SECONDS;
}
if (hours > 0) {
newTimeString += hours + " hours ";
}
// calculate minutes
int minutes = 0;
while (seconds >= MINUTE_IN_SECONDS) {
minutes++;
seconds -= MINUTE_IN_SECONDS;
}
if (minutes > 0) {
newTimeString += minutes + " minutes ";
}
// calculate seconds
if (seconds > 0) {
newTimeString += seconds + " seconds ";
}
System.out.println(newTimeString);
}
private static void showHelp() {
System.out.println("This Program converts time strings to an ordered string that makes the time");
System.out.println("information better understandable\n");
System.out.println("You can enter something like this: ");
System.out.println("java TimeCalculator 534s 400d 32453s 234h");
System.out.println("The output will be this: ");
System.out.println("410 days 3 hours 9 minutes 47 seconds");
System.out.println("Available characters: d, h, m, s");
}
}
</code></pre>
| [] | [
{
"body": "<p>Instead of subtracting the <code>day_in_seconds</code> repeatedly you could divide the total seconds by <code>day_in_seconds</code> and then set seconds equal to (<code>seconds % days_in_seconds</code>). </p>\n\n<p>Something like:</p>\n\n<pre><code>if(seconds/days_in_seconds > 0) {\n days = seconds/days_in_seconds;\n seconds = seconds%days_in_seconds;\n}\n</code></pre>\n\n<p>And so on for the other values..</p>\n\n<p>Hope that helps (Posting from mobile)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T02:11:43.997",
"Id": "209487",
"ParentId": "209476",
"Score": "3"
}
},
{
"body": "<p>A few things I'd like to point out:</p>\n\n<p>Whenever you're code gets input from a user of your code you must have some way of verifying that they're entering the right type of data and in the right format. not having this is just looking for trouble.</p>\n\n<p>Using a <code>switch</code> block is usually much easier to work with than a bunch of <code>if</code> blocks.</p>\n\n<p>There is a <code>Duration</code> class in the time api which is made for this type of situation. It is made to help with time calculations as well date/time parts.</p>\n\n<p>Here's one way all this could be put together:</p>\n\n<pre><code>import java.time.Duration;\n\npublic class TimeCalculator {\n\n\n public static void main(String[] args) {\n if (args.length == 0 || args[0].contains(\"help\")) {\n showHelp();\n return;\n }\n try{\n System.out.println(GetFormattedString(args)); \n }catch(Exception e){\n System.out.println(e.getMessage());\n }\n }\n\n private static String GetFormattedString(String[] times) throws NumberFormatException, IllegalArgumentException {\n Duration totalTime = makeTime(times);\n String test = totalTime.toString();\n long days = totalTime.toDaysPart();\n int hours = totalTime.toHoursPart();\n int minutes = totalTime.toMinutesPart();\n int seconds = totalTime.toSecondsPart();\n return String.format(\"%1$d days %2$d hours %3$d minutes %4$d seconds\", days,hours,minutes,seconds);\n }\n\n private static Duration makeTime(String[] times) throws NumberFormatException, IllegalArgumentException {\n Duration totalTime = Duration.ZERO;\n for ( var s:times) {\n long time = 0;\n int lastIndex = s.length()-1;\n try {\n time = Integer.valueOf(s.substring(0, lastIndex));\n } catch (NumberFormatException e) {\n throw new NumberFormatException(\"Invalid characters present in strings provided\");\n }\n switch (s.charAt(lastIndex)) {\n case 's':\n totalTime = totalTime.plusSeconds(time);\n break;\n case 'm':\n totalTime = totalTime.plusMinutes(time);\n break;\n case 'h':\n totalTime = totalTime.plusHours(time);\n break;\n case 'd':\n totalTime = totalTime.plusDays(time);\n break;\n default:\n throw new IllegalArgumentException(\"String provided is in the wrong format\");\n }\n }\n return totalTime;\n }\n\n private static void showHelp() {\n System.out.println(\"This Program converts time strings to an ordered string that makes the time\");\n System.out.println(\"information better understandable\\n\");\n System.out.println(\"You can enter something like this: \");\n System.out.println(\"java TimeCalculator 534s 400d 32453s 234h\");\n System.out.println(\"The output will be this: \");\n System.out.println(\"410 days 3 hours 9 minutes 47 seconds\");\n System.out.println(\"Available characters: d, h, m, s\");\n }\n}\n</code></pre>\n\n<p><strong><em>EDIT</em></strong></p>\n\n<p>I didn't really like throwing exceptions like that, so I came up with a version that eliminates throwing exceptions. I added 2 things, a <code>tryParseLong</code> method and a wrapper class(<code>TimeLong</code>) to be able to pass the time value by reference:</p>\n\n<pre><code>import java.time.Duration;\n\npublic class TimeCalculator {\n\n public static void main(String[] args) {\n if (args.length == 0 || args[0].contains(\"help\")) {\n showHelp();\n return;\n }\n String formattedString = GetFormattedString(args);\n if(formattedString.equals(\"\")){\n System.out.println(\"Invalid arguments used\");\n showHelp();\n return;\n }\n System.out.println(formattedString);\n }\n\n private static String GetFormattedString(String[] times) {\n Duration totalTime = makeTime(times);\n if (totalTime == Duration.ZERO) {\n return \"\";\n }\n long days = totalTime.toDaysPart();\n int hours = totalTime.toHoursPart();\n int minutes = totalTime.toMinutesPart();\n int seconds = totalTime.toSecondsPart();\n return String.format(\"%1$d days %2$d hours %3$d minutes %4$d seconds\", days, hours, minutes, seconds);\n }\n\n private static Duration makeTime(String[] times) {\n Duration totalTime = Duration.ZERO;\n for (var s : times) {\n TimeLong time = new TimeLong((0L));\n int lastIndex = s.length() - 1;\n if (!tryParseLong(s.substring(0, lastIndex), time)) {\n return Duration.ZERO;\n }\n switch (s.charAt(lastIndex)) {\n case 's':\n totalTime = totalTime.plusSeconds(time.value);\n break;\n case 'm':\n totalTime = totalTime.plusMinutes(time.value);\n break;\n case 'h':\n totalTime = totalTime.plusHours(time.value);\n break;\n case 'd':\n totalTime = totalTime.plusDays(time.value);\n break;\n default:\n return Duration.ZERO;\n }\n }\n return totalTime;\n }\n private static class TimeLong{\n public Long value;\n public TimeLong(Long value){\n this.value= value;\n }\n }\n private static boolean tryParseLong(String value, TimeLong outVal) {\n try {\n outVal.value = Long.valueOf(value);\n } catch (Exception e) {\n outVal.value = 0L;\n return false;\n }\n return true;\n }\n\n private static void showHelp() {\n System.out.println(\"This Program converts time strings to an ordered string that makes the time\");\n System.out.println(\"information better understandable\\n\");\n System.out.println(\"You can enter something like this: \");\n System.out.println(\"java TimeCalculator 534s 400d 32453s 234h\");\n System.out.println(\"The output will be this: \");\n System.out.println(\"410 days 3 hours 9 minutes 47 seconds\");\n System.out.println(\"Available characters: d, h, m, s\");\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T08:47:05.277",
"Id": "404931",
"Score": "0",
"body": "I get several error messages when I try to compile your code (using Java 8)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T15:05:51.313",
"Id": "404975",
"Score": "0",
"body": "@DexterThorn - I used the latest NetBeans with Java 11 to build and run this. `toDaysPart()` was added in Java 9. To use java 8, you need to use `toDays()` and then minus that amount from `totalTime`, and repeat for each time part. If you still have a problem let me know and I can add some code for that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T06:21:55.830",
"Id": "209497",
"ParentId": "209476",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209497",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T21:14:12.203",
"Id": "209476",
"Score": "2",
"Tags": [
"java",
"datetime",
"calculator",
"unit-conversion"
],
"Title": "Calculator to add time intervals"
} | 209476 |
<p>I've starting writing the card game Uno the past couple of days and was wondering if you can review my code please. The initialization is done I think, a couple of game functions already exist, please have look.</p>
<p>Please give me feedback concerning, structure, logic, data structures, naming conventions, anything you're noticing!</p>
<p>I want to make sure everything is set until I move on to the View and Controller.</p>
<pre><code>import UIKit
import Foundation
// Represents all jokers of the game.
enum Joker: String, CaseIterable {
// Only four copies of each will be created
case joker, drawFour, swapCircle
func points() -> Int {
switch self {
case .joker, .drawFour, .swapCircle: return 50
} // returns points of each card
}
}
// Represents all "normal" cards.
enum Value: String, CaseIterable {
// A cartesian product with all colors will be built.
case one, two, three, four, five, six, seven, eight, nine, drawTwo, skip, turn
// returns points of each card
func points() -> Int {
switch self {
// THIS DOES NOT LOOK VERY NICE. IS THERE A SMOOTHER WAY?
case .one: return 1
case .two: return 2
case .three: return 3
case .four: return 4
case .five: return 5
case .six: return 6
case .seven: return 7
case .eight: return 8
case .nine: return 9
case .drawTwo, .skip, .turn: return 20
}
}
}
// Represents all colors.
enum Color: String, CaseIterable {
case red, blue, yellow, green
}
// Represents the structure of a card.
struct Card {
let value: Value? // is nil when card is a joker
let color: Color? // is nil when card is a joker
let joker: Joker? // is nil when card has a value and color
}
// Represents the two stacks of the game. Game stack as well as draw stack will be instances of stack, depending on which constructor is called the correct instance will be created.
class Stack {
public var stack: [Card]
// Creates the draw when the game is first initalized.
private static func createDrawStack(with amountOfCards: Int) -> [Card] {
var cards = [Card]()
// add 2 cards of each value
for color in Color.allCases {
for value in Value.allCases {
for _ in 0..<amountOfCards { // add two copies
cards += [Card(value: value, color: color, joker: nil)]
}
}
}
for _ in 0..<(amountOfCards * 2) {
// add 1 swap-circle
cards += [Card(value: nil, color: nil, joker: .swapCircle)]
// add 1 draw-four
cards += [Card(value: nil, color: nil, joker: .drawFour)]
// add 1 joker
cards += [Card(value: nil, color: nil, joker: .joker)]
}
return cards.shuffled() // TODO: In-place shuffling wouldn't work, maybe not shuffling in here is smoother
}
// Creates the game stack when the game is first initalized.
private static func createGameStack(with drawStack: Stack) -> [Card] {
return [drawStack.stack.popLast()!]
}
init(createDrawStackWith amount: Int) {
self.stack = Stack.createDrawStack(with: amount)
}
init(createGameStackWith drawStack: Stack) {
self.stack = Stack.createGameStack(with: drawStack)
}
}
// Represents a player and the actions a player can do.
class Player {
let id: Int
var hand = [Card?]()
var didDraw = false
// Receives index of button pressed and returns the card selected, so that cardsMatch() can check if it's a valid turn. If so, playCard() will be called.
public func wantsToPlayCard(at index: Int) -> Card {
return hand[index]!
}
// Moves card requested from user hand to playStack
public func playCard(at index: Int, onto playStack: Stack) {
if let card = self.hand.remove(at: index) {
playStack.stack.append(card)
}
}
// Moves a card from drawStack to user hand
public func drawCard(from deck: Stack) {
self.hand.append(deck.stack.popLast()!)
}
init(withID id: Int) {
self.id = id
}
}
// Represents the whole game. This is the core of the game.
class Uno {
public var drawStack: Stack // creates a stack to draw from with 2 copies of each color
public var playStack: Stack // creates a stack where the game will be played
public var players: [Player] // will be initialized dependent of amount
// Moves play stack back into draw stack.
public func resetDrawStack() {
let topCard = playStack.stack.popLast()! // save top card
drawStack.stack = playStack.stack // move rest of playStack back into drawStack
drawStack.stack.shuffle()
playStack.stack.removeAll()
playStack.stack += [topCard]
}
// Checks if a requested card can be played or not.
public func cardsMatch(compare topCard: Card, with handCard: Card) -> Bool {
// if colors match
if let colorTopCard = topCard.color, let colorHandCard = handCard.color {
if colorTopCard == colorHandCard {
return true
}
}
// if values match
if let valueTopCard = topCard.value, let valueHandCard = handCard.value {
if valueTopCard == valueHandCard {
return true
}
}
// if its a joker
if let _ = handCard.joker {
return true
}
// else
return false
}
// Deals cards to players at the start of round.
private func dealCards(with amountOfCards: Int) {
for id in players.indices {
for _ in 0..<amountOfCards {
players[id].drawCard(from: drawStack)
}
}
}
// Creates the players.
private static func createPlayers(with amountOfPlayers: Int) -> [Player] {
var players = [Player]()
for id in 0..<amountOfPlayers {
players += [Player(withID: id)]
}
return players
}
// Constructs game dependent on settings.
init(amountOfPlayers: Int, amountOfCopies: Int, amountOfCards: Int) {
self.drawStack = Stack(createDrawStackWith: amountOfCopies)
print(self.drawStack.stack)
self.playStack = Stack(createGameStackWith: self.drawStack)
self.players = Uno.createPlayers(with: amountOfPlayers) // creates 2 players
self.dealCards(with: amountOfCards)
}
}
var game = Uno(amountOfPlayers: 2, amountOfCopies: 2, amountOfCards: 7)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T00:27:56.057",
"Id": "404890",
"Score": "1",
"body": "This isn’t as constructive as most other comments might be, but consider a pun in the title. Something like: Creating a Swift game of Uno or whatever you think is cool."
}
] | [
{
"body": "<p>I don't much like your <code>Card</code> struct. What would you do if you found a card that had a non-nil value for all three properties? It's better to make impossible things impossible.</p>\n\n<pre><code>enum Card {\n case suit(Value, Color)\n case special(Joker)\n}\n</code></pre>\n\n<p>With the above, there is no way to make a card that has a non-nil Joker as well as non-nil Value. It also requires every card that has a Value to also have a Color which is something else that your current struct doesn't enforce.</p>\n\n<hr>\n\n<p>As a general rule, if a function doesn't require <code>self</code>, it shouldn't be a method. At minimum it should be <code>static</code>, IMO it really should be a free function (one written outside of any class.) This rule applies to your <code>cardsMatch(compare:with:)</code> method. Either define it as static (as in <code>public static func cardsMatch...</code>) or write it outside of the class.</p>\n\n<p>Also, if you used my Card idea above, the match method would become considerably simpler.</p>\n\n<pre><code>public func cardsMatch(compare topCard: Card, with handCard: Card) -> Bool {\n switch (topCard, handCard) {\n case (_, .special):\n return true\n case let (.suit(topValue, topColor), .suit(handValue, handColor)):\n return topValue == handValue || topColor == handColor\n }\n}\n</code></pre>\n\n<p>Note, I wrote the above as a free function.</p>\n\n<p>I think the above exercise also exposed a logic error in the function. Can't you lay any card on top of a special/joker card?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T12:20:10.387",
"Id": "404951",
"Score": "0",
"body": "Thank you a lot! I will think about it later and come back to you :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T12:44:21.800",
"Id": "404956",
"Score": "0",
"body": "I added to my response."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T14:51:46.260",
"Id": "404967",
"Score": "0",
"body": "Thx! No, I should've added my assumptions. A joker will stay black in the UI but the internal color will be whatever color they chose. That will be in case draw-four and joker (both have wish-a-color). If someones plays a swap-circle, swap circle will adapt the color of the card that it was put on. Never mentioned this, sorry. That makes your solution for the card not so optimal, does it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T14:54:38.990",
"Id": "404969",
"Score": "0",
"body": "Also, why would I write a free func? I won't need to compare cards outside of game. I always thought like this: comparing two cards is the games job, so it should be a method of the game. Same with anything that mutates anything. The one that's got the job will have the method. Is this wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T15:04:18.573",
"Id": "404973",
"Score": "0",
"body": "I think you can agree that it's generally bad form to pass parameters into a function that the function doesn't need. For example you don't pass a player or stack into the compare function. Well `self` is a parameter too. If you don't use it, you shouldn't pass it in. After all, I can show you two cards and ask if one can stack on top of the other _without_ bringing along an entire deck and dealing cards out, but your function requires all of that because it requires self. This means you should either making the function static or a free function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T15:07:27.217",
"Id": "404976",
"Score": "0",
"body": "Semantically a static and free function are identical. The only difference is the syntax at the calling site. For one, I have to type `Uno.cardsMatch...` while for the other, I only have to type `cardsMatch...`. If you really want to make the caller type the word `Uno` then make the function static, or you could just add \"Uno\" to the beginning of the free function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T15:10:49.087",
"Id": "404978",
"Score": "0",
"body": "As for my Card type not being adequate for the job, that may be true, I don't remember all of Uno's rules. However, the point remains, make impossible states impossible. Best case, you can make it so such an object won't even allow the program to compile, next best would be to abort the program if such an object is created. The latter idea is obviously sub-standard because it means you won't notice the problem unless you happen to run the offending code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T19:27:19.033",
"Id": "405033",
"Score": "0",
"body": "Gotcha. Thanks a lot :-). Will review this at some point. Lots of homework these days ...."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T03:14:39.000",
"Id": "209492",
"ParentId": "209484",
"Score": "2"
}
},
{
"body": "<h3>Imports</h3>\n\n<p>If you're importing UIKit, you don't need to import Foundation. Foundation is included in the UIKit import.</p>\n\n<h3>Classes</h3>\n\n<p>The underlying class variables in all of the classes are public. In most of these cases, the methods that populate them are private. That means that the vars should most likely also be private, or at the very least <code>private (set)</code> if you wanted to be able to still view the contents of them.</p>\n\n<p>Additionally there are a lot of public methods that seem like they are unnecessarily public. When making a method or property public, you should ask yourself if it is necessary to access that value outside of the scope of your project. If not, then you're probably safe to use internal (the default).</p>\n\n<h3>Card</h3>\n\n<p>I believe Daniel T covered the Card struct in a great way. I would agree with his suggestions regarding that. Removing the unnecessary optionals and setting it up in an enum as he did would help quite a bit.</p>\n\n<h3>Stack</h3>\n\n<p>I am not a fan of the name <code>stack</code> for the array of <code>Card</code> contained in the <code>Stack</code>. It could use a more descriptive name. I would probably name it <code>cards</code> because it makes it more obvious and less redundant when you're doing things like <code>drawStack.stack.popLast()</code> as <code>drawStack.cards.popLast()</code>.</p>\n\n<p>In the createGameStack method, you force unwrap the initial draw and this should be fine. However if something were to go wrong, this would result in a crash. You could perhaps add a guard here.</p>\n\n<pre><code>private static func createGameStack(with drawStack: Stack) -> [Card] {\n guard let topCard = drawStack.stack.popLast() else {\n print(\"Why is the drawStack empty?\")\n return []\n }\n\n return [topCard]\n}\n</code></pre>\n\n<p>The initializers are kind of redundant here. You have static methods to populate the stack based on the type that you're creating, but you also have corresponding initializers. I would consider a generic initializer that would set the stack to an empty array, and then have your createDeck methods become public and return a Stack object. Finally I would update your createGameStack method to be public and not static. This is dependent on a deckStack existing, so it makes sense for it to be a method on that object. </p>\n\n<pre><code>init() {\n self.cards = [] // This could also be done as public var cards: [Card] = []\n}\n\nstatic func createDrawStack(with amountOfCards: Int) -> Stack {\n let drawStack = Stack()\n // Create the card array here.\n drawStack.cards = cards.shuffled()\n return drawStack\n}\n\nfunc createGameStack() -> Stack {\n let gameStack = Stack()\n guard let topCard = drawStack.cards.popLast() else {\n print(\"Why is the drawStack empty?\")\n return gameStack\n }\n\n gameStack.cards = [topCard]\n return gameStack\n}\n</code></pre>\n\n<p>This gives you the implementation like this: </p>\n\n<pre><code>self.drawStack = Stack.createDrawStack(with: amountOfCopies)\nself.playStack = drawStack.createGameStack()\n</code></pre>\n\n<h3>Player</h3>\n\n<p>The hand does not need to be an array of optional cards. The player should fit into one of two categories; 1. they have cards in hand or 2. they have no hand and have won the game. In both cases there isn't a situation where the user will have something but possibly nothing in their hand, which is what an optional card would represent.</p>\n\n<p>The <code>wantsToPlayCard(at index:)</code> method returns a Card, but does not perform any overflow checking. This as well as the <code>playCard(at index: onto playStack:)</code> method should both check to make sure that the index is not out of the bounds of the array at a minimum.</p>\n\n<p>The <code>playCard(at index: onto playStack:)</code> method could (should) be split into two methods, one in the player class and one in the stack class. You want to enforce separation of concerns here, and due to the way you have the method laid out, you have a direct dependency on something that the player should not.\nWhen separating the concerns here, you would want the Player.playCard method to identify the card which will be played, which you are already in the <code>wantsToPlayCard(index:)</code> method. Then in the stack there would be a <code>play(_ card: Card)</code> method that would do the append on the stack.</p>\n\n<p>Doing this enables you to remove the player's dependency on the stack and implement something like this <code>playStack.play(currentPlayer.wantsToPlayCard(at: 4))</code>.</p>\n\n<p><code>var didDraw</code> is unused.</p>\n\n<p>Similar to the above mentioned separation of concerns, <code>drawCard(from deck:)</code> seems like is should be added to the stack class and the player's implementation should be more like <code>drawCard(_ card: Card)</code> where you are provided a card from the deck and merely adding it to the player's hand.</p>\n\n<h3>Uno</h3>\n\n<p>I'll have to come back and take a look at the <code>Uno</code> class, but I feel this is a good start for suggestions and ideas.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T19:26:45.603",
"Id": "405032",
"Score": "0",
"body": "Thanks, it certainly is. Will come back to you. :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T15:42:45.900",
"Id": "209534",
"ParentId": "209484",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T00:08:38.860",
"Id": "209484",
"Score": "3",
"Tags": [
"swift",
"playing-cards"
],
"Title": "Creating a Swift game of Uno"
} | 209484 |
<p>This code is part of a VSTO add-in for Excel. As the title states it solves systems of linear equations by allowing the user to select the appropriate ranges. The code works and covers most issues I could think of. The form is displayed by a button click from the ribbon. The selection of ranges is accomplished by clicking respective buttons on the form and selecting <code>Range</code> objects on a sheet via the <a href="https://docs.microsoft.com/en-us/office/vba/api/excel.application.inputbox" rel="nofollow noreferrer">InputBox</a> where <code>Type: 8</code> stands for a Range object.</p>
<p>The problem is everything is coded in the code behind for the from, something that doesn't allow for code reuse. What can be done to foster code reuse? I've read about the Model-View-Presenter and think this pattern is applicable. I'm presently unable to bridge the gap between reading about it and writing code according to that pattern. If MVP isn't applicable then what pattern would best suited?</p>
<p>Code generated by the designer.</p>
<pre><code>//SystemsOfEquationsView.Designer.cs is of the type `System.Windows.Forms.Form`.
namespace ExcelAddIn1.System_Of_Linear_Equations
{
partial class SystemsOfEquationsView
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.SelectAnswerVectorBotton = new System.Windows.Forms.Button();
this.SelectCoefficientButton = new System.Windows.Forms.Button();
this.AnswerVectorDisplay = new System.Windows.Forms.TextBox();
this.CoefficientMatrixDisplay = new System.Windows.Forms.TextBox();
this.AnswerVectorLabel = new System.Windows.Forms.Label();
this.CoefficientMatrixLabel = new System.Windows.Forms.Label();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.SelectSolutionButton = new System.Windows.Forms.Button();
this.SelectInverseCoefficientButton = new System.Windows.Forms.Button();
this.SolutionVectorDisplay = new System.Windows.Forms.TextBox();
this.InverseCoefficientMatrixDisplay = new System.Windows.Forms.TextBox();
this.SolutionVectorLabel = new System.Windows.Forms.Label();
this.InverseCoefficientMatrixLabel = new System.Windows.Forms.Label();
this.ClearButton = new System.Windows.Forms.Button();
this.SolveButton = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.SelectAnswerVectorBotton);
this.groupBox1.Controls.Add(this.SelectCoefficientButton);
this.groupBox1.Controls.Add(this.AnswerVectorDisplay);
this.groupBox1.Controls.Add(this.CoefficientMatrixDisplay);
this.groupBox1.Controls.Add(this.AnswerVectorLabel);
this.groupBox1.Controls.Add(this.CoefficientMatrixLabel);
this.groupBox1.Location = new System.Drawing.Point(12, 12);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(474, 86);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Inputs";
//
// SelectAnswerVectorBotton
//
this.SelectAnswerVectorBotton.Location = new System.Drawing.Point(335, 57);
this.SelectAnswerVectorBotton.Name = "SelectAnswerVectorBotton";
this.SelectAnswerVectorBotton.Size = new System.Drawing.Size(128, 23);
this.SelectAnswerVectorBotton.TabIndex = 5;
this.SelectAnswerVectorBotton.Text = "Select Answer Vector";
this.SelectAnswerVectorBotton.UseVisualStyleBackColor = true;
this.SelectAnswerVectorBotton.Click += new System.EventHandler(this.SelectAnswerVectorBotton_Click);
//
// SelectCoefficientButton
//
this.SelectCoefficientButton.Location = new System.Drawing.Point(156, 57);
this.SelectCoefficientButton.Name = "SelectCoefficientButton";
this.SelectCoefficientButton.Size = new System.Drawing.Size(100, 23);
this.SelectCoefficientButton.TabIndex = 4;
this.SelectCoefficientButton.Text = "Select Coefficient";
this.SelectCoefficientButton.UseVisualStyleBackColor = true;
this.SelectCoefficientButton.Click += new System.EventHandler(this.SelectCoefficientButton_Click);
//
// AnswerVectorDisplay
//
this.AnswerVectorDisplay.Enabled = false;
this.AnswerVectorDisplay.Location = new System.Drawing.Point(349, 31);
this.AnswerVectorDisplay.Name = "AnswerVectorDisplay";
this.AnswerVectorDisplay.ReadOnly = true;
this.AnswerVectorDisplay.Size = new System.Drawing.Size(100, 20);
this.AnswerVectorDisplay.TabIndex = 3;
//
// CoefficientMatrixDisplay
//
this.CoefficientMatrixDisplay.Enabled = false;
this.CoefficientMatrixDisplay.Location = new System.Drawing.Point(156, 31);
this.CoefficientMatrixDisplay.Name = "CoefficientMatrixDisplay";
this.CoefficientMatrixDisplay.ReadOnly = true;
this.CoefficientMatrixDisplay.Size = new System.Drawing.Size(100, 20);
this.CoefficientMatrixDisplay.TabIndex = 2;
//
// AnswerVectorLabel
//
this.AnswerVectorLabel.AutoSize = true;
this.AnswerVectorLabel.Location = new System.Drawing.Point(268, 34);
this.AnswerVectorLabel.Name = "AnswerVectorLabel";
this.AnswerVectorLabel.Size = new System.Drawing.Size(75, 13);
this.AnswerVectorLabel.TabIndex = 1;
this.AnswerVectorLabel.Text = "Answer vector";
//
// CoefficientMatrixLabel
//
this.CoefficientMatrixLabel.AutoSize = true;
this.CoefficientMatrixLabel.Location = new System.Drawing.Point(63, 34);
this.CoefficientMatrixLabel.Name = "CoefficientMatrixLabel";
this.CoefficientMatrixLabel.Size = new System.Drawing.Size(87, 13);
this.CoefficientMatrixLabel.TabIndex = 0;
this.CoefficientMatrixLabel.Text = "Coefficient matrix";
//
// groupBox2
//
this.groupBox2.Controls.Add(this.SelectSolutionButton);
this.groupBox2.Controls.Add(this.SelectInverseCoefficientButton);
this.groupBox2.Controls.Add(this.SolutionVectorDisplay);
this.groupBox2.Controls.Add(this.InverseCoefficientMatrixDisplay);
this.groupBox2.Controls.Add(this.SolutionVectorLabel);
this.groupBox2.Controls.Add(this.InverseCoefficientMatrixLabel);
this.groupBox2.Location = new System.Drawing.Point(12, 104);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(474, 86);
this.groupBox2.TabIndex = 1;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Outputs: Top left cell";
//
// SelectSolutionButton
//
this.SelectSolutionButton.Location = new System.Drawing.Point(335, 57);
this.SelectSolutionButton.Name = "SelectSolutionButton";
this.SelectSolutionButton.Size = new System.Drawing.Size(128, 23);
this.SelectSolutionButton.TabIndex = 6;
this.SelectSolutionButton.Text = "Select Solution Vector";
this.SelectSolutionButton.UseVisualStyleBackColor = true;
this.SelectSolutionButton.Click += new System.EventHandler(this.SelectSolutionButton_Click);
//
// SelectInverseCoefficientButton
//
this.SelectInverseCoefficientButton.Location = new System.Drawing.Point(156, 57);
this.SelectInverseCoefficientButton.Name = "SelectInverseCoefficientButton";
this.SelectInverseCoefficientButton.Size = new System.Drawing.Size(100, 23);
this.SelectInverseCoefficientButton.TabIndex = 5;
this.SelectInverseCoefficientButton.Text = "Select Inverse";
this.SelectInverseCoefficientButton.UseVisualStyleBackColor = true;
this.SelectInverseCoefficientButton.Click += new System.EventHandler(this.SelectInverseCoefficientButton_Click);
//
// SolutionVectorDisplay
//
this.SolutionVectorDisplay.Enabled = false;
this.SolutionVectorDisplay.Location = new System.Drawing.Point(349, 31);
this.SolutionVectorDisplay.Name = "SolutionVectorDisplay";
this.SolutionVectorDisplay.ReadOnly = true;
this.SolutionVectorDisplay.Size = new System.Drawing.Size(100, 20);
this.SolutionVectorDisplay.TabIndex = 4;
//
// InverseCoefficientMatrixDisplay
//
this.InverseCoefficientMatrixDisplay.Enabled = false;
this.InverseCoefficientMatrixDisplay.Location = new System.Drawing.Point(156, 31);
this.InverseCoefficientMatrixDisplay.Name = "InverseCoefficientMatrixDisplay";
this.InverseCoefficientMatrixDisplay.ReadOnly = true;
this.InverseCoefficientMatrixDisplay.Size = new System.Drawing.Size(100, 20);
this.InverseCoefficientMatrixDisplay.TabIndex = 3;
//
// SolutionVectorLabel
//
this.SolutionVectorLabel.AutoSize = true;
this.SolutionVectorLabel.Location = new System.Drawing.Point(265, 34);
this.SolutionVectorLabel.Name = "SolutionVectorLabel";
this.SolutionVectorLabel.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.SolutionVectorLabel.Size = new System.Drawing.Size(78, 13);
this.SolutionVectorLabel.TabIndex = 1;
this.SolutionVectorLabel.Text = "Solution vector";
//
// InverseCoefficientMatrixLabel
//
this.InverseCoefficientMatrixLabel.AutoSize = true;
this.InverseCoefficientMatrixLabel.Location = new System.Drawing.Point(26, 34);
this.InverseCoefficientMatrixLabel.Name = "InverseCoefficientMatrixLabel";
this.InverseCoefficientMatrixLabel.Size = new System.Drawing.Size(124, 13);
this.InverseCoefficientMatrixLabel.TabIndex = 0;
this.InverseCoefficientMatrixLabel.Text = "Inverse coefficient matrix";
//
// ClearButton
//
this.ClearButton.Location = new System.Drawing.Point(179, 215);
this.ClearButton.Name = "ClearButton";
this.ClearButton.Size = new System.Drawing.Size(75, 23);
this.ClearButton.TabIndex = 2;
this.ClearButton.Text = "Clear";
this.ClearButton.UseVisualStyleBackColor = true;
this.ClearButton.Click += new System.EventHandler(this.ClearButton_Click);
//
// SolveButton
//
this.SolveButton.Location = new System.Drawing.Point(260, 215);
this.SolveButton.Name = "SolveButton";
this.SolveButton.Size = new System.Drawing.Size(75, 23);
this.SolveButton.TabIndex = 3;
this.SolveButton.Text = "Solve";
this.SolveButton.UseVisualStyleBackColor = true;
this.SolveButton.Click += new System.EventHandler(this.SolveButton_Click);
//
// SystemsOfEquationsView
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(496, 250);
this.Controls.Add(this.SolveButton);
this.Controls.Add(this.ClearButton);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Name = "SystemsOfEquationsView";
this.Text = "SystemsOfEquationsView";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label AnswerVectorLabel;
private System.Windows.Forms.Label CoefficientMatrixLabel;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Label SolutionVectorLabel;
private System.Windows.Forms.Label InverseCoefficientMatrixLabel;
private System.Windows.Forms.Button ClearButton;
private System.Windows.Forms.Button SolveButton;
private System.Windows.Forms.Button SelectAnswerVectorBotton;
private System.Windows.Forms.Button SelectCoefficientButton;
private System.Windows.Forms.Button SelectSolutionButton;
private System.Windows.Forms.Button SelectInverseCoefficientButton;
private System.Windows.Forms.TextBox AnswerVectorDisplay;
private System.Windows.Forms.TextBox CoefficientMatrixDisplay;
private System.Windows.Forms.TextBox SolutionVectorDisplay;
private System.Windows.Forms.TextBox InverseCoefficientMatrixDisplay;
}
}
</code></pre>
<p>Code I've written for the logic.</p>
<pre><code>//SystemsOfEquationsView.cs
using System;
using System.Drawing;
using System.Windows.Forms;
using XL = Microsoft.Office.Interop.Excel;
namespace ExcelAddIn1.System_Of_Linear_Equations
{
public partial class SystemsOfEquationsView : Form
{
private readonly Color _defaultForeColor = Color.Black;
private readonly Color _alertForeColor = Color.Red;
public SystemsOfEquationsView()
{
InitializeComponent();
}
private void SolveButton_Click(object sender, EventArgs e)
{
RestoreDefaultColoring();
if (AreInputValuesInValid())
{
//MessageBox.Show(SystemOfLinearEquations.InvalidInputText, SystemOfLinearEquations.InvalidInputCaption);
MessageBox.Show("Inputs need to be valid, correct cell references before continuing.", "Invalid input");
return;
}
if (CoefficientMatrix.Rows.Count != CoefficientMatrix.Columns.Count)
{
CoefficientMatrixDisplay.ForeColor = Color.Red;
//MessageBox.Show(SystemOfLinearEquations.NonSquareMatrixText, SystemOfLinearEquations.NonSquareMatrixCaption);
MessageBox.Show("A non - square matrix cannot be solved for", "Non - square matrix");
return;
}
double matrixDeterminant;
try
{
matrixDeterminant = Globals.ThisAddIn.Application.WorksheetFunction.MDeterm(CoefficientMatrix);
}
catch (Exception)
{
MessageBox.Show(SystemOfLinearEquations.NonSingularMatrixText, SystemOfLinearEquations.NonSingularMatrixCaption);
return;
}
if (AnswerVector.Rows.Count != CoefficientMatrix.Columns.Count)
{
AnswerVectorDisplay.ForeColor = _alertForeColor;
//MessageBox.Show(SystemOfLinearEquations.AnswerVectorMustMatchCoeffMatrixColumns);
MessageBox.Show("Answer vector rows must match coefficient matrix columns");
return;
}
if (AnswerVector.Columns.Count != 1)
{
AnswerVectorDisplay.ForeColor = _alertForeColor;
//MessageBox.Show(SystemOfLinearEquations.AnswerVectorSingleColumn);
MessageBox.Show("A non - square matrix cannot be solved for") ;
return;
}
InverseCoefficientMatrix = InverseCoefficientMatrix.Resize[CoefficientMatrix.Rows.Count, CoefficientMatrix.Columns.Count];
SolutionVector = SolutionVector.Resize[AnswerVector.Rows.Count, 1];
if (WillOverwriteInformation(InverseCoefficientMatrix) || WillOverwriteInformation(SolutionVector))
{
DialogResult result = MessageBox.Show("Information will be erased if you continue", "Ok to proceed?", MessageBoxButtons.YesNo);
if (result.Equals(DialogResult.No))
{
return;
}
}
InverseCoefficientMatrix.FormulaArray = $"=minverse({CoefficientMatrix.Address})";
SolutionVector.FormulaArray = $"=mmult({InverseCoefficientMatrix.Address},{AnswerVector.Address})";
}
private void RestoreDefaultColoring()
{
CoefficientMatrixLabel.ForeColor = _defaultForeColor;
AnswerVectorLabel.ForeColor = _defaultForeColor;
InverseCoefficientMatrixLabel.ForeColor = _defaultForeColor;
SolutionVectorLabel.ForeColor = _defaultForeColor;
}
//TODO convert to static utility class
private bool WillOverwriteInformation(XL.Range destination, bool checkForConstants = true, bool checkForFormulas = true)
{
bool willOverwriteConstants = false;
bool willOverwriteFormulas = false;
if (checkForConstants)
{
try
{
willOverwriteConstants = destination.SpecialCells(XL.XlCellType.xlCellTypeConstants).Count > 0;
}
catch (System.Runtime.InteropServices.COMException e)
{
willOverwriteConstants = false;
}
}
if (checkForFormulas)
{
try
{
willOverwriteFormulas = destination.SpecialCells(XL.XlCellType.xlCellTypeFormulas).Count > 0;
}
catch (System.Runtime.InteropServices.COMException e)
{
willOverwriteFormulas = false;
}
}
return willOverwriteConstants || willOverwriteFormulas;
}
private void ClearButton_Click(object sender, EventArgs e)
{
CoefficientMatrixDisplay.Clear();
AnswerVectorDisplay.Clear();
InverseCoefficientMatrixDisplay.Clear();
SolutionVectorDisplay.Clear();
RestoreDefaultColoring();
}
private bool AreInputValuesInValid()
{
CoefficientMatrixLabel.ForeColor = CoefficientMatrix is null
? _alertForeColor
: _defaultForeColor;
AnswerVectorLabel.ForeColor = AnswerVector is null
? _alertForeColor
: _defaultForeColor;
InverseCoefficientMatrixLabel.ForeColor = InverseCoefficientMatrix is null
? _alertForeColor
: _defaultForeColor;
SolutionVectorLabel.ForeColor = SolutionVector is null
? _alertForeColor
: _defaultForeColor;
return CoefficientMatrixLabel.ForeColor.Equals(_alertForeColor)
|| AnswerVectorLabel.Equals(_alertForeColor)
|| InverseCoefficientMatrixLabel.Equals(_alertForeColor)
|| SolutionVectorLabel.Equals(_alertForeColor);
}
public XL.Range CoefficientMatrix { get; set; }
private void SelectCoefficientButton_Click(object sender, EventArgs e)
{
Hide();
dynamic unsafeCoefficientMatrix = Globals.ThisAddIn.Application.InputBox("Select coefficient matrix range", "Coefficient Matrix", Type: 8);
if (unsafeCoefficientMatrix is XL.Range)
{
CoefficientMatrix = unsafeCoefficientMatrix;
CoefficientMatrixDisplay.Text = CoefficientMatrix.Address[false, false];
}
Show();
}
public XL.Range AnswerVector { get; set; }
private void SelectAnswerVectorBotton_Click(object sender, EventArgs e)
{
Hide();
dynamic unsafeRHSVector = Globals.ThisAddIn.Application.InputBox("Select answer vector", "Answer vector", Type: 8);
if (unsafeRHSVector is XL.Range)
{
AnswerVector = unsafeRHSVector;
AnswerVectorDisplay.Text = AnswerVector.Address[false, false];
}
Show();
}
public XL.Range InverseCoefficientMatrix { get; set; }
private void SelectInverseCoefficientButton_Click(object sender, EventArgs e)
{
Hide();
dynamic unsafeInverceCoefficient = Globals.ThisAddIn.Application.InputBox("Select coefficient matrix", "Coefficient matrix", Type: 8);
if (unsafeInverceCoefficient is XL.Range)
{
InverseCoefficientMatrix = unsafeInverceCoefficient;
InverseCoefficientMatrixDisplay.Text = InverseCoefficientMatrix.Address[false, false];
}
Show();
}
public XL.Range SolutionVector { get; set; }
private void SelectSolutionButton_Click(object sender, EventArgs e)
{
Hide();
dynamic unsafeSolutionVector = Globals.ThisAddIn.Application.InputBox("Select solution vector", "Solution vector", Type: 8);
if (unsafeSolutionVector is XL.Range)
{
SolutionVector = unsafeSolutionVector;
SolutionVectorDisplay.Text = SolutionVector.Address[false, false];
}
Show();
}
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T01:08:06.573",
"Id": "209485",
"Score": "2",
"Tags": [
"c#",
"excel"
],
"Title": "VSTO add-in for Excel to solve systems of linear equations"
} | 209485 |
<p>I've spent the best part of a day on this question. It is marked as <em>Expert level</em>. There are about fifteen submission test cases and my solution manages to satisfy the first four. However, from there on in it hits timeouts due to performance issues.</p>
<p><a href="https://www.hackerrank.com/challenges/almost-equal-advanced/problem" rel="nofollow noreferrer">Hackerrank question</a></p>
<p>There doesn't seem to be much information or solutions for this question around, so I would appreciate if anyone had any suggestion on how I can improve the performance. Maybe I need to go back to the drawing board with my approach.</p>
<ul>
<li>N = number of elements in the array</li>
<li>K = The height difference allowed</li>
<li>H = Array of heights</li>
<li>queries = 2D array of ranges within which you must find the number of matching pairs (i.e. how many fighters in this range meet the height requirements to fight each other)</li>
</ul>
<p>My approach is to copy the subset (I know this is slow and would like to get around it somehow)and then run a quicksort over this new subset.</p>
<p>With this we can now quickly figure out what heights are within range of each other (i.e. if we get height = 1 and we know k = 2, then the maximum height he can fight against is going to be 3).</p>
<pre><code> static int[] solve(int n, int k, int[] h, int[][] queries) {
// N = no. heights
// K = Difference
// L & R = First and Last fighters
int[] results = new int[queries.length];
int count = 1;
int pairs = 0;
int l, r =0;
for(int j=0; j<queries.length; j++) {
l = queries[j][0];
r = queries[j][1];
int[] range = Arrays.copyOfRange(h, l, r+1);
int[] sortedSubset = sort(range);
for(int i=0; i<sortedSubset.length-1; i++) {
count = i+1;
while((count != sortedSubset.length) && sortedSubset[count] <= (sortedSubset[i]+k)) {
// While the current number is still in range of the number we are checking i.e. (number + k)
pairs++;
count++;
}
}
results[j] = pairs;
pairs = 0;
}
return results;
}
</code></pre>
<blockquote>
<p>A Sumo wrestling championship is scheduled to be held this winter
in the <em>HackerCity</em> where <em>N</em> wrestlers
from different parts of the world are going to participate.<br>
The rules state that two wrestlers can fight against each other
if and only if the difference in their height
is less than or equal to K, (i.e.)<br>
wrestler A and wrestler B can fight
if and only if |<em>height(A)-height(B)</em>|≤<em>K</em>. </p>
<p>Given an array <em>H[]</em>, where
<em>H[i]</em> represents the height of the <em>i</em><sup>th</sup>
fighter, for a given l, r where <code>0 <= l <= r < N</code>, can you count the
number of pairs of fighters between l and r (both inclusive) who
qualify to play a game?</p>
<p><strong>Input Format</strong><br>
The first line contains an integer <em>N</em> and <em>K</em> separated by
a single space representing the number of Sumo wrestlers who are going
to participate and the height difference <em>K</em>.<br>
The second line contains <em>N</em> integers separated by a single space,
representing their heights
<em>H[0] H[1] ... H[N - 1]</em>.<br>
The third line contains <em>Q</em>, the number of queries.
This is followed by <em>Q</em> lines each having two integers l and r
separated by a space. </p>
<p><strong>Output Format</strong><br>
For each query Q, output the corresponding value of
the number of pairs of fighters for whom the absolute difference of
height is not greater that K. </p>
<p><strong>Constraints</strong><br>
1 <= N <= 100000<br>
0 <= K <= 10<sup>9</sup><br>
0 <= H[i] <= 10<sup>9</sup><br>
1 <= Q <= 100000<br>
0 <= l <= r < N </p>
<p><strong>Sample Input</strong></p>
<pre><code>5 2
1 3 4 3 0
3
0 1
1 3
0 4
</code></pre>
<p><strong>Sample Output</strong></p>
<pre><code>1
3
6
</code></pre>
<p><strong>Explanation</strong><br>
Query #0: Between 0 and 1 we have i,j as (0,1) and
|H[0]-H[1]|=2 therefore output is 1.<br>
Query #1: The pairs (H[1],H[2]) (H[1],H[3])
and (H[2],H[3]) are the pairs such that |H[i]-H[j]| <=2.
Hence output is 3.<br>
Query #2: Apart from those in Query #1, we have
(H[0],H[1]), (H[0], H[3]), (H[0], H[4]), hence 6. </p>
<p><strong>Timelimits</strong> </p>
<p>Timelimits are given <a href="https://hr-assets.s3.amazonaws.com/7bb46cae_challenge_assets/checker_limits/1361/limits.json" rel="nofollow noreferrer">here</a></p>
</blockquote>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T09:50:39.790",
"Id": "404934",
"Score": "1",
"body": "In any programming challenge, if you get time limit exceeded then it's back to the drawing board as that means you have the wrong time complexity. Unless you've REALLY messed up the implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T17:21:58.467",
"Id": "405009",
"Score": "2",
"body": "Please reproduce the problem formulation in whole in your question, links rot and you cannot view that page without being registered on HR."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T17:58:33.893",
"Id": "405015",
"Score": "0",
"body": "Where is `sort()` defined?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T13:17:59.007",
"Id": "405139",
"Score": "0",
"body": "It's just a quicksort method to arrange the number."
}
] | [
{
"body": "<p>I suggest you do the following:</p>\n\n<ol>\n<li>Sort the entire heights array once.</li>\n<li>Finds all the matching pairs for the full array (i.e. <code>l=0; r=h.length-1;</code>).</li>\n<li>For each matching pair you find, loop over the <code>queries</code> array, and add it to the counts of all the subsets that contain both fighters. For example, if the pair <code>h[2]</code>,<code>h[5]</code> is matching, increment <code>results[j]</code> for all <code>j</code> such that <code>queries[j][0] <=2</code> and <code>5 <= queries[j][1]</code>.</li>\n</ol>\n\n<p>I believe running a single sort instead of <code>queries.length</code> sorts will improve the performance.</p>\n\n<p>The only downside of this algorithm is that if all the queries cover a small subset of the full heights array, the algorithm will do a lot of unnecessary work (finding matching pairs for indices that we'll never need to count).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T14:28:36.497",
"Id": "404961",
"Score": "0",
"body": "If you sort the entire array initially, wont you lose the ability to check between certain ranges? You have re-arranged the entire array and so when you read in the left and right values for the subset you are to check, they correspond to the old unsorted array and not the sorted one?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T14:51:57.507",
"Id": "404968",
"Score": "0",
"body": "@Mark I guess my solution is not complete. You'll have to create a Map of the heights to their original indices"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T15:07:53.767",
"Id": "404977",
"Score": "0",
"body": "I will give it a try later, I'm not sure it will be an improvment though. For example, if the array of height's is >100,000 and you have only 1 query of indices {2, 6}. You do a lot of unnecessary work, its a tricky question."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T03:02:04.657",
"Id": "209490",
"ParentId": "209489",
"Score": "1"
}
},
{
"body": "<blockquote>\n <blockquote>\n <p><strong>Constraints</strong><br>\n 1 <= N <= 100000<br>\n 0 <= K <= 10<sup>9</sup><br>\n 0 <= H[i] <= 10<sup>9</sup><br>\n 1 <= Q <= 100000<br>\n 0 <= l <= r < N</p>\n </blockquote>\n</blockquote>\n\n<p>My rule of thumb for this kind of challenge is that 10<sup>9</sup> operations is a limit. So, ignoring the hidden constant of Landau notation, we're looking at something which is <span class=\"math-container\">\\$O(N\\sqrt N + Q\\sqrt Q + Q\\sqrt{N} + K)\\$</span>. In particular, each query shouldn't take more than <span class=\"math-container\">\\$\\sqrt N\\$</span> time. That would seem to push us towards a preprocessing step which is <span class=\"math-container\">\\$O(N\\sqrt N + K)\\$</span> and which allows us to process individual queries fast. Alternatively, we might have a preprocessing step which takes into account the queries, but that's likely to be more complicated.</p>\n\n<p>Since your approach takes (in the worst case) <span class=\"math-container\">\\$O(QN\\lg N)\\$</span> time, it's definitely nowhere near complying with my rule of thumb.</p>\n\n<hr>\n\n<p>If we consider first the idea of a preprocessing step which takes into account the queries, it's quite easy to construct a really nasty case where we have boundaries between every consecutive pair of wrestlers, and each one contributes to multiple queries. E.g. take the following 100000 queries:</p>\n\n<pre><code>(0, 99999), (1, 99998), (2, 99997), ..., (49999,50000),\n(0, 49999), (1, 50000), (2, 50001), ..., (49999, 99998)\n</code></pre>\n\n<p>I don't find that approach promising.</p>\n\n<hr>\n\n<p>Ideas which might be more promising are bucketing the wrestlers in buckets of width <span class=\"math-container\">\\$K\\$</span>, so that each wrestler can only interact with those in the same bucket and some of those in the adjacent buckets - although the \"some of\" is a problem; and inclusion-exclusion, although I can't quite get that to work. It's \"fast enough\" to precompute tables <span class=\"math-container\">\\$C[a]\\$</span> which is the number of valid fights between <span class=\"math-container\">\\$i \\le a < j\\$</span>; <span class=\"math-container\">\\$L[a]\\$</span> which is the number of valid fights between <span class=\"math-container\">\\$i < j \\le a\\$</span>; and <span class=\"math-container\">\\$R[a]\\$</span> which is the number of valid fights between <span class=\"math-container\">\\$a \\le i < j\\$</span>. But the closest I can get to the number of valid fights between <span class=\"math-container\">\\$l \\le i < j \\le r\\$</span> is the difference of that with the number of valid fights between <span class=\"math-container\">\\$i \\le l\\$</span> and <span class=\"math-container\">\\$j \\ge r\\$</span>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-19T16:50:55.820",
"Id": "440051",
"Score": "0",
"body": "What about having 2 lanes of buckets; one with a phase of K/2 over the other. Each wrestler is in 2 buckets. Is this an idea to work with or am I completely missing the point here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-19T18:25:29.480",
"Id": "440066",
"Score": "0",
"body": "@dfhwze, another, similar, idea I'm tossing around is building a quad tree in each bucket."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-19T18:26:57.640",
"Id": "440067",
"Score": "0",
"body": "I give you 200 rep if you solve this using Dancing Links :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T11:36:28.687",
"Id": "463840",
"Score": "0",
"body": "I'd bet, some sort of a single quad tree (with height and index as the directions) is the way to go. You stop when 1. the node is fully out of range [l, r], or 2. the node is fully in-range and all its fighters are compatible with each other. Unfortunately, a quad tree splitting on the height (ranging up to 1e9) and index (ranging up to 1e5) makes little sense, so I'm viewing it as a binary tree splitting on either height or index as needed. I'd build it up dynamically, hoping that I get efficient splitting....."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-19T16:37:29.350",
"Id": "226438",
"ParentId": "209489",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T02:23:46.420",
"Id": "209489",
"Score": "5",
"Tags": [
"java",
"algorithm",
"sorting",
"time-limit-exceeded"
],
"Title": "Hackerrank \"Almost Equal\" solution"
} | 209489 |
<p><strong>Background</strong></p>
<p>I wrote <code>my_length</code> class and some code. <code>my_length</code> can be stringified using <code><<</code> operator, and <code>main()</code> tests this.</p>
<p><strong>Questions</strong></p>
<ol>
<li>I think <code>operator<<</code> can be refactored. How can I rewrite <code>operator<<</code> of <code>my_length</code>, and make it better code?</li>
<li>How can I make rest of code better?</li>
</ol>
<p><strong>Code</strong></p>
<pre><code>#include <vector>
#include <string>
#include <cstdint>
#include <iostream>
class my_length {
int id;
std::string name;
uint64_t v; // unit is 'mm'
bool fmt_auto;
public:
my_length (int id, std::string name, uint64_t v)
: id{id}, name{name}, v{v}, fmt_auto(false) {}
friend std::ostream &operator<<(std::ostream &out, const my_length &l) {
out << l.id << "/" << l.name << " : ";
if (!l.fmt_auto) {
return out << l.v << "mm";
} else {
if (l.v<10)
return out << l.v << "mm";
else if (l.v<1000)
return out << double(l.v)/10 << "cm";
else if (l.v<1000000)
return out << double(l.v)/1000 << "m";
else
return out << double(l.v)/1000000 << "km";
}
}
void set_fmt_auto(bool b) {fmt_auto = b;}
};
bool need_fmt_auto(int x) {
return (x%2) != 0;
}
int main() {
std::vector<my_length> lengths;
my_length l{0, "a", 1};
lengths.push_back(l);
uint64_t val = 17;
for (int i=1; i<10; i++) {
my_length l{i, std::string(1, 'a'+i), val};
lengths.push_back(l);
val *= 10;
}
for (int i=0; i<lengths.size(); i++) {
if (need_fmt_auto(i)) {
lengths[i].set_fmt_auto(true);
std::cout << "fmt_auto: ";
}
std::cout << lengths[i] << "\n";
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T07:06:50.707",
"Id": "404914",
"Score": "0",
"body": "What's the purpose of this class? Once it's initialized you can't even access `v`, just switch `fmt_auto`. In which context would one want to create an instance? Why not just use a function `std::string length_with_unit(uint64_t v, bool fmt_auto=false)` or something similar?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T08:13:43.757",
"Id": "404922",
"Score": "0",
"body": "I updated my code to clarify the purpose of `my_length`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T08:20:03.933",
"Id": "404923",
"Score": "0",
"body": "@Yurim Maybe `std::string length_with_unit()` is a good choice. But I think this function can be used only with `my_length`. And << operator does not create string instance unlike `length_with_unit()`, so it makes little advantage on performance. Because of this two reasons, I write this as << operator."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T08:33:37.803",
"Id": "404924",
"Score": "2",
"body": "I still fail to imagine a use case where I would want to create an instance of `my_length` because all I can do with it is to write it to an `std::ostream`. Why would I want to write `my_length l(42,name,567); l.set_fmt_auto(true); std::cout << l;` instead of std::cout << length_with_unit(42, name, 567, true);` or even `std::cout << 42 << '/' << name << \" : \" << length_with_unit(567, true);`? What's your high-level motivation to write this class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T08:09:33.147",
"Id": "405088",
"Score": "0",
"body": "@Yurim It is just a toy program. I wrote this code to study c++. I just wondered \"my << operator is good enough\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T12:33:00.653",
"Id": "405129",
"Score": "0",
"body": "The lack of whitespace is a major concern here. As a bare minimum, use a blank line between different function definitions."
}
] | [
{
"body": "<p>I see a number of things that may help you improve your program.</p>\n\n<h2>Gather constants together</h2>\n\n<p>The relationship among the numerical values that determine which unit is used and the divisor and the actual unit name is contained within a single function, which is good, but it could be more clear if expressed as a structure. For example, one could use this:</p>\n\n<pre><code>struct Units {\n int limit;\n double divisor;\n std::string name;\n};\nstatic const std::array<Units,4> units; \n</code></pre>\n\n<p>Then outside of the class, we supply the values:</p>\n\n<pre><code>const std::array<my_length::Units,4> my_length::units = {{\n { 10, 1, \"mm\" },\n { 1000, 10, \"cm\" },\n { 1000000, 1000, \"m\" },\n { 0, 1000000, \"km\" },\n}};\n</code></pre>\n\n<p>This brings things into much closer proximity so that it can be more easily seen and understood. We can do a little better with C++17 by using <code>std::string_view</code> instead of <code>std::string</code> for the unit name.</p>\n\n<h2>Isolate concerns</h2>\n\n<p>It's usually better to have each function just do one thing. So insted of deciding on units and <em>also</em> printing, I'd suggest splitting those into two, using a private member function:</p>\n\n<pre><code>const Units& selectUnit() const {\n auto ret{units.cbegin()};\n if (fmt_auto) {\n while (ret->limit && v >= ret->limit) {\n ++ret; \n }\n }\n return *ret;\n}\n</code></pre>\n\n<p>Now the <code>operator<<</code> looks like this:</p>\n\n<pre><code>friend std::ostream &operator<<(std::ostream &out, const my_length &l) {\n const Units u{l.selectUnit()};\n return out << l.id << \"/\" << l.name << \" : \" \n << l.v/u.divisor << u.name;\n}\n</code></pre>\n\n<h2>Use standard algorithms</h2>\n\n<p>The test code starts with this:</p>\n\n<pre><code>std::vector<my_length> lengths;\nmy_length l{0, \"a\", 1};\nlengths.push_back(l);\nuint64_t val = 17;\nfor (int i=1; i<10; i++) {\n my_length l{i, std::string(1, 'a'+i), val};\n lengths.push_back(l);\n val *= 10;\n}\n</code></pre>\n\n<p>I'd suggest that one could use <a href=\"https://en.cppreference.com/w/cpp/algorithm/iota\" rel=\"nofollow noreferrer\"><code>std::iota</code></a> instead. I'll leave it to you to create the details of that.</p>\n\n<h2>Reconsider the design</h2>\n\n<p>Once constructed, there is no capability to do anything with the <code>my_length</code> object except to print it. If all that's needed is printing, then it may be better to use a freestanding function in a namespace instead of an object, as suggested in the comments. If not, then it makes sense to provide those other operations within the class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T20:24:55.600",
"Id": "405183",
"Score": "0",
"body": "You beat me to the punch on that one. The only difference I would have made is rather than the units be decided by the class get the user to define the units by allowing a manipulator that is applied first."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T00:31:13.857",
"Id": "405205",
"Score": "0",
"body": "You are right; that would be an improvement."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T12:30:21.260",
"Id": "209611",
"ParentId": "209496",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "209611",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T05:12:03.607",
"Id": "209496",
"Score": "3",
"Tags": [
"c++",
"beginner",
"unit-testing",
"formatting",
"io"
],
"Title": "Simple stringifying using << operator"
} | 209496 |
<p>Very amateur programmer and first-time poster here.</p>
<p>The program I wrote asks the user for a prime number, a lower and upper bound, and a degree (all of these are integers). I want to generate a list of polynomials, represented by its coefficients (see example). Each polynomial <span class="math-container">\$P(x)\$</span> satisfies the following conditions:</p>
<ol>
<li><p><span class="math-container">\$P(x) + p\$</span> is prime for <span class="math-container">\$1 \le x \le p - 2\$</span> (where <span class="math-container">\$x\$</span> is an integer), and <span class="math-container">\$P(0) = 0\$</span>. </p></li>
<li><p>Each coefficient is an integer and is confined by the user's bounds inclusively (i.e., the coefficient may equal a bound but may not be less/greater than it).</p></li>
<li><p>The highest degree a polynomial can have is the user's given degree. (The user may choose to include just polynomials with this degree or polynomials with lower degrees in the final list).</p></li>
</ol>
<p>The program then finds each polynomial with these conditions and prints a list of primes that it generates.</p>
<p>Example:</p>
<pre class="lang-none prettyprint-override"><code>Enter the prime number you want to find a poly for: 11
Enter the lower bound: -3
Enter the higher bound: 3
Enter the degree of the polynomial: 3
Press n if you do not want to include lower degree polynomials: n
possible combos (including constant func):
215
################################################
poly generating finished
[[11, -2, 0, 2]]
List of primes that [11, -2, 0, 2] generates:
[11, 11, 23, 59, 131, 251, 431, 683, 1019, 1451]
There are 1 good polynomials for 11 with bounds -3 to 3 inclusive up to degree 3
</code></pre>
<p>Here, <span class="math-container">\$[11, -2, 0, 2]\$</span> represents <span class="math-container">\$p=11\$</span> with the polynomial <span class="math-container">\$- 2x + 2x^3\$</span>.</p>
<p>The general idea is that we start with a polynomial where every coefficient is the lower bound, check if the polynomial is a "good" or "prime" polynomial (satisfies the first condition), and add it to the list of prime polynomials if it is. Repeat with the next polynomial (list of numbers) until every combination has been exhausted.</p>
<pre><code>from math import sqrt; from itertools import count, islice
import itertools
from itertools import product
#is n prime?
def isPrime(n):
#https://stackoverflow.com/questions/4114167/checking-if-a-number-is-a-prime-number-in-python
return n > 1 and all(n%i for i in islice(count(2), int(sqrt(n)-1)))
#find P(x) using the polyList to represent the polynomial
def findSingleValue(polyList, x):
#https://stackoverflow.com/questions/18093509/how-can-i-create-functions-that-handle-polynomials
return sum((a*x**i for i,a in enumerate(polyList)))
#is the polynomial prime for x <= p - 1?
def isPolyPrime(polyList, prime):
#polyValue = 0
for x in range(prime - 1):
polyValue = sum((a*x**i for i,a in enumerate(polyList)))
if not isPrime(polyValue):
return False
return True
#generate the next combo, given the previous combo
def genCombo(combo, LB, HB):
deg = len(combo)
combo = list(combo)
index = deg - 1
while index >= 0:
if combo[index] < HB:
combo[index] += 1
index = -1
elif combo[index] == HB:
combo[index] = LB
index -= 1
combo = tuple(combo)
return combo
#main function
def verifyPrime():
prime = int(input("Enter the prime number you want to find a poly for: "))
LB = int(input("Enter the lower bound: "))
HB = int(input("Enter the higher bound: "))
deg = int(input("Enter the degree of the polynomial: "))
lowDegPoly= input("Press n if you do not want to include lower degree polynomials: ")
allCombosNum = (abs(HB - LB))**deg - 1
#creates list of all possible tuples that represent a poly
print("possible combos (including constant func): ")
print(allCombosNum)
goodPolyList = []
combo = ()
#create the first combo - this is used as the basis to generate more combos
for x in range(deg):
combo += (LB,)
for x in range(allCombosNum):
polyList = []
polyList.append(prime)
for coef in combo:
polyList.append(coef)
#now has a list of the prime and coefs; p + a1*x + a2*x^2 + ...
isGoodPoly = isPolyPrime(polyList, prime)
if isGoodPoly and not(lowDegPoly == "n" and combo[deg - 1] == 0):
goodPolyList.append(polyList)
#personal usage: keeps track of how many more combos it needs to go through
numLeft = allCombosNum - x
if (numLeft % 100000) == 0:
print(numLeft)
#create the next combo
combo = genCombo(combo, LB, HB)
print("################################################")
print("poly generating finished")
print()
print(goodPolyList)
#bonus stuff
#goes over items in the goodPolyList and shows what primes each generates
for item in goodPolyList:
primeList = []
for x in range(prime - 1):
primeList.append(findSingleValue(item, x))
print()
print("List of primes that" , item, "generates: ")
print(primeList)
print()
print("There are" , len(goodPolyList) , "good polynomials for", prime ,
"with bounds" , LB , " to" , HB, "inclusive up to degree" , deg)
verifyPrime()
verifyPrime()
</code></pre>
<p>(As you see I've used a couple snippets of code from stackoverflow. Admittedly this is for simplicity's sake as I don't quite understand them.)</p>
<p>I am mostly concerned with speed since I intend to go through a very high amount of polynomials. However, since I am still very new at this, any feedback is appreciated, particularly in keeping code clean, comments/variable names -- basic stuff (but again, any feedback is fine). If it matters, this code will be for my personal use and not for any school assignment/project.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T14:46:33.097",
"Id": "404965",
"Score": "0",
"body": "How does P(x) = 11 - 2x + 2x^3 satisfy the P(0) = 0 requirement?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T22:42:32.363",
"Id": "405063",
"Score": "0",
"body": "Sorry, I suppose I wasn't very clear on that. -2x + 2x^3 is P(x) and 11 is the prime p."
}
] | [
{
"body": "<p>Firstly, on documentation: the standard term for the object you're searching for is <a href=\"http://mathworld.wolfram.com/Prime-GeneratingPolynomial.html\" rel=\"noreferrer\">prime-generating polynomial</a>. \"Prime polynomial\" is often used as a synonym for \"irreducible polynomial\", and while there is a relationship between reducibility and generation of primes it's best to use standard terms in documentation where possible.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>from math import sqrt; from itertools import count, islice\nimport itertools\nfrom itertools import product\n</code></pre>\n</blockquote>\n\n<p>This looks a bit untidy. It's not very Pythonic to put multiple statements on a line separated by <code>;</code>. The <code>import itertools</code> is unnecessary, because you explicitly import all of the itertools methods that you use. The two <code>from itertools import</code> statements can be combined into one.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>#is n prime?\ndef isPrime(n):\n #https://stackoverflow.com/questions/4114167/checking-if-a-number-is-a-prime-number-in-python\n return n > 1 and all(n%i for i in islice(count(2), int(sqrt(n)-1)))\n</code></pre>\n</blockquote>\n\n<p>This is a reasonable way to check a single number for primality if the number isn't too large, but since you're checking lots of numbers and you mention this as a performance concern, I would suggest that you think about building a sieve of Eratosphenes for smallish numbers (up to say 10 million or 100 million) and using probabilistic primality testing for numbers larger than that. Perhaps <a href=\"https://en.wikipedia.org/wiki/Baillie%E2%80%93PSW_primality_test\" rel=\"noreferrer\">BPSW</a>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>#find P(x) using the polyList to represent the polynomial\ndef findSingleValue(polyList, x):\n\n #https://stackoverflow.com/questions/18093509/how-can-i-create-functions-that-handle-polynomials\n return sum((a*x**i for i,a in enumerate(polyList)))\n</code></pre>\n</blockquote>\n\n<p>The name suggests a search, but it's actually an evaluation. I'd call it something like <code>evalPoly(coeffs, x)</code>. The evaluation can be made more efficient using <a href=\"https://en.wikipedia.org/wiki/Horner%27s_method\" rel=\"noreferrer\">Horner's method</a>, which can be written as a <code>reduce</code> call.</p>\n\n<p>It would be worth adding a docstring to document the order of the coefficients: constant term first (<code>a_0, ..., a_n</code>) or last (<code>a_n, ..., a_0</code>).</p>\n\n<hr>\n\n<blockquote>\n<pre><code>#is the polynomial prime for x <= p - 1?\ndef isPolyPrime(polyList, prime):\n #polyValue = 0\n for x in range(prime - 1):\n polyValue = sum((a*x**i for i,a in enumerate(polyList)))\n</code></pre>\n</blockquote>\n\n<p>Why is this duplicating the contents of <code>findSingleValue</code> rather than calling it?</p>\n\n<blockquote>\n<pre><code> if not isPrime(polyValue):\n return False\n\n return True\n</code></pre>\n</blockquote>\n\n<p>Why not use <code>all(...)</code>?</p>\n\n<hr>\n\n<blockquote>\n<pre><code>#generate the next combo, given the previous combo\ndef genCombo(combo, LB, HB):\n deg = len(combo)\n combo = list(combo)\n index = deg - 1\n while index >= 0:\n if combo[index] < HB:\n combo[index] += 1\n index = -1\n elif combo[index] == HB:\n combo[index] = LB\n index -= 1\n combo = tuple(combo)\n return combo\n</code></pre>\n</blockquote>\n\n<p>I'd half expect <code>permtools</code> to have a built-in method for this. Alternatively it can be done with (untested code) <code>itertools.product(range(LB, HB+1), deg)</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>#main function\ndef verifyPrime():\n\n prime = int(input(\"Enter the prime number you want to find a poly for: \"))\n LB = int(input(\"Enter the lower bound: \"))\n HB = int(input(\"Enter the higher bound: \"))\n deg = int(input(\"Enter the degree of the polynomial: \"))\n lowDegPoly= input(\"Press n if you do not want to include lower degree polynomials: \")\n</code></pre>\n</blockquote>\n\n<p>This could use a refactor: one method to do the work, and then the main method just does the I/O.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> allCombosNum = (abs(HB - LB))**deg - 1\n</code></pre>\n</blockquote>\n\n<p>I think this has an out-by-one error.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> combo = ()\n\n #create the first combo - this is used as the basis to generate more combos\n for x in range(deg):\n combo += (LB,)\n</code></pre>\n</blockquote>\n\n<p>My suggestion above would make this unnecessary, but... <code>tuple(repeat(LB, deg))</code>?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> polyList = []\n polyList.append(prime)\n for coef in combo:\n polyList.append(coef)\n</code></pre>\n</blockquote>\n\n<p>I think this is <code>polyList = [prime] + list(combo)</code></p>\n\n<hr>\n\n<blockquote>\n<pre><code> #now has a list of the prime and coefs; p + a1*x + a2*x^2 + ...\n isGoodPoly = isPolyPrime(polyList, prime)\n if isGoodPoly and not(lowDegPoly == \"n\" and combo[deg - 1] == 0):\n goodPolyList.append(polyList)\n</code></pre>\n</blockquote>\n\n<p>There's a potential performance improvement here. If <code>lowDegPoly == \"n\"</code> then it's more efficient to avoid generating and testing polynomials of lower degree.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> primeList = []\n for x in range(prime - 1):\n primeList.append(findSingleValue(item, x))\n</code></pre>\n</blockquote>\n\n<p><code>primeList = [findSingleValue(item, x) for x in range(prime - 1)]</code></p>\n\n<hr>\n\n<blockquote>\n<pre><code> verifyPrime()\n\nverifyPrime()\n</code></pre>\n</blockquote>\n\n<p>That recursive call is rather inelegant, and the direct invocation of the main method is not considered best practice. It would be better to replace these lines with</p>\n\n<pre><code>if __name__ == \"__main__\":\n while True:\n verifyPrime()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T09:07:50.593",
"Id": "209506",
"ParentId": "209498",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "209506",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T06:28:27.533",
"Id": "209498",
"Score": "8",
"Tags": [
"python",
"beginner",
"time-limit-exceeded",
"primes",
"mathematics"
],
"Title": "Find \"prime polynomials\" for a user's given prime, bounds, and degree"
} | 209498 |
<p>This is a Bash script that copies files stored inside disk images to a directory, using a defined structure provided via a JSON file. I've included the external programs it requires and the test I used so that you can test it too.</p>
<p>Any comments regarding programming style and improvements are welcome.</p>
<hr>
<h1>Overview</h1>
<p>The following is a Bash shell script that copies files stored inside disk images into a directory in the filesystem.</p>
<p>The script takes two parameters:</p>
<ul>
<li>The first one is optional and defines a root directory (existing or not) that will contain the files being copied.</li>
<li>The second one, optional when the first one is given, is a path to a valid JSON-formatted file that describes:
<ol>
<li>which disk images will be opened,</li>
<li>which files inside each disk image will be copied, and</li>
<li>which path inside the directory root will be used as the destination for the files being copied.</li>
</ol></li>
</ul>
<p>The first parameter defaults to the current directory when not given. The second one defaults to a file named <code>steps.json</code> located at the current directory. If the first parameter is not given, the second one can't be either.</p>
<h1>Prerequisites</h1>
<p>This script requires the following external programs to work correctly (installation instructions for Ubuntu are between parentheses):</p>
<ul>
<li>The JSON parsing program <code>jq</code> (<code>sudo apt install jq</code>).</li>
<li>The disk image manipulation utility <code>udisksctl</code> (<code>sudo apt install udisks2</code>)</li>
</ul>
<h1>Script</h1>
<p>The complete script is below. It's name is <strong>imgdisk-copy.sh</strong> and should be marked as executable. It can be in any directory where it can be executed. For the purpose of the test below, it is placed in a directory where it can read and write.</p>
<pre><code>#!/bin/bash
# Copying files contained inside disk images via JSON recipe.
# logo_writer
# December 12th, 2018
# Is a string contained in another? Return 0 if so; 1 if not.
# By fjarlq, from https://stackoverflow.com/a/8811800/5397930
contains() {
string="$1"
substring="$2"
if test "${string#*$substring}" != "$string"; then
return 0
else
return 1
fi
}
# Obtain the absolute path of a given directory.
# By dogbane, from https://stackoverflow.com/a/3915420
abspath() {
dir="$1"
echo "$(cd "$(dirname "$dir")"; pwd -P)/$(basename "$dir")"
}
# The main script starts here.
# If no first parameter is given, assume current directory.
if [ -z "$1" ]; then
DESTROOT="."
else
# Omit any trailing slash
DESTROOT=$(abspath "${1%/}")
fi
# If no second parameter is given, assume file "steps.json".
# If no first parameter is given, this can't be either.
if [ -z "$2" ]; then
CONF="./steps.json"
else
CONF="$2"
fi
# Create the root directory where the files will the put.
mkdir -p "$DESTROOT"
# How many disks will be processed?
LIMIT=$(cat "$CONF" | jq -r length)
i=0
while [ "$i" -lt "$LIMIT" ]; do
# For each disk, get its file name.
DISK=$(cat "$CONF" | jq -r .["$i"].disk)
echo "$DISK"
# Setup a loop device for the disk and get its name.
RES=$(udisksctl loop-setup -f "$DISK")
LOOP=$(echo "$RES" | cut -f5 -d' ' | head -c -2)
# Using the loop device obtained, mount the disk.
# Obtain the mount root directory afterwards.
RES=$(udisksctl mount -b "$LOOP")
SRCDIR=$(echo "$RES" | sed -nE 's|.*at (.*)\.|\1|p')
# How many file sets will be copied?
NOITEMS=$(cat "$CONF" | jq -r ".["$i"].files | length")
j=0
while [ "$j" -lt "$NOITEMS" ]; do
# For each file set, obtain which files will be copied and where.
FSRC=$(cat "$CONF" | jq -r .["$i"].files["$j"].src)
FDEST=$(cat "$CONF" | jq -r .["$i"].files["$j"].dest)
# Make the destination directory.
mkdir -p "$DESTROOT"/"$FDEST"
echo " ""$FSRC"
if contains "$FSRC" "\*"; then
# If a wildcard is used in the file set, copy by file expansion (option -t).
pushd "$SRCDIR" > /dev/null
cp -t "$DESTROOT"/"$FDEST" $FSRC
popd > /dev/null
else
# Else, copy normally.
cp "$SRCDIR"/"$FSRC" "$DESTROOT"/"$FDEST"
fi
j=$(($j + 1))
done
# Once all the file sets are copied, unmount the disk
# and delete its associated loop device.
udisksctl unmount -b "$LOOP" > /dev/null
udisksctl loop-delete -b "$LOOP"
i=$(($i + 1))
done
</code></pre>
<h1>Test set</h1>
<p>This script was tested with the following disk set: <a href="https://winworldpc.com/download/1ce2809c-2b4c-e280-9804-11c3a6e28094" rel="nofollow noreferrer">Microsoft C Compiler 4.0</a>. The first 3 <code>.img</code> disks inside the ZIP (<code>disk01.img</code>, <code>disk02.img</code> and <code>disk03.img</code>) should be placed in the same directory the script is.</p>
<p>The corresponding JSON recipe used for the test is below. It's named <strong>steps.json</strong> and placed in the same directory the script is for convenience.</p>
<pre><code>[
{
"disk": "disk01.img",
"files": [
{
"src": "*",
"dest": "bin"
}
]
},
{
"disk": "disk02.img",
"files": [
{
"src": "*.EXE",
"dest": "bin"
}
]
},
{
"disk": "disk03.img",
"files": [
{
"src": "LINK.EXE",
"dest": "bin"
},
{
"src": "*.H",
"dest": "include"
},
{
"src": "SYS/*.H",
"dest": "include/sys"
},
{
"src": "SLIBC.LIB",
"dest": "lib"
},
{
"src": "SLIBFP.LIB",
"dest": "lib"
},
{
"src": "EM.LIB",
"dest": "lib"
},
{
"src": "LIBH.LIB",
"dest": "lib"
}
]
}
]
</code></pre>
<p>The test is performed by opening a terminal and executing the following command:</p>
<p><code>./imgdisk-copy.sh testing/</code></p>
<p>The command will output each disk image name as it is mounted, and under it the names of the files being copied (unexpanded), as follows:</p>
<pre><code>disk01.img
*
disk02.img
*.EXE
disk03.img
LINK.EXE
*.H
SYS/*.H
SLIBC.LIB
SLIBFP.LIB
EM.LIB
LIBH.LIB
</code></pre>
<p>The result will be a directory <code>testing</code> under where the script is with the following structure:</p>
<pre><code>testing/
├── bin
│ ├── C1.EXE
│ ├── C2.EXE
│ ├── C3.EXE
│ ├── CL.EXE
│ ├── CV.EXE
│ ├── EXEMOD.EXE
│ ├── EXEPACK.EXE
│ ├── LIB.EXE
│ ├── LINK.EXE
│ ├── MAKE.EXE
│ ├── MSC.EXE
│ └── SETENV.EXE
├── include
│ ├── sys
│ │ ├── LOCKING.H
│ │ ├── STAT.H
│ │ ├── TIMEB.H
│ │ ├── TYPES.H
│ │ └── UTIME.H
│ ├── ASSERT.H
│ ├── CONIO.H
│ ├── CTYPE.H
│ ├── DIRECT.H
│ ├── DOS.H
│ ├── ERRNO.H
│ ├── FCNTL.H
│ ├── FLOAT.H
│ ├── IO.H
│ ├── LIMITS.H
│ ├── MALLOC.H
│ ├── MATH.H
│ ├── MEMORY.H
│ ├── PROCESS.H
│ ├── SEARCH.H
│ ├── SETJMP.H
│ ├── SHARE.H
│ ├── SIGNAL.H
│ ├── STDARG.H
│ ├── STDDEF.H
│ ├── STDIO.H
│ ├── STDLIB.H
│ ├── STRING.H
│ ├── TIME.H
│ ├── V2TOV3.H
│ └── VARARGS.H
└── lib
├── EM.LIB
├── LIBH.LIB
├── SLIBC.LIB
└── SLIBFP.LIB
</code></pre>
| [] | [
{
"body": "<p>Instead of <code>cat \"$x\" | command</code> or <code>echo \"$x\" | command</code>, use <code>command <$x</code> (vs cat) or <code>command <<<$x</code> (vs echo): it saves a fork and removes the need to quote.</p>\n\n<p>Instead of <code>if [ x -lt y ]</code> use <code>if [[ x -lt y ]]</code>: it saves a fork (<code>[[</code> is a bash builtin; <code>help test</code> for details) and adds some functionality.</p>\n\n<p>Functions return their last exit value already so <code>contains()</code> can be shortened to <code>contains() { test \"${1#*$2}\" != \"$1\"; }</code> Whether you prefer this is up to you.</p>\n\n<p>Use bash defaulting mechanism instead of <code>if [[ -z</code>, as in <code>CONF=${2:-./steps.json}</code></p>\n\n<p>Use <code>for ((i=0; i<$LIMIT; i++))</code> instead of <code>i=0; while ...</code></p>\n\n<p>Test the exit values of things that shouldn't fail, as in <code>mkdir -p \"$DESTROOT\" || exit 1</code>. <strong>Any invocation of <code>cd</code> or <code>pushd</code> should be checked for success, always!</strong> A general purpose <code>DIE()</code> function can replace the naked exit and take an error message as an argument. If nothing should fail, <code>set -e</code> or <code>trap DIE ERR</code> (the first argument is a function name) does this globally.</p>\n\n<p>Constructions like <code>jq -r \".[\"$i\"].files | length\")</code> and <code>echo \" \"\"$FSRC\"</code> are kind of weird and the inner double quotes probably should be removed.</p>\n\n<p>In a language where every variable is a global, it's a good habit to use fewer variables. For example, <code>RES=$(foo); LOOP=$( echo \"$RES\" | ...)</code> can just be <code>LOOP=$( foo | ...)</code></p>\n\n<p>Your get-conf pattern should be in a function like <code>get_conf() { jq -r $1<<<$CONF; }</code></p>\n\n<p>Pruning code paths is important in an interpreted language. Since the wildcard copy method works for regular copies too, just use that one unconditionally and remove <code>if contains ... \"\\*\"</code></p>\n\n<p>You don't need to escape wildcards like <code>*</code> in double quotes. When in doubt about what will be interpolated, use single quotes. Quoting in bash can be very complex and take a long time to learn; an advanced understanding of it will help to avoid common bugs.</p>\n\n<p>Since you are using commands that aren't standard, it's a good idea to set PATH in the script, or as an optional config directive, and to check that they're there before you begin, as in <code>require() { for cmd in \"$@\"; do type $cmd >/dev/null || exit 1; done; }</code> followed by <code>require jq udisksctl</code></p>\n\n<p>Read CONF just once, into a variable: <code>conf=$(<$CONF)</code>, and query that. Then you can edit the config while the script runs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T00:46:49.950",
"Id": "406462",
"Score": "1",
"body": "Thank you! I'll check all the suggestions and improve my code. Great answer!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T09:04:06.323",
"Id": "210264",
"ParentId": "209507",
"Score": "3"
}
},
{
"body": "<p>The other answer gave some really good advice; this is intended as a complementary answer with still more things to think about.</p>\n\n<h2>Put default arguments at the top of the script</h2>\n\n<p>If someone wanted to change the default arguments, they'd have to hunt through the code to find them. I typically prefer to put them at the top of the script and then only overwrite them if command line arguments are passed. For example:</p>\n\n<pre><code>#!/bin/bash\n\n# default arguments\nTARGET=./target \nJSON=steps.json\n\n# Command line args are both optional: TARGET JSON\nif [[ -z \"$1\" ]] ; then\n TARGET=\"$1\"\nfi\nif [[ -z \"$2\" ]] ; then\n JSON=\"$2\"\nfi\n</code></pre>\n\n<h2>Use <code>install</code> to copy files</h2>\n\n<p>DOS archives may or may not have proper permissions bits set and may need to have a complex path created before copying the file. We can manage all of this easily with <code>install</code> which is also a basic part of every Linux installation:</p>\n\n<pre><code>echo \"installing $src on $disk to $dst\"\ninstall -p --mode=664 -D \"$TMPDIR\"/$src -t \"$TARGET\"/$dst/\n</code></pre>\n\n<p>With the <code>-p</code> argument we preserve the original timestamp. The <code>mode</code> argument explictly sets the mode for each file (you could, of course change this to something else if you cared to). The combination of <code>-D</code> and <code>-t</code> tells install to create the destination directory if it doesn't already exist.</p>\n\n<h2>Do more with <code>jq</code></h2>\n\n<p>Since you're already requiring a dependency on <code>jq</code>, it makes sense to use its capabilities more thoroughly. As you know, it has the ability to apply one or more filters sequentially to the result of the previous step. We can use this to great advantage and only call <code>jq</code> once like this:</p>\n\n<pre><code># use jq to create disk, src, dst triplets to feed to inst\njq -r -c '.[] | {disk, file: .files[]} | {disk, src: .file.src, dst: .file.dest} | [.disk,.src,.dst] |@sh ' \"$JSON\" | while read line \n do inst ${line}\ndone\n</code></pre>\n\n<p>As you can see from the comment, this extracts disk, src, dst triplets.</p>\n\n<h2>Create a function to do the work</h2>\n\n<p>Given the above advice, what we need is the <code>inst</code> routine to actually do the work. Here's one way to write that:</p>\n\n<pre><code># working variables\nTMPDIR=\nLASTDISK=\n\n# given disk, src, dst triplet\n# mount the disk in a temporary dir\n# (if not already mounted)\n# and install from src to dst\n# src may contain wildcards\nfunction inst () {\n disk=$(eval echo $1)\n src=$(eval echo $2)\n dst=$(eval echo $3)\n if [[ \"$disk\" != \"$LASTDISK\" ]] ; then \n cleanup\n TMPDIR=\"$(mktemp -d)\"\n echo \"mounting $disk on $TMPDIR\"\n if sudo mount -r \"$disk\" \"$TMPDIR\" ; then \n LASTDISK=\"$disk\"\n else \n echo \"Failed to mount $disk\"\n sudo rmdir \"$TMPDIR\"\n fi\n fi\n echo \"installing $src on $disk to $dst\"\n install -p --mode=664 -D \"$TMPDIR\"/$src -t \"$TARGET\"/$dst/\n}\n</code></pre>\n\n<p>Notice that I've used a number of <code>bash</code>-isms here that make this non-portable, but since you've explicitly called out <code>bash</code>, I'm assuming this is OK. I've also chosen to use <code>sudo mount</code> and <code>sudo umount</code> instead of <code>udiskctl</code>. Either could work, of course; it's a matter of preference as to which is used. On one hand, <code>mount</code> is always available but on the other, it requires <code>sudo</code> privileges. Most of this will be self-explanatory, except for <code>cleanup</code> which is described in the next suggestion.</p>\n\n<h2>Use a cleanup function</h2>\n\n<p>It's annoying when a script fails for some reason and then leaves temporary files or other junk lying around as a result. One technique that's handy for this is to use <code>bash</code>'s <code>TRAP</code> feature.</p>\n\n<pre><code># un mount and remove bind dir TMPDIR if\n# TMPDIR is not empty\nfunction cleanup {\n if [[ ! -z \"$TMPDIR\" ]] ; then\n sudo umount \"$TMPDIR\"\n sudo rm -rf \"$TMPDIR\"\n fi\n}\n\n# rest of script ...\n\ntrap cleanup EXIT\n</code></pre>\n\n<p>This tells <code>bash</code> that no matter how we get to the exit (either normally or via some fatal error) it needs to invoke the specified function, which I typically name <code>cleanup</code> for obvious reasons.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T17:32:25.560",
"Id": "210317",
"ParentId": "209507",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "210264",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T09:57:10.977",
"Id": "209507",
"Score": "4",
"Tags": [
"json",
"bash",
"linux",
"file-structure"
],
"Title": "Serial copying from disk images to folder in Bash"
} | 209507 |
<p>A solution for a small algorithmic problem. I believe tests are pretty descriptive:</p>
<pre><code>def pairs(n):
return n * (n - 1) / 2
def solution(lst):
res = 0
stack = lst[0:1]
lst = sorted(lst[1:])
while(len(lst)):
nxt = lst.pop()
if len(stack) and stack[0] == nxt:
stack.append(nxt)
else:
res += pairs(len(stack))
stack = [nxt]
else:
res += pairs(len(stack))
return res
assert(pairs(3) == 3)
assert(pairs(2) == 1)
assert(pairs(0) == 0)
assert(solution([5, 3, 1, 5, 5, 3]) == 4)
assert(solution([5, 5]) == 1)
assert(solution([5]) == 0)
assert(solution([]) == 0)
</code></pre>
<p>UPDATE: there is a bug. I shouldn't take a first element before sorting an array</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T10:43:52.697",
"Id": "404941",
"Score": "4",
"body": "Please add at least a short description of what this code accomplishes. What kind of pairs are you counting?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T11:29:31.193",
"Id": "404948",
"Score": "4",
"body": "@Trevor next and list are reserved in python. I can reassign them, but it can lead to some errors"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T06:22:44.340",
"Id": "405083",
"Score": "0",
"body": "it's a convention to use one trailing underscore to bypass reserved keywords. i.e. next_"
}
] | [
{
"body": "<p>From what I see you are counting all the pairs of equal numbers that can be formed. (If not, please clarify)</p>\n\n<p>It can be done in another way:</p>\n\n<ol>\n<li>Take the first element of the array.</li>\n<li>Count the number of elements equal to it in the array. It can be done via <code>filter</code>, storing the result as a new array, then <code>len</code>.</li>\n<li>Call <code>pairs</code> over the length of the filtered array of step 2.</li>\n<li>Add the result of <code>pairs</code> to an accumulator (previously initalized at 0).</li>\n<li>Repeat steps 2--5 from the next element that is <em>not</em> equal to the one taken previously (for the first iteration, it would be the one taken in step 1). This can be done using <code>filter</code>, then assignment over the original array (if you don't want to preserve it).</li>\n</ol>\n\n<p>The accumulator will be the result.</p>\n\n<p>Quickly tested code snippet:</p>\n\n<pre><code>def countPairs(nums):\n count = 0\n\n while len(nums):\n probe = nums[0]\n count += pairs(len([x for x in nums if x == probe]))\n nums = [x for x in nums if x != probe]\n\n return count\n</code></pre>\n\n<p><strong>EDIT.</strong></p>\n\n<p>Filtering can be thought of as an <code>O(n)</code> operation (iterating and adding elements that fulfill the condition). This is done twice inside the loop. Here, <code>n = len(nums)</code>.</p>\n\n<p>On the other hand, the external loop will run as many times as <code>unique(nums)</code>, where <code>unique</code> is a function that retrieves the number of unique elements inside the array. Why <code>unique</code>? Because on each iteration, all the elements equal to the probe are taken out of the array (including the probe). They can be 1, 3, all of them. This is done <em>for each iteration</em>.</p>\n\n<p>Nevertheless, <code>unique(nums) <= len(nums)</code>, so it can be said the external loop will be a <code>O(n)</code> operation in the worst case.</p>\n\n<p>Therefore, my proposed algorithm runs in <code>O(n^2)</code> time, due to traversing the whole array at most as many times as elements would be in the array.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T11:51:24.930",
"Id": "404949",
"Score": "0",
"body": "complexity of your solutions is O(n!). is it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T12:21:01.457",
"Id": "404952",
"Score": "0",
"body": "@kharandziuk I've edited my answer to explain the time complexity. It seems yours would be `O(n log n)`, for the sorting done before the loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T12:28:23.213",
"Id": "404953",
"Score": "0",
"body": "yeah, I expect n log n. But, yeap looks like yours is faster. Thx"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T11:35:38.750",
"Id": "405124",
"Score": "0",
"body": "I have another solution below. Can you check it?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T10:50:51.650",
"Id": "209512",
"ParentId": "209510",
"Score": "1"
}
},
{
"body": "<p>Probably, a little bit better solution. Expect O(n) complexity</p>\n\n<pre><code>def pairs(n):\n return n * (n - 1) / 2\n\ndef solution(lst):·\n counts = {}\n result = 0\n for e in lst:\n counts[e] = counts.get(e, 0) + 1\n for entry, count in counts.items():\n result += pairs(count)\n return result\n\nassert(pairs(3) == 3)\nassert(pairs(2) == 1)\nassert(pairs(0) == 0)\nassert(solution([5, 3, 1, 5, 5, 3]) == 4)\nassert(solution([5, 5]) == 1)\nassert(solution([5]) == 0)\nassert(solution([]) == 0)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T00:59:33.150",
"Id": "405206",
"Score": "1",
"body": "Using a dictionary to keep the count seems better to me. `O(n)` overall (including `counts.items()` as it's being iterated over). Well done!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T11:13:53.023",
"Id": "209605",
"ParentId": "209510",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "209512",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T10:39:05.683",
"Id": "209510",
"Score": "1",
"Tags": [
"python",
"algorithm"
],
"Title": "Python: count number of pairs in array(list)"
} | 209510 |
<p>This is a follow up question from <a href="https://codereview.stackexchange.com/questions/209204/pycat-a-small-implementation-of-netcat-in-python3-x">this question</a></p>
<h1>Intro</h1>
<p><em>netcat is an all-round tool used with many applicable features</em></p>
<p>My last try felt a bit rushed, and should've improved before posting here.
But this time, I am happy with the result.</p>
<p><strong>CHANGELOG</strong></p>
<ul>
<li><code>kwargs</code></li>
<li><code>@use_ssl</code> decorator</li>
<li>Multi-Platform (Posix, *nix, Windows)</li>
<li>Improved code structure</li>
<li>Download</li>
<li>Upload</li>
</ul>
<p>I tried adding a context manager, but couldn't really make it work in an elegant way. </p>
<p>Any and all reviews are welcome.</p>
<h1>Example</h1>
<p><em>server</em></p>
<pre><code>$ python pycat.py -lsp 8080
[*] Incoming connection from 127.0.0.1:53391
username@hostame PyCat C:\dev\Pycat
> echo hooooooi
hooooooi
username@hostame PyCat C:\dev\PyCat
> cd ../
username@hostame PyCat C:\dev
> exit
</code></pre>
<p><em>client</em></p>
<pre><code>python pycat.py -si localhost -p 8080
</code></pre>
<h1>Code</h1>
<pre><code>import argparse
import datetime
from functools import wraps
import socket
from ssl import wrap_socket, create_default_context, CERT_NONE
import sys
import subprocess
import tempfile
import os
import re
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend
SUCCES_RESPONSE = b"Command succesfully completed"
def ssl_server(func):
@wraps(func)
def wrapper(inst, *args):
inst.socket.bind((inst.host, inst.port))
inst.socket.listen(0)
if inst.ssl:
inst.context = create_default_context()
inst.key, inst.cert = inst.generate_temp_cert()
inst.socket = wrap_socket(
inst.socket,
server_side=True,
certfile=inst.cert,
keyfile=inst.key
)
func(inst, *args)
return wrapper
def ssl_client(func):
@wraps(func)
def wrapper(inst, *args):
inst.socket.connect((inst.host, inst.port))
if inst.ssl:
inst.context = create_default_context()
inst.context.check_hostname = False
inst.context.verify_mode = CERT_NONE
inst.socket = wrap_socket(inst.socket)
func(inst, *args)
return wrapper
class PyCatBase():
def __init__(self, **kwargs):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.port = kwargs['port']
self.host = kwargs['host'] or "0.0.0.0"
self.operating_system = os.name == "nt"
self.upload = kwargs['upload']
self.download = kwargs['download']
self.timeout = kwargs['timeout']
self.ssl = kwargs['ssl']
def exit(self):
self.socket.close()
sys.exit(0)
def read(self, connection, length=1024):
response = b""
while True:
data = connection.recv(length)
response += data
if len(data) < length:
break
return response.decode("utf-8").rstrip()
def upload_file(self, connection, file):
with open(file, "rb") as f:
connection.send(f.read())
def download_file(self, connection, file):
recieved = self.read(connection)
with open(file, "wb") as f:
f.write(recieved)
@staticmethod
def generate_temp_cert():
_, key_path = tempfile.mkstemp()
_, cert_path = tempfile.mkstemp()
name_attributes = [
x509.NameAttribute(NameOID.COUNTRY_NAME, "OK"),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "OK"),
x509.NameAttribute(NameOID.LOCALITY_NAME, "OK"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, "OK"),
x509.NameAttribute(NameOID.COMMON_NAME, "PyCat")
]
key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
with open(key_path, "wb") as f:
f.write(
key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
)
)
subject = issuer = x509.Name(name_attributes)
cert = x509.CertificateBuilder()\
.subject_name(subject)\
.issuer_name(issuer)\
.public_key(key.public_key())\
.serial_number(x509.random_serial_number())\
.not_valid_before(datetime.datetime.utcnow())\
.not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=365))
cert = cert.sign(key, hashes.SHA256(), default_backend())
with open(cert_path, "wb") as f:
f.write(
cert.public_bytes(serialization.Encoding.PEM)
)
return key_path, cert_path
class PyCatServer(PyCatBase):
def __init__(self, **kwargs):
super(PyCatServer, self).__init__(**kwargs)
def create_prompt_string(self):
self.client.send(b"cd") if self.operating_system else self.client.send(b"pwd")
pwd = self.read(self.client)
self.client.send(b"whoami")
whoami = self.read(self.client)
self.client.send(b"hostname")
hostname = self.read(self.client)
return f"{whoami}@{hostname} PyCat {pwd}\n> "
@ssl_server
def main(self):
if self.timeout > 0:
self.socket.settimeout(self.timeout)
self.client, addr = self.socket.accept()
print(f"[*] Incomming connection from {':'.join(map(str, addr))}")
self.handle_client()
def handle_client(self):
if self.upload is not None:
self.upload_file(self.client, self.upload)
elif self.download is not None:
self.download_file(self.client, self.download)
else:
while True:
prompt_string = self.create_prompt_string()
buf = input(prompt_string)
self.client.send(buf.encode("utf-8"))
if buf == "exit":
break
print(self.read(self.client))
self.exit()
class PyCatClient(PyCatBase):
def __init__(self, **kwargs):
super(PyCatClient, self).__init__(**kwargs)
def change_dir(self, path):
try:
os.chdir(path)
return SUCCES_RESPONSE
except FileNotFoundError as e:
return str(e).encode("utf-8")
def exec_command(self, command):
try:
return subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True)
except Exception as e:
return str(e).encode("utf-8")
def handle_command(self, command):
if command == "exit":
self.exit()
change_dir = re.match(r'cd(?:\s+|$)(.*)', command)
if change_dir and change_dir.group(1):
return self.change_dir(change_dir.group(1))
return self.exec_command(command)
@ssl_client
def main(self):
if self.timeout > 0:
self.socket.settimeout(self.timeout)
if self.upload is not None:
self.upload_file(self.socket, self.upload)
elif self.download is not None:
self.download_file(self.socket, self.download)
else:
while True:
cmd = self.read(self.socket)
response = self.handle_command(cmd)
if len(response) > 0:
self.socket.send(response)
def parse_arguments():
parser = argparse.ArgumentParser(usage='%(prog)s [options]',
description='PyCat @Ludisposed',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog='Examples:\npython3 pycat.py -lvp 443\npython3 pycat.py -i localhost -p 443')
parser.add_argument('-l', '--listen', action="store_true", help='Listen')
parser.add_argument('-s', '--ssl', action="store_true", help='Encrypt connection')
parser.add_argument('-p', '--port', type=int, help='Port to listen on')
parser.add_argument('-i', '--host', type=str, help='Ip/host to connect to')
parser.add_argument('-d', '--download', type=str, help='download file')
parser.add_argument('-u', '--upload', type=str, help='upload file')
parser.add_argument('-t', '--timeout', type=int, default=0, help='timeout')
args = parser.parse_args()
if (args.listen or args.host) and not args.port:
parser.error('Specify which port to connect to')
elif not args.listen and not args.host:
parser.error('Specify --listen or --host')
return args
if __name__ == '__main__':
args = parse_arguments()
pycat_class = PyCatServer if args.listen else PyCatClient
pycat = pycat_class(**vars(args))
pycat.main()
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>I tried adding a context manager, but couldn't really make it work in an elegant way.</p>\n</blockquote>\n\n<pre><code>class PyCatBase():\n def __enter__(self):\n return self\n def __exit__(exc_type, exc_val, exc_tb):\n self.socket.close()\n return False\n\n# ...\nif __name__ == '__main__':\n args = parse_arguments()\n pycat_class = PyCatServer if args.listen else PyCatClient\n pycat = pycat_class(**vars(args))\n with pycat:\n pycat.main()\n</code></pre>\n\n<p>Other things. <code>SUCCES_RESPONSE</code> should be spelled <code>SUCCESS_RESPONSE</code>. Similarly, there's a typo in that string.</p>\n\n<p>This:</p>\n\n<pre><code>self.operating_system = os.name == \"nt\"\n</code></pre>\n\n<p>suggests one of two things. Either <code>operating_system</code> should be named <code>is_windows</code>, or you need to change it to simply <code>self.operating_system = os.name</code>.</p>\n\n<p>This:</p>\n\n<pre><code>def __init__(self, **kwargs):\n</code></pre>\n\n<p>is only a good idea in other, limited, contexts (for example, if you're extending a class with a highly complex initializer). Don't do that, here. Spell out your args. Having implicit kwargs hurts you and your users in a number of ways, including kneecapping your IDE's static analysis efforts.</p>\n\n<p>Here:</p>\n\n<pre><code>cert = x509.CertificateBuilder()\\\n .subject_name(subject)\\\n .issuer_name(issuer)\\\n .public_key(key.public_key())\\\n .serial_number(x509.random_serial_number())\\\n .not_valid_before(datetime.datetime.utcnow())\\\n .not_valid_after(datetime.datetime.utcnow() +datetime.timedelta(days=365))\n</code></pre>\n\n<p>the generally accepted thing to do rather than a handful of newline continuations is to surround the thing in parens.</p>\n\n<p>This:</p>\n\n<pre><code>change_dir = re.match(r'cd(?:\\s+|$)(.*)', command) \n</code></pre>\n\n<p>should have its regex pre-compiled in <code>__init__</code>, since you call it for every command.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T16:07:25.893",
"Id": "209537",
"ParentId": "209515",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "209537",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T12:06:11.610",
"Id": "209515",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"networking"
],
"Title": "PyCat: a netcat implementation in Python3.x v2"
} | 209515 |
<p>I'm writing one custom class for PDO connection.</p>
<p>I want these advantages:</p>
<ul>
<li>Protect credentials: user, password ...</li>
<li>Facilitate maintenance: facing future password changes for example</li>
<li>Facilitate connection: <code>$pdo=new MyPDO();</code></li>
<li>Provide my class with all the PDO functionalities</li>
</ul>
<p>I write my class as you can see here:</p>
<p>For protecting credentials I saved them into an <code>ini</code> file:</p>
<pre><code><?php return; ?>
; credentials
host=localhost
user=myUser
pass="my/very/secure/password.../UqMsN[)VPn&gunmv3KzE?3Q&Qw/..."
dbname=myDataBase
</code></pre>
<h3>The class</h3>
<pre><code>class MyPDO extends PDO
{
public function __construct()
{
$iniData = parse_ini_file("//home/.credentials/db.php.ini");
$host=$iniData["host"];
$dbname=$iniData["dbname"];
$user=$iniData["user"];
$pass=$iniData["pass"];
$dsn = "mysql:host=$host;dbname=$dbname";
$options = array(
PDO::ATTR_PERSISTENT => FALSE,
PDO::ATTR_EMULATE_PREPARES => FALSE,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"
);
try {
parent::__construct($dsn, $user, $pass, $options);
} catch (PDOException $e) {
error_log($this->error = $e->getMessage(),0);
}
}
}
?>
</code></pre>
<hr>
<h3>Usage example</h3>
<pre><code>include_once('MyPDO.php');
$pdo=new MyPDO();
/*Use any PDO method*/
$pdo->query(...);
$pdo->prepare(...);
$pdo->execute(...);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T12:38:48.630",
"Id": "404954",
"Score": "0",
"body": "So you actually *exposed* your credentials to anyone who wold have a whim of navigating to .credentials/db.php.ini"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T12:42:48.457",
"Id": "404955",
"Score": "1",
"body": "@YourCommonSense thaks for your comment. The credentials are not exposed. 1º. The folder is out of `public_html`, then, non navigation possible (i'm using shared hosting). 2º. The first line: `<?php return; ?>` prevents to show the file content in case of access to fila via browser. I think the info is protected so."
}
] | [
{
"body": "<p>There are several areas for improvement.</p>\n\n<ul>\n<li>First of all, it violates the <a href=\"https://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"nofollow noreferrer\">Liskov substitution principle</a>. I am guilty for doing it too, so I cannot blame you too much but if you want your code to follow the best practices, it's better to make your class not extend PDO but either \n\n<ul>\n<li>make a PDO instance a property of your class publicly accessible through a property or a method. </li>\n<li>or - if you want to have a class with PDO's functionality but a different constructor, you have to re-create in your class all the functionality supported by PDO. Although sounds too laborious, it is not that hard as it seems but it pays back in the future. </li>\n</ul></li>\n<li><p>Next, error reporting for the connection is rather inflexible. An exception is a precious thing that can be handled in many different ways, logging included. So I would rather re-throw a new exception, like </p>\n\n<pre><code>try {\n parent::__construct($dsn, $user, $pass, $options);\n} catch (PDOException $e) {\n throw new \\PDOException($e->getMessage(), (int)$e->getCode());\n}\n</code></pre>\n\n<p>so it won't expose the connection credentials in the stack trace but still it can be caught elsewhere or simply logged if a corresponding PHP configuration directive says so.</p></li>\n<li>Connection encoding is better to be set in the DSN, as it's going to be more generic and supported by all drivers.</li>\n<li>reading the configuration right in the class violates the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single responsibility principle</a>. I would make this class to accept an array of parameters, as to where these parameters are taken from - an <code>.ini</code>, <code>.yml</code> or <code>.env</code> file - is a distinct matter. </li>\n<li>\"Facilitate maintenance\" option is somewhat defeated by the hardcoding of the configuration file name. What if you want to change it in the future as well? A typical web application has dozens of configuration options, it's just impractical to put them in different files whose names are hardcoded in different modules. To make a maintainable application it's better to have a distinct module for configuration that will supply different options to all other modules. </li>\n<li>And all the hassle related to protecting the configuration should be delegated elsewhere. After all, database credentials are not only settings that have to be protected - there are admin email, salt, API keys, etc. </li>\n<li>protecting an ini file adding .php as one of its extensions is too risky. It would work merely by accident (It would work only under Apache web-server if a certain configuration option is set). Why not to name it straight <code>settings.php</code> and thus make sure it will be always interpreted as PHP as long as it is called through a web-server with PHP support? </li>\n<li>I would also add a possibility to add/override the PDO options</li>\n</ul>\n\n<p>So I would make your class </p>\n\n<pre><code>class DB\n{\n protected $connection;\n public function __construct($config)\n {\n $dsn = \"mysql:host=$config[host];dbname=$config[dbname];charset=$config[charset]\";\n\n $options = array(\n PDO::ATTR_PERSISTENT => FALSE,\n PDO::ATTR_EMULATE_PREPARES => FALSE,\n PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,\n );\n if (isset($config['options'])) {\n $options = array_merge($options, $config['options']);\n }\n\n try {\n $this->connection = new \\PDO ($dsn, $config['user'], $config['pass'], $options);\n } catch (\\PDOException $e) {\n throw new \\PDOException($e->getMessage(), (int)$e->getCode());\n }\n }\n public function conn() {\n return $this->connection;\n }\n}\n</code></pre>\n\n<p>used as</p>\n\n<pre><code>$db = new DB($config);\n$stmt = $db->conn()->query('SELECT * FROM users');\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T14:33:51.570",
"Id": "209530",
"ParentId": "209517",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T12:25:55.080",
"Id": "209517",
"Score": "0",
"Tags": [
"php",
"pdo"
],
"Title": "PDO class wrapper"
} | 209517 |
<p>I have a program that will ask the user to input their grades for 4 different sections of a project, then tell them what their total mark is, what grade they got and how many marks away they were from the next grade. I managed to make a single loop for all inputs rather than having a loop for each individual one, but there are still quite a lot of if statements to determine what grade they got and how far away they were from the next one, and I can't figure out how to optimise it since I'm still very new to Java.</p>
<pre><code>import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Scanner;
public class PortfolioGrade {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] words = new String[]{"Analysis", "Design", "Implementation", "Evaluation"};
int[] marks = new int[words.length];
for(int counter = 1; counter <= words.length; counter++) {
System.out.println("Enter your mark for the '" + words[counter - 1] + "' part of the project: ");
while(true) {
try {
Scanner reader = new Scanner(System.in);
marks[counter - 1] = reader.nextInt();
if(marks[counter - 1] < 0 || marks[counter - 1] > 25) {
System.out.println("Please input a number between 0 and 25.");
continue;
}
break;
} catch(InputMismatchException e) {
System.out.println("Please input a valid integer.");
}
}
}
int totalmark = Arrays.stream(marks).sum();
String grade = null;
String nextgrade = null;
Integer marksaway = null;
if(totalmark < 2) {
grade = "U";
marksaway = 2 - totalmark;
nextgrade = "1";
} else if(totalmark >= 2 && totalmark < 4) {
grade = "1";
marksaway = 4 - totalmark;
nextgrade = "2";
} else if(totalmark >= 4 && totalmark < 13) {
grade = "2";
marksaway = 13 - totalmark;
nextgrade = "3";
} else if(totalmark >= 13 && totalmark < 22) {
grade = "3";
marksaway = 22 - totalmark;
nextgrade = "4";
} else if(totalmark >= 22 && totalmark < 31) {
grade = "4";
marksaway = 31 - totalmark;
nextgrade = "5";
} else if(totalmark >= 31 && totalmark < 41) {
grade = "5";
marksaway = 41 - totalmark;
nextgrade = "6";
} else if(totalmark >= 41 && totalmark < 54) {
grade = "6";
marksaway = 54 - totalmark;
nextgrade = "7";
} else if(totalmark >= 54 && totalmark < 67) {
grade = "7";
marksaway = 67 - totalmark;
nextgrade = "8";
} else if(totalmark >= 67 && totalmark < 80) {
grade = "8";
marksaway = 80 - totalmark;
nextgrade = "9";
} else if(totalmark >= 80) {
grade = "9";
}
System.out.println("Your total mark was " + totalmark + ".");
System.out.println("You got a Grade " + grade + ".");
if(grade == "9") {
System.out.println("You achieved the highest grade!");
} else if(marksaway == 1) {
System.out.println("You were " + marksaway + " mark away from a Grade " + nextgrade + ".");
} else {
System.out.println("You were " + marksaway + " marks away from a Grade " + nextgrade + ".");
}
}
}
</code></pre>
| [] | [
{
"body": "<p>Because there are no holes you can simply have an array of \"breakpoints\".</p>\n\n<pre><code>int [] steps = new int[] { 2, 4, 13, 22, 31, 41, 54, 67, 80 };\nint i;\n\nfor(i=0; i<steps.length && totalmark>=steps[i]; i++);\ngrade = i==0 ? \"U\" : \"\"+i;\nif(i<steps.length) marksaway=steps[i]-totalmark; \nnextgrade=\"\"+(i+1);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T15:18:59.337",
"Id": "404983",
"Score": "1",
"body": "Would you mind giving me a fairly simple explanation as to how this works?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T16:01:03.870",
"Id": "404996",
"Score": "1",
"body": "The loop loops over the array and breaks out if toolmark greater the current array-entry.\nI.e. totalmark=3. First loop, i is 0 and totalmark is greater than steps[0] -> continue -- Second loop, i is 1 and totalmark is not greater than steps[1] -> break out of the loop with i=1. Set grade to \"1\", marksaway to steps[1]-totalmark and nextgrade to \"2\""
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T13:10:44.753",
"Id": "209521",
"ParentId": "209520",
"Score": "4"
}
},
{
"body": "<p>I tidied up the first section for you a bit and then implemented the technique suggested by @Holger, all seems to work perfectly after running a few tests.</p>\n\n<pre><code>import java.util.Arrays;\nimport java.util.InputMismatchException;\nimport java.util.Scanner;\n\npublic class MarkCalculator {\n\npublic static void main(String[] args) {\n // TODO Auto-generated method stub\n String[] words = new String[]{\"Analysis\", \"Design\", \"Implementation\", \"Evaluation\"};\n int[] steps = { 2, 4, 13, 22, 31, 41, 54, 67, 80 };\n int[] marks = new int[4];\n\n Scanner reader = new Scanner(System.in); // Keep instantiation of scanner outside of loop - once is enough\n\n int totalmark = 0; \n int inputMark = 0;\n int marksaway = Integer.MIN_VALUE;\n\n String grade = \"\";\n String nextgrade = \"\";\n\n for(int counter = 0; counter<words.length; counter++) {\n System.out.println(\"Enter your mark for the '\" + words[counter] + \"' part of the project: \");\n try {\n do {\n inputMark = reader.nextInt();\n if(inputMark < 0 || inputMark > 25)\n System.out.println(\"Please input a number between 0 and 25.\");\n else\n marks[counter] = inputMark;\n } while(inputMark < 0 || inputMark > 25);\n } catch(InputMismatchException e) {\n System.out.println(\"Please input a valid integer.\");\n reader.nextLine();\n counter--;\n }\n }\n\n totalmark = Arrays.stream(marks).sum();\n\n for(int i=0; i<steps.length && totalmark>=steps[i]; i++) {\n grade = (i==0 ? \"U\" : \"\"+i);\n if(i < steps.length) {\n marksaway = steps[(i+1)]-totalmark; \n nextgrade = \"\" + (i+1);\n }\n }\n\n System.out.println(\"Your total mark was \" + totalmark + \".\");\n System.out.println(\"You got a Grade \" + grade + \".\");\n if(grade == \"9\") {\n System.out.println(\"You achieved the highest grade!\");\n } else if(marksaway == 1) {\n System.out.println(\"You were \" + marksaway + \" mark away from a Grade \" + nextgrade + \".\");\n } else { \n System.out.println(\"You were \" + marksaway + \" marks away from a Grade \" + nextgrade + \".\");\n }\n}\n</code></pre>\n\n<p>}</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T15:38:33.463",
"Id": "404989",
"Score": "0",
"body": "Would a while true loop not be necessary in this case in order to skip the iteration if the user enters an invalid input?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T21:17:49.577",
"Id": "405043",
"Score": "1",
"body": "You are totally right my mistake, my edit should fix this and avoid the ugly while(true). There is still an issue with the case when someone enters a character other than an integer, will have a look at it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T21:29:40.773",
"Id": "405049",
"Score": "1",
"body": "After reading the answers to the following question, I changed the catch block so that it consumes whatever invalid token have been inputted and then decrements counters so that it asks for the same grade again. - https://stackoverflow.com/questions/24414299/java-scanner-exception-handling"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T13:48:38.573",
"Id": "209524",
"ParentId": "209520",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "209521",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T12:44:14.583",
"Id": "209520",
"Score": "4",
"Tags": [
"java",
"beginner"
],
"Title": "Grade calculator for a project with four aspects"
} | 209520 |
<p>I just started Advent of Code 2018. This is <a href="https://adventofcode.com/2018/day/1" rel="nofollow noreferrer">exercise 2 of day 1</a>, and I can't understand why my code is so slow (4 minutes 37 seconds, compared to 200ms for a friend who did it in Clojure with the same computer).</p>
<p>Basically, it accumulates integers from a provided list of ints, named <code>input</code>. Whenever the current value of the accumulator is equal to one of its previous values, it is returned. We might have to loop many times over the provided list before we find such an occurrence. Here is the code:</p>
<pre><code> let main () =
let rec my_slow_code lst history =
if lst == [] then my_slow_code input history
else
let current = List.hd lst + List.hd history in
if List.mem current history then current
else my_slow_code (List.tl lst) (current :: history)
in
my_slow_code input [0]
</code></pre>
<p>I can't understand what mistake here makes such a slow code, maybe the use of List.mem?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T14:49:45.590",
"Id": "404966",
"Score": "0",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] | [
{
"body": "<p>I won't give it all away, since that would take away some of the fun of Advent of Code, but I'll point out:</p>\n\n<p>First, yes, <code>List.mem</code> takes time proportional to the length of your list, which means if you're calling it over and over again it can be quite slow indeed. There might be faster structures you could use if you want to track if a previous value has been seen before, like <code>Set</code>s. Also, you should not be using <code>==</code> for equality here but rather <code>=</code>; I recommend learning the difference between <code>=</code> and <code>==</code>, you will want to know it.</p>\n\n<p>Second, your code is not very idiomatic OCaml; in general, if you're doing things like nesting lots of <code>if</code>s and using <code>List.hd</code> instead of pattern matching, you may not be doing things quite right. This won't impact your performance but might impact readability and correctness. (For example, the <code>match l with | [] -> ...</code> pattern will warn you if a pattern match isn't exhaustive, which avoids nasty bugs.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T17:27:48.597",
"Id": "405010",
"Score": "0",
"body": "thanks for the tips! Using `=` instead of `==` is indeed more correct - even if it did not improve the efficiency. On the other hand, using `Set ` made it much, much faster (more than 500x)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T22:47:23.807",
"Id": "405774",
"Score": "0",
"body": "It improves it from O(n) to O(1), which is vastly better than improving by a constant, no matter how large."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T15:03:56.227",
"Id": "209533",
"ParentId": "209528",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "209533",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T14:26:53.827",
"Id": "209528",
"Score": "1",
"Tags": [
"programming-challenge",
"time-limit-exceeded",
"ocaml"
],
"Title": "Advent of Code 2018 Day 1 in OCaml: Find length of cycles when accumulating deltas"
} | 209528 |
<p>Currently I'm working on parsing data from a form service into a pdf form. I created 2 classes one inheriting from the other one. However, I see that the classes I created are growing in lines of code and I'm concern that I am concern that these classes become hard to maintain. </p>
<p>I would like to request feedback from the community regarding OOP principles, style violations and best practices. If there are also security concerns points those out. Here are the classes using inheritance.</p>
<pre><code>require 'open-uri'
class FillablePdfForm
attr_writer :template_path
attr_reader :attributes
def initialize
fill_out
end
def export(file_name, output_file_path: nil)
output_file_path ||= "#{Rails.root}/tmp/pdfs/#{application_date}_#{which_application}_#{what_status}_#{file_name}.pdf"
pdftk.fill_form template_path, output_file_path, attributes
output_file_path
end
def form_fields
pdftk.get_field_names template_path
end
def template_path
pdf_form_application
@template_path ||=
"#{Rails.root}/public/pdfs/#{which_application.downcase}_#{what_status.downcase}.pdf"
end
protected
def application_date
Time.now.strftime('%Y-%m-%d')
end
def pdf_form_application
File.open("#{Rails.root}/public/pdfs/#{which_application.downcase}_#{what_status.downcase}.pdf", "wb") do |file|
file << URI.parse(url_of_pdf_form).read
end
end
def url_of_pdf_form
@form_fields.find do |field|
field['label'] == "#{which_application}_#{what_status}_URL"
end['default']
end
def attributes
@attributes ||= {}
end
def fill(key, value)
attributes[key.to_s] = value
end
def pdftk
@pdftk ||= PdfForms.new
end
def fill_out
raise 'Must be overridden by child class'
end
end
</code></pre>
<p>Also, I'm passing in the constructor <code>FormStack::Form.new</code> but I was wondering if I should pass it as an argument.</p>
<pre><code>class PdfScrie < FillablePdfForm
def initialize(user_submission_data, form_fields)
@user_submission_data = user_submission_data
@form_fields = form_fields
@formstack = FormStack::Form.new
super()
end
private
# PDF Constants
VALUE_CHECKBOX_ON = 'On'.freeze
OPTION_SEP = ' | '.freeze
LABEL_APPLICATION = 'APPLICATION'.freeze
LABEL_STATUS = 'STATUS'.freeze
def fill_out
form_fields.each do |field| # PDF form fields
unless dictionary[field]
Rails.logger.warn "#{self.class.name}: Missing \"#{field}\" mapping."
next
end
id = dictionary[field].split(OPTION_SEP)[0]
@user_submission_data
.select { |field_data| field_data[FormStack::Form::ATTR_FIELD_ID] == id }
.each { |field_data| fill_form_with_data(field, field_data) }
end
end
def fill_form_with_data(field, field_data)
field_number = field_data[FormStack::Form::ATTR_FIELD_ID]
value = field_data[FormStack::Form::ATTR_FIELD_VALUE]
field_type = FormStack::Form::field_type(@form_fields, field_number)
self_method = "fill_#{field_type}".to_sym
if self.respond_to?(self_method, :include_private)
send(self_method, field_number, field, value)
else
fill(field, value)
end
end
# Field Type Methods
def fill_address(field_number, field, value)
address_by_section = FormStack::Form.parse_formstack_nested_attrs(value)
address_by_section.each do |section, value|
fill(field, value) if form_field_has_section?(field, section) ||
FormStack::Form::address_section_aparment?(field, section)
end
end
def fill_phone(field_number, field, value)
parse_phone_number(value)
fill(field, @phone_number_sections.shift)
end
def fill_name(field_number, field, value)
full_name = FormStack::Form::parse_name(value)
fill(field, full_name)
end
def fill_checkbox(field_number, field, value)
if FormStack::Form::field_is_grouped_checkbox(@form_fields, field_number)
FormStack::Form::parse_checked_options(value).each do |option|
fill(field, VALUE_CHECKBOX_ON) if checked_option_matches_value(field, option)
end
else
fill(field, value)
end
end
# END Field Type Methods
# Helpers
def checked_option_matches_value(field, option)
dictionary[field].split(OPTION_SEP)[1].include?(option)
end
def parse_phone_number(phone_number)
if phone_number_sections_empty?
@phone_number_sections = FormStack::Form::parse_phone(phone_number)
end
end
def phone_number_sections_empty?
@phone_number_sections.nil? || @phone_number_sections.empty?
end
def form_field_has_section?(form_field_name, address_section)
form_field_name.include? address_section.upcase
end
def dictionary
@dictionary ||= JSON.parse(find_dictionary['section_text'])
end
def find_dictionary
@formstack.find_field_by_label("#{which_application}_#{what_status}_DICTIONARY",
@form_fields)
end
def which_application
@formstack.find_value_by_label(LABEL_APPLICATION,
@form_fields,
@user_submission_data)
end
def what_status
@formstack
.find_value_by_label(LABEL_STATUS, @form_fields, @user_submission_data)
end
end
</code></pre>
<p>Feel free to point out areas of improvement, feedback, best practices and resources.</p>
| [] | [
{
"body": "<p>An OOP suggestion by way of analogy:</p>\n\n<p>Consider a <code>Document</code> and a <code>Cabinet</code>. Should a <code>Document</code> know how to put a copy of itself in a <code>Cabinet</code>? Or should a <code>Cabinet</code> know how to copy a document into itself?</p>\n\n<p>In a small program, either is probably fine. However, it will become unmaintainable as more ways for them to interact are added as the system grows in complexity.</p>\n\n<p>When that happens, there should be an actor at a higher abstraction level, e.g. a \"secretary\" that makes a copy (perhaps by requesting it via <code>Document#copy</code>) and files the copy into the cabinet (perhaps by requesting it of the <code>Cabinet#file</code>). In their respective isolated context, they don't need to interact or know about each other, so their implementations would not contain references to each other.</p>\n\n<p>If there is only ever \"one secretary\", just leave the action at the top level abstraction -- the main program. As complexity grows, perhaps a <code>Secretary</code> class can be defined.</p>\n\n<p>However, remember that <code>Secretary</code>'s actions are the higher abstraction and <code>Document</code> is a lower abstraction. The dependency directionality is important. A <code>Document</code> shouldn't be imposing a <code>Secretary</code> to act.</p>\n\n<p><strong>Where this applies to your code:</strong></p>\n\n<ol>\n<li><code>export</code>\n\n<ul>\n<li><code>FillablePdfForm</code> is the Document</li>\n<li><code>PdfForms</code> is the Cabinet</li>\n<li>problem: <code>FillablePdfForm#export</code> is the Document putting itself in the Cabinet</li>\n</ul></li>\n<li><code>fill_form_with_data</code>\n\n<ul>\n<li><code>field_data</code> and <code>FormStack::Form</code> are the Documents</li>\n<li><code>PdfScrie</code> is the Cabinet</li>\n<li>problem: <code>PdfScrie#fill_form_with_data</code> is the Cabinet putting the Document in itself</li>\n</ul></li>\n</ol>\n\n<p>By the way, this concept is the <a href=\"https://en.wikipedia.org/wiki/Dependency_inversion_principle\" rel=\"nofollow noreferrer\">D</a> in <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">SOLID</a></p>\n\n<p>Another issue is where <code>FillablePdfForm#template_path</code> calls <code>which_application</code>, which is implemented in the subclass <code>Scrie</code>, which the <a href=\"https://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"nofollow noreferrer\">L</a> in SOLID talks about.</p>\n\n<p>The Wikipedia articles are a little thick to get through though, Google around for some alternative explanations of each of the SOLID principles.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T11:12:51.670",
"Id": "214636",
"ParentId": "209536",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "214636",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T15:57:13.210",
"Id": "209536",
"Score": "2",
"Tags": [
"object-oriented",
"ruby",
"design-patterns"
],
"Title": "Use of inheritance using two Ruby libraries"
} | 209536 |
<p>I've got 17 currency fields on a form and need to do some calculations with their values. I wrote this method some time ago and have come back to try and refactor it to make it more efficient and/or more readable. Could I have some pointers please?</p>
<p>Note: The variables appended with <code>d</code> are the decimals used to hold the field values, their counterparts without the <code>d</code> are the fields themselves. I am aware that variables could do with renaming to make more sense. Hopefully it's fairly clear what this is doing by looking at the comments.</p>
<pre><code>private void getTotals() {
//declarations of decimal variables
decimal curPurc1d; decimal curPurc2d; decimal curPurc3d; decimal curPurc4d; //purItemxCost
decimal curItem1Totd; decimal curItem2Totd; decimal curItem3Totd; decimal curItem4Totd; //curItemxTot
decimal LessItem1Costd; decimal LessItem2Costd; decimal LessItem3Costd; decimal LessItem4Costd; decimal LessItem5Costd; //LessItemxCost
decimal ditem1Cost = 0; decimal ditem2Cost = 0; decimal ditem3Cost = 0; decimal ditem4Cost = 0; //Full cost of items
//Check if we have some valid numbers, stop if we don't
if ( !decimal.TryParse(curPurc1.Value.ToString(), out curPurc1d)
|| !decimal.TryParse(curPurc2.Value.ToString(), out curPurc2d)
|| !decimal.TryParse(curPurc3.Value.ToString(), out curPurc3d)
|| !decimal.TryParse(curPurc4.Value.ToString(), out curPurc4d)
|| !decimal.TryParse(curItem1Tot.Value.ToString(), out curItem1Totd)
|| !decimal.TryParse(curItem2Tot.Value.ToString(), out curItem2Totd)
|| !decimal.TryParse(curItem3Tot.Value.ToString(), out curItem3Totd)
|| !decimal.TryParse(curItem4Tot.Value.ToString(), out curItem4Totd)
|| !decimal.TryParse(LessItem1Cost.Value.ToString(), out LessItem1Costd)
|| !decimal.TryParse(LessItem2Cost.Value.ToString(), out LessItem2Costd)
|| !decimal.TryParse(LessItem3Cost.Value.ToString(), out LessItem3Costd)
|| !decimal.TryParse(LessItem4Cost.Value.ToString(), out LessItem4Costd)
|| !decimal.TryParse(LessItem5Cost.Value.ToString(), out LessItem5Costd)
)
return;
//For each of the 4 'items', try to get the value as a decimal, but only if the related checkbox is checked.
if (Item1RateYN.Checked)
{
decimal.TryParse(curItem1Cost.Value.ToString(), out ditem1Cost);
}
if (Item2RateYN.Checked)
{
decimal.TryParse(curItem2Cost.Value.ToString(), out ditem2Cost);
}
if (Item3RateYN.Checked)
{
decimal.TryParse(curItem3Cost.Value.ToString(), out ditem3Cost);
}
if (Item4RateYN.Checked)
{
decimal.TryParse(curItem4Cost.Value.ToString(), out ditem3Cost);
}
//Add up some values which are always part of the subtotal and then the ditemx ones, which will be 0 or set to a numerical value depending if the checkbox is checked
decimal subtotals = curPurc1d + curPurc2d + curPurc3d + curPurc4d + curItem1Totd + curItem2Totd + curItem3Totd + curItem4Totd
+ ditem1Cost + ditem2Cost + ditem3Cost + ditem4Cost;
subtotal.Value = subtotals;
//Get total minus the cost of the property (curPurc1d)
costPlusSubTotal.Value = subtotals - curPurc1d;
//add up all the "less" items to know how much to reduce by
decimal lessTotals = LessItem1Costd + LessItem2Costd + LessItem3Costd + LessItem4Costd + LessItem5Costd;
totalLess.Value = lessTotals;
//Total Balance due
//subtotal minus the 'less' values total
decimal total = (subtotals - lessTotals);
//set the final figure into the relevant field
balanceDueTot.Value = total;
}
</code></pre>
| [] | [
{
"body": "<p>Assuming the fields have definitions like the following</p>\n\n<pre><code>public class TextboxControl\n{\n public object Value { get; set; }\n}\n\npublic class CheckboxControl\n{\n public bool Checked { get; set; }\n}\n</code></pre>\n\n<p>I would create some extensions for them in order to reduce code duplication and increase readability, and pretty much this is the core idea.</p>\n\n<pre><code>public static class ControlsExtensions\n{\n public static bool HasValue(this TextboxControl source) \n => decimal.TryParse(source.Value.ToString(), out _);\n\n public static decimal GetValue(this TextboxControl source) \n => decimal.Parse(source.Value.ToString());\n\n public static decimal GetOptionalValue(this TextboxControl source, CheckboxControl checkbox) \n {\n if (checkbox.Checked)\n {\n decimal value = decimal.TryParse(source.Value.ToString(), out value) ? value : 0;\n return value;\n }\n return default(decimal);\n }\n}\n</code></pre>\n\n<p>Then my next step in refactoring would to use these extensions and rearrange a bit the lines to increase cohesion</p>\n\n<pre><code>private void getTotals()\n{\n //Check if we have some valid numbers, stop if we don't\n if ( !curPurc1.HasValue()\n || !curPurc2.HasValue()\n || !curPurc3.HasValue()\n || !curPurc4.HasValue()\n || !curItem1Tot.HasValue()\n || !curItem2Tot.HasValue()\n || !curItem3Tot.HasValue()\n || !curItem4Tot.HasValue()\n || !LessItem1Cost.HasValue()\n || !LessItem2Cost.HasValue()\n || !LessItem3Cost.HasValue()\n || !LessItem4Cost.HasValue()\n || !LessItem5Cost.HasValue() \n )\n return;\n\n //Add up some values which are always part of the subtotal and then the ditemx ones, which will be 0 or set to a numerical value depending if the checkbox is checked\n decimal subtotals = curPurc1.GetValue() + curPurc2.GetValue() + curPurc3.GetValue() \n + curPurc4.GetValue() + curItem1Tot.GetValue() + curItem2Tot.GetValue() \n + curItem3Tot.GetValue() + curItem4Tot.GetValue() \n + Item1RateYN.GetOptionalValue() + Item2RateYN.GetOptionalValue() + Item3RateYN.GetOptionalValue() + Item4RateYN.GetOptionalValue();\n\n //Get total minus the cost of the property (curPurc1d)\n decimal plusSubTotal = subtotals - curPurc1.GetValue();\n\n\n //add up all the \"less\" items to know how much to reduce by \n decimal lessTotals = LessItem1Cost.GetValue() + LessItem2Cost.GetValue() + LessItem3Cost.GetValue() + LessItem4Cost.GetValue() + LessItem5Cost.GetValue();\n\n //Total Balance due\n //subtotal minus the 'less' values total\n decimal total = (subtotals - lessTotals);\n\n //update the relevant UI field\n costPlusSubTotal.Value = plusSubTotal;\n subtotal.Value = subtotals;\n balanceDueTot.Value = total;\n totalLess.Value = lessTotals;\n}\n</code></pre>\n\n<p>Then to make the code more C#-like, I would</p>\n\n<ul>\n<li><p>use <code>var</code> instead of <code>decimal</code> </p></li>\n<li><p>rename <code>getTotals</code> to <code>GetTotals</code> </p></li>\n<li>use<code>_camelCase</code> for private fileds (so <code>Less</code> becomes <code>_less</code>)</li>\n<li>reduce redundant parenthesis from <code>(subtotals - lessTotals)</code></li>\n<li>use brackets <code>{}</code> for the <code>return</code> statement</li>\n</ul>\n\n<p>Notice that I also grouped the update of the UI at the end of the method.</p>\n\n<p>I would have some comments also for the name of the method itself as <code>GetTotals</code> implies that the method returns something, but the return signature is <code>void</code>. One idea is to use something like <code>CalculateTotals</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T17:37:22.780",
"Id": "209547",
"ParentId": "209540",
"Score": "5"
}
},
{
"body": "<p>Two words: loops and arrays.</p>\n\n<p>There a bunch of variable names that differ only by a number. Whenever you see code like this, you can probably clean it up by creating a collection of those things and looping over them. Basically, you have a checkbox and text field repeated multiple times, and one field where you display the total of all checked fields.</p>\n\n<ol>\n<li>Create a user control to encapsulate the checkbox and text field</li>\n<li>Make sure this user control has a public property <code>decimal TotalCost { get }</code> that will:\n\n<ul>\n<li>Return the decimal-parsed values of <code>total - cost</code> for the fields when checked, and zero when unchecked.</li>\n<li>Throws an exception if the decimal cannot be parsed</li>\n</ul></li>\n<li>Expose a boolean property <code>bool IsValid</code> that returns true when the user as entered a valid decimals</li>\n<li>Expose a public property <code>bool IsChecked</code> that returns whether or not the checkbox is checked</li>\n<li>Create a collection of these user controls, one for each checkbox/text field combo on screen</li>\n</ol>\n\n<p>Now loop and process:</p>\n\n<pre><code>decimal purchaseTotal = 0m;\ndecimal totalAmount = 0m;\n\nforeach (var control in PurchasedItems.Where(p => p.IsChecked && p.IsValid))\n{\n purchaseTotal += control.TotalCost;\n}\n</code></pre>\n\n<p>I left some details out, but your code isn't really clear on what the UI looks like, or what the business use case is, but it really just boils down to:</p>\n\n<ul>\n<li>Create an abstraction for what each combo of controls represents (e.g. create a new user control)</li>\n<li>Create a collection of these controls</li>\n<li>Loop and calculate</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T06:24:11.487",
"Id": "405084",
"Score": "0",
"body": "Do not throw an exception if the entry cannot be parsed. Exceptions should be reserved for \"continued processing is not possible\" conditions. And exceptions are relatively process intensive operations. A failed parse is easily captured w/o exceptions and it's obvious what to do with it, tell the user to re-enter. This is normal run of the mill user entry error handling, do not use exceptions in these cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T13:08:01.457",
"Id": "405133",
"Score": "0",
"body": "@radarbob: That's what the `IsValid` property is for. Check it before calling the TotalCost getter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T13:09:05.820",
"Id": "405134",
"Score": "0",
"body": "Besides, if you don't check `IsValid` first, and call `TotalCost` and it cannot parse the input, then \"continued processing is not possible\" and an exception is appropriate."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T18:22:45.870",
"Id": "209551",
"ParentId": "209540",
"Score": "14"
}
}
] | {
"AcceptedAnswerId": "209551",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T16:29:09.743",
"Id": "209540",
"Score": "10",
"Tags": [
"c#",
"winforms"
],
"Title": "Calculate subtotals and totals from a form with many decimal values"
} | 209540 |
<p>By default, mouse wheel scrolling in Java Swing behaves differently than in web browsers. In Swing, when you have an inner scrollable component and an outer scrollable component, the mouse wheel events are only ever dispatched to the inner component. This means that when you are in a text area inside a larger panel, you cannot use the mouse wheel to scroll the panel. You first need to move the mouse cursor out of the text area.</p>
<p>I tested Google Chrome, Firefox, Internet Explorer and Edge, and they almost behave the same. I prefer their behavior over the default Swing behavior, therefore I implemented it.</p>
<ul>
<li>The basic idea is that every top-level window has its "active scrolling component". This component receives all scroll events until it gets inactive by timeout (1 second).</li>
<li>To find a new "active component", the one at the mouse cursor is taken. If that component is not scrollable into the direction given by the event, its parent is taken, and so on.</li>
<li>The Microsoft browsers behave as if the timeout were 0 seconds, Chrome and Firefox have a timeout of 1 second.</li>
<li>When the mouse is moved while scrolling (really an edge case I think), my code happens to do the same as the browsers: scrolling continues with the component below the mouse cursor. I didn't plan for that, but it seems to be sensible.</li>
</ul>
<p>Here is the code:</p>
<pre><code>package de.roland_illig.playground.scroll;
import java.awt.Component;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public final class WheelScrolling {
/**
* Passes mouse wheel events to the parent component if this component
* cannot scroll further in the given direction.
* <p>
* This is the behavior of most web browsers and similar programs
* that need to handle nested scrollable components.
*/
public static void install(JScrollPane pane) {
pane.addMouseWheelListener(new Listener(pane));
}
private static class Listener implements MouseWheelListener {
private final JScrollPane pane;
private boolean inHandler; // To avoid StackOverflowError in nested calls
Listener(JScrollPane pane) {
this.pane = pane;
pane.setWheelScrollingEnabled(false);
}
public void mouseWheelMoved(MouseWheelEvent e) {
if (!inHandler) {
inHandler = true;
try {
handleMoved(e);
} finally {
inHandler = false;
}
}
}
private void handleMoved(MouseWheelEvent e) {
JScrollPane curr = currentPane(e);
if (curr == null || curr == pane || e.isControlDown() || e.isAltDown()) {
dispatchDefault(pane, e);
} else {
dispatchDefault(curr, (MouseWheelEvent)
SwingUtilities.convertMouseEvent(pane, e, curr));
}
}
private static void dispatchDefault(JScrollPane comp, MouseWheelEvent e) {
if (comp.isWheelScrollingEnabled()) {
comp.dispatchEvent(e);
} else {
comp.setWheelScrollingEnabled(true);
comp.dispatchEvent(e);
comp.setWheelScrollingEnabled(false);
}
}
private JScrollPane currentPane(MouseWheelEvent e) {
Current current = current(pane);
if (current == null) {
return null;
}
long validUntil = current.validUntil;
current.validUntil = e.getWhen() + 1000;
if (e.getWhen() < validUntil) {
return current.pane;
}
for (Component comp = pane; comp != null; comp = comp.getParent()) {
if (comp instanceof JScrollPane) {
JScrollPane otherPane = (JScrollPane) comp;
if (canScrollFurther(otherPane, e)) {
current.pane = otherPane;
return current.pane;
}
}
}
current.pane = null;
return null;
}
private static boolean canScrollFurther(JScrollPane pane, MouseWheelEvent e) {
// See BasicScrollPaneUI
JScrollBar bar = pane.getVerticalScrollBar();
if (bar == null || !bar.isVisible() || e.isShiftDown()) {
bar = pane.getHorizontalScrollBar();
if (bar == null || !bar.isVisible()) {
return false;
}
}
if (e.getWheelRotation() < 0) {
return bar.getValue() != 0;
} else {
int limit = bar.getMaximum() - bar.getVisibleAmount();
return bar.getValue() != limit;
}
}
private static Current current(Component component) {
if (component.getParent() == null) {
return null;
}
Component top = component;
while (top.getParent() != null) {
top = top.getParent();
}
for (MouseWheelListener listener : top.getMouseWheelListeners()) {
if (listener instanceof Current) {
return (Current) listener;
}
}
Current current = new Current();
top.addMouseWheelListener(current);
return current;
}
}
/**
* The "currently active scroll pane" needs to remembered once
* per top-level window.
* <p>
* Since a Component does not provide a storage for arbitrary data,
* this data is stored in a no-op listener.
*/
private static class Current implements MouseWheelListener {
private JScrollPane pane;
private long validUntil;
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
// Do nothing.
}
}
}
</code></pre>
<p>And here is a demo application using the above mouse wheel behavior:</p>
<pre><code>package de.roland_illig.playground.scroll;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Rectangle;
import java.util.Random;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.Scrollable;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
public final class WheelScrollingDemo {
public static void main(String[] args) {
EventQueue.invokeLater(WheelScrollingDemo::main);
}
private static void main() {
Random rnd = new Random(0);
JPanel panel = new ScrollablePanel(new JTextArea());
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
for (int i = 0; i < 10; i++) {
panel.add(newInnerPanel(rnd.nextInt(50)));
}
JScrollPane pane = new JScrollPane(panel);
JFrame frame = new JFrame("Mouse Wheel Scrolling Demo");
frame.setPreferredSize(new Dimension(500, 500)); // Just a bad guess.
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.getContentPane().add(pane, BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static JPanel newInnerPanel(int rows) {
JLabel head = new JLabel("Heading");
head.setHorizontalTextPosition(SwingConstants.CENTER);
JTextArea body = new JTextArea();
body.setColumns(20);
body.setRows(rows);
JScrollPane pane = new JScrollPane(body);
WheelScrolling.install(pane);
JPanel panel = new ScrollablePanel(body);
panel.setLayout(new BorderLayout());
panel.setBackground(Color.LIGHT_GRAY);
panel.setPreferredSize(new Dimension(400, 200)); // Just a bad guess.
panel.add(head, BorderLayout.PAGE_START);
panel.add(pane, BorderLayout.CENTER);
return panel;
}
/**
* Without this class, the mouse wheel scrolling speed differs
* between the JTextArea and the JPanel.
*/
private static final class ScrollablePanel extends JPanel implements Scrollable {
private static final long serialVersionUID = 20181212;
private final Scrollable ref;
/**
* @param ref the component providing the block and unit increments
* for scrolling
*/
private ScrollablePanel(Scrollable ref) {
this.ref = ref;
}
@Override
public Dimension getPreferredScrollableViewportSize() {
return getPreferredSize();
}
@Override
public int getScrollableUnitIncrement(
Rectangle visibleRect, int orientation, int direction) {
return ref.getScrollableUnitIncrement(visibleRect, orientation, direction);
}
@Override
public int getScrollableBlockIncrement(
Rectangle visibleRect, int orientation, int direction) {
return ref.getScrollableBlockIncrement(visibleRect, orientation, direction);
}
@Override
public boolean getScrollableTracksViewportWidth() {
return false;
}
@Override
public boolean getScrollableTracksViewportHeight() {
return false;
}
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T17:28:31.097",
"Id": "209546",
"Score": "4",
"Tags": [
"java",
"event-handling",
"swing",
"gui"
],
"Title": "Mouse wheel scrolling for nested scrollable Swing components"
} | 209546 |
<p>I have this code which opens 2 workbooks, copies a sheet and paste then to the master workbook. It is currently taking 3 minutes. Can this be done quicker (i.e. without opening each workbook to copy)?</p>
<p>It takes roughly 3 minutes to do.</p>
<pre><code>Sub Load()
Dim masterWB As Workbook
Dim dailyWB As Workbook
Dim lastweekWB As Workbook
Dim R As Range
Dim B As Range
Dim C As Range
Dim Lrow As Long
Application.DisplayAlerts = False
'Set Current Workbook as Master
Set masterWB = Application.ThisWorkbook
'Set some Workbook as the one you are copying from
Set dailyWB = Workbooks.Open(Sheets("Control Manager").Range("O2"))
'Copy the Range from dailyWB and Paste it into the MasterWB
dailyWB.Sheets("Summary1").Range("A1:BJ200").Copy masterWB.Sheets("Summary").Range("A1").Rows("1:1")
'formatting and paste as values
masterWB.Activate
Worksheets("Summary").Select
'trim values
Columns("A:BJ").Select
Selection.Columns.AutoFit
Selection.Copy
Selection.PasteSpecial xlPasteValues
'repeat for next Sheet
dailyWB.Sheets("risk1").Range("A1:BB200").Copy masterWB.Sheets("risk").Range("A1").Rows("1:1")
'formatting and paste as values'
masterWB.Activate
Worksheets("risk").Select
Columns("A:BB").Select
With Application.WorksheetFunction
For Each B In Intersect(Columns("A:BB"), ActiveSheet.UsedRange)
B.Value = .Trim(B.Value)
Next B
End With
Selection.Columns.AutoFit
Selection.Copy
Selection.PasteSpecial xlPasteValues
'repeat for CS sheet
dailyWB.Sheets("CS today").Range("A1:L3").Copy masterWB.Sheets("CS").Range("A1").Rows("1:1")
'formatting and paste as values
masterWB.Activate
Worksheets("CS").Select
Columns("A:L").Select
'trim cells to exclude spaces.
With Application.WorksheetFunction
For Each R In Intersect(Columns("A:L"), ActiveSheet.UsedRange)
R.Value = .Trim(R.Value)
Next R
End With
Selection.Columns.AutoFit
Selection.Copy
Selection.PasteSpecial xlPasteValues
''''''''''''Get Last Week Data''''''''''''''''''''''
Set lastweekWB = Workbooks.Open(Sheets("Control Manager").Range("O3"))
'repeat for next risk Sheet
lastweekWB.Sheets("risk2").Range("A1:BB200").Copy masterWB.Sheets("risk_lastweek").Range("A1").Rows("1:1")
'formatting and paste as values
masterWB.Activate
Worksheets("risk_lastweek").Select
Columns("A:BB").Select
With Application.WorksheetFunction
For Each B In Intersect(Columns("A:BB"), ActiveSheet.UsedRange)
B.Value = .Trim(B.Value)
Next B
End With
Selection.Columns.AutoFit
Selection.Copy
Selection.PasteSpecial xlPasteValues
Application.DisplayAlerts = True
'Close the Workbook without saving
dailyWB.Close False
lastweekWB.Close False
'Clear the Variables
Set dailyWB = Nothing
Set masterWB = Nothing
Set lastweekWB = Nothing
End Sub
</code></pre>
| [] | [
{
"body": "<p>Separating tasks into multiple subroutines will make the code easier to test and modify.</p>\n\n<p>This video: <a href=\"https://www.youtube.com//watch?v=c8reU-H1PKQ&index=5&list=PLNIs-AWhQzckr8Dgmgb3akx_gFMnpxTN5\" rel=\"nofollow noreferrer\">Excel VBA Introduction Part 5 - Selecting Cells (Range, Cells, Activecell, End, Offset)</a> will explain why you rarely need to Select or Activate an Object.</p>\n\n<p>I would use <code>.Range(\"A1\")</code> instead of <code>.Range(\"A1\").Rows(\"1:1\")</code> because <code>Range.Copy</code> targets the first cell in the destination. </p>\n\n<h2>Refactored Code</h2>\n\n<pre><code>Sub Load()\n LoadDailyWorkbook\n LoadLastWeeksWorkbook\nEnd Sub\n\nSub LoadDailyWorkbook()\n Const A1BJ200 As String = \"A1:BJ200\"\n Const A1L3 As String = \"A1:L3\"\n Dim masterWB As Workbook\n Dim dailyWB As Workbook\n 'Set Current Workbook as Master\n Set masterWB = Application.ThisWorkbook\n 'Set some Workbook as the one you are copying from\n Set dailyWB = getWorkbook(Sheets(\"Control Manager\").Range(\"O2\"))\n\n If Not dailyWB Is Nothing Then\n With dailyWB\n 'Copy the Range from dailyWB and Paste it into the MasterWB\n .Worksheets(\"Summary1\").Range(A1BJ200).Copy masterWB.Worksheets(\"Summary\").Range(\"A1\")\n TrimRange masterWB.Worksheets(\"Summary\").Range(A1BJ200)\n 'repeat for next Sheet\n .Worksheets(\"risk1\").Range(A1BJ200).Copy masterWB.Worksheets(\"risk\").Range(\"A1\")\n TrimRange masterWB.Worksheets(\"risk\").Range(A1BJ200)\n\n 'repeat for CS sheet\n .Worksheets(\"CS today\").Range(A1L3).Copy masterWB.Worksheets(\"CS\").Range(\"A1\").Rows(\"1:1\")\n TrimRange masterWB.Worksheets(\"CS\").Range(A1L3)\n .Close SaveChanges:=False\n End With\n\n End If\nEnd Sub\n\nSub LoadLastWeeksWorkbook()\n Const A1BJ200 As String = \"A1:BJ200\"\n Dim masterWB As Workbook\n Dim lastweekWB As Workbook\n\n 'Set Current Workbook as Master\n Set masterWB = Application.ThisWorkbook\n\n ''''''''''''Get Last Week Data''''''''''''''''''''''\n Set lastweekWB = getWorkbook(Workbooks.Open(Sheets(\"Control Manager\").Range(\"O3\")))\n If Not lastweekWB Is Nothing Then\n With lastweekWB\n 'repeat for next risk Sheet\n .Worksheets(\"risk2\").Range(A1BJ200).Copy masterWB.Worksheets(\"risk_lastweek\").Range(\"A1\")\n TrimRange masterWB.Worksheets(\"risk_lastweek\").Range(A1BJ200)\n\n TrimRange masterWB.Columns(\"A:BB\")\n .Close SaveChanges:=False\n End With\n End If\nEnd Sub\n\nFunction getWorkbook(FullName As String) As Workbook\n If Len(Dir(FullName)) = 0 Then\n MsgBox FullName & \" not found found\", vbCritical, \"File Not Found\"\n Else\n Set getWorkbook = Workbooks.Open(FullName)\n End If\nEnd Function\n\nSub TrimRange(Target As Range)\n Dim results As Variant\n Set Target = Intersect(Target.Parent.UsedRange, Target)\n If Target Is Nothing Then\n Exit Sub\n ElseIf Target.Count = 1 Then\n Target.Value = Trim(Target.Value)\n Exit Sub\n Else\n results = Target.Value\n\n Dim r As Long, c As Long\n For r = 1 To UBound(results)\n For c = 1 To UBound(results, 2)\n results(r, c) = Trim(results(r, c))\n Next\n Next\n Target.Value = results\n End If\n Target.Columns.EntireColumn.AutoFit\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T21:17:35.820",
"Id": "405042",
"Score": "0",
"body": "thanks for this, getting `type mismatch` error on `Set Target = Intersect(Target.Parent, Target)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T21:21:50.003",
"Id": "405045",
"Score": "0",
"body": "@excelguy I updated the code. Should have been `Target.Parent.UsedRange`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T21:41:03.853",
"Id": "405056",
"Score": "0",
"body": "overflow error now lol, `Target = Target.Value`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T23:28:35.483",
"Id": "405066",
"Score": "0",
"body": "Hmmm....I've been writing javascript so I put `Else If` instead of `ElseIf ` but it should be a syntax error. I don't know why you would get an overflow error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T14:06:42.730",
"Id": "405144",
"Score": "0",
"body": "Not sure either, ill look into it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-15T07:44:59.247",
"Id": "405329",
"Score": "0",
"body": "@excelguy I can't believe I made that mistake. Anyway `Target= Target.Value` should be `results = Target.Value`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-17T14:52:41.490",
"Id": "405545",
"Score": "0",
"body": "lol now im getting error on `results = Target.Value`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T04:48:26.293",
"Id": "405672",
"Score": "0",
"body": "@excelguy are there any errors in the range (e.g. `#N/A`,`#NULL!`, `#REF!`, `#DIV/0!`)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T17:24:51.757",
"Id": "405744",
"Score": "0",
"body": "weirdly I get my overflow error once I step past `Set getWorkbook = Workbooks.Open(FullName)` . So open the workbook opens I get the overflow error. I can open the workbook manually and I do not get the error. So it looks like it doesnt even get to the copy and paste part of the code yet. But for some reason the error is on `results = Target.Value`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T20:37:47.523",
"Id": "405763",
"Score": "0",
"body": "That's very strange"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T20:39:19.800",
"Id": "209561",
"ParentId": "209548",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T18:02:42.473",
"Id": "209548",
"Score": "1",
"Tags": [
"vba"
],
"Title": "Opening a workbook and copying pages to master workbook"
} | 209548 |
<p>This is a simple program to run a command-line program with given parameters and verify that it writes the expected output to stdout or stderr. The specification file is passed as the first argument. It's formatted like this:</p>
<pre><code>echo foo -> foo
man -> What manual page do you want?
</code></pre>
<p>with program and arguments to the left of -> and output on the right.</p>
<p>I don't often work so low-level, so I'm most interested in whether I'm managing resources properly. </p>
<pre><code>#define _GNU_SOURCE
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAX_ARGS 10
#define MAX_LINE 256
const char* parse_args(char **args, const char *line)
{
size_t index = 0;
size_t delimiter_index = 0;
while (args[index] != NULL && index < MAX_ARGS - 1)
{
++index;
args[index] = strtok(NULL, " ");
if (args[index] && strncmp(args[index], "->", 2) == 0)
{
delimiter_index = index;
args[index+1] = strtok(NULL, "\n");
break;
}
}
args[delimiter_index] = '\0';
const char *expected_result = args[delimiter_index + 1];
if (delimiter_index == 0 || expected_result == NULL)
{
fprintf(stderr, "Line <%s> is malformed\n", line);
return NULL;
}
if (strlen(expected_result) > MAX_LINE)
{
fprintf(stderr,
"Invalid specification. Only results less than %d chars supported",
MAX_LINE);
return NULL;
}
return expected_result;
}
bool run_test(char *line)
{
char *args[MAX_ARGS] = {};
args[0] = strtok(line, " ");
if (!args[0]) return true;
const char* expected_result = parse_args(args, line);
if (!expected_result)
{
return false;
}
int stdout_pipe[2];
if (pipe(stdout_pipe) != 0)
{
fprintf(stderr, "Unable to open pipe\n");
return false;
}
pid_t pid = fork();
if (pid == -1)
{
fprintf(stderr, "Unable to fork process\n");
return false;
}
if (pid == 0)
{
// Redirect streams so caller can read stdout
dup2(stdout_pipe[1], STDOUT_FILENO);
dup2(stdout_pipe[1], STDERR_FILENO);
close(stdout_pipe[0]);
execvp(args[0], args);
// exec* only ever returns if it fails
fprintf(stderr, "Failed to execute test program: %s\n",
strerror(errno));
return false;
}
close(stdout_pipe[1]);
char actual_result[MAX_LINE] = {};
ssize_t bytes_read = read(stdout_pipe[0], actual_result, MAX_LINE);
if (bytes_read == -1)
{
fprintf(stderr, "Unable to read program output\n");
return false;
}
// Strip newline
if (actual_result[bytes_read - 1] == '\n')
{
actual_result[bytes_read - 1] = '\0';
}
if (strcmp(actual_result, expected_result) != 0)
{
fprintf(stderr, "Test Failed: ");
for (int arg = 0; arg < MAX_ARGS; ++ arg)
{
if (!args[arg]) break;
fprintf(stderr, "%s ", args[arg]);
}
fprintf(stderr, "\n");
fprintf(stderr, "Expected: %s\n", expected_result);
fprintf(stderr, "Actual: %s\n", actual_result);
return false;
}
return true;
}
int main(int argc, char *argv[])
{
if (argc != 2)
{
fprintf(stderr, "Usage: %s <test_specification>\n", argv[0]);
return 1;
}
const char *spec_pathname = argv[1];
FILE* spec = fopen(spec_pathname, "r");
if (!spec)
{
fprintf(stderr, "Cannot open <%s> for reading\n", spec_pathname);
return 1;
}
int return_code = 0;
char *line = NULL;
size_t line_length = 0;
while (getline(&line, &line_length, spec) != -1)
{
if (!run_test(line))
{
return_code = 1;
}
}
free(line);
return return_code;
}
</code></pre>
| [] | [
{
"body": "<pre><code>while (args[index] != NULL && index < MAX_ARGS - 1)\n</code></pre>\n\n<p>I suggest that you refactor this loop a little bit; here's one option:</p>\n\n<pre><code>for (size_t index = 1; index < MAX_ARGS && args[index]; index++) { // ...\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>args[delimiter_index] = '\\0';\n</code></pre>\n\n<p>if it works without warning, that's only by accident. You're confusing pointer assignment with character assignment. It should actually be</p>\n\n<pre><code>args[delimiter_index] = NULL;\n</code></pre>\n\n<p>In all likelihood, both <code>parse_args</code> and <code>run_test</code> should be <code>static</code> because no one else is importing them.</p>\n\n<p>For code like</p>\n\n<pre><code>if (pipe(stdout_pipe) != 0)\n</code></pre>\n\n<p>You should strongly consider calling <code>perror</code> to get a human-readable error string.</p>\n\n<p>You can combine these <code>fprintf</code> calls and still have the strings on separate lines:</p>\n\n<pre><code> fprintf(stderr, \"\\n\");\n fprintf(stderr, \"Expected: %s\\n\", expected_result);\n fprintf(stderr, \"Actual: %s\\n\", actual_result);\n</code></pre>\n\n<p>can be something like</p>\n\n<pre><code> fprintf(stderr, \"\\n\"\n \"Expected: %s\\n\"\n \"Actual: %s\\n\", expected_result, actual_result);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T19:31:14.023",
"Id": "209556",
"ParentId": "209552",
"Score": "2"
}
},
{
"body": "<ul>\n<li><p><code>fprintf(stderr, \"Unable to read program output\\n\");</code> loses important information: exactly why the program output couldn't be read. Prefer <code>perror</code>.</p>\n\n<p>Ditto for other <code>fprintf(stderr, ....)</code>.</p></li>\n<li><p>The parent doesn't <code>wait</code> for children. You may produce plenty of zombies.</p></li>\n<li><p>The parent doesn't <code>close(stdout_pipe[0]);</code> when done with a child. You may run out of file descriptors.</p></li>\n<li><p>The spec file format seems naive:</p>\n\n<ul>\n<li>There is no way to deal with a multi-line output.</li>\n<li>It mixes child's <code>stdout</code> and <code>stderr</code>. If the child produces both, their order is unpredictable.</li>\n<li>It doesn't specify the child's return status.</li>\n</ul></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T20:49:00.940",
"Id": "209563",
"ParentId": "209552",
"Score": "3"
}
},
{
"body": "<h1>Conformance</h1>\n<p>A couple of violations of Standard C:</p>\n<pre class=\"lang-none prettyprint-override\"><code>209552.c: In function ‘run_test’:\n209552.c:52:28: warning: ISO C forbids empty initializer braces [-Wpedantic]\n char *args[MAX_ARGS] = {};\n ^\n209552.c:92:36: warning: ISO C forbids empty initializer braces [-Wpedantic]\n char actual_result[MAX_LINE] = {};\n ^\n</code></pre>\n<p>Another pedantic point, which you're probably aware of: this clearly targets POSIX systems, where we are guaranteed that <code>argc</code> is at least 1, and so <code>argv[0]</code> is always usable; however, when writing portable programs, code like this can be dangerous:</p>\n<blockquote>\n<pre><code>if (argc != 2)\n{\n fprintf(stderr, "Usage: %s <test_specification>\\n", argv[0]);\n return 1;\n}\n</code></pre>\n</blockquote>\n<h1>Input file format</h1>\n<p>There are some severe limitations to the input file format. It's impossible to specify commands or arguments that contain space characters, and it's impossible to specify output of more than one line.</p>\n<p>Addressing the last point first, perhaps we should consider writing one file per test, with the command as first line, and then all subsequent lines being the expected output. Adapt the program to read loop over the command-line arguments, reading every file that's specified. It's easy for users to test lots of commands, using wildcards (e.g. <code>run_tests *.test</code>).</p>\n<p>As for the first problem, we could consider using a shell to parse it instead of <code>strtok()</code> - just take the whole command and pass it to <code>/bin/sh -c</code>.</p>\n<p>Perhaps we also want to check the exit status of the program under test - I think that's an important part of the program's interface.</p>\n<h1>Output format</h1>\n<p>For syntax errors in the file format, we could improve the error message by writing the file name and line number, rather than just the contents. This would then be consistent with error messages from compilers and other tools, which can be parsed (such as in Emacs, where <code>goto-error</code> will take the user directly to the problem line).</p>\n<h1>Parsing function</h1>\n<p>The parsing might be simpler if we first divide at <code>-></code> (or newline, in my proposed input format), and then process the input and output sides separately. We really should emit a good error when the <code>MAX_ARGS</code> limit is violated (as we do for <code>MAX_LINE</code>). A worthwhile enhancement would be to eliminate these arbitrary limits.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T10:30:28.997",
"Id": "209600",
"ParentId": "209552",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "209563",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T18:27:37.453",
"Id": "209552",
"Score": "2",
"Tags": [
"c",
"unix",
"c99"
],
"Title": "Command line test runner"
} | 209552 |
<p>A bit of context:
I have 100 addresses that can send transactions to a blockchain, and I have a web app that works like this:</p>
<ol>
<li>Get request and handle it in a thread</li>
<li>Get a free address from the queue</li>
<li>Send a transaction</li>
<li>Return address to the queue</li>
</ol>
<p>It's important to know that one address cannot send two transactions at once.</p>
<p>My approach was to make a custom python queue that uses a dict of "address: free/taken" instead of the normal queue.</p>
<p>Its good for two reasons:</p>
<ol>
<li>I need to be able to get a random address for the dict</li>
<li>The base queue get and put method already handle thread-locking and timeout.</li>
</ol>
<p>This seems to work, but I would like some feedback on it.</p>
<pre><code>from queue import Queue
from enum import Enum
import random
class ChannelStatuses(Enum):
FREE = 0
TAKEN = 1
UNDERFUNDED = 2
class ChannelDict(Queue):
def __init__(self, channels_seeds):
# Init base queue
super(ChannelDict, self).__init__(len(channels_seeds))
# Change queue from a 'dqueue' object to a dict full of free channels
self.queue = {channel: ChannelStatuses.FREE for channel in channels_seeds}
def _get(self):
# Get a list of all free channels
free_channels = self.get_free_channels()
# Select a random free channel
selected_channel = random.choice(free_channels)[0]
# Change channel state to taken
self.queue[selected_channel] = ChannelStatuses.TAKEN
return selected_channel
def _put(self, channel):
# Change channel state to free
self.queue[channel] = ChannelStatuses.FREE
def _qsize(self):
# Base queue checks if the queue is not empty by checking the length of the queue (_qsize() != 0)
# We need to check it by checking how many channels are free
return len(self.get_free_channels())
def get_free_channels(self):
# Get a list of channels with "FREE" status
return list(filter(lambda item: item[1] == ChannelStatuses.FREE, self.queue.items()))
</code></pre>
<p>"channel" is another word for "address"</p>
<p>Used this answer as inspiration: <a href="https://stackoverflow.com/a/16506527/2126254">https://stackoverflow.com/a/16506527/2126254</a></p>
<p>More context on how get/put are used,these methods are exposed:</p>
<pre><code>@contextmanager
def get_channel(self, timeout=CHANNEL_QUEUE_TIMEOUT):
"""
Get the next available channel
:param float timeout: (Optional) How long to wait before raising an exception
:return next avilable channel
:rtype str
:raises KinErrors.ChannelBusyError
"""
try:
channel = self.channels.get(True, timeout=timeout)
except queue.Empty:
raise ChannelsBusyError()
try:
yield channel
finally:
self.put_channel(channel)
def put_channel(self, timeout=CHANNEL_PUT_TIMEOUT):
"""
Return a channel to the queue
:param float timeout: (Optional) How long to wait before raising an exception
:raises KinErrors.ChannelsFullError
"""
try:
self.channels.put(True, timeout=timeout)
except queue.Full:
raise ChannelsFullError()
</code></pre>
<p>And the user will use: </p>
<pre><code>with get_channel() as channel:
#send transaction
</code></pre>
| [] | [
{
"body": "<h3>1. Review</h3>\n\n<ol>\n<li><p>There is no docstring for <code>ChannelDict</code>. The text in the post would make a good start.</p></li>\n<li><p>A <code>ChannelDict</code> is not a dictionary (it doesn't support the mapping interface, <code>__getitem__</code> and <code>__setitem__</code> and so on), so the name is a bit misleading.</p></li>\n<li><p><code>ChannelDict</code> is not specialized for channels: it would work for any kind of object. A name like <code>RandomQueue</code> would make it easier for the reader to understand the purpose of the code.</p></li>\n<li><p><code>ChannelDict</code> inherits from <a href=\"https://docs.python.org/3/library/queue.html#queue-objects\" rel=\"nofollow noreferrer\"><code>queue.Queue</code></a> but has a different interface for initialization (it takes an iterable of channels instead of a maximum size). Perhaps this is convenient for your use case but it makes the code a little harder to understand because you can't just say \"it's just like a Queue except that it gets items in random order\", you have to explain the difference in initialization and that you can't set a maximum size.</p></li>\n<li><p>The algorithm for getting a random item from the queue takes time proportional to the number of items, because <code>get_free_channels</code> has to loop over all the items looking for any that are free.</p></li>\n<li><p><code>ChannelStatuses.UNDERFUNDED</code> is declared but not used.</p></li>\n</ol>\n\n<h3>2. Revised code</h3>\n\n<p>One way to efficiently pick a random item (instead of looping over all the items) is to keep the available items in a list, and to swap the randomly selected item with the last item in the list before popping the selected item.</p>\n\n<pre><code>from queue import Queue\nfrom random import randrange\n\nclass RandomQueue(Queue):\n \"\"\"Variant of Queue that retrieves items in a random order.\"\"\"\n def _init(self, maxsize):\n self.queue = []\n\n def _qsize(self):\n return len(self.queue)\n\n def _put(self, item):\n self.queue.append(item)\n\n def _get(self):\n queue = self.queue\n i = randrange(len(queue))\n queue[i], queue[-1] = queue[-1], queue[i]\n return queue.pop()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T14:38:12.560",
"Id": "209620",
"ParentId": "209558",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "209620",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T19:58:30.930",
"Id": "209558",
"Score": "7",
"Tags": [
"python",
"queue"
],
"Title": "Custom implementation of python queue to use dict instead of dqueue"
} | 209558 |
<p>Relatively new here so please let me know if I'm doing something wrong. </p>
<p>I'm mostly wondering if there's any additional way I can make this code more efficient. Specifically the moveset and win condition part of the code feels unnecessarily long or overcomplicated. Still a beginner in python, so any feedback regarding syntax is also appreciated! Thank you!</p>
<pre><code>#Contains all basic variables for ease of coding
class Player():
symbols = ['O','X']
def __init__(self, number):
self.wins = 0
self.number = number
self.symbol = self.symbols[number]
#2D list to represent the 3x3 board
def createBoard():
a = ['', '', '']
b = ['', '', '']
c = ['', '', '']
return [a, b, c]
board = createBoard()
#Makes the board look nicer for user; numbers as placeholder for empty spaces
def printBoard():
i = 0
for row in board:
print("---------------")
for place in row:
i += 1
if place == '':
print("|",i,"|", end='')
else:
print("|",place,"|", end='')
print("")
print("---------------")
#Receives numbers to return x and y position of the 2d list
def getMove():
#Any other more efficient way for this?
moveset = {
'1': (0,0),
'2': (1,0),
'3': (2,0),
'4': (0,1),
'5': (1,1),
'6': (2,1),
'7': (0,2),
'8': (1,2),
'9': (2,2)
}
print("Please enter the number of the spot to place your move",end='')
xpos, ypos = moveset[input("> ")]
return xpos, ypos
#changes the board with received x and y
def placeMove(xpos, ypos, player):
global board
board[ypos][xpos] = player.symbol
#Checkes if the spot has been filled
def validateMove(xpos, ypos):
if board[ypos][xpos] != '':
print("Cannot place there!")
return False
return True
#Checks win conditions; any more efficient way for this as well?
def checkWin():
for row in board:
if row[0]==row[1]==row[2]:
return row[0]
for i in range(0,3):
if board[0][i]==board[1][i]==board[2][i]:
return board[0][i]
if board[0][0]==board[1][1]==board[2][2]:
return board[1][1]
elif board[0][2]==board[1][1]==board[2][0]:
return board[1][1]
for row in board:
for spot in row:
if spot == '':
return False
return 2
def switchPlayer(currentPlayer):
if currentPlayer.number == 0:
return 1
else:
return 0
#game loop
def game():
global board
playerList = [Player(0), Player(1)]
game = True
currentPlayer = playerList[0]
printBoard()
while game:
print("Current Player:",currentPlayer.number+1,)
xpos, ypos = getMove()
#repeats until valid input
while not validateMove(xpos, ypos):
xpos, ypos = getMove()
placeMove(xpos, ypos, currentPlayer)
printBoard()
if checkWin() == currentPlayer.symbol:
print("Player",currentPlayer.number+1, "wins!")
game = False
elif checkWin() == 2:
print("The game is a draw!")
game = False
else:
currentPlayer = playerList[switchPlayer(currentPlayer)]
#Should I just make the game() the main() function?
def main():
game()
if __name__ == "__main__":
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T22:50:35.607",
"Id": "405064",
"Score": "0",
"body": "Not an answer, but you might want to read https://rosettacode.org/wiki/Tic-tac-toe#Python to see how others did it."
}
] | [
{
"body": "<pre><code>symbols = ['O','X']\n</code></pre>\n\n<p>This will not change, so it doesn't need to be mutable. It's better represented as a string:</p>\n\n<pre><code>symbols = 'OX'\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>def createBoard():\n a = ['', '', '']\n b = ['', '', '']\n c = ['', '', '']\n return [a, b, c]\n</code></pre>\n\n<p>can simply be</p>\n\n<pre><code>def create_board():\n return [['']*3 for _ in range(3)]\n</code></pre>\n\n<p>Note that the convention for Python is snake_case, not camelCase.</p>\n\n<p><code>getMove</code> can be made more efficient. You do not need a dictionary.</p>\n\n<pre><code>i = int(input('Please enter the number of the '\n 'spot to place your move > ')) - 1\nreturn i%3, i//3\n</code></pre>\n\n<p>You're using <code>board</code> as a global, which is a code smell. Most of these methods, along with the board member, should be put into a class.</p>\n\n<p>This:</p>\n\n<pre><code>if currentPlayer.number == 0:\n return 1\nelse:\n return 0\n</code></pre>\n\n<p>can be:</p>\n\n<pre><code>return 1 - current_player.number\n</code></pre>\n\n<p>Your boolean <code>game</code> variable is unnecessary. Rather than setting it to false, simply break out of the loop.</p>\n\n<p>At the top of the file, there should be a shebang:</p>\n\n<pre><code>#!/usr/bin/env python3\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T22:49:35.880",
"Id": "209571",
"ParentId": "209560",
"Score": "2"
}
},
{
"body": "<p>In addition to Reinderien's comments:</p>\n\n<hr>\n\n<p><code>checkWin()</code> first checks <code>board[0][0]==board[0][1]==board[0][2]</code> and returns the \"winning\" symbol (a string), if the match was found.</p>\n\n<p>This means that, with the following board:</p>\n\n<pre><code> | | \n---+---+---\n X | X | \n---+---+---\n O | O | O \n</code></pre>\n\n<p><code>checkWin()</code> returns <code>''</code>, and <code>checkWin() == currentPlayer.symbol</code> is false, so \"O\" doesn't win. And \"X\" can fill their row on their move, and will be declared the winner in two more moves!</p>\n\n<p>The only player who can win, is the one that just made a move, so pass that player's symbol to the <code>checkWin()</code> call, and explicitly check for that player winning:</p>\n\n<pre><code>def checkWin(symbol):\n for row in board:\n if row[0] == row[1] == row[2] == symbol:\n return symbol\n</code></pre>\n\n<hr>\n\n<p><code>checkWin()</code> returns 3 different types of values!</p>\n\n<ul>\n<li><code>str</code> if a winner is detected</li>\n<li><code>bool</code> if there are still moves which can be made</li>\n<li><code>int</code> if the game is tied.</li>\n</ul>\n\n<p>This is just plain wrong. Pick one return type. For instance, you could use <code>int</code>, and return <code>0</code> for game not over, <code>1</code> for a win by the current player, and <code>-1</code> for a draw game.<br>\nOr you could use <code>str</code>, and return <code>\"X\"</code> or <code>\"O\"</code> for a win by that player, <code>\"Cat's game\"</code> for a draw, and <code>\"\"</code> for the game not over. Then, created named constants for the values, and use those names in your code, instead of the actual values. Eg)</p>\n\n<pre><code>GAME_HAS_WINNER = 1\nGAME_IS_A_DRAW = -1\nGAME_IS_NOT_OVER = 0\n\n# ...\n\ndef game():\n\n # ...\n\n while True:\n # ...\n state = checkWin(currentPlayer.symbol)\n if state == GAME_HAS_WINNER:\n # ... declare winner\n break\n elif state == GAME_IS_A_DRAW:\n # ... declare a draw\n break\n else:\n # ...\n</code></pre>\n\n<p>Better would be to create an <code>Enum</code> for the return code, if you've learnt that.</p>\n\n<hr>\n\n<p>You can simplify your <code>createBoard()</code> & <code>printBoard()</code> functions, and at the same time fix the bug in <code>checkWin()</code> by initializing the board with the number characters, instead of empty strings.</p>\n\n<pre><code>def createBoard():\n return [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]\n\ndef printBoard():\n for row in board:\n print(\"---------------\")\n for place in row:\n print(\"|\", place, \"|\", end='')\n print(\"\")\n print(\"---------------\")\n</code></pre>\n\n<p>You'll need a different way to check for a draw game. The simplest would be to remove that test from <code>checkWin()</code> and change your <code>while</code> loop into a <code>for</code> loop that runs for at most 9 turns. If you finish the loop without <code>break</code>-ing out of the loop, the <code>else:</code> clause gets executed.</p>\n\n<pre><code>def game():\n\n # ...\n\n for _ in range(9):\n # ...\n if checkWin(currentPlayer.symbol) == GAME_HAS_WINNER:\n # ... announce winner\n break\n # ...\n else:\n # ... announce draw game\n</code></pre>\n\n<hr>\n\n<p>You can use list comprehension to simplify <code>checkWin()</code>. For instance, checking only for a win by a given symbol, and returning <code>True</code> for a win, and <code>False</code> otherwise:</p>\n\n<pre><code>def checkWin(symbol):\n if any( all(board[i][j] == symbol for i in range(3)) for j in range(3)):\n return True\n if any( all(board[i][j] == symbol for j in range(3)) for i in range(3)):\n return True\n if all(board[i][i] == symbol for i in range(3)):\n return True\n return all(board[i][2-i] == symbol for i in range(3)):\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T23:55:33.673",
"Id": "209574",
"ParentId": "209560",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209574",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T20:21:35.257",
"Id": "209560",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"console",
"tic-tac-toe"
],
"Title": "Simple Python 3 TicTacToe Game"
} | 209560 |
<p>I have a table that in one of the columns exists a list of file names. The names comes from other tables and the files in a folder.</p>
<p>Not all the files are used, may be attached to parcels that no longer are active. My list is of only the active parcels.</p>
<p>After creating the table I want to go through the folder of files and move the files that are being used(exist in the table) to another folder.</p>
<p>Currently I iterate the files in the folder and test whether each file one at a time returns a record or not using an SQL command.</p>
<p>This works, but the consistent checking back to the database is slow.</p>
<p>Here is the code as it sits now:</p>
<pre><code>param(
[string] $src,
[string] $dest,
[string] $table
)
$sql_instance_name = 'db'
$db_name = 'DB2'
$sql_user = 'user'
$sql_user_pswd = 'password'
Get-ChildItem -Path $src -Recurse -File | ForEach-Object {
$query = "select * from " + $table + " WHERE FILE_NAME Like '" + $_.BaseName + $_.Extension + "'"
#write-output $query
$expcsv = invoke-sqlcmd -Username $sql_user -PASSWORD $sql_user_pswd -Database $db_name -Query $query -serverinstance $sql_instance_name
if($expcsv -ne $null)
{
$nextName = Join-Path -Path $dest ( $_.BaseName + $_.EXTENSION)
Write-Output $nextName
$_ | Move-Item -Destination $nextName
}
}
</code></pre>
<p>Is there a way to load the data into memory, and search that instead of going back and forth from the database? I have to assume it would be quicker.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T13:18:11.460",
"Id": "405249",
"Score": "0",
"body": "You could run `$query = \"select * from \" + $table; $expcsvS = invoke-sqlcmd -query $query …` _before_ `Get-ChildItem -Path $src -Recurse -File | ForEach-Object {` Then I'd suppose that you can check `($_.BaseName + $_.Extension) -in $expcsvS.FILE_NAME` or alike (I don't know `FILE_NAME` format)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T14:53:54.600",
"Id": "405256",
"Score": "0",
"body": "@JosefZ write it up, it works and is much faster."
}
] | [
{
"body": "<p><a href=\"https://docs.microsoft.com/en-us/powershell/module/sqlserver/invoke-sqlcmd?view=sqlserver-ps#outputs\" rel=\"nofollow noreferrer\">Output from <code>invoke-sqlcmd</code></a> is <em>Formatted table</em> i.e. something like <code>PSCustomObject[]</code> array (or collection). Hence, one could address its columns as <code>.FILE_NAME</code> properties and apply comparison operators <code>-in</code>, <code>-contains</code>, <code>-match</code> etc. (elaborated from <a href=\"https://codereview.stackexchange.com/questions/209567/quickly-check-whether-file-name-is-in-column-in-an-sql-table-and-move-to-new-fol?noredirect=1#comment405249_209567\">my original comment</a>):</p>\n\n<pre><code>param( \n [string] $src, \n [string] $dest, \n [string] $table\n )\n\n$sql_instance_name = 'db'\n$db_name = 'DB2'\n$sql_user = 'user'\n$sql_user_pswd = 'password'\n\n$query = \"select * from $table\"\n$expcsvS = invoke-sqlcmd -Username $sql_user -PASSWORD $sql_user_pswd `\n -Database $db_name -Query $query -serverinstance $sql_instance_name\n\nGet-ChildItem -Path $src -Recurse -File | ForEach-Object {\n\n if ( $_.Name -in $expcsvS.FILE_NAME )\n {\n $nextName = Join-Path -Path $dest -ChildPath $_.Name\n Write-Output $nextName\n $_ | Move-Item -Destination $nextName\n }\n}\n</code></pre>\n\n<p>Note that I use <code>$_.Name</code> instead of <code>($_.BaseName + $_.Extension)</code> as for files, the following code snippet always returns <code>True</code>.</p>\n\n<pre><code>(Get-ChildItem -Recurse -File | \n Where-Object { $_.Name -ne ($_.BaseName + $_.Extension) }) -eq $null\n</code></pre>\n\n<p>Also note that <code>if ( $_.Name -in $expcsvS.FILE_NAME ) {}</code> is equivalent to any of (incomplete list):</p>\n\n<pre><code>if ( $expcsvS.FILE_NAME -match \"^$($_.Name)$\") {}\nif ( $expcsvS.FILE_NAME -contains $_.Name ) {}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T20:57:10.127",
"Id": "209697",
"ParentId": "209567",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "209697",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T21:51:51.673",
"Id": "209567",
"Score": "0",
"Tags": [
"sql-server",
"powershell"
],
"Title": "Quickly check whether file name is in column in an SQL Table and move to new folder"
} | 209567 |
<p>I am implementing a library (Linux) and I created some functions to block new instances of a running program and I was wonder if there are some better improvements for it.</p>
<p>Here is a program which describes what I am trying:</p>
<pre><code>#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#define SECONDS 20
static char *program_path = NULL;
char *my_strtok ( char *const msg, const char *const ch );
void block_new_instance ( const char *const instance );
void clean_instance ( void );
int main ( int argc, char *argv[] )
{
if ( argc != 1 )
{
printf( "\n\t*** Arguments are NOT allowed. ***\n" );
exit( EXIT_FAILURE );
}
block_new_instance( argv[ 0 ] );
sleep( SECONDS );
}
void block_new_instance( const char *const instance )
{
char prog_name[ strlen( instance ) + 1 ];
memset( prog_name, '\0', sizeof( prog_name ) );
strcpy( prog_name, instance );
char *buffer = my_strtok( prog_name, "/" );
struct flock file_lock;
char *dir = getenv( "HOME" );
if ( dir == NULL || dir[0] != '/' )
{
fprintf( stderr, "Wrong Directory, getenv(): %s (%d)\n", strerror( errno ), errno );
exit( EXIT_FAILURE );
}
program_path = calloc( sizeof ( *program_path ), strlen( dir ) + ( strlen( buffer ) + sizeof ( "/" ) ) );
if ( program_path == NULL )
{
printf( "Error, malloc()\n" );
exit ( EXIT_FAILURE );
}
memcpy( program_path, dir, strlen( dir ) );
memcpy( program_path + strlen( dir ), "/", sizeof( "/") );
memcpy( program_path + ( strlen( dir ) + strlen( "/" ) ), buffer, strlen( buffer ) );
int file_desk = open( program_path, O_RDWR | O_CREAT, 0600 );
if ( file_desk < 0 )
{
fprintf( stderr, "open: %s (%d)\n", strerror( errno ), errno );
exit( EXIT_FAILURE );
}
file_lock.l_start = 0;
file_lock.l_len = 0;
file_lock.l_type = F_WRLCK;
file_lock.l_whence = SEEK_SET;
if ( fcntl( file_desk, F_SETLK, &file_lock ) < 0 )
{
fprintf( stderr, "%s is already running\n", buffer );
exit( EXIT_FAILURE );
}
atexit( clean_instance );
}
char *my_strtok( char *const msg, const char *const ch )
{
char *ret = NULL;
char *tmp = strtok( msg, ch );
while ( tmp != NULL )
{
ret = tmp;
tmp = strtok( NULL, ch );
}
if ( ret == NULL )
{
return NULL;
}
return ret;
}
void clean_instance( void )
{
unlink ( program_path );
free ( program_path );
}
</code></pre>
<p>Possible Outputs are:</p>
<blockquote>
<p>*** Arguments are NOT allowed. **</p>
</blockquote>
<p>or:</p>
<blockquote>
<p>Program is already running</p>
</blockquote>
<p>I would like to know which improvements are needed?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T00:25:34.667",
"Id": "405071",
"Score": "1",
"body": "When/Why would you use this? More context would help with figuring out possible (unwanted) side-effects."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T10:32:55.217",
"Id": "405105",
"Score": "0",
"body": "The usual motivation is for daemons - but most platforms have libraries or utility programs to manage pidfiles for you (in the right place) so you don't have to roll your own. For example, Debian has `start-stop-daemon` (and even if you don't use it, you can follow its conventions)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T10:43:38.947",
"Id": "405112",
"Score": "0",
"body": "@Mast there is about an application which it will be compiled/installed in `&HOME` and I need to prevent it for running more instance of the same program on that Machine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T12:32:33.793",
"Id": "405128",
"Score": "1",
"body": "Please read [\"*What should I do when someone answers my question?*\"](https://codereview.stackexchange.com/help/someone-answers)"
}
] | [
{
"body": "<ul>\n<li><p>Three calls to <code>memcpy</code> seem to emulate <code>sprintf(program_path, \"%s/%s\", dir, buffer);</code></p></li>\n<li><p><code>my_strtok</code> is a not very clean substitute for <code>dirname</code>.</p></li>\n<li><p>The lock file is always created in the home directory, and only accounts for the base name of the executable. It means that <code>/usr/foo</code> would block <code>/opt/foo</code>.</p></li>\n<li><p>The locker does not account for the links (again, it only cares about the base name of the executable). Different names may refer to the physically same file; invocations via links would not lock each other out.</p></li>\n<li><p>A callback registered with <code>atexit</code> is only guaranteed to be called if the program exits normally. If the program is terminated by the signal, the lock file would not be removed.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T09:21:24.100",
"Id": "405093",
"Score": "0",
"body": "Ar you suggesting that I change `char *dir = getenv( \"PATH\" );` to `const char *dir = \"/tmp\";` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T09:23:23.023",
"Id": "405094",
"Score": "0",
"body": "`my_strtok is a not very clean substitute for dirname.` I was thinking to call `extern char *__progname` but I am not familiar with it. Does Apply to all Linux environments or only some of them?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T10:27:29.253",
"Id": "405101",
"Score": "0",
"body": "`A callback registered with atexit is only guaranteed to be called if the program exits normally. ` - I updated my Question and added a function called `catch_ctrl_c_and_exit` and used as argument for SIGNAL `signal( SIGINT, catch_ctrl_c_and_exit );` and I also changed `char *dir = getenv( \"PATH\" );` to `const char *dir = \"/tmp\";`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T10:32:30.863",
"Id": "405104",
"Score": "0",
"body": "Using `CTRL+C` or `killall -9 PID` seems to remove the file from `/tmp/`. Do I need some more features?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T02:02:46.720",
"Id": "209580",
"ParentId": "209573",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209580",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-12T23:33:49.170",
"Id": "209573",
"Score": "2",
"Tags": [
"c",
"linux"
],
"Title": "Block same instance of a program for running again"
} | 209573 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.