body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>Python has amazing sci-kit learn library but I am building some projects on C++ with involves some machine learning algorithms. I found machine learning libraries in C++ involves more dependencies so I have decided to implement a library without dependencies It would be nice if you could review the code.</p>
<p>I have implemented least squares regression below.</p>
<p><strong>lsr.h</strong></p>
<pre><code>// SWAMI KARUPPASWAMI THUNNAI
#pragma once
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <vector>
/*
Implementation of simple linear regression or Least Squares Regression
Written By: Visweswaran N @ 2019-08-26
*/
class simple_linear_regression
{
private:
// ~~~~~~~~~~~~~ PRIVATE VARIABLES ~~~~~~~~~~~~
unsigned int N=0.0;
// Independent and dependent variable
std::vector<double> X;
std::vector<double> y;
// XX and Xy
std::vector<double> XX;
std::vector<double> Xy;
// To print into console
bool verbose;
// Summation
double sigma_X = 0.0;
double sigma_y = 0.0;
double sigma_XX = 0.0;
double sigma_Xy = 0.0;
// Slope
double m = 0.0;
// Bias (or) Intercept
double b = 0.0;
// ~~~~~~~~~~ Methods ~~~~~~~~~~~~~
void print(std::string message);
void calculate_N();
void x_square();
void x_cross_y();
void calculate_sigma();
void calculate_slope();
void calculate_bias();
public:
simple_linear_regression(std::string model_name);
simple_linear_regression(std::vector<double> X, std::vector<double> y, bool verbose = false);
void train();
double predict(double _X);
void save_model(std::string file_name);
};
</code></pre>
<p><strong>lsr.cpp</strong></p>
<pre><code>// SWAMI KARUPPASWAMI THUNNAI
#include "lsr.h"
void simple_linear_regression::print(std::string message)
{
if (this->verbose) std::cout << message << "\n";
}
void simple_linear_regression::calculate_N()
{
if (this->X.size() == this->y.size())
{
this->N = this->X.size();
}
else
{
throw "SIZE MISMATCH";
}
}
// Calculates the X square and saves it in XX vector
void simple_linear_regression::x_square()
{
print("Calculating X*X");
for (double i : this->X)
{
this->XX.push_back(i*i);
}
}
// Calculates X*y and stores it in Xy vector
void simple_linear_regression::x_cross_y()
{
print("Calculating X*y");
for (unsigned int index = 0; index < N; index++)
{
this->Xy.push_back(this->X[index] * this->y[index]);
}
}
// Calculate all the summation
void simple_linear_regression::calculate_sigma()
{
// Calculate summation of X
print("Calculating sigma for X");
for (double i : this->X)
{
this->sigma_X += i;
}
// Calculate the summation of Y
print("Calculating sigma for Y");
for (double i : this->y)
{
this->sigma_y += i;
}
// Calculate the summation of XX
print("Calculating sigma for X*X");
for (double i : this->XX)
{
this->sigma_XX += i;
}
// Calculate the summation of Xy
print("Calculating sigma for X*y");
for (double i : this->Xy)
{
this->sigma_Xy += i;
}
}
// Calculate our slope - m
void simple_linear_regression::calculate_slope()
{
print("Calculating slope");
this->m = ((this->N * this->sigma_Xy) - (this->sigma_X * this->sigma_y)) / ((this->N * this->sigma_XX) - (this->sigma_X * this->sigma_X));
}
// Calculate our intercept (or) bias
void simple_linear_regression::calculate_bias()
{
print("Calculating Intercept (or) Bias");
this->b = (sigma_y - (this->m * this->sigma_X)) / this->N;
}
// Constructor to load existing model
simple_linear_regression::simple_linear_regression(std::string model_name)
{
std::ifstream file;
file.open(model_name);
if (!file.is_open()) throw "Model cannot be opened!";
std::stringstream stream;
stream << file.rdbuf();
std::string values = stream.str();
unsigned int index = values.find(",");
std::string _m = "";
std::string _b = "";
for (unsigned int i = 0; i < index; i++)
{
_m += values[i];
}
for (unsigned int i = index+1; i < values.size(); i++)
{
_b += values[i];
}
this->m = std::stod(_m);
this->b = std::stod(_b);
}
// constructor for start training new model
simple_linear_regression::simple_linear_regression(std::vector<double> X, std::vector<double> y, bool verbose)
{
this->X = X;
this->y = y;
this->verbose = verbose;
}
// method to train our model, where all methods merges.
void simple_linear_regression::train()
{
print("Training");
this->calculate_N();
this->x_square();
this->x_cross_y();
this->calculate_sigma();
this->calculate_slope();
this->calculate_bias();
print("Model has been trained :)");
}
// Method used for predicting future values
double simple_linear_regression::predict(double _X)
{
return (this->m * _X) + this->b;
}
// A method used to save model so that we do not need to retrain it
void simple_linear_regression::save_model(std::string file_name)
{
std::ofstream file;
file.open(file_name);
if (!file.is_open()) throw "Model cannot be saved because file cannot be opened to write.Check for permissions and make sure the file is not open!";
file << this->m << "," << this->b;
file.close();
}
</code></pre>
<p><strong>Training and saving the model</strong></p>
<pre><code>// SWAMI KARUPPASWAMI THUNNAI
#include "lsr.h"
int main()
{
// X, y, print_debug messages
simple_linear_regression slr({2, 3, 5, 7, 9}, {4, 5, 7, 10, 15}, true);
slr.train();
std::cout << slr.predict(8);
slr.save_model("model.txt");
}
</code></pre>
<p><strong>Loading the saved model:</strong></p>
<pre><code>// SWAMI KARUPPASWAMI THUNNAI
#include "lsr.h"
int main()
{
// X, y, print_debug messages
simple_linear_regression slr("model.txt");
std::cout << slr.predict(8);
}
</code></pre>
<p><strong>Example output:</strong></p>
<pre><code>Training Calculating X*X Calculating X*y Calculating sigma for X
Calculating sigma for Y Calculating sigma for X*X Calculating sigma
for X*y Calculating slope Calculating Intercept (or) Bias Model has
been trained :)
1.82317
</code></pre>
<p><a href="https://github.com/VISWESWARAN1998/sklearn" rel="nofollow noreferrer">Github for easy code download</a></p>
|
[] |
[
{
"body": "<h3>Comments</h3>\n\n<p>Please be sure your comments add something meaningful. For example:</p>\n\n<pre><code>private:\n // ~~~~~~~~~~~~~ PRIVATE VARIABLES ~~~~~~~~~~~~\n unsigned int N=0.0;\n</code></pre>\n\n<p>In this case, the <code>private:</code> already makes it pretty clear that what follows is private. The comment isn't adding anything that wasn't already pretty obvious.</p>\n\n<p>At least in the typical case, the code already answers \"what\" kinds of questions (e.g., <code>public: int n = 0;</code> tells us that <code>N</code> is an int that's publicly accessible.</p>\n\n<p>A comment should usually answer questions about \"why?\" Why does the code do one thing, when another might seem more obvious. Why did you make <code>N</code> public, even though public variables are often rather frowned upon? (and so on).</p>\n\n<h3>Type matching</h3>\n\n<p>Looking at the previous code snippet, we also note that we have <code>N</code> defined as an <code>int</code>, but being initialized with the value <code>0.0</code>, which is a <code>double</code>. Unless you have a reason to do otherwise, it's generally preferable to have the types match, so you'd use just <code>int N = 0;</code>.</p>\n\n<p>As an aside, I'd be less concerned with mismatches that are really just different sizes of what are otherwise similar types. For example, something like <code>unsigned long long foo = 0;</code> is reasonable event though <code>0</code> if of type <code>int</code> rather than <code>unsigned long long</code>. But initializing an integer type with a floating point value tends to suggest some confusion about whether that variable should really be able to hold a fractional value or not.</p>\n\n<h3>Interface Design</h3>\n\n<p>One general piece of guidance about interface design is that you should strive for an interface that's easy to use, and hard to misuse.</p>\n\n<p>So, at least as I see things, the public interface of a linear regression model consists primarily of only two functions: construct the model from some input, and get a prediction from a constructed model. As it stands right now, your class requires that the user explicitly call <code>train</code> before they can use a model. And unfortunately, it looks like they can try to make a prediction without having called <code>train</code>, which (of course) won't work.</p>\n\n<p>At a more detailed level, rather than starting with:</p>\n\n<pre><code>std::vector<double> X;\nstd::vector<double> y;\n</code></pre>\n\n<p>...and then assuring those are the same size in <code>simple_linear_regression::calculate_N()</code>, I'd prefer to start with a simple struct:</p>\n\n<pre><code>struct variable { \n double x; // independent\n double y; // dependent\n};\n</code></pre>\n\n<p>Then have a single <code>std::vector<variable></code> for the rest of the code to work with. This way, it's simply impossible to create mis-matched number of independent/dependent variables, so there's no need for the rest of the code to check that the counts are equal.</p>\n\n<h3>Avoid Boolean parameters</h3>\n\n<p>With code like:</p>\n\n<pre><code>simple_linear_regression slr({2, 3, 5, 7, 9}, {4, 5, 7, 10, 15}, true);\n</code></pre>\n\n<p>It's not immediately obvious what <code>true</code> vs. <code>false</code> as the last parameter means. I'd prefer something like:</p>\n\n<pre><code>simple_linear_regression slr({2, 3, 5, 7, 9}, {4, 5, 7, 10, 15}, DEBUG);\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>simple_linear_regression slr({2, 3, 5, 7, 9}, {4, 5, 7, 10, 15}, NODEBUG);\n</code></pre>\n\n<p>Of course, taking the previous point into account, this would be more like:</p>\n\n<pre><code>simple_linear_regression slr({{2,4},{3,5}, {5, 7}, {7, 10}, {9, 15}}, NODEBUG};\n</code></pre>\n\n<h3>Naming</h3>\n\n<p>I'm not really excited about using the name <code>train</code> for computing a linear regression. <code>train</code> is typically used with things like neural networks to mean something that's just similar enough that the name could easily mislead somebody into believing your code is something rather different than it really is (e.g., something that trains a neural network to simulate linear regression).</p>\n\n<p>As previously noted, however, I'd <em>prefer</em> to eliminate training as a separate step in any case.</p>\n\n<h3>Prefer initialization over assignment</h3>\n\n<p>Consider your constructor:</p>\n\n<pre><code>simple_linear_regression::simple_linear_regression(std::vector<double> X, std::vector<double> y, bool verbose)\n{\n this->X = X;\n this->y = y;\n this->verbose = verbose;\n}\n</code></pre>\n\n<p>Rather than assigning values inside the body of the ctor, I'd prefer to use a member initializer list:</p>\n\n<pre><code>simple_linear_regression::simple_linear_regression(std::vector<double> X,\n std::vector<double> y, \n bool verbose)\n : X(X)\n , Y(Y)\n , verbose(verbose)\n{}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T18:36:12.073",
"Id": "226868",
"ParentId": "226829",
"Score": "2"
}
},
{
"body": "<ul>\n<li><p>C++ is not Java. All these <code>this-></code> can be safely omitted.</p></li>\n<li><p>Most of the methods of <code>lsr.cpp</code> are better expressed via STL numeric algorithms. For example, <code>calculate_sigma</code> is 4 calls to <code>std::accumulate</code>, while <code>x_square</code> and <code>x_cross_y</code> are calls to std::inner_product`.</p></li>\n<li><p>From a numerical point of view, following the formulas naively may lead to significant computational errors. The intermediate results, e.g. <code>sigma_XX</code> and <code>sigma_X * sigma_X</code> could be huge. Thus the result of</p>\n\n<pre><code>(this->N * this->sigma_XX) - (this->sigma_X * this->sigma_X)\n</code></pre>\n\n<p>is already compromised, and using id as denominator further amplifies the (relative) error.</p></li>\n<li><p>In any case, the computational result is only as good as its error margin. You must compute it as well.</p></li>\n<li><p>The entire library is just that, a library. I don't see a compelling reason to wrap it in a class. Indeed, the data members are transient; they better be local variables.</p>\n\n<p>If you insist on a class, <code>calculate_N</code> should be called in a constructor.</p></li>\n<li><p>It feels strange that the saved model (which is just slope and intercept) is completely disconnected from the data on which it's been trained.</p></li>\n<li><p>Nitpick: <code>lsr.[ch]</code> should be <code>slr.[ch]</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T01:02:04.090",
"Id": "441472",
"Score": "0",
"body": "Thank you sir for your kind help +1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T23:20:58.207",
"Id": "226879",
"ParentId": "226829",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226868",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T10:06:06.387",
"Id": "226829",
"Score": "1",
"Tags": [
"c++",
"statistics",
"machine-learning"
],
"Title": "Simple Linear Regression in C++"
}
|
226829
|
<p>I have a dataframe (obtained from a csv saved from mysql) with several columns, and one of them consist of a string which is the representation of a json. The data looks like:</p>
<pre><code>id email_id provider raw_data ts
1 aa@gmail.com A {'a':'A', 2019-23-08 00:00:00
'b':'B',
'c':'C'}
</code></pre>
<p>And what my desired output is:</p>
<pre><code>email_id a b c
aa@gmail.com A B C
</code></pre>
<p>What I have coded so far is the following:</p>
<pre><code>import pandas as pd
import ast
df = pd.read_csv('data.csv')
df1 = pd.DataFrame()
for i in range(len(df)):
dict_1 = ast.literal_eval(df['raw_content'][i])
df1 = df1.append(pd.Series(dict_1),ignore_index=True)
pd.concat([df['email_id'],df1])
</code></pre>
<p>This works but it has a very big problem: it is extremely low (it takes hours for 100k rows). How could I make this operation faster?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T20:32:25.053",
"Id": "441232",
"Score": "2",
"body": "Would `json.loads` be any faster? With a more limited structure it might. Another thing to consider is doing a string join on all those `raw_data` strings, and calling `loads` once. I haven't worked with `json` enough to know what's fast or slow in its parsing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T09:30:08.737",
"Id": "441300",
"Score": "0",
"body": "Yes, actually it is a little faster, thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T20:53:52.947",
"Id": "441441",
"Score": "1",
"body": "Is the above exactly how your file looks?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T09:05:30.247",
"Id": "441515",
"Score": "0",
"body": "I forgot to close the json, sorry"
}
] |
[
{
"body": "<p>Finally I got an amazing improvement thanks to stack overflow, regarding two things:\n<a href=\"https://stackoverflow.com/questions/10715965/add-one-row-to-pandas-dataframe\">https://stackoverflow.com/questions/10715965/add-one-row-to-pandas-dataframe</a>\n<a href=\"https://stackoverflow.com/questions/37757844/pandas-df-locz-x-y-how-to-improve-speed\">https://stackoverflow.com/questions/37757844/pandas-df-locz-x-y-how-to-improve-speed</a></p>\n\n<p>Also, as hpaulj pointed, changing to json.loads slightly increases the performance. </p>\n\n<p>It went from 16 hours to 30 seconds</p>\n\n<pre><code>row_list = []\n\nfor i in range(len(df)):\n dict1 = {}\n dict1.update(json.loads(df.at[i,'raw_content']))\n row_list.append(dict1)\n\ndf1 = pd.DataFrame(row_list)\n\ndf2 = pd.concat([df['email_id'],df1],axis=1)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T12:56:50.560",
"Id": "441555",
"Score": "0",
"body": "\"got an amazing improvement thanks to stack overflow\" Do you have a link to that answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:53:12.470",
"Id": "441576",
"Score": "1",
"body": "Yes, I have edited the answer to add those links"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T09:08:57.600",
"Id": "226988",
"ParentId": "226832",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "226988",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T10:43:15.153",
"Id": "226832",
"Score": "2",
"Tags": [
"python",
"performance",
"pandas"
],
"Title": "Loop to extract json from dataframe and storing in a new dataframe"
}
|
226832
|
<h2>Prerequisites</h2>
<p>The <code>typedef</code> name <code>uint128_t</code> designates an unsigned integer type with width exactly 128 bits.</p>
<p>The <code>UINT128_MAX</code> is maximum value for an object of type <code>uint128_t</code>.</p>
<p>Function <code>int ctz(uint128_t n)</code> returns the number of trailing 0-bits in <code>n</code>, starting at the least significant bit position. If <code>n</code> is 0, the result is undefined.</p>
<p>The macro <code>UINT128_C(n)</code> shall expand to an integer constant expression corresponding to the type <code>uint128_t</code>.</p>
<p>The following macros are defined.</p>
<pre><code>/* all 3^n for n < 41 fits into uint64_t */
#define LUT_SIZE64 41
/* all 3^n for n < 81 fits into uint128_t */
#define LUT_SIZE128 81
</code></pre>
<p>The following array is defined and initialized with corresponding values.</p>
<pre><code>/* lut[n] contains 3^n */
uint128_t lut[LUT_SIZE128];
</code></pre>
<h2>Problem</h2>
<p>My program is concerned with verifying the convergence of the <a href="https://en.wikipedia.org/wiki/Collatz_conjecture" rel="nofollow noreferrer">Collatz problem</a>, using <a href="https://math.stackexchange.com/questions/3330085/computational-verification-of-collatz-problem">this algorithm</a>.</p>
<p>The convergence for all values <code>n</code> ≤ 87 × 2<sup>60</sup> has been proven. [Source: Christian Hercher, Uber die Lange nicht-trivialer Collatz-Zyklen, Artikel in der Zeitschrift "Die Wurzel" Hefte 6 und 7/2018.]</p>
<p>The following function is called for <code>n</code> of the form <span class="math-container">\$4n+3\$</span>, in order from the smallest one to the largest one, only if all preceding calls returned zero.</p>
<p>The following function should either</p>
<ul>
<li>return 0 if the Collatz problem for the <code>n</code> is convergent,</li>
<li>return 1 if the function cannot verify the convergence using 128-bit arithmetic,</li>
<li>loop infinitely if the trajectory for the <code>n</code> is cyclic.</li>
</ul>
<h2>Code</h2>
<pre><code>int check_convergence(uint128_t n)
{
uint128_t n0 = n;
int e;
do {
if (n <= UINT128_C(87) << 60) {
return 0;
}
n++;
e = ctz(n);
n >>= e;
if (n < UINT128_C(1) << 64 && e < LUT_SIZE64) {
return 0;
}
if (n > UINT128_MAX >> 2*e || e >= LUT_SIZE128) {
return 1;
}
n *= lut[e];
n--;
n >>= ctz(n);
if (n < n0) {
return 0;
}
} while (1);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T11:01:58.637",
"Id": "441306",
"Score": "0",
"body": "`n++;` & `n *= lut[e];`: Do you know for sure than none of those can overflow? If not, you need to add a check for those."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T12:19:24.830",
"Id": "441323",
"Score": "1",
"body": "@CacahueteFrito Good point. The `n++` can overflow for initial `n = UINT128_MAX`. However, `n++` in subsequent iterations of the do-while loop cannot overflow since those immediately preceding `n >>= ctz(n);` will always make room for at least one bit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T12:21:23.393",
"Id": "441325",
"Score": "1",
"body": "@CacahueteFrito The `n *= lut[e];` cannot overflow since the condition `n > UINT128_MAX >> 2*e` ensures the result of that multiplication will surely fit the `uint128_t type`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:02:33.090",
"Id": "441328",
"Score": "0",
"body": "Actually, if `ctz(n) == 0`, it wouldn't shift, and therefore it wouldn't prevent overflow. However, just before that, there is `n--;`, which would do so."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:05:55.210",
"Id": "441329",
"Score": "1",
"body": "@CacahueteFrito `ctz(n)` is always greater than 0 since the argument `n` is even."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T23:36:03.307",
"Id": "441463",
"Score": "0",
"body": "Is there any known upper bound to the number of iterations so that if the function reaches that number of iterations you can return a non-zero value instead of looping forever?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T10:28:50.473",
"Id": "441529",
"Score": "0",
"body": "Wha do you return 0 when `(n < UINT128_C(1) << 64 && e < LUT_SIZE64)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T10:55:25.033",
"Id": "441536",
"Score": "0",
"body": "@CacahueteFrito Basically, for inputs below 87 x 2^60, there is no iteration at all. On the other hand, for the numbers above this boundary, nobody knows the upper bound for the number of iterations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T10:56:55.023",
"Id": "441537",
"Score": "0",
"body": "@miracle173 This is because when the result of n*3^e, and thus also odd_part(n*3^e-1), fits the 64-bit unsigned long, it is surely less than 87*2^60. So we can immediately decide that the problem converges."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T11:17:04.033",
"Id": "441540",
"Score": "0",
"body": "I don't know about the maths behind this algorithm, but by looking at it, I would say that if your input is restricted to `UINT128_MAX - 1`, no more than `UINT128 - 1` iterations will be needed for convergence. If there were more iterations, some number would have been repeated, which would mean we're in a loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T11:20:06.197",
"Id": "441542",
"Score": "0",
"body": "@CacahueteFrito Yes, unfortunately you cannot do `UINT128_MAX - 1` iterations on contemporary computers (and computers in the near or far future)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T11:21:14.347",
"Id": "441543",
"Score": "0",
"body": "I have to say that I never tried, but why would it be impossible? Is it because of time?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T11:25:26.177",
"Id": "441545",
"Score": "1",
"body": "@CacahueteFrito Lets say we have 3 GHz CPU computing 3 000 000 000 simple instructions per second. Then going over 2^128 states would roughly take 3.6 x 10^21 years."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T11:26:55.677",
"Id": "441546",
"Score": "1",
"body": "Good to read that; sometimes I tend to forget the most basic things :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T14:37:47.043",
"Id": "441584",
"Score": "1",
"body": "I am not so firm in C but I think you check if if n<2^64 and e<41. But if n~2^64 and e=40 then n*3^e-1~ 2^64* 3^40 ~ 2^128, so the odd part of n*3^e-1 may be about 2^127., which is much higher than 87*2^60"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T15:58:19.553",
"Id": "441595",
"Score": "0",
"body": "@miracle173 Yes, this is a bug in the program. I will fix it..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T16:06:42.033",
"Id": "441600",
"Score": "0",
"body": "@miracle173 I decided to remove this condition altogether. Is it correct now?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T16:13:37.160",
"Id": "441601",
"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)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T16:16:16.460",
"Id": "441602",
"Score": "0",
"body": "@Vogel612 OK, no problem here :)"
}
] |
[
{
"body": "<p>Given that (from your comments) there is one and only one input which would cause overflow, I propose the following check at the beginning of the function:</p>\n\n<pre><code>int check_convergence(uint128_t n)\n{\n const uint128_t n0 = n;\n int e;\n\n if (n == UINT128_MAX)\n return 1;\n\n do {\n ...\n } while (true);\n}\n</code></pre>\n\n<hr>\n\n<p>I also added <code>const</code> to <code>n0</code>, given that it's constant through all the function.</p>\n\n<hr>\n\n<pre><code>if (n < UINT128_C(1) << 64 && e < LUT_SIZE64)\n return 0;\n</code></pre>\n\n<p>That can be rewritten as:</p>\n\n<pre><code>if (n <= UINT64_MAX && e < LUT_SIZE64)\n return 0;\n</code></pre>\n\n<hr>\n\n<p>Although maybe unneeded, I prefer to always parenthesize macros that evaluate to a value, just in case:</p>\n\n<pre><code>#define LUT_SIZE128 (81)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T12:27:01.530",
"Id": "441551",
"Score": "1",
"body": "`(unsigned long)(n>>64) == 0` seems to be much faster than `n < UINT128_C(1) << 64` or `n <= UINT64_MAX`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T12:50:09.943",
"Id": "441554",
"Score": "0",
"body": "@DaBler Nice. Even with `-O3` or `-Ofast` ? Does the cast affect performance (in theory it is unneeded)? I would remove that cast, or use `uint64_t` instead if it affects performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:01:40.793",
"Id": "441558",
"Score": "1",
"body": "Using `-march=native -O3` and gcc 4.6.3 (`-Ofast` should only have effect on floating-point math, right?). The `(unsigned long)(n>>64) == 0` gives speedup factor about 1.1 over `n < UINT128_C(1) << 64`, depending on the particular input range."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:21:51.580",
"Id": "441568",
"Score": "0",
"body": "@DaBler Curious. I guess GCC doesn't know how to optimize `unsigned __int128` very much, which is what I guess you are using for the `typedef`. I guess `n <= UINT64_MAX` is also slower. There's some other thing you may try, but which relies on implementation defined behaviour: Use a `union` that contains a `uint128_t` and a `uint64_t [2]`, and test which of the two elements of the array contains the MSbits. Then just compare that element of the union to `0`. It may be even faster than your shift, or it may not. Just try ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:36:22.623",
"Id": "441571",
"Score": "1",
"body": "That's exactly what I've tried for a few days back. But it did not bring any acceleration over mere `uint128_t`. See my attempt [here](https://github.com/xbarin02/collatz/blob/058030913c382b0e0a59a1cee7e80f5a2bd2c51a/collatz_enum.c) Look for `typedef union {\n unsigned long ul[2];\n uint128_t ull;\n} uint128_u;`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:41:49.357",
"Id": "441572",
"Score": "0",
"body": "@DaBler I'm curious about why you use `unsigned long` instead of the `<stdint.h>` types."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:45:29.870",
"Id": "441575",
"Score": "0",
"body": "It is because I use libgmp. The problem with gmplib is that it does not support `uintN_t`. It only supports standard C types like `unsigned int`: https://gmplib.org/manual/Assigning-Integers.html#Assigning-Integers"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T12:47:18.717",
"Id": "226920",
"ParentId": "226835",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226920",
"CommentCount": "19",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T12:54:14.443",
"Id": "226835",
"Score": "3",
"Tags": [
"c",
"mathematics",
"integer",
"collatz-sequence"
],
"Title": "Computational verification of Collatz conjecture"
}
|
226835
|
<p>Here is App.js</p>
<pre><code>const listItems=document.querySelector(".student-list").children;
const studentList=document.querySelector('.student-list');
const numberOfItems=10;
const page=document.querySelector(".page");
displayPage=(list,pageNumber)=> {
const SI=(pageNumber*numberOfItems)-numberOfItems;
const EI=pageNumber*numberOfItems;
Array.from(list).forEach((item,index)=> {
if (index>= SI && index<EI) {
item.style.display="block";
} else {
item.style.display="none";
}
})
}
addPaginationLinks=(list)=> {
const pages=Math.floor(list.length/10)
let html=``;
for (let i=0; i<pages; i++) {
if (i===0) {
html+=`
<li>
<a class="active" href="#">${i+1}</a>
</li>`;
} else {
html+=`
<li>
<a href="#">${i+1}</a>
</li>`;
}
}
const ul=document.createElement("ul");
ul.innerHTML=html;
const div=document.createElement("div");
div.classList.add("pagination");
div.appendChild(ul);
page.appendChild(div);
}
displayPage(listItems,1);
addPaginationLinks(listItems);
addEventListener=()=> {
const a=document.querySelectorAll("a");
a.forEach(item=> {
item.addEventListener('click', (e)=> {
a.forEach(item=> {
if (item.classList.contains("active")) {
item.classList.remove("active")
e.target.classList.add("active");
}
})
const pageNumber=parseInt(e.target.textContent);
displayPage(listItems,pageNumber);
})
})
}
addEventListener();
addSearchComponent=()=> {
const pageHeader=document.querySelector(".page-header.cf")
let html=`
<div class="student-search">
<input placeholder="Search for students...">
<button>Search</button>
</div>`;
pageHeader.insertAdjacentHTML('beforeend', html);
}
addSearchComponent()
const search=document.querySelector("input");
const studentDetails=document.getElementsByClassName("student-details");
noResultsItem=()=> {
const item=`
<li class="no-results" style="display: none;">
<h3>No Results Shown Found</h3>
</li>`;
studentList.insertAdjacentHTML('beforeend', item);
}
noResultsItem()
search.addEventListener('keyup', (e)=> {
const noResults=document.querySelector(".no-results");
const array=Array.from(studentDetails).filter(student=>student.children[1].textContent.includes(e.target.value))
if (array.length==0) {
Array.from(studentDetails).forEach(student=>{
student.parentNode.style.display="none";
});
noResults.style.display="block"
} else if (array.length>0) {
noResults.style.display="none"
Array.from(studentDetails).forEach(student=>{
if (student.children[1].textContent.includes(e.target.value)) {
student.parentNode.style.display="block";
} else {
student.parentNode.style.display="none";
}
});
}
});
</code></pre>
<p>I'm trying to refactor the Javascript code at the bottom of my app.js. </p>
<p>There's a keyup event in the search input, and when no results are found, I want to display the no results li item and also make it disappear immediately in case a user types in a character that creates a search match. However, I feel like I could have written this much better. I made the li's display none by default, but it feels tedious to re-alter it to display: none and display: block in both the if conditions. </p>
<p>Does anyone have any suggestions to a beginner programmer on how to make the code more efficient? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T01:34:57.983",
"Id": "441146",
"Score": "0",
"body": "don't edit the actual elements in a foreach loop...this isn't normally very effective unless the element edits are batched."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T02:13:38.403",
"Id": "441147",
"Score": "0",
"body": "@ggorlen oh okay let me take a look at that site! I didn't know it existed. Thank you so much."
}
] |
[
{
"body": "<p>1) Avoid unnecessary <code>document.querySelector</code> and <code>document.querySelectorAll</code>. Store its results if you sure there won't be any changes.</p>\n\n<p>Element searching in the DOM is relatively hard operation (it is extremely optimized, but still). So you should avoid it if you can.</p>\n\n<p>You've already done a lot for that, but I still can see unsaved <code>document.querySelector(\".page-header.cf\")</code></p>\n\n<p>2) Use event delegation pattern.</p>\n\n<p>You don't have to add event listeners to each element on the page. Especially if they are in the same container.</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 parent = document.querySelector('#parent');\r\n\r\nparent.addEventListener('click', (e) => {\r\n const target = e.target.closest('a');\r\n \r\n if (!target) return;\r\n \r\n if (target.matches('.active')) {\r\n target.classList.remove('active');\r\n \r\n resetPage();\r\n } else {\r\n target.classList.add('active');\r\n \r\n const page = target.textContent;\r\n \r\n displayPage(page);\r\n }\r\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"parent\">\r\n <a class=\"page-number\">1</a>\r\n <a class=\"page-number\">1</a>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>As a bonus, you don't have to add event listeners on newly created links or remove it from removed links.</p>\n\n<p>3) Do not modify elements content as HTML string if you can avoid it. </p>\n\n<p>In your case you can move <code>li.no-results</code> outside of <code>studentList</code> and show/hide it with <code>display: none/block</code> property. Or at least remove/append this element as a node, not as HTML-string. It is much faster.</p>\n\n<p>4) Use <code>debounce</code>.</p>\n\n<p>You don't need to trigger the search on <strong>each</strong> <code>keyup</code>. You need to trigger it only when user stops typing. So when you have event series with, let's say, 200 ms interval, you need to trigger search only for the last one. You can use <code>lodash/debounce</code> for that or write <a href=\"https://medium.com/walkme-engineering/debounce-and-throttle-in-real-life-scenarios-1cc7e2e38c68\" rel=\"nofollow noreferrer\">your own implementation</a></p>\n\n<p>5) Learn how to use <a href=\"https://developers.google.com/web/tools/chrome-devtools/rendering-tools/\" rel=\"nofollow noreferrer\">Chrome Profiling Tool</a>\nIt helps to find bottlenecks of your app and fix them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T05:48:49.930",
"Id": "226846",
"ParentId": "226845",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T01:19:38.227",
"Id": "226845",
"Score": "1",
"Tags": [
"javascript",
"search"
],
"Title": "How can I make my filter search code more efficient?"
}
|
226845
|
<p>Ever wanted a strictly conformant <code>echo(1)</code> implementation on your system? Wait no more: I've <a href="https://github.com/benknoble/echocho" rel="nofollow noreferrer">built it</a>!</p>
<h2>What is it?</h2>
<p><sup>My first large-ish body of C code in a while.</sup></p>
<p>The code provides implementations of all of the following <code>echo(1)</code> descriptions from <a href="http://pubs.opengroup.org/onlinepubs/9699919799/" rel="nofollow noreferrer">the Open Group POSIX specification</a>.</p>
<p>In summary:</p>
<ul>
<li>The echo utility writes its arguments to standard output, followed by a newline. If there are no arguments, only the newline is written.</li>
<li>POSIX admits no options or escape characters</li>
<li>BSD admits <code>-n</code> to suppress newlines</li>
<li>XSI admits the following table of escape characters</li>
</ul>
<blockquote>
<ul>
<li><code>\a</code>
Write an alert.</li>
<li><code>\b</code>
Write a backspace.</li>
<li><code>\c</code>
Suppress the newline that otherwise follows the final argument in the output. All characters following the '<code>\c</code>' in the arguments shall be ignored.</li>
<li><code>\f</code>
Write a form-feed.</li>
<li><code>\n</code>
Write a newline.</li>
<li><code>\r</code>
Write a carriage-return.</li>
<li><code>\t</code>
Write a tab.</li>
<li><code>\v</code>
Write a vertical-tab.</li>
<li><code>\\</code>
Write a backslash character.</li>
<li><code>\0num</code>
Write an 8-bit value that is the zero, one, two, or three-digit octal number <code>num</code>.</li>
</ul>
</blockquote>
<h2>A good review might...</h2>
<ul>
<li>Address the lookup-table nature of escape-character processing, and suggest a more compact (but still readable) system</li>
<li>Address the repetition in the escape-character processing (<code>++str</code>, <code>shift_left_one_char</code>, &c.)</li>
</ul>
<h2>Code organization</h2>
<p>The <a href="https://github.com/benknoble/echocho" rel="nofollow noreferrer">code</a> is broken down into roughly three (3) sections:</p>
<ol>
<li>Argument-echoing, with and without newline (<code>echo.[ch]</code>)</li>
<li>Escape-character processing (<code>escape.[ch]</code>)</li>
<li>Front-end implementations (<code>posix.c</code>, <code>bsd.c</code>, <code>xsi.c</code>, <code>sysv.c</code> is a link to <code>xsi.c</code>)</li>
</ol>
<p>Build with <code>make(1)</code> if you clone from the link.</p>
<h2>Known failings</h2>
<ul>
<li>No account for environment variables, e.g., <code>LANG</code> and <code>LC_*</code></li>
<li>Limited error checking</li>
<li>No make(1) support for installation, out-of-source building, documentation</li>
<li>No tests</li>
<li>No documentation</li>
</ul>
<hr>
<h1>Code</h1>
<h2>echo.h</h2>
<pre><code>#ifndef ECHO_H
#define ECHO_H
int echo(int argc, char **argv);
int echo_n(int argc, char **argv);
#endif
</code></pre>
<h2>echo.c</h2>
<pre><code>#include "echo.h"
#include <stdio.h>
int print_args(int argc, char **argv) {
if (argc == 0) return 0;
int err = 0;
for (int i = 0; i < argc-1; ++i) {
err = printf("%s ", argv[i]);
if (err < 0) return err;
}
err = printf("%s", argv[argc-1]);
if (err < 0) return err;
return 0;
}
int echo(int argc, char **argv) {
int err = print_args(argc, argv);
if (err < 0) return err;
err = printf("\n");
if (err < 0) return err;
return 0;
}
int echo_n(int argc, char **argv) {
return print_args(argc, argv);
}
</code></pre>
<h2>escape.h</h2>
<pre><code>#ifndef ESCAPE_H
#define ESCAPE_H
#include <stdbool.h>
int interpret_escapes(int argc, char **argv, bool *suppress_newline);
#endif
</code></pre>
<h2>escape.c</h2>
<pre><code>#include "escape.h"
#include <ctype.h>
#include <stdbool.h>
#include <stddef.h>
#include <string.h>
void shift_left_one_char(char *str) {
for (int i = 0; str[i] != '\0'; ++i) {
str[i] = str[i+1];
}
}
#define ALERT '\a'
#define BACKSPACE '\b'
#define FORMFEED '\f'
#define NEWLINE '\n'
#define CARRIAGE_RETURN '\r'
#define TAB '\t'
#define VTAB '\v'
#define BACKSLASH '\\'
#define MAX_OCTAL 3
#define START 0
#define ESC_CHAR_POS 1
#define ESC_MIN_LEN 2
int escape(char *str, bool *suppress_newline) {
int escapes_handled = 0;
while ((str = strchr(str, BACKSLASH)) != NULL) {
if (strnlen(str, ESC_MIN_LEN) < ESC_MIN_LEN) break;
int num_digits = 0;
int octal = 0;
switch (str[ESC_CHAR_POS]) {
case 'a':
str[START] = ALERT;
++str;
shift_left_one_char(str);
++escapes_handled;
break;
case 'b':
str[START] = BACKSPACE;
++str;
shift_left_one_char(str);
++escapes_handled;
break;
case 'c':
*suppress_newline = true;
// clear out this arg
str[START] = '\0';
++escapes_handled;
break;
case 'f':
str[START] = FORMFEED;
++str;
shift_left_one_char(str);
++escapes_handled;
break;
case 'n':
str[START] = NEWLINE;
++str;
shift_left_one_char(str);
++escapes_handled;
break;
case 'r':
str[START] = CARRIAGE_RETURN;
++str;
shift_left_one_char(str);
++escapes_handled;
break;
case 't':
str[START] = TAB;
++str;
shift_left_one_char(str);
++escapes_handled;
break;
case 'v':
str[START] = VTAB;
++str;
shift_left_one_char(str);
++escapes_handled;
break;
case '\\':
// unnecessary: already a backslash at str[START]
/* str[START] = BACKSLASH; */
++str;
shift_left_one_char(str);
++escapes_handled;
break;
case '0':
while (isdigit(str[ESC_CHAR_POS + num_digits])) {
octal *= 8;
switch(str[ESC_CHAR_POS + num_digits]) {
case '0': octal += 0; break;
case '1': octal += 1; break;
case '2': octal += 2; break;
case '3': octal += 3; break;
case '4': octal += 4; break;
case '5': octal += 5; break;
case '6': octal += 6; break;
case '7': octal += 7; break;
case '8': octal += 8; break;
case '9': octal += 9; break;
}
if (num_digits == MAX_OCTAL) break;
++num_digits;
}
str[START] = (char)octal;
++str;
for (int i = 0; i < ESC_CHAR_POS + num_digits; ++i)
{ shift_left_one_char(str); }
++escapes_handled;
break;
default:
break;
}
}
return escapes_handled;
}
int interpret_escapes(int argc, char **argv, bool *suppress_newline) {
*suppress_newline = false;
for (int i = 0; i < argc; ++i) {
int err = escape(argv[i], suppress_newline);
if (err < 0) return err;
if (*suppress_newline) return i+1;
}
return argc;
}
</code></pre>
<h2>posix.c</h2>
<pre><code>#include "echo.h"
#include <stdlib.h>
int main(int argc, char** argv) {
int err = echo(argc-1, &argv[1]);
if (err < 0) return EXIT_FAILURE;
return 0;
}
</code></pre>
<h2>bsd.c</h2>
<pre><code>#include "echo.h"
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv) {
int err;
if (argc > 1 && strcmp(argv[1], "-n") == 0) {
// swallow the -n
err = echo_n(argc-2, &argv[2]);
} else {
// still print newline
err = echo(argc-1, &argv[1]);
}
if (err < 0) return EXIT_FAILURE;
return 0;
}
</code></pre>
<h2>xsi.c (sysv.c links to this)</h2>
<pre><code>#include "echo.h"
#include "escape.h"
#include <stdlib.h>
#include <stdbool.h>
int main(int argc, char** argv) {
char **args = &argv[1];
bool suppress_newline;
int actual_argc = interpret_escapes(argc-1, args, &suppress_newline);
if (actual_argc < 0) return EXIT_FAILURE;
int err;
if (suppress_newline) {
err = echo_n(actual_argc, args);
} else {
err = echo(actual_argc, args);
}
if (err < 0) return EXIT_FAILURE;
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Danger!</p>\n\n<blockquote>\n<pre><code> while (isdigit(str[ESC_CHAR_POS + num_digits])) {\n</code></pre>\n</blockquote>\n\n<p>Promoting <code>char</code> to <code>int</code> (as argument to <code>isidigt()</code>) can sign-extend it. We have to launder the argument through <code>unsigned char</code> on the way:</p>\n\n<pre><code> while (isdigit((unsigned char)(str[ESC_CHAR_POS + num_digits]))) {\n</code></pre>\n\n<p>We can make this a bit more readable with a function:</p>\n\n<pre><code>static bool char_isdigit(char c) { return isdigit((unsigned char)c); }\n</code></pre>\n\n<hr>\n\n<p>Several functions ought to have <code>static</code> linkage: <code>print_args()</code>, <code>shift_left_one_char()</code> and <code>escape()</code>.</p>\n\n<hr>\n\n<p><code>escape()</code> repeatedly calls <code>shift_left_one_char()</code> to modify the string in place. This is very inefficient with long arguments, as we're repeatedly accessing the rightmost part of the string (and not even using <code>memmove()</code> for this, though a good compiler <em>might</em> spot the pattern).</p>\n\n<p>A much more efficient strategy is to treat the arguments as read-only strings - print the literal text directly, and output the escapes as they are interpreted. To get different escape-character behaviours, we would pass a function pointer to the interpreter.</p>\n\n<hr>\n\n<p>When processing <code>\\c</code> escapes, there's no need to continue reading the rest of the input string - we can return immediately after terminating the output.</p>\n\n<hr>\n\n<p>When reading octal escapes, we can make the <code>num_digits</code> test part of the loop condition instead of using <code>break</code>, and we can avoid the inner <code>switch</code> by using C's guarantee that the digits <code>0</code>..<code>9</code> must have consecutive character values:</p>\n\n<pre><code> while (isdigit(str[ESC_CHAR_POS + num_digits]) && num_digits++ <= MAX_OCTAL) {\n octal *= 8;\n octal += str[ESC_CHAR_POS + num_digits] - '0';\n }\n</code></pre>\n\n<hr>\n\n<p>When we read an octal number zero, we shouldn't truncate the string at that point. We should output a literal <code>NUL</code> character and continue.</p>\n\n<hr>\n\n<p>We could change the return value from <code>echo()</code> and <code>echo_n()</code> to be simply <code>EXIT_SUCCESS</code> or <code>EXIT_FAILURE</code>. That would simplify the frontend programs - they can simply</p>\n\n<pre><code>return echo_n(actual_argc, args);\n</code></pre>\n\n<p>instead of</p>\n\n<blockquote>\n<pre><code>int err;\nerr = echo_n(actual_argc, args);\nif (err < 0) return EXIT_FAILURE;\nreturn 0;\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:27:49.520",
"Id": "441337",
"Score": "0",
"body": "Great comments, thanks; suggestions on how to output the NUL and not truncate the string? Placing a null into the string is clearly what truncates it, but im not sure if its possible to place an « escaped null » into the string that, eg, printf wont choke on. Can you clarify *several functions ought to have static linkage*?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:53:34.697",
"Id": "441344",
"Score": "0",
"body": "Two ways to output the NUL. First and most obvious is to output as you go, as suggested elsewhere in this answer. The other (if you want to retain the transform-in-place method) is to return the new length to the caller, and use `fwrite()` instead of `fprintf()` or `fputs()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:55:29.717",
"Id": "441346",
"Score": "1",
"body": "Static linkage makes the functions visible only to code in the same translation unit, and not to code in other TUs at link time. So declaring those functions `static` allows us to freely use those names in other TUs without fear of conflict. Not a big deal in a small program like this, but it's good hygiene that can avoid surprises in big codebases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T14:04:45.070",
"Id": "441354",
"Score": "0",
"body": "The problem with `fwrite` as I see it is that each item must be the same length (and for echo that's just not guaranteeable). That said, I like the transformation approach, as it's clearer. I will have to think on this"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T14:54:19.157",
"Id": "441364",
"Score": "0",
"body": "I did move the test `num_digits < MAX_OCTAL` to the while condition (and redefined `MAX_OCTAL` as 4, to account for the 0), but I can't modify it until after it has been used in the while body: `while (char_isdigit(str[ESC_CHAR_POS + num_digits])\n && num_digits < MAX_OCTAL) {\n octal *= 8;\n octal += str[ESC_CHAR_POS + num_digits] - '0';\n ++num_digits;\n }\n`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T15:29:46.770",
"Id": "441366",
"Score": "1",
"body": "`fwrite()` does require objects of all the same length, but those objects can be `char` objects (i.e. pass 1 for the `size` argument, and length of string for the `count`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T02:13:43.643",
"Id": "443195",
"Score": "0",
"body": "I think I got it all right (if you check the GitHub; you may not care). anyways, thanks for the review; helpful stuff."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T08:22:32.010",
"Id": "226903",
"ParentId": "226848",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "226903",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T14:27:24.243",
"Id": "226848",
"Score": "5",
"Tags": [
"beginner",
"c",
"posix",
"lookup"
],
"Title": "POSIX+ implementations of echo(1)"
}
|
226848
|
<p>This function is used to modify values in list <code>List<GoogleUsageMapping></code> and prepare them for entering into billing system.</p>
<p>I'm hoping this function can be more simplified and prettified, logic works.
Function needs to keep track of <code>maxValue</code> and if the <code>maxValue</code> is of type <code>LOGICAL_SIZE</code>. Would love to eliminate one of the for-loop if possible for instance. </p>
<pre><code>private void checkForOverage(List<GoogleUsageMapping> records) {
BigDecimal highestQuantity = new BigDecimal(0);
GoogleUsageMapping recordHighestQuantity = null;
for (GoogleUsageMapping record : records) {
if (record.getUsage().getQuantity().compareTo(highestQuantity) > 0) {
highestQuantity = record.getUsage().getQuantity();
recordHighestQuantity = record;
}
}
if (recordHighestQuantity.getUsage().getMeasuredType() == MeasuredType.LOGICAL_SIZE) {
s_logger.info("Overage scenario accord LOGICAL_SIZE: " + recordHighestQuantity.getUsage().getQuantity() + " greater than ALLOCATED_SIZE");
for (GoogleUsageMapping record : records) {
if (record.getUsage().getMeasuredType() == MeasuredType.LOGICAL_SIZE) {
continue;
}
record.setState(GoogleTrackingState.IGNORED_OVERAGE);
}
}
}
</code></pre>
<p>modified version:</p>
<pre><code>private void checkForOverage(List<GoogleUsageMapping> records) {
GoogleUsageMapping recordUsageHighestQuantity = Collections.max(records, Comparator.comparing(c -> c.getUsage().getQuantity()));
if (recordUsageHighestQuantity.getUsage().getMeasuredType() == MeasuredType.LOGICAL_SIZE) {
s_logger.info("Overage scenario accord LOGICAL_SIZE: " + recordUsageHighestQuantity.getUsage().getQuantity() + " greater than ALLOCATED_SIZE");
for (GoogleUsageMapping record : records) {
if (record.getUsage().getMeasuredType() == MeasuredType.LOGICAL_SIZE) {
continue;
}
record.setState(GoogleTrackingState.IGNORED_OVERAGE);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T16:57:39.830",
"Id": "441187",
"Score": "1",
"body": "How would you use this code? What library you are using for the input _GoogleUsageMapping_? The code you presented in its current form is not meaningfully reviewable. We require sufficient context to make a proper review. See [What topics can I ask about?](https://codereview.stackexchange.com/help/on-topic) for reference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T17:04:19.877",
"Id": "441189",
"Score": "0",
"body": "@dfhwze added some more description as you pointed out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T03:09:39.007",
"Id": "441249",
"Score": "1",
"body": "Possible `NullPointerException` if given an empty list or a list with no records with a usage quantity greater than zero. Perhaps that can never happen, but not possible to tell without greater context."
}
] |
[
{
"body": "<p>If you want to get rid of a for-loop just for code clarity, you could use a <code>Stream</code> and the <code>max()</code> function. (Assuming you're using Java 8+). You could also use Streams for the second for-loop.</p>\n\n<p>Note however, it's not logically possible to avoid iterating through the list twice. You have to check every element to get the largest value, and again to set values on every item in the list.</p>\n\n<p>I don't see you using <code>highestQuantity</code>, it's not really necessary since you have a pointer to <code>recordHighestQuantity</code> already.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T16:59:08.447",
"Id": "441188",
"Score": "0",
"body": "good pointers, will take a look at it, thank you"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T16:55:35.160",
"Id": "226859",
"ParentId": "226853",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T15:57:47.517",
"Id": "226853",
"Score": "1",
"Tags": [
"java"
],
"Title": "Simplify and prettify function looking for max value in a list and modifying some underlying values within that list"
}
|
226853
|
<p>The purpose of below code is to stop/start a couple of windows services if they are running/not running, this will be called from a windows command line. The services could be either on a windows stand alone server or could be a bundled into a Windows Failover cluster Role on a clustered server. </p>
<p>I believe I handled all the cases and validating the inputs and using functions where ever possible. However I'm sure there is room for improvement and to make it more robust and reliable, please critique or comment on it. </p>
<p>this will be run or evoked by humans thus the need to make it robust ..</p>
<pre><code>$mode = 'run'
$Servername = $env:computername
$Environment = $Servername.substring(9)
$DateTime = Get-Date -Uformat "%Y%m%d";
$LogfilePath = 'c:\Logs\MySoftware_' + $action + '_' + $Environment + '_' + $DateTime + '.txt'
Start-Transcript -path $LogfilePath -append
function Getvariables {
Write-Host 'action is' $action
Write-Host 'action.Length is' $action.Length
Write-Host 'IsComputerACluster is' $IsComputerACluster
Write-Host 'IsComputerACluster.Length is' $IsComputerACluster.Length
Write-Host 'Servername is' $Servername
Write-Host 'ServiceName1 is' $ServiceName1
Write-Host 'ServiceName2 is' $ServiceName2
Write-Host 'ClusterGroup is' $ClusterGroup
}
function IsCluster {
param([string]$serverName)
$ErrorActionPreference = "SilentlyContinue"
trap [Exception] {
return $false
}
if ($null -ne (Get-WMIObject -Class MSCluster_ResourceGroup -ComputerName $Servername -Namespace root\mscluster) ) {
return $true
}
else {
return $false
}
}
function Get-ServiceStatus {
Param ($ServiceName)
$arrService = (Get-Service -Name $ServiceName).Status
#Write-Host $ServiceName is $arrService.Status
return $arrService
}
function Get-ClusterGroupStatus {
Param ($ClusterGroup)
[string ]$arrService = (Get-ClusterGroup -Name $ClusterGroup).State
#Write-Host $ServiceName is $arrService.Status
return $arrService
}
$IsComputerACluster = (IsCluster $Servername)
if ($mode -eq 'debug') { Getvariables }
if (($action -in ('start' , 'stop')) -and ($IsComputerACluster -eq $false )) {
#Start MySoftware Services
$ServiceName1 = 'MySoftwareServer'
$ServiceName2 = 'MySoftwareUIConsole'
[string]$ServiceStatus1 = ''
[string]$ServiceStatus2 = ''
$ServiceStatus1 = (Get-ServiceStatus $ServiceName1)
$ServiceStatus2 = (Get-ServiceStatus $ServiceName2)
if ($mode -eq 'debug') { Getvariables }
if ($action -eq 'stop') {
if ($ServiceStatus1 -ne 'Stopped' -Or $ServiceStatus2 -ne 'Stopped') {
Write-Host $ServiceName1 is now (Get-ServiceStatus $ServiceName1)
Write-Host $ServiceName2 is now (Get-ServiceStatus $ServiceName2)
Write-Host 'Now Attempting to Stop the services '$ServiceName1' & '$ServiceName2
stop-Service $ServiceName1
if (Get-ServiceStatus $ServiceName1 -eq 'Stopped') {
stop-Service $ServiceName2
}
else { Write-Host 'Waiting for '+$ServiceName1+' to stop..' }
Write-Host $ServiceName1 is now (Get-ServiceStatus $ServiceName1)
Write-Host $ServiceName2 is now (Get-ServiceStatus $ServiceName2)
}
else
{ Write-Host 'Services are already stopped' }
}
else {
if ($ServiceStatus1 -ne 'Running' -Or $ServiceStatus2 -ne 'Running') {
Write-Host $ServiceName1 is now (Get-ServiceStatus $ServiceName1)
Write-Host $ServiceName2 is now (Get-ServiceStatus $ServiceName2)
Write-Host 'Now Attempting to Start the services '$ServiceName1' & '$ServiceName2
start-Service $ServiceName1
if (Get-ServiceStatus $ServiceName1 -eq 'Running') {
start-Service $ServiceName2
}
else { Write-Host 'Waiting for '+$ServiceName1+' to start..' }
Write-Host $ServiceName1 is now (Get-ServiceStatus $ServiceName1)
Write-Host $ServiceName2 is now (Get-ServiceStatus $ServiceName2)
}
else
{ Write-Host 'Services are already running' }
}
}
elseif (($action -in ('start' , 'stop')) -and ($IsComputerACluster -eq 'True' )) {
$ClusterGroup = 'MySoftware'
$ClusterGroupStatus = Get-ClusterGroupStatus $ClusterGroup
if ($mode -eq 'debug') { Getvariables }
if ($action -eq 'stop') {
if ($ClusterGroupStatus -eq 'Online' ) {
Write-Host $ClusterGroup is now $ClusterGroupStatus
Write-Host 'Now Attempting to Stop the cluster group ' $ClusterGroup
Stop-ClusterGroup $ClusterGroup
if (Get-ClusterGroupStatus $ClusterGroup -eq 'Offline') {
Write-Host $ClusterGroup is now Offline
break
}
else { Write-Host 'Waiting for '+$ClusterGroup+' to go offline..' }
$ClusterGroupStatus = Get-ClusterGroupStatus $ClusterGroup
Write-Host $ClusterGroup is now $ClusterGroupStatus
}
else {
Write-Host $ClusterGroup 'is already offline'
}
}
else {
if ($ClusterGroupStatus -eq 'Offline' ) {
Write-Host $ClusterGroup is now $ClusterGroupStatus
Write-Host 'Now Attempting to Start the cluster group ' $ClusterGroup
Start-ClusterGroup $ClusterGroup
if (Get-ClusterGroupStatus $ClusterGroup -eq 'Online') {
Write-Host $ClusterGroup is now Online
break
}
else { Write-Host 'Waiting for '+$ClusterGroup+' to become Online..' }
$ClusterGroupStatus = Get-ClusterGroupStatus $ClusterGroup
Write-Host $ClusterGroup is now $ClusterGroupStatus
}
else
{ Write-Host $ClusterGroup 'is already Online' }
}
}
else {
if ($mode -eq 'debug') { Getvariables }
Write-Host 'Invalid paramater value for variable: action'
Write-Host 'Valid ways to call the script are:
powershell.exe -file FullyQualifiedPowershellFilePath.ps1 -action "stop"
powershell.exe -file FullyQualifiedPowershellFilePath.ps1 -action "start"'
}
Write-Host 'Scritp Execution Completed'
Stop-Transcript<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T15:12:14.653",
"Id": "442403",
"Score": "0",
"body": "1st, lacking `param( [string]$action)`, maybe with even `param( [ValidateSet('start','stop')] [string]$action)`. Then you could omit all `if ($action -in ('start' , 'stop'))`… 2nd, `$Servername.substring(9)` poses a strong requirement about `$Servername.Length`. 3rd, `Get-ServiceStatus` function assumes that supplied `$ServiceName` is a valid and installed service; use `Get-Service -Name $ServiceName -EA SilentlyContinue | Select-Object -ExpandProperty Status` (could return `$Null`). Moreover, I'd prefer output from `Getvariables` function in a table-like fashion for better readability."
}
] |
[
{
"body": "<p>Here are my thoughts, in no particular order of importance: </p>\n\n<ol>\n<li><p>Use parameter validation and script parameters, they are stupidly convenient in powershell, for example, put this at the very top of the script:</p>\n\n<pre><code>param(\n [Parameter]\n [ValidateSet('Start','Stop')} # Can have more than two possible values of course\n [string] $mode\n)\n</code></pre>\n\n<p>The error message from ValidateSet can be a bit cryptic, but you can also use <code>ValidateScript</code> to print your own exceptions and error messages. Look up <code>ValidateRegex</code> as well, you'll use it someday.</p></li>\n<li><p>You could make shorter function declarations with <code>function myfunc([type]$arg) { ...</code> instead of using two more verbose lines for that. Don't overdo it if you have lots of parameters, but it's perfectly acceptable for short functions with few arguments.</p></li>\n<li><p>Line 103, <code>$IsComputerACluster -eq 'True'</code>: you can trim off everything and just keep <code>$IsComputerACluster</code>. It is already <code>$true</code> or <code>$false</code> from your IsCluster function. Generally, avoid checking if something is equal to the string 'true' or 'false'*. In <code>if</code> blocks, just use <code>if($MyVar)</code> or <code>if(-not $MyVar)</code>.</p></li>\n<li><p>Lines 55-58, I don't really get what you are going for, you're assigning a value to a variable and then overwriting it with an empty string ?</p></li>\n<li><p>That's a personal choice, but I'd replace every occurence of <code>Get-ServiceStatus $name</code> by <code>Get-Service $name | select -exp Status</code>. But your function name is pretty explicit and that's just my love of one-liners speaking. Same for <code>Get-ClusterGroupStatus</code> which has a less explicit name.</p></li>\n<li><p>Line 51, <code>$var -eq $false</code> can be replaced by <code>-not $var</code> or even <code>!$var</code>.</p></li>\n<li><p>Line 135, if you don't include <code>-Wait</code> in your call to <code>Start-ClusterGroup</code>, the cmdlet will wait until the operation is over. Two cases where this could go wrong:</p>\n\n<ul>\n<li>Your cluster gets stuck in the startup process and the cmdlet never returns</li>\n<li>Your cluster fails to start and the <code>else</code> block executes, telling your user the cluster is waiting to become online, despite it having failed.</li>\n</ul>\n\n<p>So I'd either include a <code>-Wait</code> with a reasonably long time (after which you assume that the cluster is stuck), or include a <code>-wait 0</code> so that the cmdlet returns immediately, then check the cluster status with <code>Get-ClusterGroupStatus</code> until you reach a timeout or until the cluster comes online. Here's a template:</p>\n\n<pre><code>Start-LongOperation -NoWait -Wait 0 -WhateverYourCmdletUsesToRunAsynchronously\n\nWhile(-not Check-LongOperationCompleted -and $CheckRetries -lt 20) { \n Start-Sleep -Seconds 5 \n $CheckRetries += 1\n}\n\n$success = ($CheckRetries -lt 20) # If this is true, it's because the operation completed before the timeout was reached\n</code></pre>\n\n<p>You can make countless variations of this, with exceptions, with actual timers using Get-Date, etc., which are left as an exercise to the reader. Also look into powershell jobs if you want to make asynchronous stuff.</p></li>\n<li><p>Change the log directory to something like <code>$env:temp</code> to avoid scaring the user for whom <code>c:\\Logs</code> will not exist ? You could make a parameter with a default value from this.</p></li>\n<li><p>In IsCluster, there is a <code>if(condition){return $true}else{return $false}</code> block. You can shorten it into <code>return (condition)</code> 95% of the time. This is true for other languages as well.</p></li>\n<li><p>Make this a module for easier deployment ?</p></li>\n</ol>\n\n<p>That's all I can come up with. I'd say your script is pretty good, it's verbose but I found that most user-facing powershell scripts are super verbose when you just try to make a wrapper. If you don't have too many potential users, consider just explaining them the basics of <code>Get/Start/Stop-Service</code> and <code>Get/Start/Stop-ClusterGroup</code> ? I'd definitely make <code>IsCluster</code> a module or put it in my powershell profile though.</p>\n\n<p>*For example, <code>'false' -eq $false</code> is True (pretty reasonable), but <code>$false -eq 'false'</code> returns False (counter-intuitive).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T15:45:31.350",
"Id": "227733",
"ParentId": "226855",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T16:43:05.633",
"Id": "226855",
"Score": "3",
"Tags": [
"shell",
"powershell"
],
"Title": "Powershell script to stop and start services on demand"
}
|
226855
|
<p>I created a simple calculator with multiplication, division, addition, and subtraction. Is there a way to write it shorter? I am a beginner so I do not know much about programming other than if...else statements and different data types.</p>
<pre><code> Console.WriteLine("Welcome to the simple calculator! The four operators of this calculator are +, -, *(multiply), and /(divide)");
Console.Write("Number: ");
string number = Console.ReadLine();
Console.Write("Second Number: ");
string secondNumber = Console.ReadLine();
Console.Write("Operator: ");
string operatorType = Console.ReadLine();
var numberConversion = Convert.ToInt64(number);
var secondNumberConversion = Convert.ToInt64(secondNumber);
var sum = numberConversion + secondNumberConversion; //Result of addition
var difference = numberConversion - secondNumberConversion; //Result of subtraction
var product = numberConversion * secondNumberConversion; //Result of multiplication
var quotient = numberConversion / secondNumberConversion; //Result of division
if (operatorType == "+")
{
Console.WriteLine(sum);
} else if (operatorType == "-")
{
Console.WriteLine(difference);
} else if (operatorType == "*")
{
Console.WriteLine(product);
} else if (operatorType == "/")
{
Console.WriteLine(quotient);
} else
{
Console.WriteLine("Please enter the correct operator");
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T16:33:00.707",
"Id": "441180",
"Score": "0",
"body": "I suggest moving the calculation inside the `if`/`elseif` tree, otherwise you may find that `2 + 0` causes a divide-by-zero error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T16:35:08.933",
"Id": "441181",
"Score": "0",
"body": "Or [code golf](https://codegolf.stackexchange.com/) :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T16:42:45.227",
"Id": "441182",
"Score": "0",
"body": "instead of convert.toint, use the tryparse method and handle exceptions if you have learned about them yet or getting to that lesson at some point. You want to be able to handle an error prone user typing in + + +.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T17:27:08.417",
"Id": "441193",
"Score": "0",
"body": "Nice question. However, you should include your whole program (including the `static void Main()` method signature)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T17:28:06.780",
"Id": "441194",
"Score": "0",
"body": "You need to understand that quality has usually nothing to do with how long your code is but how extensible and stable. But, of course, beginners tend to do many things in a roundabout and overly wordy way.."
}
] |
[
{
"body": "<p>Here's how I would do it:</p>\n\n<pre><code> Console.WriteLine(\"Welcome to the simple calculator! The four operators of this calculator are +, -, *(multiply), and /(divide)\");\n Console.Write(\"Number: \");\n string number = Console.ReadLine();\n Console.Write(\"Second Number: \");\n string secondNumber = Console.ReadLine();\n Console.Write(\"Operator: \");\n string operatorType = Console.ReadLine();\n\n var numberConversion = Convert.ToInt64(number);\n var secondNumberConversion = Convert.ToInt64(secondNumber);\n\n switch (operatorType)\n {\n case \"+\":\n Console.WriteLine(numberConversion + secondNumberConversion);\n break;\n case \"-\":\n Console.WriteLine(numberConversion - secondNumberConversion);\n break;\n case \"*\":\n Console.WriteLine(numberConversion * secondNumberConversion);\n break;\n case \"/\":\n Console.WriteLine(numberConversion / secondNumberConversion);\n break;\n default:\n Console.WriteLine(\"Please enter the correct operator\");\n break;\n }\n</code></pre>\n\n<p>More info here on <code>switch</code>: <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch</a></p>\n\n<p>I prefer using <code>switch</code> over a long <code>If Then</code> just because it's easier to read.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T16:42:03.080",
"Id": "226857",
"ParentId": "226856",
"Score": "0"
}
},
{
"body": "<ol>\n<li>You need to check for input validity and have a mechanism for retry. Users can enter all sorts of things</li>\n<li>Your variable names aren't consistent. <code>number</code> and <code>secondNumber</code>. I would go with <code>firstNumber</code> and <code>secondNumber</code> in your scheme, but I would not use your scheme.</li>\n<li>Your variable names are too verbose: <code>secondNumberConversion</code>. How about <code>n1</code> and <code>n2</code>?</li>\n<li>A simple, elegant, maintainable and extensible solution is to use a Dictionary.</li>\n</ol>\n\n<p>Not addressing 1. here is my version:</p>\n\n<pre><code>Console.WriteLine(\"Welcome to the simple calculator!\"\n + \" The four operators of this calculator are \"\n + \"+, -, *(multiply), and /(divide)\");\n\nConsole.Write(\"First Number: \");\nInt64 n1 = Int64.Parse(Console.ReadLine());\n\nConsole.Write(\"Second Number: \");\nInt64 n2 = Int64.Parse(Console.ReadLine());\n\nConsole.Write(\"Operator: \");\nstring operatorType = Console.ReadLine();\n\nvar operatorsFuncMap = new Dictionary<string, Func<Int64, Int64, Int64>> \n{\n {\"+\", (a, b) => a + b},\n {\"-\", (a, b) => a - b},\n {\"*\", (a, b) => a * b},\n {\"/\", (a, b) => a / b},\n};\n\nConsole.WriteLine(operatorsFuncMap[operatorType](n1, n2));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T17:06:31.380",
"Id": "226862",
"ParentId": "226856",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T16:27:42.310",
"Id": "226856",
"Score": "1",
"Tags": [
"c#",
"beginner",
"console",
"calculator"
],
"Title": "Very simple calculator with four basic operations using only if/else statements"
}
|
226856
|
<p>I wanted a data structure that allowed me to set the chances of randomly returning each of it's elements. </p>
<p>For example, suppose I have a Human class. Every Human has an attribute called eyeColor. I don't know what the actual percentages are, but let's say 60% of people have brown eyes, 30% have blue eyes, and 10% have green eyes.</p>
<p>Using this class I set the chances, out of 100, of returning any given eye color. </p>
<p>To do this, I use a TreeMap and choose a random double between 0, and 100 (inclusive). Then I return the value using the TreeMap's ceilingEntry method, unless that would return a null. In that case I return the value from the floorEntry method.</p>
<p>The restriction is that the sum of all the chances must equal 100, or nearly so, to return anything.</p>
<p><em>How can I make this data structure run faster, and make the code more elegant?</em></p>
<p><strong>My Data Structure:</strong></p>
<pre><code>import java.util.TreeMap;
import java.util.concurrent.ThreadLocalRandom;
/**
* Objects of this class can have object or primitive types added to them and
* retrieved randomly with a different chance for different objects.
* <p>
* This is done by having the user include a "percentage chance" when adding new
* elements.
* <p>
* The percentage chance represents the percentage, out of 100, that the added
* element will be returned when the getRandomElement() method is called.
* <p>
* The sum of all the percentage chances should never be greater than 100 or the
* program will throw an IllegalArgumentException.
*/
public final class RandomTree<T> {
// holds the objects and primitives to be randomly returned
private TreeMap<Double, T> tree;
// keeps track of whether the RandomSet is full
private double sum;
public RandomTree() {
// contains the values to be randomly returned with getRandomElement()
this.tree = new TreeMap<>();
// keeps track of the sum of the percentages
this.sum = 0.0;
}
/**
* Adds a new object or primitive to the RandomTree. The percentChance
* argument represents the chances, out of 100, that the element will be
* return when the getRandomElement() method is called.
* <p>
* The sum of all the percentage chances including the given percentChance
* argument must be less than or equal to 100. Also, the percentChance
* argument must be greater than zero. Otherwise, the program throws
* an IllegalArgumentException.
*
* @param object The object or primitive to add.
* @param percentChance The chance of returning the object argument.
*/
public void add(final T object, final double percentChance) {
this.sum += percentChance;
// do not allow negative percent chances
if (percentChance <= 0.0) {
throw new IllegalArgumentException("percentChance must be > 0.0");
// prevent unnecessary exception throwing over being slightly more than 100.0
} else if (Math.abs(this.sum - 100.0) < 0.1 && this.sum != 100.0) {
this.sum = 100.0;
this.tree.put(this.sum, object);
// do not allow values to be above 100.0
} else if (this.sum > 100.0) {
throw new IllegalArgumentException(this.sum + " is > 100.");
// prevent unnecessary exception throwing over being slightly less than 100.0
} else if (100.0 - this.sum < 0.1 && this.sum != 100.0) {
this.sum = 100.0;
this.tree.put(this.sum, object);
} else // add the key and value to this.tree
this.tree.put(this.sum, object);
}
/**
* Returns a getRandomRace element from this.values.
* Elements with higher associated percentage-change values (in this.keys)
* are more likely to be returned.
* <p>
* Throws an IllegalArgumentException if this.sum is not equal to 100.
*/
public T getRandomElement() {
// don't allow retrieval before this.sum == 100.0
if (this.sum != 100.0)
throw new IllegalArgumentException("sum == " + this.sum);
double choice = ThreadLocalRandom.current().nextDouble(Math.nextUp(100.0));
final T obj = this.tree.ceilingEntry(choice).getValue();
if (obj != null)
return obj;
else
return this.tree.floorEntry(choice).getValue();
}
/**
* Returns the sum of the percentage chances added to this RandomTree.
*
* @return The sum of the percentage chances added to this RandomTree.
*/
public double getSum() {
return this.sum;
}
}
</code></pre>
<p><strong>Test Class:</strong></p>
<pre><code>public class RandomTreeTest {
public static void main(String[] args) {
RandomTree<String> randTree = new RandomTree<>();
randTree.add("ten", 10.0);
randTree.add("twenty", 20.0);
randTree.add("thirty", 30.0);
randTree.add("forty", 40.0);
int countTens = 0;
int countTwenties = 0;
int countThirties = 0;
int countForties = 0;
final double iterationNumber = 1000.0;
for(int i = 0; i < iterationNumber; i++) {
String num = randTree.getRandomElement();
switch(num) {
case "ten":
countTens++;
break;
case "twenty":
countTwenties++;
break;
case "thirty":
countThirties++;
break;
case "forty":
countForties++;
break;
}
}
double percentOfTens = (countTens / iterationNumber) * 100;
double percentOfTwenties = (countTwenties / iterationNumber) * 100;
double percentOfThirties = (countThirties / iterationNumber) * 100;
double percentOfForties = (countForties / iterationNumber) * 100;
String msg = "tens: " + percentOfTens + "%" + System.lineSeparator();
msg += "twenties: " + percentOfTwenties + "%" + System.lineSeparator();
msg += "thirties: " + percentOfThirties + "%" + System.lineSeparator();
msg += "forties: " + percentOfForties + "%" + System.lineSeparator();
System.out.println(msg);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T17:13:49.157",
"Id": "441192",
"Score": "1",
"body": "Have you considered `RandomTree(int[] percentages, T[] items)`? You can then enforce `sum(percentages) == 100` much more effectively. From an API design perspective, it's problematic to support an `add` function where you have specific input restrictions across multiple calls. It's easy for clients to screw up the input."
}
] |
[
{
"body": "<h2>Validate using Builder pattern</h2>\n\n<p>Building a <code>RandomTree</code> follows a very canonical pattern: you add data, validate, and then start using the tree. However, your object-oriented design fails to reflect this: a valid or invalid <code>RandomTree</code> has the same type. I recommend using the Builder pattern to remedy this: instantiate a <code>RandomTree.Builder</code>, add entries to the builder, and then call a <code>build()</code> method to validate and return a <code>RandomTree</code>. If done properly, this guarantees that all <code>RandomTree</code> objects are valid. It also leads to a clean separation of validation and sampling code.</p>\n\n<h2>Simplify approximate double equality</h2>\n\n<p>If you use <code>Math.abs</code> properly, you should be able to deal with the cases where sum is slightly too high and slightly too low at the same time.</p>\n\n<h2>Use simpler data structure</h2>\n\n<p>Using your tree, each call to <code>getRandomElement</code> takes time O(log(n)); this is already very fast. However, building the tree takes time O(n log(n)).</p>\n\n<p>We can do better using a simple array: store the same \"cumulative probability\" values you currently have in your tree in an array. Then binary search the array to find the ceiling entry. This too takes time O(log(n)) to search, but only takes O(n) to build. Concretely, searching a list should be a bit faster than searching a tree; you'd have to do some profiling to test this.</p>\n\n<h2>Randomness</h2>\n\n<p>Percents are kind of arbitrary; a much more natural way to represent probabilities in with numbers in [0,1]. You can always divide the input by 100 if need be.</p>\n\n<p>In addition, you should let the caller pass in an instance of <code>Random</code> to <code>getRandomElement</code>. Since your class doesn't care how the randomness arises, this allows more flexibility.</p>\n\n<h2>Changes</h2>\n\n<p>Here is my stab at the changes (comments omitted)</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Random;\n\npublic class RandomSampler<T> {\n private static final double PRECISION = 0.001;\n\n public static class Builder<T> {\n private List<T> items;\n private List<Double> probabilities;\n\n private Builder() {\n this.items = new ArrayList<T>();\n this.probabilities = new ArrayList<Double>();\n }\n\n public void add(final T item, final double probability) {\n this.items.add(item);\n this.probabilities.add(probability);\n }\n\n public RandomSampler<T> build() {\n return new RandomSampler<T>(items, probabilities);\n }\n }\n\n public static <T> Builder<T> builder() {\n return new Builder<T>();\n }\n\n private final List<T> items;\n private final double[] cumulativeProbabilities;\n\n private RandomSampler(final List<T> items, final List<Double> probabilities) {\n double cumulativeProbability = 0.0;\n\n this.items = items;\n this.cumulativeProbabilities = new double[items.size()];\n\n Iterator<Double> it = probabilities.iterator();\n for (int i = 0; i < items.size(); i++) {\n cumulativeProbability += it.next();\n this.cumulativeProbabilities[i] = cumulativeProbability;\n }\n\n if (Math.abs(cumulativeProbability - 1.0) > PRECISION) {\n throw new IllegalStateException(\"probabilities do not sum to 1.0\");\n } else {\n // fix last cumulative probability to 1.0\n this.cumulativeProbabilities[items.size() - 1] = 1.0;\n }\n }\n\n public T getRandomElement(Random rand) {\n double choice = rand.nextDouble();\n\n // equal to (-(i)-1) where cumulativeProbabilities[i] is the first element > choice\n int searchResult = Arrays.binarySearch(this.cumulativeProbabilities, choice);\n int i = -(searchResult + 1);\n\n return this.items.get(i);\n }\n}\n</code></pre>\n\n<pre><code>import java.util.concurrent.ThreadLocalRandom;\n\npublic class RandomSamplerTest {\n\n public static void main(String[] args) {\n RandomSampler.Builder<String> builder = RandomSampler.builder();\n\n builder.add(\"ten\", 0.1);\n builder.add(\"twenty\", 0.2);\n builder.add(\"thirty\", 0.3);\n builder.add(\"forty\", 0.4);\n\n RandomSampler<String> sampler = builder.build();\n ThreadLocalRandom rand = ThreadLocalRandom.current();\n\n int countTens = 0;\n int countTwenties = 0;\n int countThirties = 0;\n int countForties = 0;\n\n final double iterationNumber = 1000;\n\n for(int i = 0; i < iterationNumber; i++) {\n String num = sampler.getRandomElement(rand);\n\n switch(num) {\n case \"ten\":\n countTens++;\n break;\n case \"twenty\":\n countTwenties++;\n break;\n case \"thirty\":\n countThirties++;\n break;\n case \"forty\":\n countForties++;\n break;\n }\n }\n\n double percentOfTens = (countTens / iterationNumber) * 100;\n double percentOfTwenties = (countTwenties / iterationNumber) * 100;\n double percentOfThirties = (countThirties / iterationNumber) * 100;\n double percentOfForties = (countForties / iterationNumber) * 100;\n\n String msg = \"tens: \" + percentOfTens + \"%\" + System.lineSeparator();\n msg += \"twenties: \" + percentOfTwenties + \"%\" + System.lineSeparator();\n msg += \"thirties: \" + percentOfThirties + \"%\" + System.lineSeparator();\n msg += \"forties: \" + percentOfForties + \"%\" + System.lineSeparator();\n\n System.out.println(msg);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T20:09:59.380",
"Id": "226872",
"ParentId": "226860",
"Score": "2"
}
},
{
"body": "<p>How much storage space and accuracy are you willing to trade for O(1)?</p>\n\n<p>Initialize a 100 element array that contains all samples (60 brown eyes, 30 blue eyes, and 10 green eyes) and pick an index randomly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T06:07:21.067",
"Id": "441275",
"Score": "1",
"body": "This idea works quite well for integer (or even rational valued) percentages; but not for arbitrary doubles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T06:13:16.380",
"Id": "441276",
"Score": "0",
"body": "That's right. The correct balance of accuracy, performance and storage must be selected to match the requirements."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T05:46:31.210",
"Id": "226892",
"ParentId": "226860",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "226872",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T17:02:42.600",
"Id": "226860",
"Score": "4",
"Tags": [
"java",
"performance",
"tree",
"random"
],
"Title": "Data structure that retrieves each item with a specified probability"
}
|
226860
|
<p>This question is the second version of the code <a href="https://codereview.stackexchange.com/questions/226709/javascript-tree-class">here</a>.</p>
<p>I'm writing a general tree class. Specifically, each node should have oen parent, some number of children, and hold a value.</p>
<p>I'm looking for general advice on how to make this code more idiomatic. I'm also looking for thoughts on the <code>traverse</code> function, any functions that should be present in a general tree class but aren't, and also any way to simplify the existing functions.</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>// Code to review
class Node {
constructor(value = 0, children = []) {
this.value = value;
this.children = children;
}
traverse({ preorder, postorder, levelorder }) {
if (levelorder) {
let nodes = [this];
while (nodes.length > 0) {
const current = nodes.shift();
levelorder(current);
nodes = nodes.concat(current.children);
}
}
else {
if (preorder) preorder(this);
this.children.forEach(n => n.traverse({ preorder, postorder }));
if (postorder) postorder(this);
}
return this;
}
clone() {
const copy = n => Object.assign(new Node(), n);
let that = copy(this);
that.traverse({ preorder: n => n.children = n.children.map(copy) });
return that;
}
map(callback) {
let that = this.clone();
that.traverse({ levelorder: n => n.value = callback(n.value) });
return that;
}
reduce(callback, initial) {
let a = initial;
this.traverse({ levelorder: n => a = (n === this && initial === undefined)? n.value: callback(a, n.value) });
return a;
}
filter(callback) {
let that = this.clone();
that.traverse({ levelorder: n => n.children = n.children.filter(m => callback(m.value)) });
return that;
}
every(callback) {
return Boolean(this.reduce((a, b) => a && callback(b), true));
}
some(callback) {
return Boolean(this.reduce((a, b) => a || callback(b), false));
}
find(callback) {
return this.reduce((a, b) => (callback(b)? a.push(b): null, a), []);
}
includes(value) {
return this.some(a => a === value);
}
}
// Testing code
let tree = new Node(0);
let a = new Node(1);
let b = new Node(2);
let c = new Node(3);
let d = new Node(4);
let e = new Node(5);
let f = new Node(6);
tree.children = [a, b, c];
a.children = [d];
d.children = [e, f];
console.log("\nmap", tree.map(a => a + "2"));
console.log("\nreduce", tree.reduce((a, b) => String(a) + String(b)));
console.log("\nfilter", tree.filter(a => a < 3));
console.log("\nevery", tree.every(a => a < 3));
console.log("\nsome", tree.some(a => a < 3))
console.log("\nfind", tree.find(a => a > 2));
console.log("\nincludes", tree.includes(3));</code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<h3>Review</h3>\n\n<p>Well written API, but I am not happy with this one:</p>\n\n<blockquote>\n<pre><code>traverse({ preorder, postorder, levelorder })\n</code></pre>\n</blockquote>\n\n<p><code>preorder</code> and <code>postorder</code> can be combined, but they are always mutually exclusive with <code>levelorder</code>.</p>\n\n<blockquote>\n<pre><code>traverse({ preorder, postorder, levelorder }) {\n if (levelorder) {\n // levelorder ..\n }\n else {\n // preorder conditional and/or postorder conditional ..\n }\n return this;\n}\n</code></pre>\n</blockquote>\n\n<p>Instead, use 2 separate methods, each doing their own well known type of traversal.</p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Depth-first_search\" rel=\"nofollow noreferrer\">DFS</a></p>\n\n<pre><code> traverseDepthFirst({ preorder, postorder })\n</code></pre>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Breadth-first_search\" rel=\"nofollow noreferrer\">BFS</a></p>\n\n<pre><code> traverseBreadthFirst({ levelorder })\n</code></pre>\n\n<p>Some general thoughts:</p>\n\n<ul>\n<li>should you allow cyclic graphs? </li>\n<li>should you want to traverse up the ancestors?</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T17:21:49.343",
"Id": "226864",
"ParentId": "226861",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T17:04:54.490",
"Id": "226861",
"Score": "3",
"Tags": [
"javascript",
"tree",
"reinventing-the-wheel",
"breadth-first-search",
"depth-first-search"
],
"Title": "Javascript Tree Class 2"
}
|
226861
|
<p>I have rewritten my tokenizer according to most of the suggestions from the previous question <a href="https://codereview.stackexchange.com/questions/226739/simple-tokenizer-v1-reading-char-by-char">here</a>. </p>
<h3>API</h3>
<p>It now reads all chars as long as they match the pattern. I use three types of attributes to achieve this. </p>
<ul>
<li><code>Regex</code> - reads by regular expressions; this one requires a single group that is the value of the token; it can match more but only the value of <code>Groups[1]</code> is used as a result</li>
<li><code>Const</code> - reads a constant pattern where the entire length must match</li>
<li><code>QText</code> - reads quoted text or falls back to regex. I chose not to use regex for quoted strings because this is pretty damn tricky.</li>
</ul>
<p>They return a tuple where:</p>
<ul>
<li><code>Success</code> - indicates whther a pattern was matched</li>
<li><code>Token</code> - the actual value of the token</li>
<li><code>Length</code> - the total length of the match; I use this to advance the index to the next token</li>
</ul>
<p>These are the tree attributes:</p>
<pre><code>public delegate (bool Success, string Token, int Length) MatchDelegate(string value, int offset);
public abstract class MatcherAttribute : Attribute
{
public abstract (bool Success, string Token, int Length) Match(string value, int offset);
}
public class RegexAttribute : MatcherAttribute
{
private readonly Regex _regex;
public RegexAttribute([RegexPattern] string pattern)
{
_regex = new Regex(pattern);
}
public override (bool Success, string Token, int Length) Match(string value, int offset)
{
var match = _regex.Match(value, offset);
// Make sure the match was at the offset.
return (match.Success && match.Index == offset, match.Groups[1].Value, match.Length);
}
}
public class ConstAttribute : MatcherAttribute
{
private readonly string _pattern;
public ConstAttribute(string pattern) => _pattern = pattern;
public override (bool Success, string Token, int Length) Match(string value, int offset)
{
var matchCount = _pattern.TakeWhile((t, i) => value[offset + i].Equals(t)).Count();
// All characters have to be matched.
return (matchCount == _pattern.Length, _pattern, matchCount);
}
}
// "foo \"bar\" baz"
// ^ starts here ^ ends here
public class QTextAttribute : RegexAttribute
{
public static readonly IImmutableSet<char> Escapables = new[] { '\\', '"' }.ToImmutableHashSet();
public QTextAttribute([RegexPattern] string pattern) : base(pattern) { }
public override (bool Success, string Token, int Length) Match(string value, int offset)
{
return
value[offset] == '"'
? MatchQuoted(value, offset)
: base.Match(value, offset);
}
private (bool Success, string Token, int Length) MatchQuoted(string value, int offset)
{
var token = new StringBuilder();
var escapeSequence = false;
var quote = false;
for (var i = offset; i < value.Length; i++)
{
var c = value[i];
switch (c)
{
case '"' when !escapeSequence:
switch (i == offset)
{
// Entering quoted text.
case true:
quote = !quote;
continue; // Don't eat quotes.
// End of quoted text.
case false:
return (true, token.ToString(), i - offset + 1);
}
break; // Makes the compiler happy.
case '\\' when !escapeSequence:
escapeSequence = true;
break;
default:
switch (escapeSequence)
{
case true:
switch (Escapables.Contains(c))
{
case true:
// Remove escape char.
token.Length--;
break;
}
escapeSequence = false;
break;
}
break;
}
token.Append(c);
}
return (false, token.ToString(), 0);
}
}
</code></pre>
<p>The tokenizer is now an instantiable class with an interface. It can be used <em>raw</em> or be derived to create a specific tokenizer. When created, it turns state transitions into a dictionary. This is what the <code>StateTransitionMapper</code> is for. The tokenizer picks the first non-empty token. I guess I probably should use the longest one - as this is what different websites suggest - so I might change this later. What do you think? Would that be better?</p>
<p>It starts with the <code>default</code> state which is by convention <code>0</code> becuase <code>TToken</code> is constrained to be <code>Enum</code> and its default value is <code>0</code>. I named this <em>dummy</em> state simply <code>Start</code>.</p>
<pre><code>public static class StateTransitionMapper
{
public static IImmutableDictionary<TToken, IImmutableList<State<TToken>>> CreateTransitionMap<TToken>(IImmutableList<State<TToken>> states) where TToken : Enum
{
return states.Aggregate(ImmutableDictionary<TToken, IImmutableList<State<TToken>>>.Empty, (mappings, state) =>
{
var nextStates =
from n in state.Next
join s in states on n equals s.Token
select s;
return mappings.Add(state.Token, nextStates.ToImmutableList());
});
}
}
public interface ITokenizer<TToken> where TToken : Enum
{
IEnumerable<Token<TToken>> Tokenize(string value);
}
public class Tokenizer<TToken> : ITokenizer<TToken> where TToken : Enum
{
private readonly IImmutableDictionary<TToken, IImmutableList<State<TToken>>> _transitions;
public Tokenizer(IImmutableList<State<TToken>> states)
{
_transitions = StateTransitionMapper.CreateTransitionMap(states);
}
public IEnumerable<Token<TToken>> Tokenize(string value)
{
var current = _transitions[default];
for (var i = 0; i < value.Length;)
{
var matches =
from state in current
let token = state.Consume(value, i)
// Consider only non-empty tokens.
where token.Length > 0
select (state, token);
if (matches.FirstOrDefault() is var match && match.token is null)
{
throw new ArgumentException($"Invalid character '{value[i]}' at {i}.");
}
else
{
if (match.state.IsToken)
{
yield return match.token;
}
i += match.token.Length;
current = _transitions[match.state.Token];
}
}
}
}
</code></pre>
<p>The tokenizer is supported by the <code>State</code> and <code>Token</code> classes where the <code>State</code> now reads all matching chars and <em>caches</em> the <code>MatchDelegate</code> it gets from the <code>MatcherAttribute</code>. <code>IsToken</code> property is used to ignore tokens that aren't actually <em>real</em> or usable tokens. I use this with the <code>CommandLineTokenizer</code>.</p>
<pre><code>public class State<TToken> where TToken : Enum
{
private readonly MatchDelegate _match;
public State(TToken token, params TToken[] next)
{
Token = token;
Next = next;
_match =
typeof(TToken)
.GetField(token.ToString())
.GetCustomAttribute<MatcherAttribute>() is MatcherAttribute matcher
? (MatchDelegate)(matcher.Match)
: (MatchDelegate)((value, offset) => (false, string.Empty, 0));
}
public bool IsToken { get; set; } = true;
public TToken Token { get; }
public IEnumerable<TToken> Next { get; }
public Token<TToken> Consume(string value, int offset)
{
return new Token<TToken>(_match(value, offset))
{
Type = Token,
Index = offset
};
}
public override string ToString() => $"{Token} --> [{string.Join(", ", Next)}]";
}
public class Token<TToken> where TToken : Enum
{
public Token((bool Success, string Token, int Length) match)
{
Length = match.Success ? match.Length : 0;
Text = match.Success ? match.Token : string.Empty;
}
public int Index { get; set; }
public int Length { get; set; }
public string Text { get; set; }
public TToken Type { get; set; }
public override string ToString() => $"{Index}: {Text} ({Type})";
}
</code></pre>
<h3>Examples and tests</h3>
<p>I tested it with two tokenizers. They are very simple because just derived from the <code>Tokenizer</code>. They define their own state transitions and tokens.</p>
<p>One if for a <code>UriString</code>:</p>
<pre><code>using static UriToken;
public class UriStringParserTest
{
private static readonly ITokenizer<UriToken> Tokenizer = new UriStringTokenizer();
[Theory]
[InlineData(
"scheme://user@host:123/pa/th?key-1=val-1&key-2=val-2#f",
"scheme //user host 123/pa/th key-1 val-1 key-2 val-2 f")]
[InlineData(
"scheme://user@host:123/pa/th?key-1=val-1&key-2=val-2",
"scheme //user host 123/pa/th key-1 val-1 key-2 val-2")]
[InlineData(
"scheme://user@host:123/pa/th?key-1=val-1",
"scheme //user host 123/pa/th key-1 val-1")]
[InlineData(
"scheme://user@host:123/pa/th",
"scheme //user host 123/pa/th")]
[InlineData(
"scheme:///pa/th",
"scheme ///pa/th"
)]
public void Can_tokenize_URIs(string uri, string expected)
{
var tokens = Tokenizer.Tokenize(uri).ToList();
var actual = string.Join("", tokens.Select(t => t.Text));
Assert.Equal(expected.Replace(" ", string.Empty), actual);
}
[Fact]
public void Throws_when_invalid_character()
{
// Using single letters for faster debugging.
var uri = "s://:u@h:1/p?k=v&k=v#f";
// ^ - invalid character
var ex = Assert.Throws<ArgumentException>(() => Tokenizer.Tokenize(uri).ToList());
Assert.Equal("Invalid character ':' at 4.", ex.Message);
}
}
public class UriStringTokenizer : Tokenizer<UriToken>
{
/*
scheme:[//[userinfo@]host[:port]]path[?key=value&key=value][#fragment]
[ ----- authority ----- ] [ ----- query ------ ]
scheme: ------------------------ '/'path ------------------------- --------- UriString
\ / \ /\ /
// --------- host ----- / ?key ------ &key ------ / #fragment
\ / \ / \ / \ /
userinfo@ :port =value =value
*/
private static readonly State<UriToken>[] States =
{
new State<UriToken>(default, Scheme),
new State<UriToken>(Scheme, AuthorityPrefix, Path),
new State<UriToken>(AuthorityPrefix, UserInfo, Host, Path),
new State<UriToken>(UserInfo, Host),
new State<UriToken>(Host, Port, Path),
new State<UriToken>(Port, Path),
new State<UriToken>(Path, Key, Fragment),
new State<UriToken>(Key, UriToken.Value, Fragment),
new State<UriToken>(UriToken.Value, Key, Fragment),
new State<UriToken>(Fragment, Fragment),
};
public UriStringTokenizer() : base(States.ToImmutableList()) { }
}
public enum UriToken
{
Start = 0,
[Regex(@"([a-z0-9\+\.\-]+):")]
Scheme,
[Const("//")]
AuthorityPrefix,
[Regex(@"([a-z0-9_][a-z0-9\.\-_:]+)@")]
UserInfo,
[Regex(@"([a-z0-9\.\-_]+)")]
Host,
[Regex(@":([0-9]*)")]
Port,
[Regex(@"(\/?[a-z_][a-z0-9\/:\.\-\%_@]+)")]
Path,
[Regex(@"[\?\&\;]([a-z0-9\-]*)")]
Key,
[Regex(@"=([a-z0-9\-]*)")]
Value,
[Regex(@"#([a-z]*)")]
Fragment,
}
</code></pre>
<p>and the other for a <code>CommandLine</code>:</p>
<pre><code>using static CommandLineToken;
public class CommandLineTokenizerTest
{
private static readonly ITokenizer<CommandLineToken> Tokenizer = new CommandLineTokenizer();
[Theory]
[InlineData(
"command -argument value -argument",
"command argument value argument")]
[InlineData(
"command -argument value value",
"command argument value value")]
[InlineData(
"command -argument:value,value",
"command argument value value")]
[InlineData(
"command -argument=value",
"command argument value")]
[InlineData(
@"command -argument=""foo--bar"",value -argument value",
@"command argument foo--bar value argument value")]
[InlineData(
@"command -argument=""foo--\""bar"",value -argument value",
@"command argument foo-- ""bar value argument value")]
public void Can_tokenize_command_lines(string uri, string expected)
{
var tokens = Tokenizer.Tokenize(uri).ToList();
var actual = string.Join("", tokens.Select(t => t.Text));
Assert.Equal(expected.Replace(" ", string.Empty), actual);
}
}
public enum CommandLineToken
{
Start = 0,
[Regex(@"\s*(\?|[a-z0-9][a-z0-9\-_]*)")]
Command,
[Regex(@"\s*[\-\.\/]([a-z0-9][a-z\-_]*)")]
Argument,
[Regex(@"[\=\:\,\s]")]
ValueBegin,
[QText(@"([a-z0-9\.\;\-]*)")]
Value,
}
public class CommandLineTokenizer : Tokenizer<CommandLineToken>
{
/*
command [-argument][=value][,value]
command --------------------------- CommandLine
\ /
-argument ------ ------ /
\ / \ /
=value ,value
*/
private static readonly State<CommandLineToken>[] States =
{
new State<CommandLineToken>(default, Command),
new State<CommandLineToken>(Command, Argument),
new State<CommandLineToken>(Argument, Argument, ValueBegin),
new State<CommandLineToken>(ValueBegin, Value) { IsToken = false },
new State<CommandLineToken>(Value, Argument, ValueBegin),
};
public CommandLineTokenizer() : base(States.ToImmutableList()) { }
}
</code></pre>
<hr>
<h3>Questions</h3>
<ul>
<li>Would you say this is an improvement?</li>
<li>Maybe something is still too unconventional? I guess this is probably still not a <em>true</em> state-machine becuase of the <em>loop</em> inside the tokenizer. Am I right?</li>
<li>Did I miss any important suggestion or misinterpreted it?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T17:41:25.717",
"Id": "441197",
"Score": "1",
"body": "Impressive refactoring, I like this approach. The loop in tokenizer is fine, the important part is that _state_ decides how much to consume at _i_. A _true_ state machine is hard to define because many different models exist. Even the simplest _yield_ generator could very well be a proper state machine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T18:00:21.607",
"Id": "441204",
"Score": "0",
"body": "This _chaos_ can also be viewed as a single file on [GitHub](https://github.com/he-dev/reusable/blob/dev/Reusable.Tests/src/Experimental/UriStringTokenizerTest_v3.cs)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T18:06:02.897",
"Id": "441210",
"Score": "0",
"body": "Since there is no clear spec for command line, I take it we can do requests :p there is a second quote 'my quoted string that allows \"double quotes\" as part of the literal'."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T18:07:23.857",
"Id": "441211",
"Score": "0",
"body": "@dfhwze not in my matrix :-P too many _standards_ is unhealthy ;-] I like it pragmatic and not _let's support everything we can only think of, no matter how insane and useless this is_ alghouth the framework could handle that too. I will try it with json in a couple of days but for this I will need a new matcher for comments. This will then definitely require both types of quotes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T18:12:13.943",
"Id": "441213",
"Score": "0",
"body": "One more thing about command line: _\"my value\"_ is a quoted value, but is _my\" value\"_ also a proper value? Or are double quotes not just literal regions, but also value delimiters?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T18:14:14.190",
"Id": "441214",
"Score": "0",
"body": "@dfhwze only quoted values count. `my\"value\"` would be invalid because there is no valid delimiter before it... it must be either a white-space or a comma. I wonder whether this thing can handle it - it should throw. I'll check that tommorow. The same principle as with json. quotes must enclose the entire value. anything else would be wrong. The only difference is that \"continuous\" values don't require quotes. Think of it as a friendly command line without all that crap with one hundred syntaxes :-]"
}
] |
[
{
"body": "<h2><code>MatchDelegate</code></h2>\n\n<p>Much as I love .NET's nominal delegates, I almost always regret using a <code>delegate</code> rather than an <code>interface</code>, so I would introduced an <code>IMatcher</code> (which <code>MatcherAttribute</code> can implement directly) in its place. Granted delegates usually go wrong because I need to serialise them, which won't be an issue here, but the ability to attach meta data could be useful.</p>\n\n<h2>The Tuple</h2>\n\n<p>And as you know, I loathe tuples with a passion (when part of a public API), and would instead provide a dedicated <code>MatchResult</code> type, which can provide the same accessors but a nicer API for creation (e.g. providing one constructor for <code>Token</code> and <code>Length</code> (corresponding to success), and a <code>static readonly</code> corresponding to failure. The 'success' constructor can do all manner of wonderful checks to ensure that when you try to return nonsense that you are shouted at before it can do any damage (e.g. <code>Token != null && Length >= Token.Length</code>). This will also significantly declutter the code (which is full of <code>(bool Success, string Token, int Length)</code> at the moment), improve maintainability (you can modify the type in future without having to 'fix' everything that uses it), and you'll make <em>me</em> less miserable, which will make <em>you</em> feel warm and fuzzy inside. You can even add a <code>Deconstructor</code> magic-method if you really wish to access the tree attributes in such a manner. I'd also expect <code>MatchResult</code> to be immutable, which a <code>ValueTuple</code> cannot give you.</p>\n\n<h2><code>RegexTextAttribute</code></h2>\n\n<p>You might want to look at the <code>\\G</code> regex token, which forces the match to occur at the exact position: this will avoid the match position check, and significantly improve performance for failed matches. I'm not sure how versatile <code>\\G</code> is, but combined with lookaheads I doubt there is anything it can't give you. See the remarks on <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.match?redirectedfrom=MSDN&view=netframework-4.8#System_Text_RegularExpressions_Regex_Match_System_String_System_Int32_\" rel=\"nofollow noreferrer\">Regex.Match</a> (ctrl-f for <code>\"\\G\"</code>).</p>\n\n<h2><code>QTextAttribute</code></h2>\n\n<p>You could make the compiler happy by using <code>if (i == offset)</code> instead of the <code>switch</code>, which will be easier to maintain because it won't have code lying around for the sole purpose of making the compiler happy.</p>\n\n<p>Regarding <code>// Don't eat quotes</code>, it seems that you an I have different definitions of 'eat', which suggests maybe a clearer term is in order.</p>\n\n<p>I don't understand this: <code>return (false, token.ToString(), 0);</code></p>\n\n<h2><code>Tokenize</code></h2>\n\n<p>I think <code>if (matches.FirstOrDefault() is var match ...)</code> might as wall be <code>match = matches.FirstOrDefault()</code>. This would have the benefit of not being thoroughly confusing, since if that conditions was to fail the code would crash, but I don't believe it ever can.</p>\n\n<p>I don't see the point in generating the tuple when you generate <code>matches</code>: I would find the match first, then generate the token if there was a successful match. This removes the tuple (did I mention I don't like tuples?), and would rip up <code>Consume</code>.</p>\n\n<p>You might as well provide the parameter name for the <code>ArgumentException</code>: it just gives you that little bit more confidence that <code>Tokenize</code> is throwing the exception, and it isn't some re-packaged message.</p>\n\n<p>I think the increment should be <code>i += match.Length</code>.</p>\n\n<h2><code>State<TToken></code></h2>\n\n<p>I don't see the need to restrict <code>TToken</code> to an <code>Enum</code>, and I don't understand why <code>IsToken</code> isn't readonly and assigned in the constructor. Following on, I don't like that <code>State<TToken></code> is tied to the attributes: why not provide a constructor that allows you to determine the matcher as well?</p>\n\n<p><code>Consume</code> should return <code>null</code> for a failed match, so that anyone trying to use it finds out sooner than later. I don't think <code>Token<TToken>..ctor</code> should take a <code>MatchResult</code> (tuple thing): why does it care it came from a match? If it will take a <code>MatchResult</code>, then it should throw on an unsuccessful match. I also think it is bad that you don't allow empty matches: they could be misused to create misery, but equally there is no documentation saying the match must be non-empty, and they could be useful for 'optional' components.</p>\n\n<h2>Misc</h2>\n\n<p>As always, inline documentation would be appreciated.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T02:52:48.597",
"Id": "441248",
"Score": "1",
"body": "Reading this at 4.47 in the morning :-) I like all the suggestions. About that making the compiler happy, I like it sometimes _switchy_ - it's on purpose without _if_s lol I'll use more comments in future that document these conventions. Your review shows me how many assumptions I made that I wasn't really aware of. This means again, more comments to the rescue!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T01:50:29.993",
"Id": "226882",
"ParentId": "226863",
"Score": "8"
}
},
{
"body": "<h3>General thoughts</h3>\n\n<p>You have managed to create a somewhat elegant API that balances between a state machine pattern and a regex engine. This is reusable for small and context-free use cases, but will get to haunt you if you need to <em>tokenize</em> more complex and context-bound grammars. </p>\n\n<p>I can only add to VisualMelon's spot-on review:</p>\n\n<ul>\n<li>Tuples are fantastic constructs for internal data representation of an API, utility classes to avoid boiler-plate classes/structs. For the public connection points of any API however, they are more of a code smell. They somehow hurt readability. I feel a class name adds so much more to an input or result argument.</li>\n<li>There is room for improvement when dealing with escape characters and sequences. Currently only the double quote gets escaped. You could make a mini API for this.</li>\n</ul>\n\n<h3>Commandline API</h3>\n\n<p>Although this API is kept very simple, it already shows how you'd have to manage/corrupt your token design, just to be able to maintain simple regex patterns.</p>\n\n<blockquote>\n<pre><code>public enum CommandLineToken\n{\n // .. other\n\n [Regex(@\"[\\=\\:\\,\\s]\")]\n ValueBegin,\n\n [QText(@\"([a-z0-9\\.\\;\\-]*)\")]\n Value,\n}\n</code></pre>\n</blockquote>\n\n<p>In my opinion, there should not be a distinction between <code>ValueBegin</code> and <code>Value</code>. They are both <code>Value</code> syntactically, only their semantics differ. I would never allow semantics to hurt my API design. This is a good example to show that regex only has benefits for the simpler grammars. Another proof to that point is that you required to make a custom pattern matcher <code>QTextAttribute</code>, because a regex would be too much pain to write (if even possible for balanced and escaped delimiters). </p>\n\n<p>I like the API for its simplicity, and I see use cases for it. However, I'm afraid for most use cases, as more functionality is added over time, you'd end up with convoluted tokens and complex regexes to maintain. A next step is to ditch the regex engine and go for a full blown <strong>lexer</strong>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T05:24:22.237",
"Id": "441264",
"Score": "0",
"body": "I always wonder about one thing. When there are already _professional_ lexers that can do a lot of _magic_ - why does everybody have to write their own parser every single time? It's like nobody uses these academic tools that can do virtually everything. I believe they aren't at all that good. Does json.net use any of these? nope. Does nlog use any of these? nope? does anyone at all use any of these? I don't think so. I know I might be reinventing the wheel but I'd like to have a wheel this is as round as possible and just some polygon for students ;-] and it's a great exercise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T05:26:46.270",
"Id": "441265",
"Score": "0",
"body": "I would not use a professional lexer, I would write my own, using a professional lexer generator ;-) There is a nice API you could check out NCalc. This shows you the power of generating a lexer and parser from a grammar using ANTLR and it allows for visitors and tree walking."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T05:28:58.623",
"Id": "441267",
"Score": "0",
"body": "tomato tomatho ... do you know any such tools? NCalc is exactly what I mean, an academic example. There aren't any _real_ products using these generators."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T05:32:53.667",
"Id": "441269",
"Score": "0",
"body": "Tools? Like lexer generators?: https://en.wikipedia.org/wiki/Lexical_analysis#Lexer_generator. Or what do you mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T05:34:23.647",
"Id": "441270",
"Score": "0",
"body": "yes, I mean the generators. Who is using them for real? Not as an experiment but for real real like in a very popular IDE/editor/framework/etc?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T05:35:22.010",
"Id": "441271",
"Score": "0",
"body": "Well I have written one myself heavily based on NCalc at a previous project. I needed to parse mathematical expressions, using custom functions and external parameters. Even recursive and dependant formulas. I found using lexer/parser generator was a great way. To be honest, I have no idea how to have done it any other way. I think writing an API for math expressions is a perfect candidate for it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T05:38:26.513",
"Id": "441272",
"Score": "0",
"body": "Also, if I were to write a full-blown command line parser, I would also go the lexer/parser way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T05:39:20.237",
"Id": "441273",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/97916/discussion-between-dfhwze-and-t3chb0t)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T05:13:59.260",
"Id": "226891",
"ParentId": "226863",
"Score": "4"
}
},
{
"body": "<h1>Unnecessary <code>switch</code>-statements</h1>\n\n<p><code>switch</code> statements are nice as a way of avoiding long chains of <code>if (){} else if(){} .... else {}</code> statements. Switching on a <code>bool</code> doesn't make much sense, as is much more unclear than using <code>if</code> statements. So replace this</p>\n\n<pre><code>switch (Escapables.Contains(c))\n{\n case true:\n // Remove escape char.\n token.Length--;\n break;\n}\n</code></pre>\n\n<p>for</p>\n\n<pre><code>if (Escapables.Contains(C))\n{\n // Remove escape char.\n token.Length--;\n}\n</code></pre>\n\n<p>and this</p>\n\n<pre><code>switch (i == offset)\n{\n // Entering quoted text.\n case true:\n quote = !quote;\n continue; // Don't eat quotes.\n\n // End of quoted text.\n case false:\n return (true, token.ToString(), i - offset + 1);\n}\n</code></pre>\n\n<p>for</p>\n\n<pre><code>if (i === offset)\n{\n // Entering quoted text.\n quote = !quote;\n continue; // Don't eat quotes.\n}\nelse \n{\n // End of quoted text.\n return (true, token.ToString(), i - offset + 1);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T11:15:18.590",
"Id": "441308",
"Score": "1",
"body": "This part was taken from my other question [here](https://codereview.stackexchange.com/questions/155364/command-line-parser-only-with-switches-if-less). You would love it too haha ;-]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T12:19:00.763",
"Id": "441322",
"Score": "0",
"body": "@t3chb0t I was wondering what it was about. ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T10:52:53.640",
"Id": "226911",
"ParentId": "226863",
"Score": "3"
}
},
{
"body": "<p>A couple of tiny tidbits:</p>\n\n<ol>\n<li><p>You could easily make <code>Token</code> immutable (removing the property setters) by passing <code>type</code> and <code>index</code> into the constructor as such:</p>\n\n<pre><code>public Token((bool Success, string Token, int Length) match, TToken type, int index)\n{\n (bool success, string token, int length) = match;\n this.Length = success ? length : 0;\n this.Text = success ? token : string.Empty;\n this.Type = type;\n this.Index = index;\n}\n</code></pre></li>\n</ol>\n\n<p>then you just have to adjust <code>Consume</code> in the <code>State</code> class like so:</p>\n\n<pre><code>public Token<TToken> Consume(string value, int offset)\n{\n return new Token<TToken>(_match(value, offset), Token, offset);\n}\n</code></pre>\n\n<ol start=\"2\">\n<li><code>Token</code> and <code>State</code> are, in my opinion, screaming to have their own interfaces:</li>\n</ol>\n\n<pre><code> public interface IState<TToken> where TToken : Enum\n {\n bool IsToken { get; }\n\n TToken Token { get; }\n\n IEnumerable<TToken> Next { get; }\n\n IToken<TToken> Consume(string value, int offset);\n }\n\n public interface IToken<TToken> where TToken : Enum\n {\n int Length { get; }\n\n string Text { get; }\n }\n</code></pre>\n\n<p>(adjust accordingly in the bunch of places they're used)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T16:57:47.180",
"Id": "226934",
"ParentId": "226863",
"Score": "2"
}
},
{
"body": "<p><em>(self-answer)</em></p>\n\n<hr>\n\n<p>I'll post another question when I made some more signifficant changes and for now I'll just summarize your feedback:</p>\n\n<p>Suggestions by <a href=\"https://codereview.stackexchange.com/a/226882/59161\">@VisualMelon</a></p>\n\n<ul>\n<li>✔ - no public tuples (but one small extension) (you need to forgive me)</li>\n<li>✔ - I must use the <code>\\G</code> anchor more often; this simplfied the <code>Regex</code> matching</li>\n<li>✔ - no more <em>Making the compiler happy</em> - removed <em>weird</em> <code>switche</code>s</li>\n<li>✔ - replaced mysterious <code>return (false, token.ToString(), 0)</code> with <code>MatchResult<T>.Failure</code></li>\n<li>✔ - <code>Tokenize</code> - a clean small <code>while</code> with a good looking <code>switch</code></li>\n<li>✔ - not generating tuples anymore; replaces with <code>MatchResult<T></code></li>\n<li>✔ - <code>State<TToken></code> is no longer restricted to <code>Enum</code>; instead, it now handles <code>TToken</code> via the new <code>MatcherProviderAttribute</code> that knows more about <code>TToken</code> and how to get <code>IMatcher</code></li>\n<li>✔ - <code>MatchDelegate</code> replaced with <code>IMacher</code> interface</li>\n<li>✔/✖ - <em>inline documentation</em> - I'm trying ;-]</li>\n</ul>\n\n<p>Suggestions by <a href=\"https://codereview.stackexchange.com/a/226891/59161\">@dfhwze</a></p>\n\n<ul>\n<li>✔ - both double and single quotes can be used; the first found is the one that must close a string</li>\n<li>✔ - no more <em>helper</em> tokens like <code>ValueBegin</code> that weren't returned</li>\n<li>✖ - <em>context-bound grammars</em> - maybe another time;</li>\n<li>✖ - <em>use a full blown lexer</em> - maybe another time; for now this is fun</li>\n</ul>\n\n<p>Suggestions by <a href=\"https://codereview.stackexchange.com/a/226911/59161\">@JAD</a></p>\n\n<ul>\n<li>✔ - no more <code>switch</code> flood</li>\n</ul>\n\n<blockquote class=\"spoiler\">\n <p> <strong>Conventions</strong> I might use some <em>unusual</em> conventions in my code and I think it's good to know them so that you're not surprised<br>\n - <code>else if</code> - this is worse than a <code>goto</code><br>\n - <code>is var x</code> - I like this expression so I often use it to create inline variables<br>\n - <code>?:</code> - I use this only for single expressions; who would want to debug a giant ternary; I prefer <code>if/else</code> with multiple conditions<br>\n - beware of <code>var str = default(string)</code> because I <strong>never</strong> define variables explicitly; this is not negotiable ;-P<br>\n - I use local functions to encapsulate <em>small</em> expressions<br>\n - I tend to (over)use <code>System.Collections.Immutable</code> because these classes have very convenient APIs<br>\n - I usually don't include parameter checking in proof-of-concept code </p>\n</blockquote>\n\n<h3>API</h3>\n\n<p>The <code>Tokenizer</code> is now only a small loop:</p>\n\n<pre><code>public interface ITokenizer<TToken> where TToken : Enum\n{\n IEnumerable<Token<TToken>> Tokenize(string value);\n}\n\npublic class Tokenizer<TToken> : ITokenizer<TToken> where TToken : Enum\n{\n private readonly IImmutableDictionary<TToken, IImmutableList<State<TToken>>> _transitions;\n\n public Tokenizer(IImmutableList<State<TToken>> states)\n {\n _transitions = StateTransitionMapper.CreateTransitionMap(states);\n }\n\n public IEnumerable<Token<TToken>> Tokenize(string value)\n {\n var state = _transitions[default];\n var offset = 0;\n\n while (Any())\n {\n // Using a switch because it looks good here. \n switch (state.Select(s => s.Match(value, offset)).FirstOrDefault(m => m.Success))\n {\n case null:\n throw new ArgumentException($\"Invalid character '{value[offset]}' at {offset}.\");\n\n case MatchResult<TToken> match:\n yield return new Token<TToken>(match.Token, match.Length, offset, match.TokenType);\n offset += match.Length;\n state = _transitions[match.TokenType];\n break;\n }\n }\n\n // Let's hide this ugly expression behind this nice helper.\n bool Any() => offset < value.Length - 1;\n }\n}\n\npublic static class StateTransitionMapper\n{\n // Turns the adjacency-list of states into a dictionary for faster lookup.\n public static IImmutableDictionary<TToken, IImmutableList<State<TToken>>> CreateTransitionMap<TToken>(IImmutableList<State<TToken>> states) where TToken : Enum\n {\n return states.Aggregate(ImmutableDictionary<TToken, IImmutableList<State<TToken>>>.Empty, (mappings, state) =>\n {\n var nextStates =\n from n in state.Next\n join s in states on n equals s.Token\n select s;\n\n return mappings.Add(state.Token, nextStates.ToImmutableList());\n });\n }\n}\n</code></pre>\n\n<h3>Supporting types</h3>\n\n<p>All other supporting types implementing the changes listed in the summary above.</p>\n\n<pre><code>public class MatchResult<TToken>\n{\n public MatchResult(string token, int length, TToken tokenType)\n {\n Success = true;\n Token = token;\n Length = length;\n TokenType = tokenType;\n }\n\n public static MatchResult<TToken> Failure(TToken tokenType) => new MatchResult<TToken>(string.Empty, 0, tokenType) { Success = false };\n\n public bool Success { get; private set; }\n\n public string Token { get; }\n\n public int Length { get; }\n\n public TToken TokenType { get; }\n}\n\npublic interface IMatcher\n{\n MatchResult<TToken> Match<TToken>(string value, int offset, TToken tokenType);\n}\n\npublic abstract class MatcherAttribute : Attribute, IMatcher\n{\n public abstract MatchResult<TToken> Match<TToken>(string value, int offset, TToken tokenType);\n}\n\n// Can recognize regexable patterns.\n// The pattern requires one group that is the token to return. \npublic class RegexAttribute : MatcherAttribute\n{\n private readonly Regex _regex;\n\n public RegexAttribute([RegexPattern] string prefixPattern)\n {\n _regex = new Regex($@\"\\G{prefixPattern}\");\n }\n\n public override MatchResult<TToken> Match<TToken>(string value, int offset, TToken tokenType)\n {\n return\n _regex.Match(value, offset) is var match && match.Success\n ? new MatchResult<TToken>(match.Groups[1].Value, match.Length, tokenType)\n : MatchResult<TToken>.Failure(tokenType);\n }\n}\n\n// Can recognize constant patterns.\npublic class ConstAttribute : MatcherAttribute\n{\n private readonly string _pattern;\n\n public ConstAttribute(string pattern) => _pattern = pattern;\n\n public override MatchResult<TToken> Match<TToken>(string value, int offset, TToken tokenType)\n {\n return\n // All characters have to be matched.\n MatchLength() == _pattern.Length\n ? new MatchResult<TToken>(_pattern, _pattern.Length, tokenType)\n : MatchResult<TToken>.Failure(tokenType);\n\n int MatchLength() => _pattern.TakeWhile((t, i) => value[offset + i].Equals(t)).Count();\n }\n}\n\n// Assists regex in tokenizing quoted strings because regex has no memory of what it has seen.\n// Requires two patterns:\n// - one for the separator because it has to know where the value begins\n// - the other for an unquoted value if it's not already quoted\npublic class QTextAttribute : MatcherAttribute\n{\n public static readonly IImmutableSet<char> Escapables = new[] { '\\\\', '\"', '\\'' }.ToImmutableHashSet();\n\n private readonly Regex _prefixRegex;\n private readonly Regex _unquotedValuePattern;\n\n public QTextAttribute([RegexPattern] string separatorPattern, [RegexPattern] string unquotedValuePattern)\n {\n _prefixRegex = new Regex($@\"\\G{separatorPattern}\");\n _unquotedValuePattern = new Regex($@\"\\G{unquotedValuePattern}\");\n }\n\n public override MatchResult<TToken> Match<TToken>(string value, int offset, TToken tokenType)\n {\n if (_prefixRegex.Match(value, offset) is var prefixMatch && prefixMatch.Success)\n {\n if (MatchQuoted(value, offset + prefixMatch.Length, tokenType) is var matchQuoted && matchQuoted.Success)\n {\n return matchQuoted;\n }\n else\n {\n if (_unquotedValuePattern.Match(value, offset + prefixMatch.Length) is var valueMatch && valueMatch.Groups[1].Success)\n {\n return new MatchResult<TToken>(valueMatch.Groups[1].Value, prefixMatch.Length + valueMatch.Length, tokenType);\n }\n }\n }\n\n return MatchResult<TToken>.Failure(tokenType);\n }\n\n // \"foo \\\"bar\\\" baz\"\n // ^ start ^ end\n private static MatchResult<TToken> MatchQuoted<TToken>(string value, int offset, TToken tokenType)\n {\n var token = new StringBuilder();\n var escapeSequence = false;\n var quote = '\\0'; // Opening/closing quote.\n\n foreach (var (c, i) in value.SkipFastOrDefault(offset).SelectIndexed())\n {\n if (i == 0)\n {\n if (@\"'\"\"\".Contains(c))\n {\n quote = c;\n }\n else\n {\n // It doesn't start with a quote. This is unacceptable. Either an empty value or an unquoted one.\n return MatchResult<TToken>.Failure(tokenType);\n }\n }\n else\n {\n if (c == '\\\\' && !escapeSequence)\n {\n escapeSequence = true;\n }\n else\n {\n if (escapeSequence)\n {\n if (Escapables.Contains(c))\n {\n // Remove escape char. We don't need them in the result.\n token.Length--;\n }\n\n escapeSequence = false;\n }\n else\n {\n if (c == quote)\n {\n // +2 because there were two quotes.\n return new MatchResult<TToken>(token.ToString(), i + 2, tokenType);\n }\n }\n }\n\n token.Append(c);\n }\n }\n\n return MatchResult<TToken>.Failure(tokenType);\n }\n}\n\npublic static class StringExtensions\n{\n // Doesn't enumerate the string from the beginning for skipping.\n public static IEnumerable<char> SkipFastOrDefault(this string source, int offset)\n {\n // Who uses for-loop these days? Let's hide it here so nobody can see this monster.\n for (var i = offset; i < source.Length; i++)\n {\n yield return source[i];\n }\n }\n\n // Doesn't enumerate a collection from the beginning if it implements `IList<T>`.\n // Falls back to the default `Skip`.\n public static IEnumerable<T> SkipFastOrDefault<T>(this IEnumerable<T> source, int offset)\n {\n // Even more for-loops to hide.\n switch (source)\n {\n case IList<T> list:\n for (var i = offset; i < list.Count; i++)\n {\n yield return list[i];\n }\n\n break;\n\n default:\n foreach (var item in source.Skip(offset))\n {\n yield return item;\n }\n\n break;\n }\n }\n}\n\npublic static class EnumerableExtensions\n{\n // This is so common that it deserves its own extension.\n public static IEnumerable<(T Item, int Index)> SelectIndexed<T>(this IEnumerable<T> source)\n {\n return source.Select((c, i) => (c, i));\n }\n}\n\npublic abstract class MatcherProviderAttribute : Attribute\n{\n public abstract IMatcher GetMatcher<TToken>(TToken token);\n}\n\npublic class EnumMatcherProviderAttribute : MatcherProviderAttribute\n{\n public override IMatcher GetMatcher<TToken>(TToken token)\n {\n if (!typeof(TToken).IsEnum) throw new ArgumentException($\"Token must by of Enum type.\");\n\n return\n typeof(TToken)\n .GetField(token.ToString())\n .GetCustomAttribute<MatcherAttribute>();\n }\n}\n\npublic class State<TToken> where TToken : Enum\n{\n private readonly IMatcher _matcher;\n\n public State(TToken token, params TToken[] next)\n {\n Token = token;\n Next = next;\n _matcher =\n typeof(TToken)\n .GetCustomAttribute<MatcherProviderAttribute>()\n .GetMatcher(token);\n }\n\n public TToken Token { get; }\n\n public IEnumerable<TToken> Next { get; }\n\n public MatchResult<TToken> Match(string value, int offset) => _matcher.Match(value, offset, Token);\n\n public override string ToString() => $\"{Token} --> [{string.Join(\", \", Next)}]\";\n}\n\npublic class Token<TToken>\n{\n public Token(string token, int length, int index, TToken type)\n {\n Text = token;\n Length = length;\n Index = index;\n Type = type;\n }\n\n public int Index { get; }\n\n public int Length { get; }\n\n public string Text { get; }\n\n public TToken Type { get; }\n\n public override string ToString() => $\"{Index}: {Text} ({Type})\";\n}\n</code></pre>\n\n<h3>Tests & Examples</h3>\n\n<p>This is how I use it with a simplfied commad-line syntax:</p>\n\n<pre><code>using static CommandLineToken;\n\npublic class CommandLineTokenizerTest\n{\n private static readonly ITokenizer<CommandLineToken> Tokenizer = new CommandLineTokenizer();\n\n [Theory]\n [InlineData(\n \"command -argument value -argument\",\n \"command argument value argument\")]\n [InlineData(\n \"command -argument value value\",\n \"command argument value value\")]\n [InlineData(\n \"command -argument:value,value\",\n \"command argument value value\")]\n [InlineData(\n \"command -argument=value\",\n \"command argument value\")]\n [InlineData(\n \"command -argument:value,value\",\n \"command argument value value\")]\n [InlineData(\n @\"command -argument=\"\"foo--bar\"\",value -argument value\",\n @\"command argument foo--bar value argument value\")]\n [InlineData(\n @\"command -argument=\"\"foo--\\\"\"bar\"\",value -argument value\",\n @\"command argument foo-- \"\"bar value argument value\")]\n public void Can_tokenize_command_lines(string uri, string expected)\n {\n var tokens = Tokenizer.Tokenize(uri).ToList();\n var actual = string.Join(\"\", tokens.Select(t => t.Text));\n Assert.Equal(expected.Replace(\" \", string.Empty), actual);\n }\n}\n\n[EnumMatcherProvider]\npublic enum CommandLineToken\n{\n Start = 0,\n\n [Regex(@\"\\s*(\\?|[a-z0-9][a-z0-9\\-_]*)\")]\n Command,\n\n [Regex(@\"\\s*[\\-\\.\\/]([a-z0-9][a-z\\-_]*)\")]\n Argument,\n\n [QText(@\"([\\=\\:\\,]|\\,?\\s*)\", @\"([a-z0-9\\.\\;\\-]+)\")]\n Value,\n}\n\npublic class CommandLineTokenizer : Tokenizer<CommandLineToken>\n{\n /*\n\n command [-argument][=value][,value]\n\n command --------------------------- CommandLine\n \\ /\n -argument ------ ------ / \n \\ / \\ /\n =value ,value\n\n */\n private static readonly State<CommandLineToken>[] States =\n {\n new State<CommandLineToken>(default, Command),\n new State<CommandLineToken>(Command, Argument),\n new State<CommandLineToken>(Argument, Argument, Value),\n new State<CommandLineToken>(Value, Argument, Value),\n };\n\n public CommandLineTokenizer() : base(States.ToImmutableList()) { }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T17:02:55.080",
"Id": "441375",
"Score": "1",
"body": "I think I might borrow these (✔/✖) from you for future purposes yet unknown :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T17:03:53.853",
"Id": "441376",
"Score": "1",
"body": "@dfhwze [this](https://www.toptal.com/designers/htmlarrows/symbols/) is where they grow"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T16:59:37.420",
"Id": "226936",
"ParentId": "226863",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "226882",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T17:16:43.043",
"Id": "226863",
"Score": "6",
"Tags": [
"c#",
"regex",
"state-machine",
"lexer"
],
"Title": "Simple tokenizer v2 - reading all matching chars at once"
}
|
226863
|
<p>The following code implements the Hungarian algorithm. The algorithm is used to find minimum cost perfect matching on a bipartite graph.</p>
<p>Looking for comments on correctness, efficiency, clarity and idiomatic C++ usages. It passes all tests on <a href="https://leetcode.com/problems/campus-bikes-ii/" rel="nofollow noreferrer">LeetCode</a>.</p>
<pre><code>class Solution
{
public:
int assignBikes(vector<vector<int>>& workers, vector<vector<int>>& bikes)
{
if (workers.size() == 0)
{
return 0;
}
if (bikes.size() == 0)
{
return 0;
}
vector<vector<int>> costs;
costs.resize(workers.size());
for (int i = 0; i < workers.size(); i++)
{
costs[i].resize(bikes.size());
for (int j = 0; j < bikes.size(); j++)
{
int wx = workers[i][0];
int wy = workers[i][1];
int bx = bikes[j][0];
int by = bikes[j][1];
int dx = wx - bx;
int dy = wy - by;
dx = dx > 0 ? dx : -dx;
dy = dy > 0 ? dy : -dy;
costs[i][j] = dx + dy;
}
}
vector<pair<int, int>> answer = hungarian(costs);
int result = 0;
for (auto edge : answer)
{
result += costs[edge.first][edge.second];
}
return result;
}
private:
// Implementation of the Hungarian algorithm for finding a minimum cost perfect matching
// The implementation is based on the description on https://en.wikipedia.org/wiki/Hungarian_algorithm
vector<pair<int, int>> hungarian(const vector<vector<int>>& costs)
{
// The problem of finding a minimum cost assignment is the same as
// finding the minimum cost perfect matching between the rows (workers) and the columns (jobs)
int n = (int)costs.size();
int m = (int)costs[0].size();
// At all times, the algorithm maintains an integer named potential for all nodes.
// The algorithm make sure potential(u) + potential(v) <= cost[u,v]
// The nodes that represents the row are [0,n) and the nodes that represents the columns are [n, m + n)
// Potential values are initialized to 0.
vector<int> potential;
potential.resize(m + n);
for (int i = 0; i < m + n; i++)
{
potential[i] = 0;
}
// We maintain a directed graph, the edges of the graph is tight (i.e. potential(u) + potential(v) = cost[u,v]).
// The edges from [n, m + n) back to [0, n) has to form a matching. (i.e. these edges does not share source/target)
vector<vector<bool>> direction;
direction.resize(n);
for (int i = 0; i < n; i++)
{
direction[i].resize(m);
for (int j = 0; j < m; j++)
{
direction[i][j] = true;
}
}
// If a node is involved in the matching, the matched flag will be true.
vector<bool> matched;
matched.resize(m + n);
for (int i = 0; i < m + n; i++)
{
matched[i] = false;
}
// We will do a BFS to find paths. The parent array store the parent node used to discover a node.
vector<int> parent;
parent.resize(m + n);
while (true)
{
queue<int> bfs;
for (int i = 0; i < m + n; i++)
{
// Parent == -1 means it is not enqueued yet, so there is no parent
parent[i] = -1;
}
for (int i = 0; i < n; i++)
{
if (!matched[i])
{
bfs.push(i);
// Parent == -2 means it is enqueued because it is a not matched source node.
// It should NOT be enqueued again
parent[i] = -2;
}
}
// This is just a standard BFS, note that the cost and direction array must be read from row to column
while (bfs.size() > 0)
{
int visiting = bfs.front();
bfs.pop();
if (visiting < n)
{
for (int neighbor = n; neighbor < m + n; neighbor++)
{
bool tight = costs[visiting][neighbor - n] - potential[visiting] - potential[neighbor] == 0;
if (direction[visiting][neighbor - n] && tight)
{
if (parent[neighbor] == -1)
{
bfs.push(neighbor);
parent[neighbor] = visiting;
}
}
}
}
else
{
for (int neighbor = 0; neighbor < n; neighbor++)
{
bool tight = costs[neighbor][visiting - n] - potential[visiting] - potential[neighbor] == 0;
if (!direction[neighbor][visiting - n] && tight)
{
if (parent[neighbor] == -1)
{
bfs.push(neighbor);
parent[neighbor] = visiting;
}
}
}
}
}
bool found = false;
for (int i = n; i < m + n; i++)
{
if (!matched[i] && parent[i] != -1)
{
// If there is a way to reach from a source unmatched node to a target
// unmatched node, then we have an augmenting path, using the parent
// pointer chain, we can reverse all the paths to increasing the size
// of the matching by 1.
found = true;
int current = i;
while (true)
{
if (parent[current] == -2)
{
matched[i] = true;
matched[current] = true;
break;
}
int small = min(current, parent[current]);
int large = max(current, parent[current]);
direction[small][large - n] = !direction[small][large - n];
current = parent[current];
}
break;
}
}
if (!found)
{
// If we cannot find an augmenting path, we will modify the potential
// so that we have more nodes reachable from the unmatched sources
int delta = -1;
for (int i = 0; i < n; i++)
{
if (parent[i] != -1)
{
for (int j = n; j < m + n; j++)
{
if (parent[j] == -1)
{
// Make sure the delta does not violate the constraint
// between each pair of reachable source/unreachable target
int margin = costs[i][j - n] - potential[i] - potential[j];
if (delta == -1 || margin < delta)
{
delta = margin;
}
}
}
}
}
if (delta == -1)
{
break;
}
for (int i = 0; i < n; i++)
{
if (parent[i] != -1)
{
// For each reachable source, the potential is increased by delta
potential[i] += delta;
}
}
for (int i = n; i < m + n; i++)
{
if (parent[i] != -1)
{
// For each reachable target, the potential is decreased by delta
potential[i] -= delta;
}
}
// After the manipulation:
// The potential is feasible for reachable source, reachable target because the sum didn't change.
// The potential is feasible for reachable source, unreachable target because the increase is checked earlier.
// The potential is feasible for unreachable source, reachable target because the sum decrease.
// The potential is feasible for unreachable source, unreachable target because the sum didn't change.
}
}
vector<pair<int, int>> answer;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (!direction[i][j])
{
answer.push_back(make_pair(i, j));
}
}
}
return answer;
}
};
</code></pre>
|
[] |
[
{
"body": "<p>So in general the code is already quite good. It is well formated and easily readable. </p>\n\n<p>From what I can see the most important task ahead is to familiarize yourself better with the stl and all the things it brings to the table:</p>\n\n<ol>\n<li><p>Use qualified calls</p>\n\n<p>The habit of <code>using namespace std</code> is a vary bad one you should try to avoid as soon as possible. It doesnt really save you a lot and can get you in trouble quickly.</p></li>\n<li><p>Use the appropriate member functions</p>\n\n<pre><code>if (workers.size() == 0)\n{\n return 0;\n}\n</code></pre>\n\n<p>This is technically correct and not even too bad performance wise for <code>std::vector</code>. However this is terrible for every other container. All containers feature a <code>empty()</code> method that should be used </p>\n\n<pre><code>if (workers.empty())\n{\n return 0;\n}\n</code></pre>\n\n<p>The advantages are numerous. First you can never be too sure if <code>workers.size() == 0</code> is really correct. Did he mean <code>!= 0</code> or maybe <code>== 1</code> or whatever. With <code>empty</code> the intend is clear and there are only two possible cases which are often quite obvious to check. Also for any non-continuous container e.g <code>std::unorderd_set</code>, <code>std::set</code>, <code>std::forward_list</code> and <code>std::list</code> the determination of <code>size</code> requires a full traversal of the container. In contrast <code>empty</code> only checks a single pointer. So it is considerable cheaper.</p></li>\n<li><p>Know the constructors</p>\n\n<p>The elements in the standard containers are value constructed</p>\n\n<pre><code>vector<int> potential;\npotential.resize(m + n);\nfor (int i = 0; i < m + n; i++)\n{\n potential[i] = 0;\n}\n</code></pre>\n\n<p>Is equivalent to this</p>\n\n<pre><code>vector<int> potential(m + n);\n</code></pre>\n\n<p>If you have a certain value in mind you can also write it more explicitely as</p>\n\n<pre><code>vector<int> potential(m + n, 0);\n</code></pre>\n\n<p>This also works for nested containers so instead of</p>\n\n<pre><code>vector<vector<bool>> direction;\ndirection.resize(n);\nfor (int i = 0; i < n; i++)\n{\n direction[i].resize(m);\n for (int j = 0; j < m; j++)\n {\n direction[i][j] = true;\n }\n}\n</code></pre>\n\n<p>We can write</p>\n\n<pre><code>vector<vector<bool>> direction(n, std::vector<bool>(m, true));\n</code></pre></li>\n<li><p>Try to enforce const correctness</p>\n\n<p>I know this can seem like a lot of clutter but always mark constants as const so code like</p>\n\n<pre><code>bool tight = costs[visiting][neighbor - n] - potential[visiting] - potential[neighbor] == 0;\nif (direction[visiting][neighbor - n] && tight)\n ...\n</code></pre>\n\n<p>Should be written as</p>\n\n<pre><code>const bool tight = costs[visiting][neighbor - n] - potential[visiting] - potential[neighbor] == 0;\nif (direction[visiting][neighbor - n] && tight)\n ...\n</code></pre>\n\n<p>There is a great talk by <a href=\"https://www.youtube.com/watch?v=-Hb-9TUyjoo\" rel=\"nofollow noreferrer\">Kate Gregory</a> about it. In a nutshell you want to convey as much information as possible, so that any variable that is <em>not</em> <code>const</code> sticks out</p></li>\n<li><p>Do not build mountains</p>\n\n<p>There is only one occurence of it but try to avoid writing canyons like</p>\n\n<pre><code>for (...) {\n if (condition) {\n ...\n }\n}\n</code></pre>\n\n<p>In this example there is only one level of identation but from personal expirience I can tell you that these mountains grow. Instead use early returns/continues</p>\n\n<pre><code>for (...) {\n if (!condition) {\n continue;\n }\n ...\n}\n</code></pre>\n\n<p>This greatly improves readability if there are multiple nested conditions and also makes is much clearer what is a precondition and what not.</p></li>\n<li><p>Know you algorithms</p>\n\n<p>The stl offers a great variety of algorithms. There are numerous cases where you could use <code>std::accumulate</code> or <code>std::copy_if</code>. Try to learn those algorithms by heart. In general you can assume that the algorithms of the standard library are better tested and more performant that what you or I could cook up</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T07:07:40.973",
"Id": "226895",
"ParentId": "226874",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T20:57:52.077",
"Id": "226874",
"Score": "2",
"Tags": [
"c++",
"algorithm"
],
"Title": "LeetCode #1066 - Campus Bikes II"
}
|
226874
|
<p>I was going to post this in code golf, but I think it may be better suited here. I'm not really interested in scoring it beyond accepting the best answer.</p>
<p>I'm wanting to minimize this series of <code>IFS</code>, if possible or necessary. I'm brand new to javascript/coding, but it just seems like there may be some redundancy here.</p>
<pre><code>if(activeCell.getRow() > 2 && activeCell.getColumn() == 1){
activeCell.offset(0, 1).setDataValidation(projectTasksAdjItemValidationRule);
activeCell.offset(0, 2).setDataValidation(projectTasksAdjSubItemValidationRule);
activeCell.offset(0, 3).setDataValidation(projectTasksAdjActionValidationRule);
activeCell.offset(0, 4).setDataValidation(projectTasksAdjTaskValidationRule);
} else if(activeCell.getRow() > 2 && activeCell.getColumn() == 2){
activeCell.offset(0, 1).setDataValidation(projectTasksAdjSubItemValidationRule);
activeCell.offset(0, 2).setDataValidation(projectTasksAdjActionValidationRule);
activeCell.offset(0, 3).setDataValidation(projectTasksAdjTaskValidationRule);
} else if(activeCell.getRow() > 2 && activeCell.getColumn() == 3){
activeCell.offset(0, 1).setDataValidation(projectTasksAdjActionValidationRule);
activeCell.offset(0, 2).setDataValidation(projectTasksAdjTaskValidationRule);
} else if(activeCell.getRow() > 2 && activeCell.getColumn() == 4){
activeCell.offset(0, 1).setDataValidation(projectTasksAdjTaskValidationRule);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T23:08:09.827",
"Id": "441239",
"Score": "3",
"body": "I'd say this is off-topic for both Code Golf and Code Review. The purpose of the site is not to really \"compete\" for best or shortest answers. The purpose is to get meaningful feedback on a complete program or module that has substantial context and motivation. Please see [ask]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T23:10:24.767",
"Id": "441240",
"Score": "0",
"body": "Ok. Didn't mean to abuse the site or anything. I'm just learning and thought maybe there is an easier way. But, on code golf, the tags do say specifically that it's a competition. But I'll remove the post regardless."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T23:12:42.427",
"Id": "441241",
"Score": "2",
"body": "So on Code Golf, you can make a competition, but just asking people to minimize an arbitrary `if` statement will likely be closed as [off-topic](https://codegolf.stackexchange.com/help/on-topic). See their [how to ask](https://codegolf.stackexchange.com/help/how-to-ask) and, typically, PCG questions should go through the [sandbox for proposed challenges](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges) and be vetted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T23:14:04.463",
"Id": "441242",
"Score": "0",
"body": "I definitely appreciate the tip! I did try to find something on posting etiquette and looked everywhere but the question mark icon. So thank you for bringing that to my attention. I'll be sure to check there first before posting anything in the future."
}
] |
[
{
"body": "<p>Since the <code>activeCell.getRow()</code> is repeated in all ifs, the only way I see of refactoring your code without overcomplicating the script is the following:</p>\n\n<pre><code>if(activeCell.getRow() > 2){\n if(activeCell.getColumn() == 1){\n activeCell.offset(0, 1).setDataValidation(projectTasksAdjItemValidationRule);\n activeCell.offset(0, 2).setDataValidation(projectTasksAdjSubItemValidationRule);\n activeCell.offset(0, 3).setDataValidation(projectTasksAdjActionValidationRule);\n activeCell.offset(0, 4).setDataValidation(projectTasksAdjTaskValidationRule);\n\n } else if(activeCell.getColumn() == 2){\n activeCell.offset(0, 1).setDataValidation(projectTasksAdjSubItemValidationRule);\n activeCell.offset(0, 2).setDataValidation(projectTasksAdjActionValidationRule);\n activeCell.offset(0, 3).setDataValidation(projectTasksAdjTaskValidationRule);\n\n } else if(activeCell.getColumn() == 3){\n activeCell.offset(0, 1).setDataValidation(projectTasksAdjActionValidationRule);\n activeCell.offset(0, 2).setDataValidation(projectTasksAdjTaskValidationRule);\n\n } else if(activeCell.getColumn() == 4){\n activeCell.offset(0, 1).setDataValidation(projectTasksAdjTaskValidationRule);\n }\n}\n</code></pre>\n\n<p>Hope it helps ;)</p>\n\n<p><em>EDIT:</em>\nAs it has been pointed out by \"esote\" in the comments of this answer, you could add a switch statement to improve the readability, the code would be:</p>\n\n<pre><code>if(activeCell.getRow() > 2){\n switch(activeCell.getColumn()){\n case 1:\n activeCell.offset(0, 4).setDataValidation(projectTasksAdjTaskValidationRule);\n case 2:\n activeCell.offset(0, 3).setDataValidation(projectTasksAdjTaskValidationRule);\n case 3:\n activeCell.offset(0, 2).setDataValidation(projectTasksAdjTaskValidationRule);\n case 4:\n activeCell.offset(0, 1).setDataValidation(projectTasksAdjTaskValidationRule);\n break;\n }\n}\n</code></pre>\n\n<p>If you have any doubt about how switches work, see on <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch\" rel=\"nofollow noreferrer\">this page</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T23:52:42.277",
"Id": "441244",
"Score": "3",
"body": "You should also use a switch statement for `activeCell.getColumn()`, rather than a bunch of if-else-if's"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T05:28:25.800",
"Id": "441266",
"Score": "0",
"body": "Inside the first if block, you can use a map of `var actions = { 1: () => { ...}, 2: () => {...}}; actions[activeCell.getColumn()]();` You need to handle the scenario when there is no action defined."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T23:10:15.280",
"Id": "226877",
"ParentId": "226876",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226877",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T22:51:31.483",
"Id": "226876",
"Score": "-4",
"Tags": [
"javascript",
"google-apps-script"
],
"Title": "Minimize this IF statement"
}
|
226876
|
<p>This is the simple back-end, albeit crude, that I made for a React Native mobile app project as a proof of concept. It's a basic CRUD for tracking supply inventory. The "shopping list" is items with a <code>Buy qty > 0</code>.</p>
<p><code>selectData()</code> is a wrapper for a <em>SELECT</em> query using prepared statements:</p>
<ul>
<li>Signature: <code>selectData($columns, $table, $where, $fetchType)</code></li>
<li><code>fetchType</code> is a <em>switch/case</em> to set the argument for <code>fetchAll()</code>. </li>
<li><code>$stmt = $conn->prepare("SELECT $columns FROM $table WHERE $where");</code></li>
</ul>
<p>It was easier for testing to use a remote MySQL database than to learn how to make/use a local database in React Native.</p>
<p>While I know that it works, does this even remotely count as a web API? How RESTful is it (or not)? Roast me if you must, but please explain it simply so I can learn.</p>
<p>After I created this, I started learning/using Laravel, but I haven't gotten into Laravel APIs yet.</p>
<pre><code> <?php
if(isset($_GET['action'])) {
include "initial.php"; //DB config, etc.
if ($_GET['action'] === "getShoppingList") {
echo json_encode(getShoppingList());
}
else if ($_GET['action'] === "getSingleItem") {
echo json_encode(getSingleItem($_GET['id']), JSON_NUMERIC_CHECK);
}
else if ($_GET['action'] === "getAllItems") {
echo json_encode(getAllItems());
}
else if ($_GET['action'] === "insert") {
if (!isset($_GET['in_use'])) {
echo json_encode(insertItem($_GET['itemName']));
}
else if (isset($_GET['in_use']) && isset($_GET['spare']) && isset($_GET['target'])) {
echo json_encode(insertItem($_GET['itemName'], $_GET['in_use'], $_GET['spare'], $_GET['target']));
}
}
else if ($_GET['action'] === "update") {
if (isset($_GET['field'])) {
echo json_encode(updateSingleItemField($_GET['id'], $_GET['field'], $_GET['value']));
}
else {
echo json_encode(updateItem($_GET['id'], $_GET['in_use'], $_GET['spare'], $_GET['target']));
}
}
else if ($_GET['action'] === "delete") {
echo json_encode(deleteItem($_GET['id']));
}
}
function getShoppingList(){
$items = selectData("id, item_name as name, in_use_quantity as 'in_use', spare_quantity as spare, target_quantity as target, CEILING(target_quantity - in_use_quantity - spare_quantity) as buy, updated", "items", "(target_quantity - in_use_quantity - spare_quantity > 0) ORDER BY item_name ASC", "obj");
return $items;
}
function getSingleItem($id){
$item = selectData("id, item_name as name, in_use_quantity as 'in_use', spare_quantity as spare, target_quantity as target, FORMAT(CEILING(target_quantity - in_use_quantity - spare_quantity),2) as buy, updated", "items", "id = $id", "obj");
return $item;
}
function getAllItems(){
$items = selectData("id, item_name as name, in_use_quantity as 'in_use', spare_quantity as spare, target_quantity as target, FORMAT(CEILING(target_quantity - in_use_quantity - spare_quantity),2) as buy, updated", "items", "1 ORDER BY item_name ASC", "obj");
return $items;
}
function insertItem($itemName, $inUseQuantity=0, $spareQuantity=0, $targetQuantity=0){
$conn = loadDatabase();
$query = "INSERT INTO `items` (`id`, `item_name`, `in_use_quantity`, `spare_quantity`, `target_quantity`, `updated`) VALUES (NULL, '$itemName', '$inUseQuantity', '$spareQuantity', '$targetQuantity', CURRENT_TIMESTAMP())";
$stmt = $conn->prepare($query);
$stmt->execute();
$id = $conn->lastInsertId();
$conn = null;
return $id;
}
function updateSingleItemField($id, $field, $value){
$conn = loadDatabase();
$fieldName = $field . "_quantity";
$stmt = $conn->prepare("UPDATE `items` SET `$fieldName` = $value WHERE `items`.`id` = $id");
$stmt->execute();
$conn = null;
return $stmt->rowCount(); //returns TRUE if it was successful or FALSE if it failed
}
function updateItem($id, $inUseQuantity=0, $spareQuantity=0, $targetQuantity=0){
$conn = loadDatabase();
$stmt = $conn->prepare("UPDATE `items` SET `in_use_quantity` = $inUseQuantity, `spare_quantity` = $spareQuantity, `target_quantity` = $targetQuantity WHERE `items`.`id` = $id");
$stmt->execute();
$conn = null;
return $stmt->rowCount(); //returns TRUE if it was successful or FALSE if it failed
}
function deleteItem($id){
$conn = loadDatabase();
$stmt = $conn->prepare("DELETE FROM `items` WHERE `items`.`id` = $id");
$stmt->execute();
$conn = null;
//returns TRUE if it was successful or FALSE if it failed
return $stmt->rowCount();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T05:00:38.493",
"Id": "441260",
"Score": "1",
"body": "Just a personal style comment: I would rather use a `switch` if you've got no other criteria than the content of a variable."
}
] |
[
{
"body": "<p>Disclaimer: there will be a lot of links to my own site because I am helping people with PHP for 20+ years and got an obsession with writing articles about most common issues. </p>\n\n<p>I don't know much about restful stuff or whether it does matter, but there are many other areas of improvement. Let's review some of them</p>\n\n<h3>The selectData() function</h3>\n\n<p>First of all, the <code>selectData()</code> function is a wrapper for a SELECT query using <a href=\"https://phpdelusions.net/pdo/cargo_cult_prepared_statement\" rel=\"noreferrer\"><em>cargo cult</em> prepared statements</a> which makes it essentially <strong>insecure</strong>. It's a placeholder that makes your prepared query secure, not just a magical call to prepare().</p>\n\n<p>Another thing is that <a href=\"https://phpdelusions.net/pdo/common_mistakes#select\" rel=\"noreferrer\">gibberish <code>selectData()</code> syntax</a>. Honestly, what are you trying to bargain here for? Spare yourself typing a few SQL keywords, seriously? Making it gibberish out of a precious almost-natural-English sentence, convenient and compatible? \nLook, you are already abusing the <code>$where</code> parameter by weird <code>\"1 ORDER BY item_name ASC\"</code> statement. Last but not least: such a syntax makes it harder to use prepared statements.<br>\nCome on. Let's keep it SQL.</p>\n\n<p>Also, it seems that <code>selectData()</code> connects every time of it's own. Although it is not a problem for a primitive atomic API that always perform just a single SQL query per HTTP request, <em>no API would remain thus</em>. It will grow up to perform many queries per request and having each query to connect of its own will become a problem. Your script should always create just a single connection per single HTTP request and use it for all queries. So create a $conn variable as shown <a href=\"https://phpdelusions.net/pdo_examples/connect_to_mysql\" rel=\"noreferrer\">here</a> and then use it for all database interactions in your code. </p>\n\n<p>Also, I suppose that <code>selectData()</code> always returns a simple 2-dimensional list, which severely cripples the <a href=\"https://phpdelusions.net/pdo#fetchcolumn\" rel=\"noreferrer\">PDO's great ability to return the requested data in many different formats</a>. So, instead make this function to return a PDO statement from which you'll be able to get the resulting data. So it will work as a sort of that \"obj\" thingy, but in a much more versatile way. </p>\n\n<p>Given all the above, create a <a href=\"https://phpdelusions.net/pdo/pdo_wrapper#function\" rel=\"noreferrer\">PDO helper function</a> like this: </p>\n\n<pre><code>function pdo($pdo, $sql, $args = NULL)\n{\n if (!$args)\n {\n return $pdo->query($sql);\n }\n $stmt = $pdo->prepare($sql);\n $stmt->execute($args);\n return $stmt;\n}\n</code></pre>\n\n<p>So it keeps the SQL syntax intact yet makes all your queries <em>safe</em> and result sets versatile. </p>\n\n<p>Let's rewrite some your functions to this new format</p>\n\n<pre><code>function getShoppingList($conn){\n $sql = \"SELECT id, item_name as name, in_use_quantity as 'in_use',\n spare_quantity as spare, target_quantity as target, \n CEILING(target_quantity - in_use_quantity - spare_quantity) as buy, \n updated \n FROM items \n WHERE target_quantity - in_use_quantity - spare_quantity > 0\n ORDER BY item_name ASC\";\n return pdo($conn, $sql)->fetchAll();\n}\n\nfunction getSingleItem($conn, $id) {\n $sql = \"SELECT id, item_name as name, in_use_quantity as 'in_use', \n spare_quantity as spare, target_quantity as target,\n FORMAT(CEILING(target_quantity - in_use_quantity - spare_quantity),2)\n as buy, updated \n FROM items\n WHERE id = ?\";\n return pdo($conn, $sql, $id)->fetch();\n}\n\nfunction insertItem($conn, $itemName, $inUseQuantity=0, $spareQuantity=0, $targetQuantity=0){\n $sql = \"INSERT INTO `items` \n (`id`, `item_name`, `in_use_quantity`, `spare_quantity`, `target_quantity`, `updated`) \n VALUES (NULL, ?,?,?,?, CURRENT_TIMESTAMP())\";\n pdo($conn, $sql, [$itemName, $inUseQuantity, $spareQuantity, $targetQuantity]);\n return $conn->lastInsertId();\n}\n</code></pre>\n\n<p>a couple notes:</p>\n\n<ul>\n<li><code>getSingleItem()</code> returns a <em>single item</em>, not a multidimensional array</li>\n<li>although you can designate the row format as a parameter in <code>fetch()</code> or <code>fetchAll()</code>, it would be most convenient to set up the default fetch mode in the beginning. So you would only define it explicitly in case you will need some different format. Therefore n need for that ever-present \"obj\" parameter.</li>\n<li>notice the brand new <code>insertItem()</code>. Neat, eh?</li>\n<li>all your queries are <strong>secure</strong> now</li>\n</ul>\n\n<p>Now you can rewrite all other functions to this format. </p>\n\n<h3>The router part</h3>\n\n<p>There are some repetitions in the router part that could be optimized</p>\n\n<pre><code>switch ($_GET['action']) {\n case \"getShoppingList\":\n $response = getShoppingList();\n break;\n\n case \"getSingleItem\":\n $response = getSingleItem($_GET['id']);\n break;\n\n case \"getAllItems\":\n $response = getAllItems();\n break;\n\n case \"insert\":\n if (!isset($_GET['in_use'])) {\n $response = insertItem($_GET['itemName']);\n } elseif (isset($_GET['spare'], $_GET['target'])) {\n $response = insertItem(\n $_GET['itemName'], $_GET['in_use'], $_GET['spare'], $_GET['target']\n );\n }\n\n case \"update\":\n if (isset($_GET['field'])) {\n $response = updateSingleItemField($_GET['id'], $_GET['field'], $_GET['value']));\n } else {\n $response = updateItem(\n $_GET['id'], $_GET['in_use'], $_GET['spare'], $_GET['target']\n );\n }\n\n case \"delete\":\n $response = deleteItem($_GET['id']);\n\n}\necho json_encode($response);\n</code></pre>\n\n<h3>The code formatting</h3>\n\n<p>In your question, one has to scroll A LOT to read the code. And in my answer you have all the code visible. Please do not torture yourself or anyone else by making that awhul horizontal scrollbar. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T07:25:59.877",
"Id": "226897",
"ParentId": "226883",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "226897",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T03:18:22.880",
"Id": "226883",
"Score": "1",
"Tags": [
"php",
"mysql",
"api",
"rest",
"crud"
],
"Title": "Simple CRUD back-end for an inventory-tracking web API"
}
|
226883
|
<h2>Problem Statement:</h2>
<blockquote>
<p>Given an unsorted array of positive integers. Find the number of
triangles that can be formed with three different array elements as
lengths of three sides of triangles. </p>
<p><strong>Input:</strong> The first line of the input contains T denoting the number of testcases. First line of test case is the length of array N and
second line of test case are its elements.</p>
<p><strong>Output:</strong> Number of possible triangles are displayed to the user.</p>
<p><strong>Constraints:</strong></p>
<p><span class="math-container">\$1 \le T \le 200\$</span><br>
<span class="math-container">\$3 \le N \le 10^7\$</span><br>
<span class="math-container">\$1 \le \mathrm{arr}[i] \le 10^3\$</span></p>
<p><strong>Example:</strong></p>
<p><strong>Input:</strong></p>
<pre class="lang-none prettyprint-override"><code>2
3
3 5 4
5
6 4 9 7 8
</code></pre>
<p><strong>Output:</strong></p>
<pre class="lang-none prettyprint-override"><code>1
10
</code></pre>
</blockquote>
<h2>Algorithm:</h2>
<p>The efficient <span class="math-container">\$O(n^2)\$</span> algorithm for solving this problem has been explained <a href="https://www.geeksforgeeks.org/find-number-of-triangles-possible/" rel="nofollow noreferrer">here</a>. </p>
<blockquote>
<p>Let <span class="math-container">\$a\$</span>, <span class="math-container">\$b\$</span> and <span class="math-container">\$c\$</span> be three sides. The below condition must
hold for a triangle (Sum of two sides is greater than the third side)
i) <span class="math-container">\$a + b > c\$</span> ii) <span class="math-container">\$b + c > a\$</span> iii) <span class="math-container">\$a + c > b\$</span></p>
<p>Following are steps to count triangle.</p>
<ol>
<li><p>Sort the array in non-decreasing order.</p></li>
<li><p>Initialize two pointers <code>i</code> and <code>j</code> to first and second elements respectively, and initialize count of triangles as <code>0</code>.</p></li>
<li><p>Fix <code>i</code> and <code>j</code> and find the rightmost index <code>k</code> (or largest <code>arr[k]</code>) such that <code>arr[i] + arr[j] > arr[k]</code>. The number of
triangles that can be formed with <code>arr[i]</code> and <code>arr[j]</code> as two sides
is <code>k – j</code>. Add <code>k – j</code> to count of triangles.</p>
<p>Let us consider <code>arr[i]</code> as <span class="math-container">\$a\$</span>, <code>arr[j]</code> as <span class="math-container">\$b\$</span> and all
elements between <code>arr[j+1]</code> and <code>arr[k]</code> as <span class="math-container">\$c\$</span>. The above mentioned
conditions (ii) and (iii) are satisfied because <code>arr[i] < arr[j] <
arr[k]</code>. And we check for condition (i) when we pick <code>k</code>.</p></li>
<li><p>Increment <code>j</code> to fix the second element again.</p>
<p>Note that in step 3, we can use the previous value of <code>k</code>. The reason is simple, if we know that the value of <code>arr[i] + arr[j-1]</code> is
greater than <code>arr[k]</code>, then we can say <code>arr[i] + arr[j]</code> will also be
greater than <code>arr[k]</code>, because the array is sorted in increasing
order.</p></li>
<li><p>If <code>j</code> has reached end, then increment <code>i</code>. Initialize <code>j</code> as <code>i + 1</code>, <code>k</code> as <code>i+2</code> and repeat the steps 3 and 4.</p></li>
</ol>
</blockquote>
<h2>Code Implementation (in C++):</h2>
<p>This is my implementation of the algorithm in C++ (using vectors instead of raw arrays):</p>
<pre><code>#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
int triangles (vector<int> &V, int N);
int main () {
int T;
cin >> T;
vector<int> V;
for (int i = 0; i < T; i++)
{
int N;
cin >> N;
for (int j = 0; j < N; j++)
{
int temp;
cin >> temp;
V.push_back(temp);
}
cout << triangles (V, N) << endl;
V.clear();
}
return 0;
}
int triangles (vector<int> &V, int N)
{
int sum = 0;
sort(V.begin(), V.end());
for (int i = 0; i <= N-3; i++)
{
int k = i + 2;
for (int j = i + 1; j <= N-2; j++)
{
while (k < N && V[k] < V[i] + V[j])
k++;
sum += k-j-1;
}
}
return sum;
}
</code></pre>
<h2>Problem:</h2>
<p>The code gives the perfectly correct output for any input, however, when I submit the code on <a href="https://practice.geeksforgeeks.org/problems/count-possible-triangles/0" rel="nofollow noreferrer">GeekForGeeks Practice</a>, it says </p>
<blockquote>
<p>Your program took more time than expected (Time Limit Exceeded).
Expected Time Limit < 2.656sec. Hint: Please optimize your code and submit again.</p>
</blockquote>
<p>At this point, I'm not sure how to optimize my code. Any ideas? Do I necessarily need to use an array instead of a vector in order to speed up the program? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T04:02:23.503",
"Id": "441251",
"Score": "1",
"body": "Choose telling names for your variables. From a 9 second glance at the source code, I could not recognise the algorithm described following `The efficient O(n²) … explained here.`: document what problem is solved with what algorithm *in your program source*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T04:13:24.380",
"Id": "441252",
"Score": "1",
"body": "There's a comment on the linked page that says: \"I am very surprised that qsort() is not giving a TLE, whereas std::sort() does.\" Perhaps that's one place to start looking for an answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T04:16:38.620",
"Id": "441253",
"Score": "1",
"body": "@user1118321 That almost guarantees that the commentator is misusing `std::sort`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T04:46:39.603",
"Id": "441258",
"Score": "0",
"body": "Fair point. Are there any large input files available to test the code with? If so, it can be profiled. If not, it's kind of a pain to come up with some to do the testing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:42:18.313",
"Id": "441339",
"Score": "1",
"body": "If \\$N\\$ might be \\$10^7\\$ then you don't want to use a \\$\\Theta(N^2)\\$ algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T14:16:31.710",
"Id": "441357",
"Score": "0",
"body": "@Peter Do you happen to know a better algorithm for such cases?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T19:09:37.890",
"Id": "441423",
"Score": "1",
"body": "See AJNeufeld's answer."
}
] |
[
{
"body": "<p>The statement <code>V.push_back(temp);</code> can be inefficient, as the vector <code>V</code> may need to be reallocated multiple times.</p>\n\n<p>Use <a href=\"http://www.cplusplus.com/reference/vector/vector/reserve/\" rel=\"noreferrer\"><code>std::vector::reserve(N)</code></a> to ensure sufficient space exists in the vector before reading in the data to avoid multiple reallocations.</p>\n\n<hr>\n\n<blockquote>\n <p><span class=\"math-container\">\\$3 \\le N \\le 10^7\\$</span><br>\n <span class=\"math-container\">\\$1 \\le \\mathrm{arr}[i] \\le 10^3\\$</span></p>\n</blockquote>\n\n<p>With <span class=\"math-container\">\\$10^7\\$</span> pigeons and <span class=\"math-container\">\\$10^3\\$</span> holes, many holes can have over 10,000 pigeons! You might want to consider an array of counts indexed by side length. No sort required; it is automatically sorted. But your algorithm will need considerable reworking.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T04:45:20.013",
"Id": "226888",
"ParentId": "226885",
"Score": "6"
}
},
{
"body": "<p><strong>Don't use <code>using namespace std;</code>. It is extremely bad practice and will ruin your life.</strong> You will have trouble on common identifiers like <code>count</code>, <code>size</code>, etc. See <a href=\"https://stackoverflow.com/q/1452721\">Why is “using namespace std;” considered bad practice?</a> for more information.</p>\n\n<p>The input format is extremely awkward, but this seems to be beyond your control, so I'll leave it alone.</p>\n\n<p>Instead of using a linear search as you are doing in your loop, it might be beneficial to do a binary search if the amount of data is large. (This needs some testing.) Also, use standard algorithms to make your code more readable.</p>\n\n<p>Also, in this very case, a dynamic vector may not be the best way to appeal to the timer. (I'm not sure how I would phrase that.) <code>reserve</code> may help. You can try using a static vector like <a href=\"https://codereview.stackexchange.com/q/226757\">this one</a> because you know that the size is below a limit.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T04:47:03.750",
"Id": "226889",
"ParentId": "226885",
"Score": "6"
}
},
{
"body": "<p>Even after using <a href=\"http://www.cplusplus.com/reference/vector/vector/reserve/\" rel=\"nofollow noreferrer\"><code>reserve</code></a>, as suggested by <a href=\"https://codereview.stackexchange.com/users/188857/l-f\">@L.F.</a> and <a href=\"https://codereview.stackexchange.com/users/100620/ajneufeld\">@AJNeufeld</a>, there was no considerable speedup and it was still timing out. So I decided to use dynamically allocated <strong>arrays</strong> instead. I also removed <code>using namespace std</code>, and instead only imported those <code>std</code> functions which are required in the program. </p>\n\n<pre><code>#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <iterator>\n\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::sort;\n\nlong long int triangles (int arr[], int N);\n\nint main () {\n int T;\n cin >> T;\n for (int i = 0; i < T; i++)\n {\n int N;\n cin >> N;\n int *arr = new int[N];\n for (int j = 0; j < N; j++)\n {\n cin >> arr[j];\n }\n cout << triangles (arr, N) << endl;\n delete arr;\n }\n return 0;\n}\n\nlong long int triangles (int arr[], int N)\n{\n long long int sum = 0;\n sort(arr, arr+N);\n for (int i = 0; i <= N-3; i++)\n { \n int k = i + 2;\n for (int j = i + 1; j <= N-2; j++)\n {\n while (k < N && arr[k] < (arr[i] + arr[j]))\n k++;\n sum += k-j-1;\n }\n }\n return sum;\n}\n</code></pre>\n\n<p>Note that the data type of the <code>sum</code> which is returned by the <code>triangles()</code> function must be <em>at least</em> <code>long long int</code>, as it otherwise <a href=\"https://en.cppreference.com/w/cpp/language/types\" rel=\"nofollow noreferrer\">exceeds the range</a> of regular <code>int</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T11:45:18.600",
"Id": "441316",
"Score": "2",
"body": "That geeksforgeeks page is very wrong. Prior to C++20, the range of `int` is an implementation-defined superset of integers in [-32767, 32767], and the range of `long int` is an implementation-defined superset of integers in [-2,147,483,647, 2,147,483,647]. You should use `long long int`. I recommended that you use a more accurate C++ reference like https://en.cppreference.com."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T11:51:17.353",
"Id": "441319",
"Score": "0",
"body": "@L.F. Thanks, I will check that reference. By the way, do you happen to have any idea about why dynamically allocated arrays outperform vectors in this context? According to the discussion [here](https://stackoverflow.com/questions/3664272/is-stdvector-so-much-slower-than-plain-arrays), they should approximately have the same speed/performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T11:54:44.007",
"Id": "441320",
"Score": "1",
"body": "Vectors are more flexible and do a lot of bookkeeping for you. It is much more than just a dynamically allocated array. So with extremist timing, it can be \"observably\" slower than arrays. In practice, this small difference probably doesn't matter at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T12:20:50.313",
"Id": "441324",
"Score": "1",
"body": "Note that `std:;cin`, `std::cout` and `std::endl` are used only inside `main()`, so the scope of those `using` statements can be reduced. Similarly, `std::sort` is used only in `triangles()` - and there, only once, so is the `using` really necessary?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:40:34.097",
"Id": "441338",
"Score": "0",
"body": "@L.F., surely the type to use (ever since C++11 came out) is one of the types defined in `cstdint`? (Well, or it would be if any of them were wide enough. The output requires 117 bits in the worst case, and 128-bit integer types are non-standard extensions)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:55:26.187",
"Id": "441345",
"Score": "0",
"body": "@PeterTaylor I have a bit of trouble understanding your comment. Do you mean that I shouldn't have suggested `long long int`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T14:01:16.350",
"Id": "441352",
"Score": "0",
"body": "@L.F., yes. I would have suggested `uint_64t`, but then I realised that it's not wide enough."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T14:03:55.900",
"Id": "441353",
"Score": "0",
"body": "@PeterTaylor I get your point. Well, `mpz_class` then :) I think that's beyond the scope of the challenge."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T11:28:18.927",
"Id": "226914",
"ParentId": "226885",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "226889",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T03:41:24.547",
"Id": "226885",
"Score": "7",
"Tags": [
"c++",
"algorithm",
"programming-challenge",
"time-limit-exceeded",
"computational-geometry"
],
"Title": "Counting the triangles that can be formed from segments of given lengths"
}
|
226885
|
<p>This is the first project I have coded using Python.</p>
<p>Therefore, I am looking for someone to give me some comments to further improve my code.</p>
<h3>Purpose of the application</h3>
<p>This application help the staff in my organization to import the spreadsheet and store it into the database.</p>
<h3>Flow</h3>
<ol>
<li>User would need to provide the document location before the application execute.</li>
<li>System will extract the information from spreadsheet and import into the database.</li>
</ol>
<h3>Source Code</h3>
<p>Below is my source code.</p>
<p>The link below is the complete source code on Github,
<a href="https://github.com/WeeHong/0703-Extractor/blob/d037a2a53428dc37c77e6fd9803e2869383f3d01/Main.ipynb" rel="nofollow noreferrer">https://github.com/WeeHong/0703-Extractor/blob/master/Main.ipynb</a></p>
<pre><code># Establish database connection
database = mysql.connector.connect(
host = 'localhost',
user = 'root',
password = '',
database = 'projects_0703'
)
# More about cursor:
# https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor.html
mycursor = database.cursor()
# Fetch all companies records from the companies table from database
mycursor.execute('SELECT id, name FROM companies')
companies = mycursor.fetchall()
# Spreadsheet location
# location = ("./Cluster.xlsx")
location = input()
# Open the spreadsheet from the given path based on the sheet index
workbook = xlrd.open_workbook(location)
sheet = workbook.sheet_by_index(3)
# Fetch all the value from the sheet and store into an array
for excel_row in range(2, sheet.nrows):
# Check respective fields are empty
# Cell 26 = Techsector
# Cell 27 = Sub-techsector
if sheet.cell_value(excel_row, 26):
category = categories[sheet.cell_value(excel_row, 26)]
else:
category = None
if sheet.cell_value(excel_row, 27):
subcategory = subcategories[sheet.cell_value(excel_row, 27)]
else:
subcategory = None
# Assign ID = 10 if the stage is 0 in spreadsheet
if sheet.cell_value(excel_row, 0) == 0:
stage = 10
else:
stage = sheet.cell_value(excel_row, 0)
# Replace NA into 0 for Manday
if sheet.cell_value(excel_row, 19) == 'NA':
manday = 0
else:
manday = sheet.cell_value(excel_row, 19)
# Check if workbook's company exists in database company
# Yes, fetch the company ID
# No, create new company record and fetch the company ID
if sheet.cell_value(excel_row, 1) in companies:
for company in companies:
if sheet.cell_value(excel_row, 1) == company[0][1]:
company_id = company[0][0]
else:
if sheet.cell_value(excel_row, 3):
# Get the industry ID from industries dictionary
industry_id = industries[sheet.cell_value(excel_row, 3)]
mycursor.execute('INSERT INTO companies(industry_id, name, category, country, source, created_at, updated_at) VALUES (%s, %s, %s, %s, %s, NOW(), NOW())', (industry_id, sheet.cell_value(excel_row, 1), 'a:1:{i:0;s:6:"Client";}', 'SINGAPORE', '0703',),)
company_id = mycursor.lastrowid
database.commit()
# Create new project record
mycursor.execute('INSERT INTO projects(company_id, source_id, stage_id, service_id, leader_id, category_id, subcategory_id, name, revenue, forecast, quotation, remarks, created_at, updated_at) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW())', (company_id, sources[sheet.cell_value(excel_row, 4)], stage, services[sheet.cell_value(excel_row, 5)], staffs[sheet.cell_value(excel_row, 20)], category, subcategory, sheet.cell_value(excel_row, 2), sheet.cell_value(excel_row, 17), sheet.cell_value(excel_row, 16), sheet.cell_value(excel_row, 18), sheet.cell_value(excel_row, 28)),)
project_id = mycursor.lastrowid
database.commit()
# Check the number of project member in charge of the project
# Create new project member record
if sheet.cell_value(excel_row, 21):
members = sheet.cell_value(excel_row, 21).split(',')
for member in members:
mycursor.execute('INSERT INTO member_project(member_id, project_id, manday, created_at, updated_at) VALUES (%s, %s, %s, NOW(), NOW())', (staffs[member.strip()], project_id, manday),)
database.commit()
# Create new project techpartner record
# Cell 22 = Techpartner 1
# Cell 23 = Techpartner 2
# Cell 24 = Techpartner 3
# Cell 25 = Techpartner 4
for excel_cell in range(22, 26):
techpartner = sheet.cell_value(excel_row, excel_cell)
if techpartner:
if techpartner in companies:
for company in companies:
if techpartner == company[0][1]:
techpartner_id = company[0][0]
else:
mycursor.execute('INSERT INTO companies(name, category, country, source, created_at, updated_at) VALUES (%s, %s, %s, %s, NOW(), NOW())', (techpartner, 'a:1:{i:0;s:7:\"Partner\";)', 'SINGAPORE', '0703',),)
techpartner_id = mycursor.lastrowid
database.commit()
mycursor.execute('INSERT INTO project_techpartners(project_id, techpartner_id, created_at, updated_at) VALUES (%s, %s, NOW(), NOW())', (project_id, techpartner_id),)
database.commit()
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T05:01:17.123",
"Id": "441261",
"Score": "1",
"body": "`workbook = xlrd.open_workbook(location)` Where is `xlrd` defined? Please include your imports."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T05:13:27.917",
"Id": "441262",
"Score": "0",
"body": "@Mast I think that this is a reasonable excerpt, given the GitHub link that contains the full code."
}
] |
[
{
"body": "<p>The code isn't unreasonable. There are ways to clean it up, though.</p>\n\n<h2>Functions</h2>\n\n<p>Organize your code into sub-routines - perhaps one to load categories from your spreadsheet, one to write information to your database, etc.</p>\n\n<h2>Magic numbers</h2>\n\n<p>Numbers like 26, 27, 19, etc. should be assigned to constants, to make the code easier to understand.</p>\n\n<h2>Ineffectual commit</h2>\n\n<p>The last line of your code is a commit after no operation. Perhaps this is just an indentation error and you meant to commit after your <code>execute</code>.</p>\n\n<p>Delete the commit before it in the <code>else</code>. More broadly, you may want to consider reducing the number of commits in your code, maybe even to one at the end. This depends on a number of things, including how you want to deal with errors and whether they effect validity of the data as a whole, as well as performance.</p>\n\n<p>Finally, have a read through <a href=\"https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlconnection-autocommit.html\" rel=\"nofollow noreferrer\">https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlconnection-autocommit.html</a> . The way you're using commits now, you're better off just turning on autocommit.</p>\n\n<h2>Combined inserts</h2>\n\n<p>Your <code>insert into member_project</code> is inefficient. You should not insert in a loop. Read <a href=\"https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-executemany.html\" rel=\"nofollow noreferrer\">https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-executemany.html</a></p>\n\n<h2>Add a prompt to your input()</h2>\n\n<p>Otherwise, the user doesn't know why the program has suddenly hung.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T04:06:12.423",
"Id": "441484",
"Score": "0",
"body": "Thank you. I will look into it and improve my code.\nMuch appreciated."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T20:50:16.587",
"Id": "226948",
"ParentId": "226890",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226948",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T04:52:22.393",
"Id": "226890",
"Score": "3",
"Tags": [
"python",
"beginner",
"mysql",
"excel"
],
"Title": "Import Excel sheet into MySQL"
}
|
226890
|
<p>The original idea behind the problem is that the API I'm working with returns one type of a response for <code>GET</code>, and requires another type to do <code>POST</code> / <code>PUT</code>. The object I'm receiving from the <code>GET</code> has a format like this:</p>
<pre><code> const rawObject = {
data1: {
id: 1,
value: 444
},
data2: null
}
</code></pre>
<p>In order to be able to update it, or do a <code>POST</code> request to create a new one, I had to convert it into this format (This is the final output of my solution as well):</p>
<pre><code>const convertedObject = {
data1: 444,
data2: null
};
</code></pre>
<p>The object I'm converting consists of another objects within it (One level max - as in the first example) or <strong>null</strong>. If the object is not null, I only care about the <code>value</code> of a nested object, therefore I flatten it as - <code>data1: 444</code>. </p>
<p>The solution I came up with is this (It works perfectly):</p>
<pre><code>const rawObject = {
data1: {
id: 1,
value: 444
},
data2: null
}
let convertedObject: any = {};
Object.entries(rawObject).map((item: any) => {
const rawObjectKey = item[0];
const rawObjectValue = item[1];
if (rawObjectValue) {
convertedObject = {...convertedObject, ...{[rawObjectKey]: rawObjectValue.value}};
return;
}
convertedObject = {...convertedObject, ...{[rawObjectKey]: null}};
return;
});
console.log(convertedObject); // Check the Output in example above
</code></pre>
<p><a href="https://stackblitz.com/edit/js-3agbqj?file=index.js" rel="nofollow noreferrer"><strong>Stackblitz</strong></a></p>
<p>I decided to use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries" rel="nofollow noreferrer">Object.entries()</a> as I need both key:value pairs available. The if check I'm doing is there because object could have null value, therefore <code>rawObjectValue</code> would be null.</p>
|
[] |
[
{
"body": "<h2>Review</h2>\n\n<ul>\n<li>Your final <code>return</code> statement is redundant.</li>\n<li>The use of <code>const</code> is correct here (<code>rawObjectKey</code>, <code>rawObjectValue</code>) because you only assign these variables once. Many developers tend to use <code>let</code> or <code>var</code> here incorrectly.</li>\n<li>Your method is a bit convoluted with those almost-equal code blocks. <code>convertedObject = {...convertedObject, ...</code></li>\n</ul>\n\n<hr>\n\n<h2>Alternative</h2>\n\n<p>You could write this more compact, DRY and using built-in function <code>reduce</code>. We start with an empty object <code>{}</code> and inject each entry with the flattened data to obtain the result.</p>\n\n<pre><code> const convertedObject = Object.entries(rawObject).reduce(\n (acc, item) => { \n acc[item[0]] = item[1] != null ? item[1].value : null;\n return acc;\n }, {});\n</code></pre>\n\n<hr>\n\n<h2>Future Releases</h2>\n\n<p>There is a thing called <a href=\"https://medium.com/bsadd/optional-chaining-in-react-native-805a374788d3\" rel=\"nofollow noreferrer\"><em>optional chaining</em></a> aka <a href=\"https://ponyfoo.com/articles/null-propagation-operator\" rel=\"nofollow noreferrer\"><em>null propagation</em></a> aka <a href=\"https://www.beyondjava.net/elvis-operator-aka-safe-navigation-javascript-typescript\" rel=\"nofollow noreferrer\">the Elvis operator</a>. It's not standard Typescript (yet?), but is already supported in <a href=\"https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining\" rel=\"nofollow noreferrer\">babel-plugin-proposal-optional-chaining</a>.</p>\n\n<p>This is a feature request to track. If ever implemented, it would allow us to call something like <code>item[1]?.value:null</code> instead of <code>item[1] != null ? item[1].value : null</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T08:16:48.723",
"Id": "226902",
"ParentId": "226894",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226902",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T06:59:55.663",
"Id": "226894",
"Score": "1",
"Tags": [
"javascript",
"ecmascript-6",
"typescript"
],
"Title": "Flattening the nested Objects"
}
|
226894
|
<p>The actual code layout of a text adventure. This text adventure is a much-improved sequel to the <a href="https://gist.github.com/tyronewantedsmok/3f4156dd5f4673fecbdf8417cdd57f12" rel="nofollow noreferrer">first</a> <a href="https://codereview.stackexchange.com/questions/222720/story-based-adventure-with-functions-and-relationships">code</a>. It is three times as long but three times more efficient. The setting is based on the setting of Telltale's TWD: A New Frontier. The storylines can be found <a href="https://gist.github.com/tyronewantedsmok/5a687494faad4822e3fd81fbd204c3ad" rel="nofollow noreferrer">here</a>. I suggest running the code with the storylines before analyzing</p>
<pre><code>import sys
import time
def load(seconds):
print('\nLoading', end='', flush=True)
for _ in range(seconds):
time.sleep(1)
print('.', end='', flush=True)
print()
def to_win():
print('85/15 TO WIN', end='')
for dot in range(4):
print('.', end='', flush=True)
time.sleep(1)
print('or lose')
print('Loading', end='', flush=True)
for _ in range(15):
time.sleep(1)
print('.', end='', flush=True)
print()
class People:
"""Enum to represent the societal positions found in the game"""
ARMY = "The Army"
GOVERNMENT = 'The Government'
CIVILIAN = "Civilians"
# People is the type of person accessed
class Forces:
YOU = 'You'
ENEMY = 'Enemy'
relationships = {People.ARMY: 0, People.CIVILIAN: 0, People.GOVERNMENT: 0}
tide = {Forces.YOU: 50, Forces.ENEMY: 50}
choices = []
def prompt_for_input(prompt, valid_inputs, max_tries=6):
print(prompt)
the_roadblock = '\nPlease enter a valid input\n'
while max_tries > 0:
user_input = input('> ').upper()
if user_input in valid_inputs:
return user_input
else:
print(the_roadblock)
max_tries -= 1
# the input was not valid, show the roadblock
print('Seems like you are not willing to play. Goodbye!')
sys.exit(0)
def change_relation(*args):
string = ''
for arg in args:
type_of_person = arg[0]
type_of_change = arg[1]
type_of_change_copy = type_of_change
"""Change the standing of the player with a given faction
faction and type_of_change are case insensitive and have to correspond to
class variables of People and RelationshipChanges. type_of_change
describes by how much the relationship score is altered.
This function returns a message that describes the change.
"""
type_translation = {
"---": -2, "--": -1, "-": -0.5, "+++": 2, "++": 1, "+": 0.5
}
if type_of_change in type_translation:
# only apply the translation if it's own of ---/--/.../+++
type_of_change_copy = type_translation[type_of_change]
type_person_name = getattr(People, type_of_person.upper())
relationships[type_person_name] += type_of_change_copy
string += '{}{} '.format(type_of_change, type_of_person).lower()
return string
def change_tide(change_of_tide):
tide[Forces.YOU] += change_of_tide
tide[Forces.ENEMY] -= change_of_tide
return '\n[{} %{}|{}% {}]'.format(Forces.YOU.upper(), tide[Forces.YOU], tide[Forces.ENEMY],
Forces.ENEMY.upper())
def win_loss():
if tide[Forces.YOU] >= 85:
return 'VICTORY! The New Frontier has been overpowered and has surrendered. The End.'
elif tide[Forces.ENEMY] >= 85:
return 'DEFEAT! The New Frontier has conquered and killed you all. Nice one chief. The End.'
else:
return 'PEACE! The war is over and you know live alongside the New Frontier in tranquility.'
def pro_con(skill, pro1, pro2, pro3, con1, con2):
return ' Skill / Pros / Cons ({} / {}, {}, {} / {}, {})'.format(skill, pro1, pro2, pro3, con1, con2)
def person(name, birthdate, ethnicity, sex, hometown, idea_a, idea_b, pros_cons):
identity = ' Background & Identity (born: {}, ethnicity: {}, sex: {}, hometown: {})'.format(birthdate, ethnicity,
sex, hometown)
aims_belief = ' Aims & Beliefs (A. {}; B. {})'.format(idea_a, idea_b)
return '{}\n{}\n{}\n{}'.format(name.upper(), identity, aims_belief, pros_cons)
cox_idea1 = '"numbers is key"'
cox_idea2 = '"hit the frontier hard with a direct attack to the most secure but vital part of them: downtown"'
cox_pro_cons = pro_con('militarist', 'quick-minded', 'assertive', 'convincing', 'irrational', 'close-minded')
chloe_cox = person('chloe cox', '09/25/98', 'Caucasian-American', 'F', 'Arlington, VA', cox_idea1, cox_idea2,
cox_pro_cons)
vazquez_idea1 = '"strategy is key"'
vazquez_idea2 = '"we weaken every strength, target every weakness and exploit every mistake rationally and ' \
'intelligently until they fall"'
vazquez_pros_cons = pro_con('strategist', 'smart', 'methodical', 'realistic', 'flawed', 'negligent')
benjamin_vazquez = person('benjamin vazquez', '10/23/88', 'Mexican-American', 'M', 'Richmond, VA', vazquez_idea1,
vazquez_idea2, vazquez_pros_cons)
washington_idea1 = '"a prosperous army is key'
washington_idea2 = '"as long as are soldiers are well supplied and well fed, they will fight outstandingly"'
washington_pro_cons = pro_con('supplier', 'considerate', 'benevolent', 'focused', 'old', 'unassertive')
zaid_washington = person('zaid washington', '12/10/74', 'African-American', 'M', 'Virgina Beach, VA',
washington_idea1, washington_idea2, washington_pro_cons)
waters_idea1 = '"morale is key"'
waters_idea2 = '"as long as our soldiers have the drive and motivation to fight, they will conquer"'
waters_pro_cons = pro_con('therapist', 'energetic', 'optimistic', 'motivator', 'malleable', 'unassertive')
rob_waters = person('rob waters', '12/17/87', 'Caucasian-American', 'M', 'Roanoke Rapids, NC', waters_idea1,
waters_idea2, waters_pro_cons)
li_idea1 = '"firepower and intimidation is key"'
li_idea2 = '''"our priority is our guns, bombs, transportation and technology. we make as much weapons as possible use
them, kill, send a message"'''
li_pro_cons = pro_con('warlord', 'aggressive', 'fearless', 'rational', 'inarticulate', 'young')
ju_li = person('ju_li', '02/06/03', 'Chinese-American', 'F', 'Richmond, VA', li_idea1, li_idea2, li_pro_cons)
lieutenants = [chloe_cox, benjamin_vazquez, rob_waters, zaid_washington, ju_li]
def present_person(people):
for individual in people:
print('\n{}'.format(individual))
load(15)
def start():
button = prompt_for_input(scavenge, ('X', 'B'))
load(5)
if button == 'X':
print('\n{}\n\n{}{}\n'.format(scavenge_rescue, change_relation(('civilian', '+++'), ('army', '---'),
('government', '---')), change_tide(-5)))
choices.append('morals: chose lives over land')
to_win()
defend()
elif button == 'B':
print('\n{}\n\n{}{}\n'.format(scavenge_remain, change_relation(('civilian', '---'), ('army', '++')),
change_tide(15)))
choices.append('morals: chose land over lives')
to_win()
approach()
def defend():
button = prompt_for_input(rescue_defend, ('X', 'B', 'Y'))
load(5)
if button == 'X':
print('\n{}\n\n{}{}\n'.format(defend_none, change_relation(('army', '---'), ('civilian', '---'),
('government', '---')), change_tide(-10)))
choices.append('defence: did nothing')
to_win()
losing()
elif button == 'B':
print('\n{}\n\n{}{}\n'.format(defend_some, change_relation(('army', '+++'), ('civilian', '+++'),
('government', '+++')), change_tide(5)))
choices.append('defence: did something')
to_win()
defect()
elif button == 'Y':
print('\n{}\n\n{}{}\n'.format(defend_many, change_relation(('army', '-'), ('civilian', '---'),
('government', '---')), change_tide(0)))
choices.append('defence: did plenty')
to_win()
warfare()
def approach():
button = prompt_for_input(remain_approach, ('X', 'B', 'A'))
load(5)
if button == 'X':
print('\n{}\n\n{}{}\n'.format(approach_north, change_relation(('army', '---'), ('government', '---'),
('civilian', '---')), change_tide(-15)))
choices.append('approach: used stealth')
to_win()
defect()
elif button == 'B':
print('\n{}\n\n{}{}\n'.format(approach_river, change_relation(('army', '+++'), ('government', '+++'),
('civilian', '+++')), change_tide(15)))
choices.append('approach: targeted stock')
to_win()
so_close()
elif button == 'A':
print('\n{}\n\n{}{}\n'.format(approach_west_end, change_relation(('army', '--'), ('government', '++'),
('civilian', '+++')), change_tide(10)))
choices.append('approach: used force')
to_win()
so_close()
def so_close():
button = prompt_for_input(almost, ('X', 'B', 'Y'))
load(5)
if button == 'X':
print('\n\n{}\n\n{}{}\n'.format(almost_supplies, change_relation(('army', '--')), change_tide(-10)))
choices.append('finishing touch: failed chance at victory')
to_win()
spy()
elif button == 'B':
print('\n\n{}\n\n{}{}\n'.format(almost_attack, change_relation(('civilian', '---'), ('government', '--')),
change_tide(-10)))
choices.append('finishing touch: failed chance at victory')
to_win()
spy()
elif button == 'Y':
print('\n\n{}\n\n{}{}\n\n{}'.format(almost_inside, change_relation(('civilian', '+++'), ('army', '+++'),
('government', '+++')), change_tide(15),
win_loss()))
choices.append('finishing touch: succeeded and won')
def losing():
button = prompt_for_input(none_losing, ('X', 'B', 'Y', 'A'))
load(5)
if button == 'X':
print('\n\n{}\n\n{}{}\n'.format(losing_soldiers, change_relation(('army', '++'), ('civilian', '---'),
('government', '--')), change_tide(5)))
choices.append('priority: valued arms')
to_win()
replace()
elif button == 'B':
print('\n\n{}\n\n{}{}\n'.format(losing_yields, change_relation(('army', '+'), ('civilian', '+++'),
('government', '+++')), change_tide(20)))
choices.append('priority: valued production')
to_win()
supply_defend()
elif button == 'Y':
print('\n{}\n\n{}{}\n'.format(losing_technology, change_relation(('army', '-'), ('civilian', '---'),
('government', '+++')), change_tide(-15)))
choices.append('priority: valued innovation')
to_win()
nuclear()
elif button == 'A':
print('\n\n{}\n\n{}{}\n'.format(losing_exploration, change_relation(('army', '--'), ('civilian', '++'),
('government', '+++')), change_tide(30)))
choices.append('priority: valued outreach')
to_win()
persuasion()
def defect():
button = prompt_for_input(some_north_defect, ('X', 'B', 'Y', 'A'))
load(5)
if button == 'X':
print('\n{}\n\n{}{}\n'.format(defect_execution, change_relation(('civilian', '---'), ('government', '---')),
change_tide(15)))
choices.append('punishment: execution')
to_win()
rebel()
elif button == 'B':
print('\n{}\n\n{}{}\n'.format(defect_prison, change_relation(('civilian', '---'), ('government', '--')),
change_tide(5)))
choices.append('punishment: incarceration')
to_win()
rebel()
elif button == 'Y':
print('\n{}\n\n{}{}\n'.format(defect_warn, change_relation(('government', '+++'), ('army', '--')),
change_tide(-10)))
choices.append('punishment: privileges')
to_win()
slaves()
elif button == 'A':
print('\n{}\n\n{}{}\n'.format(defect_ignore, change_relation(('government', '---'), ('army', '---')),
change_tide(-15)))
choices.append('punishment: none')
to_win()
slaves()
def warfare():
button = prompt_for_input(many_warfare, ('X', 'B', 'A'))
load(5)
if button == 'X':
print('\n{}\n\n{}{}\n'.format(warfare_air, change_relation(('army', '+++'), ('government', '+++'),
('civilian', '-')), change_tide(20)))
choices.append('warfare: aerial')
to_win()
peace()
elif button == 'B':
print('\n{}\n\n{}{}\n'.format(warfare_water, change_relation(('government', '--')), change_tide(-5)))
choices.append('warfare: naval')
to_win()
assassination()
elif button == 'A':
print('\n{}\n\n{}{}\n'.format(warfare_bio, change_relation(('army', '---'), ('government', '+')),
change_tide(5)))
choices.append('warfare: biological')
to_win()
contaminated()
def nuclear():
nuke = prompt_for_input(technology_nuke, ('X', 'B'))
load(5)
if nuke == 'X':
change_tide(tide[Forces.ENEMY])
print('\n{}\n\n{}\n\n{}'.format(nuke_threaten, change_relation(('civilian', '+'), ('army', '+++'),
('government', '+++')), win_loss()))
choices.append('risk: included nukes')
elif nuke == 'B':
print('\n{}\n\n{}{}\n\n{}'.format(nuke_withdraw, change_relation(('civilian', '---'), ('army', '---'),
('government', '---')), change_tide(-15),
win_loss()))
choices.append('risk: excluded nukes')
def persuasion():
persuade = prompt_for_input(exploration_persuade, ('X', 'B', 'A'))
load(5)
if persuade == 'X':
print('\n{}\n\n{}{}\n\n{}'.format(persuade_reciprocate, change_relation(('government', '+++'), ('army', '+++')),
change_tide(30), win_loss()))
choices.append('rebuttal: dodged the predicament')
elif persuade == 'B':
print('\n{}\n\n{}{}\n'.format(persuade_lie, change_relation(('government', '---'), ('civilian', '---')),
change_tide(0)))
choices.append('rebuttal: lied')
to_win()
vengeance()
elif persuade == 'A':
print('\n{}\n\n{}{}\n'.format(persuade_admit, change_relation(('army', '--')), change_tide(-30)))
choices.append('rebuttal: admitted')
change_tide(-30)
print('{}\n\n{}'.format(persuade_lose, win_loss()))
def supply_defend():
button = prompt_for_input(yield_supply_defense, ('X', 'B', 'Y'))
load(5)
if button == 'X':
print('\n{}\n\n{}{}\n'.format(supply_defense_defend, change_relation(('government', '-')),
change_tide(-5)))
choices.append('supply defense: direct')
to_win()
blackout()
elif button == 'B':
print('\n{}\n\n{}{}\n'.format(supply_defense_contaminate, change_relation(('government', '+++'),
('army', '+++')), change_tide(15)))
choices.append('supply defense: poisonous')
change_tide(15)
print('{}\n\n{}'.format(supply_defense_win, win_loss()))
elif button == 'Y':
print('\n{}\n\n{}{}\n'.format(supply_defense_conceal, change_relation(('civilian', '++'), ('government', '+')),
change_tide(0)))
choices.append('supply defense: evasive')
to_win()
almost_fifty()
def replace():
print(soldiers_replace)
load(15)
present_person(lieutenants)
civil = {'first': 0, 'second': 0}
army = {'first': 0, 'second': 0}
gov = {'first': 0, 'second': 0}
valid_stick_input = ['<<', '<', '<>', '>', '>>']
def balance_relation_change(type_of_person, first_relation_change, second_relation_change):
get_person = getattr(People, type_of_person.upper())
relation_change_sum = first_relation_change + second_relation_change
change_output = ''
def get_relation_balance(thresholds):
if relation_change_sum > 0:
for threshold in thresholds:
if relation_change_sum >= threshold:
return threshold
elif relation_change_sum < 0:
for threshold in thresholds:
if relation_change_sum <= threshold:
return threshold
if relation_change_sum < 0:
for dash in range(abs(relation_change_sum)):
change_output += '-'
change_output += str(type_of_person)
relationships[get_person] += get_relation_balance(range(-4, 0, 1))
elif relation_change_sum > 0:
for dash in range(relation_change_sum):
change_output += '+'
change_output += str(type_of_person)
relationships[get_person] += get_relation_balance(range(4, 0, -1))
return change_output
left_stick = prompt_for_input(replace_pick_generals, valid_stick_input)
def pick_left_stick(stick, first_or_second):
if stick == '<<':
change_tide(-5)
army[first_or_second] -= 3
gov[first_or_second] -= 3
elif stick == '<':
change_tide(10)
army[first_or_second] += 3
gov[first_or_second] += 3
civil[first_or_second] += 3
elif stick == '<>':
change_tide(-15)
army[first_or_second] += 2
gov[first_or_second] -= 3
civil[first_or_second] -= 3
elif stick == '>':
change_tide(5)
army[first_or_second] += 3
civil[first_or_second] -= 3
elif stick == '>>':
change_tide(15)
army[first_or_second] += 2
gov[first_or_second] += 1
civil[first_or_second] -= 1
del valid_stick_input[valid_stick_input.index(stick)]
pick_left_stick(left_stick, 'first')
load(3)
left_stick = prompt_for_input('\nYour second?\n', valid_stick_input)
pick_left_stick(left_stick, 'second')
def print_results():
print(change_tide(0))
for people in [balance_relation_change('army', army['first'], army['second']),
balance_relation_change('civilian', civil['first'], civil['second']),
balance_relation_change('government', gov['first'], gov['second'])]:
if people:
print(people, end=' ')
print('\n')
load(5)
if tide[Forces.YOU] < 40:
print('\n{}'.format(pick_generals_bad))
print_results()
change_tide(-25)
choices.append('general: chose poorly')
print('\n{}\n\n{}'.format(replace_lose, win_loss()))
elif tide[Forces.YOU] > 50:
print('\n{}'.format(pick_generals_good))
print_results()
change_tide(35)
choices.append('general: chose wisely')
print('\n{}\n\n{}'.format(replace_win, win_loss()))
else:
print('\n{}'.format(pick_generals_ok))
print_results()
choices.append('general: chose ineffectively')
to_win()
strategy()
def rebel():
button = prompt_for_input(execution_prison_rebellion, ('X', 'B', 'Y'))
load(5)
if button == 'X':
print('\n{}\n\n{}{}\n'.format(rebellion_quell, change_relation(('army', '+++')), change_tide(5)))
choices.append('peacekeeping: forceful')
to_win()
offer()
elif button == 'B':
print('\n{}\n\n{}{}\n'.format(rebellion_reason, change_relation(('army', '---')), change_tide(-20)))
choices.append('peacekeeping: peaceful')
change_tide(-30)
print('{}\n\n{}'.format(rebellion_lose, win_loss()))
elif button == 'Y':
print('\n{}\n\n{}{}\n'.format(rebellion_intimidate, change_relation(('civilian', '---'), ('government', '-'),
('army', '++')), change_tide(15)))
choices.append('peacekeeping: beneficial')
change_tide(15)
print('{}\n\n{}'.format(rebellion_lose, win_loss()))
def slaves():
button = prompt_for_input(warn_ignore_slaves, ('X', 'B', 'Y', 'A'))
load(5)
if button == 'X':
print('\n{}\n\n{}{}\n'.format(slaves_army, change_relation(('civilian', '---'), ('army', '++')),
change_tide(15)))
choices.append('punishment: army')
to_win()
almost_fifty()
elif button == 'B':
print('\n{}\n\n{}{}\n'.format(slaves_produce, change_relation(('army', '---')), change_tide(-15)))
choices.append('punishment: production')
change_tide(-10)
print('{}\n\n{}'.format(slaves_lose, win_loss()))
elif button == 'Y':
print('\n{}\n\n{}{}\n'.format(slaves_plan, change_relation(('government', '++'), ('civilian', '---')),
change_tide(25)))
choices.append('punishment: plans')
change_tide(25)
print('{}\n\n{}'.format(slaves_win, win_loss()))
elif button == 'A':
print('\n{}\n\n{}{}\n'.format(slaves_infrastructure, change_relation(('civilian', '---'), ('army', '---')),
change_tide(-5)))
choices.append('punishment: infrastructure')
to_win()
zombies()
def spy():
button = prompt_for_input(supply_attack_espionage, ('X', 'B', 'A'))
load(5)
if button == 'X':
print('\n{}\n\n{}{}\n'.format(espionage_rush, change_relation(('civilian', '---'), ('army', '---'),
('government', '---')), change_tide(-5)))
choices.append('patience: impatient')
to_win()
offer()
elif button == 'B':
print('\n{}\n\n{}{}\n'.format(espionage_fair, change_relation(('government', '--')), change_tide(-15)))
choices.append('patience: sufficient')
to_win()
blackout()
elif button == 'A':
print('\n{}\n\n{}{}\n'.format(espionage_careful, change_relation(('army', '-'), ('government', '+++')),
change_tide(10)))
choices.append('patience: long')
change_tide(10)
print('{}\n\n{}'.format(espionage_win, win_loss()))
def assassination():
button = prompt_for_input(water_assassinate, ('X', 'B', 'Y'))
load(5)
if button == 'X':
print('\n{}\n\n{}{}\n'.format(assassinate_javier, change_relation(('government', '+++'), ('army', '++')),
change_tide(10)))
choices.append('safety: 100% (Javier Garcia)')
to_win()
almost_fifty()
elif button == 'B':
print('\n{}\n\n{}{}\n'.format(assassinate_gabriel, change_relation(('civilian', '---')), change_tide(-15)))
choices.append('safety: 50% (Gabriel Garcia)')
change_tide(-15)
print('{}\n\n{}'.format(assassinate_lose, win_loss()))
elif button == 'Y':
print('\n{}\n\n{}{}\n'.format(assassinate_bullock, change_relation(('civilian', '+++'), ('army', '---'),
('government', '-')), change_tide(25)))
choices.append('safety: 0% (Jude Bullock)')
change_tide(20)
print('{}\n\n{}'.format(assassinate_win, win_loss()))
def peace():
button = prompt_for_input(air_peace, ('X', 'B', 'A'))
load(5)
if button == 'X':
print('\n{}\n\n{}{}\n'.format(peace_willing, change_relation(('government', '---'), ('army', '---')),
change_tide(10)))
choices.append('request: trusted')
change_tide(15)
print('{}\n\n{}'.format(peace_win, win_loss()))
elif button == 'B':
print('\n{}\n\n{}{}\n'.format(peace_cautious, change_relation(('government', '-')), change_tide(-15)))
choices.append('request: doubted')
to_win()
almost_fifty()
elif button == 'A':
print('\n{}\n\n{}{}\n'.format(peace_no, change_relation(('civilian', '---')), change_tide(0)))
choices.append('request: declined')
to_win()
cybersecurity()
def contaminated():
button = prompt_for_input(bio_contaminated, ('X', 'B'))
load(5)
if button == 'X':
print('\n{}\n\n{}{}\n'.format(contaminated_finish, change_relation(('civilian', '---'), ('government', '---')),
change_tide(-20)))
choices.append('focus: New Frontier')
change_tide(-15)
print('{}\n\n{}'.format(contaminated_lose, win_loss()))
elif button == 'B':
print('\n{}\n\n{}{}\n'.format(contaminated_fix, change_relation(('civilian', '+++'), ('army', '--')),
change_tide(20)))
choices.append('focus: inhabitants')
change_tide(20)
print('{}\n\n{}'.format(contaminated_win, win_loss()))
def strategy():
button = prompt_for_input(ok_strategy, ('X', 'Y', 'A', 'B'))
load(5)
if button == 'X':
print('\n{}\n\n{}{}\n'.format(strategy_direct, change_relation(('civilian', '---'), ('government', '---')),
change_tide(-20)))
choices.append('strategy: direct')
change_tide(-20)
print(f'{strategy_lose_direct}\n\n{win_loss()}')
elif button == 'B':
print('\n{}\n\n{}{}\n'.format(strategy_wide, change_relation(('civilian', '---'), ('government', '---'),
('army', '---')), change_tide(-20)))
choices.append('strategy: longitudinal')
change_tide(-15)
print(f'{strategy_lose_wide}\n\n{win_loss()}')
elif button == 'Y':
print('\n{}\n\n{}{}\n'.format(strategy_psycho, change_relation(('government', '+++'), ('civilian', '-'),
('army', '-')), change_tide(15)))
choices.append('strategy: psychological')
change_tide(30)
print(f'{strategy_win_psycho}\n\n{win_loss()}')
elif button == 'A':
print('\n{}\n\n{}{}\n'.format(strategy_patient, change_relation(('army', '+++'), ('civilian', '+++'),
('government', '+++')), change_tide(20)))
choices.append('strategy: patient')
change_tide(30)
print(f'{strategy_win_patient}\n\n{win_loss()}')
def vengeance():
button = prompt_for_input(lie_revenge, ('X', 'B', 'Y'))
load(5)
if button == 'X':
print('\n{}\n\n{}{}\n'.format(revenge_attack, change_relation(('government', '---'), ('civilian', '-')),
change_tide(-25)))
choices.append('vengeance: hasty')
change_tide(-30)
print('{}\n\n{}'.format(revenge_lose, win_loss()))
elif button == 'B':
print('\n{}\n\n{}{}\n'.format(revenge_wait, change_relation(('government', '+++'), ('civilian', '+++'),
('army', '+++')), change_tide(15)))
choices.append('vengeance: patient')
change_tide(20)
print('{}\n\n{}'.format(revenge_win_wait, win_loss()))
elif button == 'Y':
print('{}\n\n{}{}\n'.format(revenge_infiltrate, change_relation(('government', '+++'), ('army', '-'),
('civilian', '+++')), change_tide(15)))
choices.append('vengeance: strategic')
change_tide(15)
print('{}\n\n{}'.format(revenge_win_infiltrate, win_loss()))
def blackout():
button = prompt_for_input(defend_infrastructure_blackout, ('X', 'B'))
load(5)
if button == 'X':
print('\n{}\n\n{}{}\n'.format(blackout_evacuate, change_relation(('government', '---'), ('army', '---')),
change_tide(-20)))
choices.append('fight or flight: flight')
change_tide(-25)
print(f'{blackout_lose}\n\n{win_loss()}')
elif button == 'B':
print('\n{}\n\n{}{}\n'.format(blackout_stay, change_relation(('civilian', '+++'), ('government', '+++'),
('army', '+++')), change_tide(20)))
choices.append('fight or flight: fight')
change_tide(25)
print(f'{blackout_win}\n\n{win_loss()}')
def offer():
button = prompt_for_input(quell_rush_offer, ('X', 'B'))
load(5)
if button == 'X':
print('\n{}\n\n{}\n\n{}'.format(offer_accept, change_relation(('civilian', '+++'), ('government', '+++')),
win_loss()))
choices.append('offer: accepted')
elif button == 'B':
print('\n{}\n\n{}{}\n\n{}'.format(offer_decline, change_relation(('civilian', '---'), ('government', '---')),
change_tide(25), win_loss()))
choices.append('offer: declined')
def almost_fifty():
button = prompt_for_input(army_cautious_conceal_javier_half, ('X', 'B', 'A'))
load(5)
if button == 'X':
print('\n{}\n\n{}{}\n'.format(half_third, change_relation(('civilian', '+++'), ('government', '+++'),
('army', '-')), change_tide(20)))
choices.append('jeopardy: sent few')
change_tide(15)
print(f'{half_win}\n\n{win_loss()}')
elif button == 'B':
print('\n{}\n\n{}{}\n'.format(half_move, change_relation(('civilian', '---'), ('army', '---'),
('government', '---')), change_tide(-25)))
choices.append('jeopardy: evacuated')
change_tide(-20)
print(f'{half_lose}\n\n{win_loss()}')
elif button == 'A':
print('\n{}\n\n{}{}\n'.format(half_surround, change_relation(('army', '+++')), change_tide(-10)))
choices.append('jeopardy: surrounded')
to_win()
surrounded()
def zombies():
button = prompt_for_input(infrastructure_horde, ('X', 'B', 'Y'))
load(5)
if button == 'X':
print('\n{}\n\n{}{}\n'.format(horde_redirect, change_relation(('army', '--')), change_tide(-10)))
choices.append('horde: redirected')
change_tide(-10)
print('{}\n\n{}'.format(horde_lose, win_loss()))
elif button == 'B':
print('\n{}\n\n{}{}\n'.format(horde_lure, change_relation(('civilian', '+++'), ('government', '+++'),
('army', '+')), change_tide(25)))
choices.append('horde: fed')
change_tide(30)
print(f'{horde_win}\n\n{win_loss()}')
elif button == 'Y':
print('\n{}\n\n{}{}\n\n{}'.format(horde_clear, change_relation(('civilian', '---')), change_tide(-20),
win_loss()))
choices.append('horde: cleared')
def cybersecurity():
button = prompt_for_input(no_hack, ('X', 'B'))
load(5)
if button == 'X':
print('\n{}\n\n{}{}\n'.format(hack_destroy, change_relation(('government', '---')), change_tide(-20)))
choices.append('cybersecurity: physical')
change_tide(-30)
print('{}\n\n{}'.format(hack_lose, win_loss()))
elif button == 'B':
print('\n{}\n\n{}{}\n'.format(hack_cyber, change_relation(('government', '+++'), ('army', '+++')),
change_tide(0)))
choices.append('cybersecurity: cyber')
to_win()
areas()
def areas():
button = prompt_for_input(cyber_areas, ('X', 'B', 'A'))
load(5)
if button == 'X':
print('\n{}\n\n{}{}\n\n{}'.format(areas_virginia_beach, change_relation(('civilian', '+++'),
('government', '+++')), change_tide(20),
win_loss()))
choices.append('city: Virginia Beach')
elif button == 'B':
button = prompt_for_input('\n{}'.format(areas_raleigh), ('X', 'B'))
load(3)
choices.append('city: Raleigh')
if button == 'X':
print('\n{}\n\n{}{}\n\n{}'.format(raleigh_lie, change_relation(('government', '---'), ('civilian', '---')),
change_tide(-65), do_not_lie))
choices.append('honesty: dishonest')
elif button == 'B':
print('\n{}\n\n{}{}\n\n{}'.format(raleigh_honest, change_relation(('government', '+++'), ('army', '++'),
('civilian', '+++')), change_tide(20),
win_loss()))
choices.append('honesty: honesty')
elif button == 'A':
print('\n{}\n\n{}{}\n'.format(areas_dc, change_relation(('civilian', '---')), change_tide(-40)))
change_tide(-25)
print('{}\n\n{}'.format(areas_lose, win_loss()))
def surrounded():
button = prompt_for_input(surround_surrounded, ('X', 'B', 'Y'))
load(5)
if button == 'X':
print('\n{}\n\n{}{}\n'.format(surrounded_richmond, change_relation(('civilian', '---')), change_tide(-20)))
choices.append('escape: through thinnest')
change_tide(-25)
print(f'{surrounded_lose_richmond}\n\n{win_loss()}')
elif button == 'B':
print('\n{}\n\n{}{}\n'.format(surrounded_thin, change_relation(('civilian', '+++'), ('government', '+++'),
('army', '+++')), change_tide(20)))
choices.append('escape: to Richmond')
change_tide(25)
print(f'{surrounded_win}\n\n{win_loss()}')
elif button == 'Y':
print('\n{}\n\n{}{}\n'.format(surrounded_stay, change_relation(('civilian', '---'), ('government', '---'),
('army', '---')), change_tide(-25)))
choices.append('escape: no')
change_tide(-20)
print(f'{surrounded_lose_stay}\n\n{win_loss()}')
def end():
infuriate = '\033[38;5;199m' + "INFURIATED" + '\033[m'
angered = '\033[31m' + "ANGERED" + '\033[m'
displeased = '\033[38;5;208m' + "DISPLEASED" + '\033[m'
unimpressed = '\033[93m' + "LEFT UNIMPRESSED," + '\033[m'
satisfied = '\033[32m' + "SATISFIED" + '\033[m'
delighted = '\033[36m' + "DELIGHTED" + '\033[m'
views = [infuriate, angered, displeased, unimpressed, satisfied, delighted]
thresholds = (-8.5, -6, -4.5, -2, .5)
def get_final_standing(relation_score):
for threshold, view in zip(thresholds, views):
if relation_score <= threshold:
return view
return views[-1]
load(5)
view_civilians = '\nYou {} the Civilians'.format(get_final_standing(relationships[People.CIVILIAN]))
view_army = 'You {} the Military'.format(get_final_standing(relationships[People.ARMY]))
view_government = 'You {} the Government'.format(get_final_standing(relationships[People.GOVERNMENT]))
for people in [view_civilians, view_government, view_army]:
print(people)
time.sleep(4)
load(5)
print('\nYOUR DECISIONS:')
indent = ' '
for choice in choices:
print(indent + choice)
indent += ' '
print(introduction)
load(15)
start()
end()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T07:31:35.173",
"Id": "441283",
"Score": "2",
"body": "I guess you can post the code without all the dialogs, since there isn't much to review on them. Include one dialog as an example and omit the rest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T07:54:51.963",
"Id": "441286",
"Score": "1",
"body": "IMO your previous title was a lot better than the current one..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T08:56:18.927",
"Id": "441291",
"Score": "0",
"body": "@eric.m I disagree about omitting the story from the question. If the plot is so complex that it gets in the way of the code, then that's a valid point to be addressed in a review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:21:17.927",
"Id": "441333",
"Score": "0",
"body": "that's why there's a link to the full version"
}
] |
[
{
"body": "<p>Only going to comment on a couple things I noticed while scrolling, not enough time to review the full code.</p>\n\n<h1>Be Consistent</h1>\n\n<p>Here is your <code>to_win</code> function:</p>\n\n<pre><code>def to_win():\n print('85/15 TO WIN', end='')\n for dot in range(4):\n print('.', end='', flush=True)\n time.sleep(1)\n print('or lose')\n print('Loading', end='', flush=True)\n for _ in range(15):\n time.sleep(1)\n print('.', end='', flush=True)\n print()\n</code></pre>\n\n<p>Looking through your code, you know when and when not to use an underscore as a loop variable. So, why do you use <code>dot</code> when you don't need to? You should be consistent everywhere in your code.</p>\n\n<h1>Docstrings</h1>\n\n<p>I may be wrong, but I only noticed <em>one</em> docstring for all your functions and classes. You should include a docstring at the beginning of every module, class, and function you write. It allows documentation to identify what your code is supposed to do. Also helps readers quickly understand your program from reading the module docstring.</p>\n\n<h1>Constants Naming</h1>\n\n<pre><code>ox_idea1 = '\"numbers is key\"'\ncox_idea2 = '\"hit the frontier hard with a direct attack to the most secure but vital part of them: downtown\"'\ncox_pro_cons = pro_con('militarist', 'quick-minded', 'assertive', 'convincing', 'irrational', 'close-minded')\nchloe_cox = person('chloe cox', '09/25/98', 'Caucasian-American', 'F', 'Arlington, VA', cox_idea1, cox_idea2,\n cox_pro_cons)\nvazquez_idea1 = '\"strategy is key\"'\nvazquez_idea2 = '\"we weaken every strength, target every weakness and exploit every mistake rationally and ' \\\n 'intelligently until they fall\"'\nvazquez_pros_cons = pro_con('strategist', 'smart', 'methodical', 'realistic', 'flawed', 'negligent')\nbenjamin_vazquez = person('benjamin vazquez', '10/23/88', 'Mexican-American', 'M', 'Richmond, VA', vazquez_idea1,\n vazquez_idea2, vazquez_pros_cons)\nwashington_idea1 = '\"a prosperous army is key'\nwashington_idea2 = '\"as long as are soldiers are well supplied and well fed, they will fight outstandingly\"'\nwashington_pro_cons = pro_con('supplier', 'considerate', 'benevolent', 'focused', 'old', 'unassertive')\nzaid_washington = person('zaid washington', '12/10/74', 'African-American', 'M', 'Virgina Beach, VA',\n washington_idea1, washington_idea2, washington_pro_cons)\nwaters_idea1 = '\"morale is key\"'\nwaters_idea2 = '\"as long as our soldiers have the drive and motivation to fight, they will conquer\"'\nwaters_pro_cons = pro_con('therapist', 'energetic', 'optimistic', 'motivator', 'malleable', 'unassertive')\nrob_waters = person('rob waters', '12/17/87', 'Caucasian-American', 'M', 'Roanoke Rapids, NC', waters_idea1,\n waters_idea2, waters_pro_cons)\nli_idea1 = '\"firepower and intimidation is key\"'\nli_idea2 = '''\"our priority is our guns, bombs, transportation and technology. we make as much weapons as possible use \n them, kill, send a message\"'''\nli_pro_cons = pro_con('warlord', 'aggressive', 'fearless', 'rational', 'inarticulate', 'young')\nju_li = person('ju_li', '02/06/03', 'Chinese-American', 'F', 'Richmond, VA', li_idea1, li_idea2, li_pro_cons)\nlieutenants = [chloe_cox, benjamin_vazquez, rob_waters, zaid_washington, ju_li]\n</code></pre>\n\n<p>These are all constants. They should be UPPER_CASE to identify them as such.</p>\n\n<h1>Meaningful Function Names</h1>\n\n<pre><code>def present_person(people):\n for individual in people:\n print('\\n{}'.format(individual))\n load(15)\n</code></pre>\n\n<p>From the name of this function, it seems that the code presents a <em>person</em>. Yet the function accepts <em>people</em> and prints <em>individuals</em>, not one person. Perhaps change the name of this function to make it clear what it's supposed to do.</p>\n\n<h1>Unnecessary <code>else</code> after returning</h1>\n\n<p>You have this function:</p>\n\n<pre><code>def prompt_for_input(prompt, valid_inputs, max_tries=6):\n print(prompt)\n the_roadblock = '\\nPlease enter a valid input\\n'\n\n while max_tries > 0:\n user_input = input('> ').upper()\n\n if user_input in valid_inputs:\n return user_input\n else:\n print(the_roadblock)\n max_tries -= 1\n\n # the input was not valid, show the roadblock\n print('Seems like you are not willing to play. Goodbye!')\n sys.exit(0)\n</code></pre>\n\n<p>After returning in a function, the rest of the code is not executed. So it is unnecessary to have an else here. Your function should look like this now:</p>\n\n<pre><code>def prompt_for_input(prompt, valid_inputs, max_tries=6):\n \"\"\"\n Docstring here\n \"\"\"\n print(prompt)\n the_roadblock = '\\nPlease enter a valid input\\n'\n\n while max_tries > 0:\n user_input = input('> ').upper()\n\n if user_input in valid_inputs:\n return user_input\n print(the_roadblock)\n max_tries -= 1\n\n # the input was not valid, show the roadblock\n print('Seems like you are not willing to play. Goodbye!')\n sys.exit(0)\n</code></pre>\n\n<p>The same goes for your <code>win_loss</code> function:</p>\n\n<pre><code>def win_loss():\n if tide[Forces.YOU] >= 85:\n return 'VICTORY! The New Frontier has been overpowered and has surrendered. The End.'\n elif tide[Forces.ENEMY] >= 85:\n return 'DEFEAT! The New Frontier has conquered and killed you all. Nice one chief. The End.'\n else:\n return 'PEACE! The war is over and you know live alongside the New Frontier in tranquility.'\n</code></pre>\n\n<p>You don't need <code>elif</code> and an <code>else</code> here. Just have two if checks for the first two returns, and return the last one if both aren't true. This function should look like this now:</p>\n\n<pre><code>def win_loss():\n \"\"\"\n Docstring here\n \"\"\"\n if tide[Forces.YOU] >= 85:\n return 'VICTORY! The New Frontier has been overpowered and has surrendered. The End.'\n if tide[Forces.ENEMY] >= 85:\n return 'DEFEAT! The New Frontier has conquered and killed you all. Nice one chief. The End.'\n return 'PEACE! The war is over and you know live alongside the New Frontier in tranquility.'\n</code></pre>\n\n<h1>Main Guard</h1>\n\n<p>You should wrap the code that starts your game in a main guard. It prevents this code from running if you decide to import this program into another program. <a href=\"https://stackoverflow.com/a/419185/8968906\">This StackOverflow answer</a> provides excellent reasoning to what it is and why to use it. So the starting code should look like this:</p>\n\n<pre><code>if __name__ == '__main__':\n print(introduction)\n load(15)\n start()\n end()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T08:28:15.220",
"Id": "226906",
"ParentId": "226896",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "226906",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T07:17:07.063",
"Id": "226896",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"game",
"adventure-game"
],
"Title": "Revised text adventure game with a war theme"
}
|
226896
|
<p>I'm new with Kotlin, and this is my first attempt of a two dimensional array.</p>
<pre><code> // private var roomGrid = arrayOfNulls<arrayOfNulls<Room>>(4)
private var roomGrid = Array(roomCountX) {arrayOfNulls<Room>(roomCountY)}
init {
for (gridY in 0 until roomCountY) {
for (gridX in 0 until roomCountX) {
val pixelX = gridX * roomWidth
val pixelY = gridY * roomHeight
val room = Room(pixelX.toFloat(), pixelY.toFloat(), s)
roomGrid[gridX][gridY] = room
}
}
// neighbor relations
for (gridY in 0 until roomCountY) {
for (gridX in 0 until roomCountX) {
val room = roomGrid[gridX][gridY]
if (gridY > 0)
roomGrid[gridX][gridY - 1]?.let { room?.setNeighbor(Room.SOUTH, it) }
if (gridY < roomCountY - 1)
roomGrid[gridX][gridY + 1]?.let { room?.setNeighbor(Room.NORTH, it) }
if (gridX > 0)
roomGrid[gridX - 1][gridY]?.let { room?.setNeighbor(Room.WEST, it) }
if (gridX < roomCountX - 1)
roomGrid[gridX + 1][gridY]?.let { room?.setNeighbor(Room.EAST, it) }
}
}
}
</code></pre>
<p>Even though it works I don't like the look of these:</p>
<pre><code>roomGrid[gridX][gridY + 1]?.let { room?.setNeighbor(Room.NORTH, it) }
</code></pre>
<p>They are harder to read, and I'm not really sure what <code>.let</code> and <code>it</code> are.
I would like some simpler syntax/solution to a two dimensional array.</p>
<p>How might I improve this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T12:42:08.997",
"Id": "442812",
"Score": "0",
"body": "can't you get rid of the `null`s?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T07:57:07.370",
"Id": "443216",
"Score": "2",
"body": "What are these arrays for? What is the actual problem you are working on?"
}
] |
[
{
"body": "<h1>let</h1>\n\n<p>If you use let, you ask Kotlin to create an invisible function with a parameter.</p>\n\n<pre><code>1.let { println(5) }\n //changes to:\n fun func(it : Int) {\n println(5)\n }\n func(1)\n</code></pre>\n\n<p>Do you see the <em>it</em>? That's the name of the parameter.\nTherefor, you can use <em>it</em> inside let.</p>\n\n<pre><code>1.let { println(it) }\n//changes to\nfun func(it : Int) {\n println(it)\n}\nfunc(1)\n</code></pre>\n\n<p>Now, the function returns something too, namely the result of the last statement. \nIn this case, it's just Unit, or void in Java (emptyNess):</p>\n\n<pre><code>fun func(it : Int) : Unit {\n return println(it)\n}\nfunc(1)\n</code></pre>\n\n<p>If we take another example, it will be clearer:</p>\n\n<pre><code>val a = 5.let { 3 + it }\n//changes to\nfun func(it: Int) : Int {\n return 3 + it\n}\nval a = func(5)\n</code></pre>\n\n<h1>?.let</h1>\n\n<p>?. is very simple:</p>\n\n<pre><code>val b = a?.foo()\n//changes to:\nval b = if (a == null) a else a.foo()\n</code></pre>\n\n<p>?.let is exactly the same:</p>\n\n<pre><code>val b = a?.let { it+3 }\n//changes to\nfun func(it: Int){\n it + 3\n}\nval b = if (a == null) null else func(a)\n</code></pre>\n\n<h1>inline</h1>\n\n<p>Kotlin is smart. it actually uses an inline function for let.<br>\nAn inline function is a function that actually doesn't exist.<br>\nInstead, the code is copy pasted into the real code.<br>\nThe parameters are just variables with random names.</p>\n\n<p>so</p>\n\n<pre><code>val b = a?.let { it + 3 }\n//is actually changed to\nval b = if (a == null) null else {\n val ac432cd = a\n ac432cd + 3\n}\n</code></pre>\n\n<h1>simplyfication</h1>\n\n<pre><code>roomGrid[gridX][gridY - 1]?.let { room?.setNeighbor(Room.SOUTH, it) }\n</code></pre>\n\n<h2>step 1</h2>\n\n<pre><code>// I would check room first:\nif (room != null) {\n roomGrid[gridX][gridY - 1]?.let { room.setNeighbor(room.SOUTH, it) }\n}\n</code></pre>\n\n<h2>step 2</h2>\n\n<pre><code>// flip the rooms (and directions)\nif (room != null) {\n roomGrid[gridX][gridY - 1]?.let{ it.setNeighbor(room.SOUTH, room) }\n}\n</code></pre>\n\n<h2>step 3</h2>\n\n<pre><code>//remove let\nif (room != null) {\n roomGrid[gridX][gridY - 1]?.setNeighbor(room.SOUTH, room)\n}\n</code></pre>\n\n<p><strong>full code until now</strong></p>\n\n<pre><code> // neighbor relations\nfor (gridY in 0 until roomCountY) {\n for (gridX in 0 until roomCountX) {\n val room = roomGrid[gridX][gridY]\n if (room != null) {\n if (gridY > 0)\n roomGrid[gridX][gridY - 1]?.setNeighbor(Room.NORTH, room)\n if (gridY < roomCountY - 1)\n roomGrid[gridX][gridY + 1]?.setNeighbor(Room.SOUTH, room)\n if (gridX > 0)\n roomGrid[gridX - 1][gridY]?.setNeighbor(Room.EAST, room)\n if (gridX < roomCountX - 1)\n roomGrid[gridX + 1][gridY]?.setNeighbor(Room.WEST, room)\n }\n }\n}\n</code></pre>\n\n<h2>step 4</h2>\n\n<p>At the moment, we test in the beginning if <code>room</code> isn't null.<br>\nIf it is, it skips the if-statement and continues with the next iteration.<br>\nWe can tell to go to the next iteration immediately using the keyword continue.</p>\n\n<pre><code>// neighbor relations\nfor (gridY in 0 until roomCountY) {\n for (gridX in 0 until roomCountX) {\n val room = roomGrid[gridX][gridY]\n if (room == null) continue\n if (gridY > 0)\n roomGrid[gridX][gridY - 1]?.setNeighbor(Room.NORTH, room)\n ...\n }\n}\n</code></pre>\n\n<h2>step 5</h2>\n\n<p>last, kotlin has another language feature: <code>?:</code></p>\n\n<pre><code>val a = foo() ?: bar()\n//will be rewritten to\nval tmp = foo()\nval a = if (tmp != null) tmp else bar()\n</code></pre>\n\n<p>Just as <code>return</code> <code>continue</code> skips immediately to the next variable.\nThis means that we can rewrite the code we wrote in step 4.</p>\n\n<pre><code>// neighbor relations\nfor (gridY in 0 until roomCountY) {\n for (gridX in 0 until roomCountX) {\n val room = roomGrid[gridX][gridY] ?: continue\n if (gridY > 0)\n roomGrid[gridX][gridY - 1]?.setNeighbor(Room.NORTH, room)\n ...\n }\n}\n</code></pre>\n\n<h2>full code</h2>\n\n<pre><code> // neighbor relations\nfor (gridY in 0 until roomCountY) {\n for (gridX in 0 until roomCountX) {\n val room = roomGrid[gridX][gridY] ?: continue\n if (gridY > 0)\n roomGrid[gridX][gridY - 1]?.setNeighbor(Room.NORTH, room)\n if (gridY < roomCountY - 1)\n roomGrid[gridX][gridY + 1]?.setNeighbor(Room.SOUTH, room)\n if (gridX > 0)\n roomGrid[gridX - 1][gridY]?.setNeighbor(Room.EAST, room)\n if (gridX < roomCountX - 1)\n roomGrid[gridX + 1][gridY]?.setNeighbor(Room.WEST, room)\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T09:24:59.383",
"Id": "443327",
"Score": "1",
"body": "Your right. val room = expr ?: continue. I update tomorrow, as I don't have access to a computer at the moment... Thx!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T08:04:11.030",
"Id": "443533",
"Score": "1",
"body": "@RolandIllig fixed. Hopefully, it can helpsome people understand Kotlin better."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T12:37:28.853",
"Id": "227566",
"ParentId": "226900",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227566",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T07:54:36.720",
"Id": "226900",
"Score": "0",
"Tags": [
"beginner",
"kotlin"
],
"Title": "Two dimensional arrays with nulls"
}
|
226900
|
<p>I'm relatively new to Python. Here is a Tic Tac Toe game I've created in Python:</p>
<pre><code>def is_valid_move(x,y,board):
return ((0 <= x <= 2) and (0 <= y <= 2)) and (board[x][y] == '_')
def check_win(board):
if board[0][0] == board[0][1] == board[0][2] != '_':
return True
if board[1][0] == board[1][1] == board[1][2] != '_':
return True
if board[2][0] == board[2][1] == board[2][2] != '_':
return True
if board[0][0] == board[0][1] == board[0][2] != '_':
return True
if board[0][1] == board[1][1] == board[2][1] != '_':
return True
if board[0][2] == board[1][2] == board[2][2] != '_':
return True
if board[0][0] == board[1][1] == board[2][2] != '_':
return True
if board[2][0] == board[1][1] == board[0][2] != '_':
return True
return False
def get_input_from_user(message:str):
coord = input(message)
str_x, str_y = coord.split()
return int(str_x), int(str_y)
def make_move(idx,board):
if idx % 2 == 0:
x, y = get_input_from_user("Player X, please enter a move:")
while not is_valid_move(x, y,board):
x,y = get_input_from_user("Invalid move, please try again:")
board[x][y] = 'X'
else:
x, y = get_input_from_user("Player O, please enter a move:")
while not is_valid_move(x, y,board):
x, y = get_input_from_user("Invalid move, please try again:")
board[x][y] = 'O'
def print_board(board):
for i in range(3):
print(board[i])
if __name__ == '__main__':
idx = 0
board = [['_','_','_'] for i in range(3)]
condition = False
while condition is not True or idx <= 8:
make_move(idx,board)
print_board(board)
condition = check_win(board)
if condition is True and idx % 2 == 0:
print("Player X is the Winner!")
elif condition is True:
print("Player O is the Winner!")
idx += 1
if idx > 8 and condition is not True:
print("Its a Draw!")
</code></pre>
<p>Here is a simple test run of this code:</p>
<pre><code>Player X, please enter a move:0 2
['_', '_', 'X']
['_', '_', '_']
['_', '_', '_']
Player O, please enter a move:0 1
['_', 'O', 'X']
['_', '_', '_']
['_', '_', '_']
Player X, please enter a move:1 1
['_', 'O', 'X']
['_', 'X', '_']
['_', '_', '_']
Player O, please enter a move:0 0
['O', 'O', 'X']
['_', 'X', '_']
['_', '_', '_']
Player X, please enter a move:2 0
['O', 'O', 'X']
['_', 'X', '_']
['X', '_', '_']
Player X is the Winner!
</code></pre>
<p>Let me know your thoughts about my code.</p>
|
[] |
[
{
"body": "<p>I see a few areas where you can improve.</p>\n\n<ul>\n<li><p>You don't need parenthesis around the expressions you <code>and</code> or <code>return</code>:</p>\n\n<pre><code>def is_valid_move(x, y, board):\n return 0 <= x <= 2 and 0 <= y <= 2 and board[x][y] == '_'\n</code></pre>\n\n<p>Sometimes you <em>do</em> need parenthesis, but only if the operator precedence is wrong otherwise. I.e <code>A and B or C</code> is different from <code>A and (B or C)</code>.</p></li>\n<li><p>Your <code>check_win</code> function is very hard to debug. How sure are you that you did not mess up any of the indices while copy&pasting, and how long would it take you to check that you didn't?</p>\n\n<p>Instead divide the function into sub-responsibilities, which you can name and reason about individually:</p>\n\n<pre><code>def all_equal(it):\n it = iter(it)\n first = next(it)\n return all(x == first for x in it)\n\ndef check_rows(board):\n for row in board:\n if row[0] != \"_\" and all_equal(row):\n return True\n return False\n\ndef check_cols(board):\n for col in zip(*board): # transpose the board\n if col[0] != \"_\" and all_equal(col):\n return True\n return False\n\ndef check_diagonals(board):\n if board[0][0] != \"_\" and all_equal(board[i][i] for i in range(len(board))):\n return True\n if board[0][2] != \"_\" and all_equal([board[0][2], board[1][1], board[2][0]]):\n return True\n return False\n\ndef check_win(board):\n return check_rows(board) or check_cols(board) or check_diagonals(board)\n</code></pre>\n\n<p>While this code is longer, it should also be more readable. Also, this way only the diagonal check is still complicated to check for correctness, but at least it is localized.</p></li>\n<li><p>Your <code>get_input_from_user</code> function can be shortened a bit, at the cost of some readability (at least until you get used to functional programming):</p>\n\n<pre><code>def get_input_from_user(message: str):\n return tuple(map(int, input(message).split()))\n</code></pre></li>\n<li><p><a href=\"https://nedbatchelder.com/text/iter.html\" rel=\"nofollow noreferrer\">Don't iterate over the indices, if what you really want to do is iterate over the elements</a>:</p>\n\n<pre><code>def print_board(board):\n for row in board:\n print(row)\n</code></pre></li>\n<li><p>Your main loop and the <code>make_move</code> function. The <code>make_move</code> function has two almost identical branches, the only difference is the player mark. So why not pass that instead of the index? In your main loop you can also change that to just swap between the two players, which lets you use a <code>for</code> loop which is automatically restricted to n iterations:</p>\n\n<pre><code>def make_move(player, board):\n x, y = get_input_from_user(f\"Player {player}, please enter a move:\")\n while not is_valid_move(x, y, board):\n x,y = get_input_from_user(\"Invalid move, please try again:\")\n board[x][y] = player\n\nif __name__ == '__main__':\n players = \"X\", \"O\"\n board = [['_'] * 3 for _ in range(3)]\n for _ in range(9):\n make_move(players[0], board)\n print_board(board)\n if check_win(board):\n print(f\"Player {players[0]} is the Winner!\")\n break\n players = players[::-1] # equivalent to players[0], players[1] = players[1], players[0]\n else: # only runs if no `break` broke the loop\n print(\"Its a Draw!\")\n</code></pre>\n\n<p>I also used some <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\"><code>f-string</code>s</a> for formatting, <a href=\"https://riptutorial.com/python/example/12259/list-multiplication-and-common-references\" rel=\"nofollow noreferrer\">multiplication of lists</a>, and the <a href=\"http://book.pythontips.com/en/latest/for_-_else.html#for-else\" rel=\"nofollow noreferrer\"><code>else</code> clause of loops</a> to detect a draw.</p></li>\n<li><p>Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. It recommends always puting a space after commas in parameter lists, etc.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T10:20:06.337",
"Id": "226909",
"ParentId": "226908",
"Score": "3"
}
},
{
"body": "<p>This code looks quite good! Just some recommendations:</p>\n\n<hr>\n\n<p>Try to follow the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8 Style Guidelines</a> so that your code is more standard and readable; you already do it with the naming, but you are missing some whitespaces: <code>is_valid_move(x,y,board)</code> should be <code>is_valid_move(x, y, board)</code>, <code>(message:str)</code> should be <code>(message: str)</code>,...</p>\n\n<hr>\n\n<p>In the <code>make_move</code> function you are repeating the same code twice: the only thing that changes is the text displayed and the symbol used. In fact, the prompt text just depends on the player symbol. So it can be rewritten as this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def make_move(idx,board):\n if idx % 2 == 0:\n symbol = 'X'\n else:\n symbol = 'O'\n\n x, y = get_input_from_user(f\"Player {symbol}, please enter a move:\")\n while not is_valid_move(x, y, board):\n x,y = get_input_from_user(\"Invalid move, please try again:\")\n board[x][y] = symbol\n</code></pre>\n\n<p>Here I used an <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">f-string</a> to format the prompt text. If you want shorter code, you can also replace the conditional with a <a href=\"http://book.pythontips.com/en/latest/ternary_operators.html\" rel=\"nofollow noreferrer\">ternary</a>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>symbol = 'X' if idx % 2 == 0 else 'O'\n</code></pre>\n\n<hr>\n\n<p>The <code>print_board</code> can be made more contat using a \"for each\" loop. Instead of iterating indices, you iterate the elements of the list directly:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for row in board:\n print(row)\n</code></pre>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code>board = [['_','_','_'] for i in range(3)]\n</code></pre>\n\n<p>When the index variable in a loop is not used, it's better to use the anonymous <code>_</code> instead. Furthermore, you can use <code>*</code> to make a list with a default value:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>board = [['_'] * 3 for _ in range(3)\n</code></pre>\n\n<p>It might be tempting to just do <code>[['_'] * 3] * 3</code>, but that's a trap: <code>board</code> will contain the same list reference for all three rows, so editing one will edit all of them.</p>\n\n<hr>\n\n<p>Variable names should clearly indicate what they are; <code>condition</code> does not seem clear enough to me, as I had to look at the code to understand its meaning. Try a more explicit name like <code>has_winner</code>.</p>\n\n<p>Additionally, <code>condition</code> is a boolean (can only be true or false), so you don't have to check <code>is True</code> explicitly; you can just do <code>if condition and ...</code> (use <code>if not condition</code> to check if it's false).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T10:24:22.930",
"Id": "226910",
"ParentId": "226908",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226909",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T09:50:26.237",
"Id": "226908",
"Score": "4",
"Tags": [
"python",
"beginner",
"python-3.x",
"tic-tac-toe"
],
"Title": "\"Tic Tac Toe\" game in Python"
}
|
226908
|
<p>I have the following code which I am running through fortify. Why it gets marked for poor error handling, throw inside finally? </p>
<pre><code>private String getResourceContent(String fileName) throws IOException {
try (InputStream resource = ErrorResource.classLoader.getResourceAsStream(fileName)) {
return new String(resource.readAllBytes(), StandardCharsets.UTF_8);
} catch (NullPointerException n) {
throw new ErrorDescriptorException(
String.format("Error loading Error description data from Resource file [%s].", fileName), n);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T11:24:09.630",
"Id": "441309",
"Score": "0",
"body": "What is `ErrorDescriptorException`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T11:24:54.487",
"Id": "441311",
"Score": "0",
"body": "class ErrorDescriptorException extends RuntimeException"
}
] |
[
{
"body": "<p><a href=\"https://docs.oracle.com/javase/9/docs/api/java/lang/ClassLoader.html#getResourceAsStream-java.lang.String-\" rel=\"noreferrer\"><code>ClassLoader.getResourceAsStream()</code></a> throws a <code>NullPointerException</code> if the given name is null, something you can easily check. <a href=\"https://docs.oracle.com/javase/9/docs/api/java/io/InputStream.html#readAllBytes--\" rel=\"noreferrer\"><code>InputStream.readAllBytes()</code></a> does not throw a <code>NullPointerException</code>, and neither does instatiating the String. </p>\n\n<p>So basically, the null exception will happen if and only if <code>fileName</code> is null, or if the resource is not found and therefore resource is null; you can easily check both without catching an exception:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private String getResourceContent(String fileName) throws IOException {\n if (fileName == null) {\n // now what?\n }\n try (InputStream resource = ErrorResource.classLoader.getResourceAsStream(fileName)) {\n if (resource == null) {\n // now what?\n }\n return new String(resource.readAllBytes(), StandardCharsets.UTF_8);\n }\n}\n</code></pre>\n\n<p>The question now is what you want to do if <code>fileName</code> or <code>resource</code> is null. This depends on how you want your function to be used; in my opinion, you should expect the user to give a file name that is not null, so throw a <code>NullPointerException</code> if that is not the case. In the <code>resource</code> case, you could use your custom exception for that.</p>\n\n<p>Now, what if <code>readAllBytes()</code> throws an exception? You can either let it propagate to the caller (like it's happening now) or use <code>ErrorDescriptorException</code> as a wrapper (but maybe this makes fortify complain again):</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private String getResourceContent(String fileName) throws ErrorDescriptorException {\n if (fileName == null) {\n throw new NullPointerException();\n }\n try (InputStream resource = ErrorResource.classLoader.getResourceAsStream(fileName)) {\n if (resource == null) {\n throw new ErrorDescriptorException(\n String.format(\"Error loading Error description data from Resource file [%s].\", fileName));\n }\n return new String(resource.readAllBytes(), StandardCharsets.UTF_8);\n }\n catch (IOException | OutOfMemoryException e) {\n throw new ErrorDescriptorException(\n String.format(\"Error loading Error description data from Resource file [%s].\", fileName), e);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T11:49:46.937",
"Id": "441317",
"Score": "2",
"body": "NPE can also be there at ErrorResource.classLoader.getResourceAsStream(fileName). ErrorResource.classLoader can be null if loaded by bootstrap classloader."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T11:51:14.787",
"Id": "441318",
"Score": "2",
"body": "True, you should add a case for that one too. The idea here is that catching `NullPointerException` is *generally* a bad idea as you can usually just check if `== null`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T11:39:44.160",
"Id": "226916",
"ParentId": "226913",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T11:23:01.507",
"Id": "226913",
"Score": "3",
"Tags": [
"java",
"error-handling"
],
"Title": "Poor error handling: Throw inside Finally"
}
|
226913
|
<p>Attached my data class, datas is not fetched from realm database while performing filtering in <code>performFiltering</code> method:</p>
<pre><code>Worker.kt
package com.oyespace.guards.models
import io.realm.RealmList
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import io.realm.annotations.RealmClass
@RealmClass
open class Worker:RealmObject(){
@PrimaryKey
var wkWorkID:Int = 0
var wkfName:String = ""
var wklName:String = ""
var wkMobile:String = ""
var wkEntryImg:String = ""
var wkWrkType:String = ""
var wkDesgn:String = ""
var wkdob:String = ""
var wkidCrdNo:String =""
var vnVendorID:Long = 0
var blBlockID:Long = 0
var unUnitID:String = ""
var asAssnID:Long = 0
var wkIsActive:Boolean = false
var unUniName:String = ""
}
data class GetWorkersResponse<T>(
val apiVersion: String,
val `data`: WorkersList,
val success: Boolean
)
data class WorkersList(
val worker: RealmList<Worker>
)
data class GetGuardsListResponse<T>(
val apiVersion: String,
val `data`: GuardsList,
val success: Boolean
)
data class GuardsList(
val workers: RealmList<Worker>
)
I want to fetch data from realm database and perform searching and view in recyclerview
override fun performFiltering(charSequence: CharSequence?): FilterResults {
val filteredList = ArrayList<Worker>()
// Toast.makeText(mcontext,items.get(0).wkfName,Toast.LENGTH_LONG).show()
for (row in items) {
// Log.d("Inside for loop",row.wkfName)
// if (row.wkfName!!.toLowerCase().contains(charString.toLowerCase()) || row.age!!.contains(charSequence)) {
if (row.wkfName.toLowerCase().contains(charString.toLowerCase().trim())) {
filteredList.add(row)
}
}
searchList = filteredList
}
val filterResults = Filter.FilterResults()
filterResults.values = searchList
return filterResults
}
override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
searchList = results?.values as? ArrayList<Worker>
notifyDataSetChanged()
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T12:00:47.630",
"Id": "441321",
"Score": "1",
"body": "those are some mighty indentations"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T17:26:25.063",
"Id": "441379",
"Score": "2",
"body": "@dfhwze this happens when your monitor is tilted. The code slides to either of the sides then."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T11:58:31.870",
"Id": "226918",
"Score": "1",
"Tags": [
"kotlin"
],
"Title": "Fetching data from realm database and searching and viewed in recyclerView"
}
|
226918
|
<p>I've created a battle screen transition effect similar to Final Fantasy games, you can see it in action here: <a href="https://gilles-leblanc.github.io/ff8-transition/" rel="nofollow noreferrer">https://gilles-leblanc.github.io/ff8-transition/</a></p>
<p>I'm interested in code quality, performance, optimizations and general JavaScript usage.</p>
<p>One thing in particular is I declared the <code>color</code> function inside the <code>colorSwoosh</code> function to make it private to that function as a form of encapsulation, I'm unsure about whether this is a good thing.</p>
<pre><code>const SideEnum = Object.freeze({"left": 1, "right": -1});
const Pass = Object.freeze({"first": 1, "second": 2});
let canvas;
let context;
let imageData;
const numberOfIndicesPerPixel = 4;
let xProgress = [];
const onColor = 255;
const offColor = 0;
let height, width, segmentLength, sideMultiplier, initialX, lineHeight;
let numberOfFramesRan;
const config = {
color: onColor,
currentPass: Pass.first,
direction: SideEnum.left,
frameLimitFactor: 1,
horizontalSegments: 10,
initSpread: 0.2,
lineHeight: 4,
}
var initTransition = function() {
xProgress = [];
const spread = width * config.initSpread;
for (let y = 0; y < height; y += config.lineHeight) {
let numberOfPixelsToInit = Math.floor(Math.random() * Math.floor(spread));
for (let z = 0; z < config.lineHeight; z++) {
xProgress.push(numberOfPixelsToInit);
for (let x = 0; x <= numberOfPixelsToInit; x++) {
imageData.data[(y + z) * width + (initialX + x * sideMultiplier)] = config.color;
}
}
}
context.putImageData(imageData, 0, 0);
}
var colorSwoosh = function(timestamp) {
function color(passMultiplier) {
const calcValueToAddFunc = function(x, segmentLength) {
return config.horizontalSegments - Math.floor(x / segmentLength);
}
for (let y = 0; y < height; y++) {
for (let x = xProgress[y]; x <= width; x++) {
const valueToAdd = calcValueToAddFunc(x, segmentLength + xProgress[y]);
imageData.data[y * width + (initialX + x * sideMultiplier)] += valueToAdd * passMultiplier;
}
}
context.putImageData(imageData, 0, 0);
}
if (config.frameLimitFactor === 0 || Math.floor(timestamp % config.frameLimitFactor) === 0) {
color(config.currentPass === Pass.first ? 1 : -1);
}
const lastValueToCheck = config.direction === SideEnum.right ? 1 : imageData.data.length - numberOfIndicesPerPixel;
numberOfFramesRan++;
if (config.currentPass === Pass.first) {
if (numberOfFramesRan < 100 && imageData.data[lastValueToCheck] < config.color) {
window.requestAnimationFrame(colorSwoosh);
} else {
config.color = offColor;
config.currentPass = Pass.second;
config.frameLimitFactor = 1;
initTransition();
window.requestAnimationFrame(colorSwoosh);
setTimeout(() => {
document.getElementById('start-button').disabled = false;
}, 2000);
}
} else {
if (imageData.data[lastValueToCheck] > config.color) {
window.requestAnimationFrame(colorSwoosh);
}
}
};
window.addEventListener("load", function() {
canvas = document.getElementById('main-canvas');
startButton = document.getElementById('start-button');
const canvasWidth = canvas.getBoundingClientRect().width;
const canvasHeight = canvas.getBoundingClientRect().height;
canvas.setAttribute("width", canvasWidth);
canvas.setAttribute("height", canvasHeight);
context = canvas.getContext('2d', { alpha: false });
context.fillStyle = "black";
context.fillRect(0, 0, canvasWidth, canvasHeight);
startButton.onclick = function() {
numberOfFramesRan = 0;
startButton.disabled = true;
startButton.blur();
config.color = onColor;
config.currentPass = Pass.first;
if (Math.floor(Math.random() * 2) === 0) {
config.direction = SideEnum.right;
}
config.frameLimitFactor = +document.getElementById('frameSkip').value;
config.horizontalSegments = +document.getElementById('segmentation').value;
config.initSpread = +document.getElementById('initSpread').value;
config.lineHeight = +document.getElementById('lineHeight').value;
if (document.documentElement.clientWidth <= 800) {
config.lineHeight = 2;
}
context.drawImage(document.getElementById('ff8'), 0, 0, canvasWidth, canvasHeight);
setTimeout(() => {
imageData = context.getImageData(0, 0, canvasWidth, canvasHeight);
width = imageData.width * numberOfIndicesPerPixel;
height = imageData.height;
segmentLength = width / config.horizontalSegments;
sideMultiplier = config.direction === SideEnum.left ? 1 : -1;
initialX = config.direction === SideEnum.left ? 0 : width - 1;
initTransition();
window.requestAnimationFrame(colorSwoosh);
}, 1000);
};
});
</code></pre>
|
[] |
[
{
"body": "<h2>Code and style</h2>\n\n<ul>\n<li>Many variables you have declared can be constants <code>const</code> rather than <code>let</code>.</li>\n<li>Element properties defined in the DOM do not need to be set via <code>setAttribute</code> eg <code>canvas.setAttribute(\"width\", canvasWidth);</code> can be <code>canvas.width = canvasWidth</code></li>\n<li><code>window</code> is the global this. You do not need to specify it. eg <code>window.requestAnimationFrame</code> can be <code>requestAnimationFrame</code>, <code>window.addEventListener(</code> as <code>addEventListener</code> </li>\n<li>Declare functions using statements (a function declaration) rather than expressions. eg <code>var funcName = function() {</code> is better as <code>function funcName() {</code> because function <strike>statements</strike> seclarations are hoisted, while function expressions are not.</li>\n<li>Try to avoid <code>for(let</code> as this pattern has some additional memory and assignment overhead, it also has some very unusual behavior that can catch the unwary. eg in the function <code>initTransition</code> the 3 loop counters <code>x,y,z</code> are better declared as function scoped <code>var</code></li>\n<li>Try to keep variable names short and concise. They only exist within the scope they are declared in and as such gain much of their semantic meaning from that scope. eg <code>numberOfPixelsToInit</code> is a sentence and <code>pixelLen</code>, <code>pixels</code>, or just <code>size</code> would fit the role.</li>\n<li>Don't reassign variables if you don't need to. Eg you declare and define <code>let xProgress = [];</code> and the first time you use it you reassign an array to it in <code>initTransition</code>. In this case rather than create a new array just empty the array with <code>xProgress.length = 0</code> and then you can define it as a <code>const xProgress</code></li>\n<li>There is no need to do the double floor. Eg <code>Math.floor(Math.random() * Math.floor(spread));</code> can be <code>Math.floor(Math.random() * spread);</code> and will produce the same result. You can use the shorter form if the value is positive 32bit signed integer <code>Math.random() * spread | 0</code> bitwise <code>|</code> (OR) 0 to floor. All bitwise operations will convert the Number to a signed 32bit integer. </li>\n<li>Use aliases to reduce overhead of compound property lookups. eg <code>const lineHeight = config.lineHeight;</code> in function <code>initTransition</code> so you need not have the lookup overhead in the loops</li>\n<li>Variables <code>SideEnum</code> and <code>Pass</code> should start with lowercase. PascalCase naming is reserved for functions called with the <code>new</code> token</li>\n<li>Always use <code>addEventListener</code> to add event, adding events via the named event should be avoided. eg <code>startButton.onclick = function() {</code> should be <code>startButton.addEventListener(\"click\", ....</code></li>\n</ul>\n\n<p>There are more issues however your use of <code>getImageData</code> and <code>setImageDate</code> is a major point of concern so I have spent the time creating an example rather than stepping through your code line by line.</p>\n\n<h2>Question</h2>\n\n<blockquote>\n <p><em>\"One thing in particular is I declared the color function inside the colorSwoosh function to make it private to that function as a form of encapsulation, I'm unsure about whether this is a good thing.\"</em></p>\n</blockquote>\n\n<p>Neither good nor bad. </p>\n\n<p>Modern JS has modules that will encapsulate the content to the modules scope so if you used a module <code>color</code> as a function would be fine in modules main scope.</p>\n\n<p>If you don't use modules use IIF pattern and to encapsulate. IIF is an immediately invoked function. The function is created <code>(function(){})()</code> and the brackets at the end call it. The function will close over and encapsulate the content. You can return an interface if needed. </p>\n\n<h3>IIF</h3>\n\n<pre><code>const myFX = (() => {\n\n // all the code vars and functions within the IIF scope\n const myPrivateConst = \"foo\";\n var myPrivateVar;\n function myPrivateFunction() {}\n\n\n\n // Define an interface if you need to access outside this scope\n const API = {\n someStartFunction() { /* do stuff */ }, \n someOtherStuff() { /* do stuff */ }, \n stopStuff() { /* do stuff */ }, \n\n };\n return API\n\n})();\n</code></pre>\n\n<h2>GPUs do pixels, not CPUs</h2>\n\n<p><code>setImageData</code> and <code>getImageData</code> are frame rate killers, if you use them to animate you are doing it wrong.</p>\n\n<h2>Using the GPU via canvas 2D API</h2>\n\n<p>The example below attempts to mimic your wipe animation without using image data and CPU to process pixels. Rather it uses the GPU (via 2D API) to manipulate pixels and lets the CPU handle timing and setting up.</p>\n\n<p>I could not work out (too many options) just what you wanted it to look like so the example is very basic and just wipes right to left.</p>\n\n<p>It uses a mask image (canvas that is not displayed) that on the first swipe reduces pixel alpha to show the canvas background (white) and on the chasing swipe refills the pixels to the final swipe color (black).\nWill resize to fit page once media has loaded. Resize will reset animations. Click to restart wipe FX. If media can not be found animation will not start.</p>\n\n<p>There are comments where I think you need them. I have used your image, I hope that is OK and you have rights to use?</p>\n\n<h3>Example</h3>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>/*\n Notes\n Display canvas alpha setting must be true as the canvas background will be the first wipe colour (white in this example)\n Frame rate is assumed constant at 60 fps\n I am assuming you have usage rights and I am using this image under assumption of fair use in response\n to your question https://codereview.stackexchange.com/questions/226919/screen-transition-effect-like-in-final-fantasy-games\n \n*/\n\nrequestAnimationFrame(mainLoop); // request first frame. This starts the main animation loop. will not reader till ready\nvar update = true; // When true render content \nvar ready = false; // When content loaded and ready to animate\nconst FRAME_RATE = 60; // Per second. This does not set frame rate\n\n// settings for the alpha gradient used in the FX\nconst GRAD_RES = 1 / 40; // resolution of grad curve, no smaller than 1/GRAD_WIDTH\nconst GRAD_POW = 4.2; // Ease power of grad curve\nconst GRAD_WIDTH = 256; // 256 to match max alpha steps\n\nconst config = {\n imgURL: \"https://gilles-leblanc.github.io/ff8-transition/ff8.jpg\",\n image: new Image(),\n width: innerWidth,\n height: innerHeight,\n spread: 0.6, // fraction of display size. Max spread amount\n spreadMin: 0.2, // fraction of display size. Min spread amount\n lineHeight: 4, // in pixels\n wipeBOffset: 0.5, // distance behind first swipe of second swipe in fractions of display width * 2\n // if wipeBOffset > 1 then second swipe will not happen\n // MUST be greater than 0 \n wipeStrength: 0.1,// alpha setting of wipe FX\n wipeTime: 1, // in seconds. MUST!!! be greater than 1/60 second\n wipeEase: 2, // strength of wipe ease. if 1 no ease,0 < val < 1 ease out, 1 < val ease in\n waitTime: 0.5, // in seconds, time to wait after FX before displaying info\n font: \"32px Arial Black\", // font to render info\n infoColor: \"white\", // Color to render info. MUST BE VALID css color\n info: \"Click to repeat!\", // text displayed after wipe complete\n wipeAColor: \"#FFF\", // WipeA colour MUST be valid CSS color\n wipeBColor: \"0,0,0,\", // WipeB colour R,G,B parts of CSS color format rgba(R,G,B,A)\n};\nconfig.image.src = config.imgURL;\nconfig.image.addEventListener(\"load\", setup);\n\nconst animation = {\n wipeA: { posX: 0,},\n wipeB: { posX: 0,},\n waitForInfo: 0,\n active: false,\n speed: 0, \n reset() {\n animation.waitForInfo = config.waitTime * FRAME_RATE | 0;\n animation.active = true;\n animation.wipeA.posX = 1;\n animation.wipeB.posX = 1 + config.wipeBOffset;\n animation.speed = (config.width / (config.wipeTime * FRAME_RATE)) / config.width;\n config.display.ctx.drawImage(config.image, 0, 0, config.width, config.height);\n },\n render() {\n const ctx = config.display.ctx;\n const mask = config.mask;\n animation.wipeA.posX -= animation.speed;\n animation.wipeB.posX -= animation.speed;\n var x = calcEasePos(animation.wipeA.posX);\n animation.active = false;\n ctx.globalAlpha = config.wipeStrength;\n if (x < config.width && x > -config.width) {\n ctx.globalCompositeOperation = \"destination-out\";\n ctx.drawImage(mask, x, 0);\n ctx.globalCompositeOperation = \"source-over\"; \n animation.active = true;\n }\n x = calcEasePos(animation.wipeB.posX);;\n if (x <= config.width && x > -config.width * config.spread) {\n ctx.drawImage(mask,x,0);\n // fill rect that is trailing edge of this swipe\n ctx.fillStyle = `rgba(${config.wipeBColor}1)`;\n ctx.fillRect(x + config.width,0,ctx.canvas.width, ctx.canvas.height); \n animation.active = true;\n }\n ctx.globalAlpha = 1;\n },\n \n}\nfunction calcEasePos(unitPos) {\n return unitPos > 1 ? config.width + 1 :\n unitPos < 0 ? -config.width : unitPos ** config.wipeEase * config.width * 2 - config.width;\n}\n\nfunction createCanvas(width, height) {\n return Object.assign(document.createElement(\"canvas\"), {width, height});\n}\nfunction createGradient(ctx) {\n var i;\n const grad = ctx.createLinearGradient(0, 0, GRAD_WIDTH, 0);\n grad.addColorStop(0, `rgba(${config.wipeBColor}0)`); // from alpha 0 on the left\n for (i = GRAD_RES; i < 1; i += GRAD_RES) { // Create logarithmic curve on gradient \n grad.addColorStop(i, `rgba(${config.wipeBColor}${i ** GRAD_POW})`); \n }\n grad.addColorStop(1, `rgba(${config.wipeBColor}1)`); // to alpha 1 on the right\n return grad;\n}\nfunction drawFinalfade() { // after wipeB complete this ensures that canvas color ends up matching desired color\n const ctx = config.display.ctx;\n ctx.globalAlpha = config.wipeStrength;\n ctx.fillStyle = `rgba(${config.wipeBColor}1)`;\n ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);\n ctx.globalAlpha = 1;\n}\nfunction displayInfo() {\n const ctx = config.display.ctx;\n ctx.font = config.font;\n ctx.textAlign = \"center\";\n ctx.textbaseline = \"middle\";\n ctx.fillStyle = config.infoColor;\n ctx.fillText(config.info , config.width / 2, config.height / 2);\n}\nfunction createMask() { \n var y;\n const can = createCanvas(config.width, config.height), ctx = can.getContext(\"2d\");\n const spread = config.width * (config.spread - config.spreadMin), lineH = config.lineHeight;\n const spreadMin = config.width * config.spreadMin;\n const spreadRange = config.width * config.spread;\n const grad = createGradient(ctx);\n ctx.fillStyle = `rgba(${config.wipeBColor}1)`; // filling right side of mask\n ctx.fillRect(spreadRange, 0, config.width - spreadRange | 0, config.height);\n \n // render each row scaling (via setTransform) the gradient to fit the random spread\n ctx.fillStyle = grad;\n for (y = 0; y < config.height; y += lineH) {\n const size = Math.random() * spread + spreadMin | 0\n const scale = size / GRAD_WIDTH;\n ctx.setTransform(scale, 0, 0, 1, 0, y); // only scale x axis \n ctx.fillRect(0, 0, spreadRange * GRAD_WIDTH / scale, lineH);\n }\n ctx.setTransform(1, 0, 0, 1, 0, 0); // restore default transform\n return can;\n}\nfunction createDisplay() { // Main render canvas added to document.body\n const can = createCanvas(config.width, config.height); \n can.style.backgroundColor = config.wipeAColor;\n const ctx = can.ctx = can.getContext(\"2d\", {alpha : true});\n ctx.drawImage(config.image, 0, 0, can.width, can.height);\n document.body.appendChild(can); // There should be a CSS rule for canvas element\n can.addEventListener(\"click\",() => {\n if (!animation.active) {\n animation.reset();\n update = true;\n }\n });\n return can;\n}\nfunction setup() { // call once only\n config.display = createDisplay();\n config.mask = createMask();\n animation.reset();\n ready = update = true;\n setup = undefined; // This will force an exception if setup is called a second time\n}\n \nfunction mainLoop() {\n if (ready) { // if ready check for resize\n if (innerWidth !== config.width || innerHeight !== config.height) {\n config.display.width = config.width = innerWidth;\n config.display.height = config.height = innerHeight;\n config.mask = createMask();\n animation.reset();\n ready = update = true;\n }\n }\n \n\n if (ready && update) { // Avoid unneeded rendering\n if (animation.active) {\n animation.render();\n update = true; \n } else {\n if (animation.waitForInfo) {\n drawFinalfade();\n animation.waitForInfo --;\n update = true; \n } else {\n update = false; // stops rendering\n displayInfo();\n }\n }\n }\n requestAnimationFrame(mainLoop);\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>canvas {\n position: absolute;\n left: 0px;\n top: 0px;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T01:19:17.620",
"Id": "441679",
"Score": "0",
"body": "I was hoping the use of a single image was considered fair use. Thanks for the thorough answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T03:07:33.723",
"Id": "441682",
"Score": "0",
"body": "About: declare functions using statements rather than expressions [...] because function statements are hoisted, while function expressions are not. Isn't that reversed? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function#Function_expression_hoisting Function declaration are hoisted and not function expressions . https://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T05:34:38.237",
"Id": "441684",
"Score": "0",
"body": "@Gilles ??? As in answer Function expressions are not hoisted. Function statement and function declarations are the same thing. I gave example of each in the answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T18:24:23.920",
"Id": "441807",
"Score": "0",
"body": "@Gilles I just re read my answer and it was full of typos and bad punctuation. I have cleaned it up a little. Sorry about that, I must have been more worn out than I thought."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T19:33:30.947",
"Id": "227037",
"ParentId": "226919",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227037",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T12:20:20.510",
"Id": "226919",
"Score": "4",
"Tags": [
"javascript",
"dom",
"animation"
],
"Title": "Screen transition effect like in Final Fantasy games"
}
|
226919
|
<p>Recently, a company has asked me to make an implementation of a doubly linked list with unity tests to test my skills. In the task description they specified that the solution should be as academic as possible. After seeing the test, they said it was not passed, so, since they have not specified what could be improved or what was directly wrong, I was hoping to find the answer here.</p>
<p>Here is my code</p>
<pre><code>package org.raider.list;
/**
* Lista doblemente enlazada con métodos básicos de inserción, consulta y
* borrado
*
* @author Raider
* @param <E>
*
*/
public class CustomDoubleLinkedList<E> {
transient CustomNode<E> first;
transient CustomNode<E> last;
transient int length;
/**
* Constructor básico
*/
public CustomDoubleLinkedList() {
this.first = null;
this.last = null;
this.length = 0;
}
/**
* Método para comprobar si la lista está vacia
*
* @return
*/
public boolean isEmpty() {
return this.length == 0 && this.first == null && this.last == null;
}
/**
* Devuelve el tamaño de la lista
*
* @return número de elementos de la lista
*/
public int size() {
return this.length;
}
/**
* Agrega un elemento al final de la lista
*
* @param element
*/
public void add(E element) {
final CustomNode<E> lastElm = this.last;
final CustomNode<E> newCustomNode = new CustomNode<>(lastElm, element, null);
this.last = newCustomNode;
if (lastElm == null) {
this.first = newCustomNode;
} else {
lastElm.nextItem = newCustomNode;
}
this.length++;
}
/**
* Agrega un elemento al principio de la lista
*
* @param element
*/
public void addAtBegin(E element) {
final CustomNode<E> firstElm = this.first;
final CustomNode<E> newCustomNode = new CustomNode<>(null, element, firstElm);
this.first = newCustomNode;
if (firstElm == null) {
this.last = newCustomNode;
} else {
firstElm.prevItem = newCustomNode;
}
this.length++;
}
/**
* Agrega un elemento en una determinada índice (comienza en 0)
*
* @param elem elemento a agregar
* @param index índice
*/
public void addAt(E elem, int index) {
if (index == 0) {
addAtBegin(elem);
return;
} else {
CustomNode<E> existingNode = searchNode(index);
CustomNode<E> newElem = new CustomNode<>(null, elem, null);
CustomNode<E> tmp = existingNode.prevItem;
newElem.nextItem = existingNode;
tmp.nextItem = newElem;
newElem.prevItem = tmp;
existingNode.prevItem = newElem;
}
this.length++;
}
/**
* Agregamos todos los elementos de una lista en una determinada posición de
* otra
*
* @param index lugar a partir del que añadiremos la otra lista
* @param list lista a añadir
*/
public void addAll(int index, CustomDoubleLinkedList list) {
int originalSize = list.size();
if (originalSize > 0) {
CustomNode<E> prev;
CustomNode<E> next;
if (index == originalSize) {
next = null;
prev = this.last;
} else {
next = searchNode(index);
prev = next.prevItem;
}
for (int i = 0; i < originalSize; i++) {
E e = (E) list.get(i);
CustomNode<E> newNode = new CustomNode<>(prev, e, null);
if (prev == null) {
this.first = newNode;
} else {
prev.nextItem = newNode;
}
prev = newNode;
}
if (next == null) {
this.last = prev;
} else {
prev.nextItem = next;
next.prevItem = prev;
}
this.length += originalSize;
}
}
/**
* Elimina todos los elementos de la lista
*/
public void clear() {
/*
* Realmente podríamos eliminar el primero, el último y poner el tamaño a 0,
* pero de esta forma nos aseguramos liberar memoria
*/
CustomNode<E> cn = this.first;
for (int i = 0; i < this.length; i++) {
CustomNode<E> next = cn.nextItem;
cn.item = null;
cn.nextItem = null;
cn.prevItem = null;
cn = next;
}
this.first = null;
this.last = null;
this.length = 0;
}
/**
* Elimina todos los elementos que coincidan
*
* @param element
*/
public void remove(Object element) {
for (int i = 0; i < this.length; i++) {
CustomNode<E> node = searchNode(i);
if (element == null) {
if (node.item == null) {
deleteNode(node);
}
} else {
if (element.equals(node.item)) {
deleteNode(node);
}
}
}
}
/**
* Elimina un elemento en determinado índice
*
* @param index
*/
public void removeIndex(int index) {
CustomNode<E> node = searchNode(index);
deleteNode(node);
}
/**
* Obtiene un elemento por su índice
*
* @param index índice
* @return elemento
* @throws NullPointerException si el objeto es null
*/
public E get(int index) {
CustomNode<E> node = searchNode(index);
return node.item;
}
/**
* Devuelve el primer elemento
*
* @return elemento
*/
public E getFirst() {
return this.first.item;
}
/**
* Devuelve el ultimo elemento
*
* @return elemento
*/
public E getLast() {
return this.last.item;
}
/**
* Devuelve el índice de un objeto, si no existe, devuelve -1
*
* @param element elemento a buscar
* @return índice del objeto o -1
*/
public int indexOf(E element) {
int index = -1;
for (int i = 0; i < this.length; i++) {
// for (CustomNode<E> node = first; node != null; node = node.nextItem) {
CustomNode<E> node = searchNode(i);
if (element == null) {
if (node.item == null) {
index = i;
break;
}
} else {
if (element.equals(node.item)) {
index = i;
break;
}
}
}
return index;
}
/**
* Elimina un nodo
*
* @param node
*/
private void deleteNode(CustomNode<E> node) {
final E element = node.item;
final CustomNode<E> next = node.nextItem;
final CustomNode<E> prev = node.prevItem;
if (prev == null) {
this.first = next;
} else {
prev.nextItem = next;
node.prevItem = null;
}
if (next == null) {
this.last = prev;
} else {
next.prevItem = prev;
node.nextItem = null;
}
node.item = null;
this.length--;
}
/**
* Devuelve un nodo de una determinada posición
*
* @param index indice
* @return nodo
*/
private CustomNode<E> searchNode(int index) {
/*
* Si index < 0 cogeremos el primer elemento y si es mayor que la longitud
* cogeremos el último
*/
if (index < 0) {
index = 0;
}
if (index < this.length) {
CustomNode<E> aux = this.first;
for (int i = 0; i < index; i++) {
aux = aux.nextItem;
}
return aux;
} else {
CustomNode<E> aux = last;
return aux;
}
}
/**
* Clase CustomNode (nombrada así debido a que ya existe una similar en java)
* que usaremos para obtener los valores anterior y posterior de un determinado
* elemento de la lista
*
* @author Raider
*
* @param <E> Parámetro genéico para que nuestra lista pueda aceptar todos los
* tipos de parámetros
*/
private static class CustomNode<E> {
E item;
CustomNode<E> nextItem;
CustomNode<E> prevItem;
/**
* Constructor de CustomNode
*
* @param prev elemento anterior
* @param element elemento referenciado
* @param next elemento siguiente
*/
CustomNode(CustomNode<E> prev, E element, CustomNode<E> next) {
this.item = element;
this.nextItem = next;
this.prevItem = prev;
}
}
}
</code></pre>
<p>And here JUnit tests (surely the worst part)</p>
<pre><code>package org.raider.junit.tests;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.aam.list.CustomDoubleLinkedList;
import org.junit.jupiter.api.Test;
class CustomDoubleLinkedListTest {
CustomDoubleLinkedList<String> strList;
@Test
public void addAndGetTest() {
strList = new CustomDoubleLinkedList();
strList.add("pos 0");
strList.add("pos 1");
strList.add("pos 2");
strList.add("pos 3");
assertEquals("pos 0", strList.get(0));
assertEquals("pos 1", strList.get(1));
assertEquals("pos 2", strList.get(2));
assertEquals("pos 3", strList.get(3));
}
@Test
public void outOfBounds() {
strList = new CustomDoubleLinkedList();
strList.add("pos 0");
strList.add("pos 1");
strList.add("pos 2");
strList.add("pos 3");
assertEquals("pos 3", strList.get(288));
assertEquals("pos 0", strList.get(-100));
}
@Test
public void isEmpty() {
strList = new CustomDoubleLinkedList();
assertEquals(true, strList.isEmpty());
strList.add("pos 0");
assertEquals(false, strList.isEmpty());
}
@Test
public void size() {
strList = new CustomDoubleLinkedList();
assertEquals(0, strList.size());
strList.add("pos 0");
strList.add("pos 1");
strList.add("pos 2");
strList.add("pos 3");
assertEquals(4, strList.size());
}
@Test
public void addAtBegin() {
strList = new CustomDoubleLinkedList();
strList.add("pos 0");
strList.add("pos 1");
strList.add("pos 2");
strList.add("pos 3");
assertEquals("pos 0", strList.get(0));
strList.addAtBegin("pos -1");
assertEquals("pos -1", strList.get(0));
assertEquals("pos 0", strList.get(1));
}
@Test
public void addAt() {
strList = new CustomDoubleLinkedList();
strList.add("pos 0");
strList.add("pos 1");
strList.add("pos 2");
strList.add("pos 3");
assertEquals("pos 0", strList.get(0));
assertEquals("pos 1", strList.get(1));
assertEquals("pos 2", strList.get(2));
assertEquals("pos 3", strList.get(3));
strList.addAt("pos x", 2);
assertEquals("pos 0", strList.get(0));
assertEquals("pos 1", strList.get(1));
assertEquals("pos x", strList.get(2));
assertEquals("pos 2", strList.get(3));
assertEquals("pos 3", strList.get(4));
assertEquals(5, strList.size());
strList.addAt("pos y", 0);
assertEquals("pos y", strList.get(0));
}
@Test
public void addAll() {
strList = new CustomDoubleLinkedList();
CustomDoubleLinkedList<String> listToAdd = new CustomDoubleLinkedList();
strList.add("pos 0");
strList.add("pos 1");
strList.add("pos 2");
strList.add("pos 3");
assertEquals("pos 0", strList.get(0));
assertEquals("pos 1", strList.get(1));
assertEquals("pos 2", strList.get(2));
assertEquals("pos 3", strList.get(3));
listToAdd.add("pos x");
listToAdd.add("pos y");
listToAdd.add("pos z");
assertEquals("pos x", listToAdd.get(0));
assertEquals("pos y", listToAdd.get(1));
assertEquals("pos z", listToAdd.get(2));
strList.addAll(2, listToAdd);
assertEquals("pos 0", strList.get(0));
assertEquals("pos 1", strList.get(1));
assertEquals("pos x", strList.get(2));
assertEquals("pos y", strList.get(3));
assertEquals("pos z", strList.get(4));
assertEquals("pos 2", strList.get(5));
assertEquals("pos 3", strList.get(6));
}
@Test
public void clear() {
strList = new CustomDoubleLinkedList();
strList.add("pos 0");
strList.add("pos 1");
strList.add("pos 2");
strList.add("pos 3");
assertEquals("pos 0", strList.get(0));
assertEquals("pos 1", strList.get(1));
assertEquals("pos 2", strList.get(2));
assertEquals("pos 3", strList.get(3));
assertEquals(4, strList.size());
strList.clear();
assertThrows(NullPointerException.class, () -> strList.get(0));
assertThrows(NullPointerException.class, () -> strList.get(1));
assertThrows(NullPointerException.class, () -> strList.get(2));
assertThrows(NullPointerException.class, () -> strList.get(3));
assertEquals(0, strList.size());
}
@Test
public void remove() {
strList = new CustomDoubleLinkedList();
strList.add("pos 0");
strList.add("pos 1");
strList.add("pos 2");
strList.add("pos 3");
assertEquals("pos 0", strList.get(0));
assertEquals("pos 1", strList.get(1));
assertEquals("pos 2", strList.get(2));
assertEquals("pos 3", strList.get(3));
assertEquals(4, strList.size());
strList.remove("pos 2");
assertEquals("pos 0", strList.get(0));
assertEquals("pos 1", strList.get(1));
assertEquals("pos 3", strList.get(2));
assertEquals(3, strList.size());
strList.add("pos 1");
strList.add("pos 4");
assertEquals("pos 0", strList.get(0));
assertEquals("pos 1", strList.get(1));
assertEquals("pos 3", strList.get(2));
assertEquals("pos 1", strList.get(3));
assertEquals("pos 4", strList.get(4));
assertEquals(5, strList.size());
strList.remove("pos 1");
assertEquals("pos 0", strList.get(0));
assertEquals("pos 3", strList.get(1));
assertEquals("pos 4", strList.get(2));
assertEquals(3, strList.size());
}
@Test
public void removeIndex() {
strList = new CustomDoubleLinkedList();
strList.add("pos 0");
strList.add("pos 1");
strList.add("pos 2");
strList.add("pos 3");
assertEquals("pos 0", strList.get(0));
assertEquals("pos 1", strList.get(1));
assertEquals("pos 2", strList.get(2));
assertEquals("pos 3", strList.get(3));
assertEquals(4, strList.size());
strList.removeIndex(2);
assertEquals("pos 0", strList.get(0));
assertEquals("pos 1", strList.get(1));
assertEquals("pos 3", strList.get(2));
assertEquals(3, strList.size());
}
@Test
public void getFirstAndLast() {
strList = new CustomDoubleLinkedList();
strList.add("pos 0");
strList.add("pos 1");
strList.add("pos 2");
strList.add("pos 3");
assertEquals("pos 0", strList.getFirst());
assertEquals("pos 3", strList.getLast());
}
@Test
public void indexOf() {
strList = new CustomDoubleLinkedList();
strList.add("pos 0");
strList.add("pos 1");
strList.add("pos 2");
strList.add("pos 3");
assertEquals(2, strList.indexOf("pos 2"));
}
}
</code></pre>
<p>Could someone try to explain me where I can improve this code, what I forgot or what is the most academic way to do this?</p>
<p><strong>EDIT</strong>: I didn't implement or extend from <code>Collection</code> or another interfaces/clasess because in the test it was specified that it would not be used</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:08:50.090",
"Id": "441330",
"Score": "6",
"body": "what is academic solution?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:11:36.180",
"Id": "441331",
"Score": "0",
"body": "I don't know, I expect someone can tell me..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:25:26.053",
"Id": "441336",
"Score": "6",
"body": "maybe you should have asked for clarification on the academic requirement"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T00:54:27.053",
"Id": "441471",
"Score": "7",
"body": "@SharonBenAsher Usually, one that is needlessly complicated and has no practical use except to impress other academics."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:18:15.280",
"Id": "441566",
"Score": "0",
"body": "Could it be possible that they also expected information about the complexity of the implementation?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T15:05:57.830",
"Id": "441587",
"Score": "0",
"body": "I think addressing some outstanding oddities in the code, all pointed out in answers, will go much further than trying to suss out whether academic ness played any role."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T01:56:10.567",
"Id": "441680",
"Score": "1",
"body": "An academic solution would be one that closely syncs up to the concept of a linked-list, without regard for implementation concerns. By contrast, normally when you program up stuff, you'd be interested in making your code as useful as possible -- you might put in optimizations, omit features no one'd ever use, add in features that're very helpful even if they're not necessary for a \"_linked list_\", etc.. I mean, yeah, you should probably ask for clarification, but it sounds like they're asking you for a concept-first implementation rather than something someone'd actually want to use."
}
] |
[
{
"body": "<p>Your class does not implement any of Java collection interfaces. the solution is meant to be an implementation of a linked list that can be used as drop-in replacement for any java list/collection (and also queue). if you look at the <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html\" rel=\"nofollow noreferrer\"><code>LinkedList</code></a> from the jdk, you will see just what functionality you are missing. (for example, iterator, subList)</p>\n\n<p>now I see that the class does not even implement the most basic contract from <code>Object</code> (namely, <code>equals()</code> and <code>hashCode()</code>) so you cannot safely compare two lists or put one in hash map....</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:18:57.507",
"Id": "441332",
"Score": "1",
"body": "As I said in edit *I didn't implement or extend from Collection or another interfaces/clasess because in the test it was specified that it would not be used*. But not implement ``equals()`` and ``hashCode()`` it's a really big mistake, thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:21:25.070",
"Id": "441334",
"Score": "0",
"body": "what does it mean \"it would not be used\"? anyway, you can look for missing functionality in those interfaces. and implementing methods of `Object` is a basic requirement. like I said, the class does not support comparing two lists at all"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:23:38.947",
"Id": "441335",
"Score": "0",
"body": "They said I mustn't implement collection"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:47:50.323",
"Id": "441341",
"Score": "0",
"body": "The OP's last edit of the question invalidates this answer. I suggest we roll back the question, what do you think?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:58:19.017",
"Id": "441349",
"Score": "0",
"body": "1) in my comment I explained that collection interfaces can be used as source to show missing functionality 2) I further explained about the critical importance of the contract specified in `Object`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T14:03:25.077",
"Id": "441580",
"Score": "0",
"body": "Unless you were the interviewer, everything in this answer is either speculation or wrong. You don't know whether the code was supposed to implement `java.util.List`; and calling the default implementation of `equals` or `hashCode()` is not *unsafe*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T17:17:11.380",
"Id": "441618",
"Score": "0",
"body": "@PeterTaylor, the answer is no more speculative than all the others simply because the requirements are unclear to everyone, including OP. and the answer is very much correct in terms of software engineering principles and best practices. I have already stated and will do again: even if the class was *not* supposed to implement Java collection interfaces, they can be used to understand what features are missing from the solution. a glaring example is that b/c there is no `iterator()` (or similar, like `getNext()`), there is no way to iterate over this linked list in o(n) fashion"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T17:17:43.707",
"Id": "441619",
"Score": "0",
"body": "@PeterTaylor, regarding `equals()` and `hashCode()`, perhaps \"safely\" is the wrong word here, however, I meant that the default implementations return results that are unreliable."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:15:17.903",
"Id": "226924",
"ParentId": "226921",
"Score": "3"
}
},
{
"body": "<p>With regard to the academic solution, perhaps they were referring to things like you would see in an assignment such as line lengths, appropriate naming and use of visibility modifiers, no compilation errors, etc.</p>\n\n<ul>\n<li>I feel your javadocs could have been better, equally there are <code>@params</code> that have no detail about the expected parameter such as in the <code>add(E element)</code> and <code>addAtBegin(E element)</code> methods.</li>\n<li>There were a few places where you should have used generics such as the <code>addAll(int index, CustomDoubleLinkedList list)</code> method should have been <code>public void addAll(int index, CustomDoubleLinkedList<? extends E> list)</code></li>\n</ul>\n\n<p>There were a few improvements you could make to the unit tests as well. While it looks like the code coverage is 90%, there are lots of edge cases and subtleties that aren't clear and the unit tests tell as much about what you can do with a class as what you can't do with it.</p>\n\n<ul>\n<li>You are mixing jUnit 4 and 5\n\n<ul>\n<li><code>org.junit.Assert.assertEquals</code> is jUnit 4, while</li>\n<li><code>org.junit.jupiter.api.Assertions.assertThrows</code> is jUnit 5.</li>\n</ul></li>\n<li>If you are using jUnit 5 the <code>public</code> is not required for each method. It was excluded for the class but not the tests.</li>\n<li>You didn't use the <code><></code> operator on any of the instantiations of the <code>CustomDoubleLinkedList</code>.</li>\n<li>Ideally you should have one assert per method.\n\n<ul>\n<li>This isn't a hard and fast rule but for testing a method like <code>isEmpty()</code> it may be preferable. </li>\n<li>If the list should return true to <code>isEmpty()</code> once everything has been removed, a test should assert that.</li>\n</ul></li>\n</ul>\n\n<pre class=\"lang-java prettyprint-override\"><code>@Test\npublic void isEmpty() {\n strList = new CustomDoubleLinkedList();\n\n assertEquals(true, strList.isEmpty());\n strList.add(\"pos 0\");\n assertEquals(false, strList.isEmpty());\n\n}\n</code></pre>\n\n<p>could become something more like the below</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>@Test\npublic void emptyListReturnsTrueOnIsEmpty() {\n strList = new CustomDoubleLinkedList();\n assertTrue(strList.isEmpty());\n}\n\n@Test\npublic void nonEmptyListReturnsFalseOnIsEmpty() {\n strList = new CustomDoubleLinkedList();\n strList.add(\"pos 0\");\n assertFalse(strList.isEmpty());\n}\n\n@Test\npublic void addedToAndRemovedFromListReturnsTrueOnIsEmpty() {\n strList = new CustomDoubleLinkedList();\n strList.add(\"pos 0\");\n strList.remove(\"pos 0\");\n assertTrue(strList.isEmpty());\n}\n</code></pre>\n\n<p>While you have said you were asked not to implement Java Collections, the Deque interface <code>getFirst()</code> method says you should throw a no such element exception if the deque is empty. This test throws a null pointer instead</p>\n\n<pre><code>@Test\npublic void test() {\n strList = new CustomDoubleLinkedList<>();\n strList.getFirst();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T17:51:26.997",
"Id": "226939",
"ParentId": "226921",
"Score": "7"
}
},
{
"body": "<ul>\n<li><p><code>searchNode(int i)</code> performs a loop. Wrapping it inside yet another loop makes <code>indexOf</code> and <code>remove(Object element)</code> quadratic in the length of the list, instead of linear which they supposed to be.</p></li>\n<li><p>Testing for emptiness via <code>this.length == 0 && this.first == null && this.last == null;</code> feels strange. It is enough to test just for length. If first and/or last happen to be non-null in this situation means that integrity of the list is broken, and probably should cause an exception.</p></li>\n<li><p><code>add</code> and <code>addAtBegin</code> are bit more wordy than necessary. You don't really need <code>lastElm/firstElm</code>.</p>\n\n<p>While we are here, their names should be more symmetric. Traditionally they are <code>append</code> and <code>prepend</code>, or <code>addFirst/addLast</code> (or even <code>push_front/push_back</code> in C++ parlance).</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T21:12:32.573",
"Id": "441443",
"Score": "1",
"body": "one solution for that tripple bool check is to only check one of them, and add asserts for the other 2 (https://en.wikibooks.org/wiki/Java_Programming/Keywords/assert) in production code, the asserts should be disabled, since the class 'should' be written in a way these asserts never trigger."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T21:08:48.720",
"Id": "226952",
"ParentId": "226921",
"Score": "5"
}
},
{
"body": "<p>Next time you're in such a scenario, ask them to clarify what \"academic\" means. For me it means a solution that concentrates on the essence of data structure, not an implementation of a specific API. But we probably never know so let's not concentrate on that. Instead, let's look at the red flags...</p>\n\n<p>(I have ignored the comments as I do not understand the language.)</p>\n\n<p><strong>Transient</strong></p>\n\n<p>The first red flag that jumps at me is the transient keywords. Your collection does not implement Serializable so the keyword does not mean anything. It's a sign to thereader that you don't understand what transient means.</p>\n\n<p><strong>Non-private fields</strong></p>\n\n<p>The fields in CustomeDoubleLinkedList are not private so they are visible to all classes defined in the same package, allowing for other parties to break the internal state of the collection.</p>\n\n<p><strong>Redundant code</strong></p>\n\n<p>The isEmpty() method relies on three different fields to figure out if it is empty. You should be confident enough in your code and tests to rely on just the length counter. If you use a static code analyzer it rises a flag every time you use \"collection.size() == 0\" and recommends to use \"isEmpty()\". Your isEmpty should work likewise.</p>\n\n<p><strong>Inconsistent naming</strong></p>\n\n<p>The add() and addAtBeginning() are a bit inconsistent. The latter explicitly states it adds to the beginning while the former has to rely on documentation. I would have been looking for addLast() and addFirst() or add() and addAt(0).</p>\n\n<p>The addAll() doesn't convey in it's name that it requires an index parameter like addAt() does.</p>\n\n<p>The removeIndex() is inconsitent with addAt(). Should be removeAt().</p>\n\n<p><strong>Range checking</strong></p>\n\n<p>The addAt method does not check if index is beyond the size of the collection. A method that returns a valid value with invalid input is surprising behaviour which welcomes programming errors from the caller. An IllegalArgumentException should be thrown here.</p>\n\n<p><strong>Inconsistent parameters</strong></p>\n\n<p>The addAt and addAll have the index parameter at different part of the method signature. It should be first or last in both.</p>\n\n<p><strong>Generics or not?</strong></p>\n\n<p>The addAll does not use the generic type declared in the class signature.</p>\n\n<p><strong>Unnecessary code</strong></p>\n\n<p>The clear-method should just set the first and last to null and size to zero and let the garbage collector deal with the rest.</p>\n\n<p><strong>No null checking</strong></p>\n\n<p>The getFirst and getLast throw NullPointerExceptions if the list is empty.</p>\n\n<p><strong>Code duplication</strong></p>\n\n<p>You have copy-pasted the linking of nodes to their successors and predecessors to several places. Those should have been refactored to private methods like \"insertAfter(existingNode, newNode)\" and \"insertBefore(existingNode, newNode)\" or made that operation a function of the Node.</p>\n\n<p>There may be more, but I have to go now.</p>\n\n<p>Edit:</p>\n\n<p><strong>Academic shmacademic</strong></p>\n\n<p>I want to contemplate this a bit. A linked list is a recursive data structure consisting of a head node and a tail (which is a linked list). Prolog programmers know this by heart. Your solution is pragmatic and concentrates on the collection API.</p>\n\n<p>It may have been that they wanted you to concentrate more on the recursive nature of the Node-class. Something like this (you need to imagine the double linking :) ):</p>\n\n<pre><code>public class LinkedList<T> {\n private T head = null;\n private LinkedList<T> tail = null;\n\n public void add(T element) {\n if (head == null) {\n head = element;\n tail = new LinkedList<>();\n } else {\n tail.add(element);\n }\n }\n\n public boolean contains(T element) {\n if (head == null) {\n return false;\n } else if (head.equals(element)) {\n return true;\n } else {\n return tail.contains(element);\n }\n }\n\n ...\n}\n</code></pre>\n\n<p>Anyway... What you can get out of this is knowing that asking clarifying questions in a job interview is a good thing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T20:31:25.897",
"Id": "441655",
"Score": "1",
"body": "When *I* hear about \"academic-style double-linked list\", the first thing that comes to *my* mind is \"persistent data structures\". So, the `add()` method would return a new linked list, etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T18:14:24.887",
"Id": "445979",
"Score": "0",
"body": "@Joker_vD A persistent doubly-linked list is not a trivial thing"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T05:23:06.490",
"Id": "226977",
"ParentId": "226921",
"Score": "17"
}
},
{
"body": "<p>Since this is the fifth answer I shall try not to repeat many things that have already been said.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public void addAll(int index, CustomDoubleLinkedList list) {\n int originalSize = list.size();\n if (originalSize > 0) {\n</code></pre>\n</blockquote>\n\n<p>If this were instead <code>if (originalSize == 0) return;</code> then the rest of the method could save one level of indentation.</p>\n\n<blockquote>\n<pre><code> if (index == originalSize) {\n</code></pre>\n</blockquote>\n\n<p>I don't understand this line at all, and I think it might be buggy. Why compare an index into this list with the length of the other one?</p>\n\n<blockquote>\n<pre><code> for (int i = 0; i < originalSize; i++) {\n E e = (E) list.get(i);\n</code></pre>\n</blockquote>\n\n<p>There are two big problems with that line. Firstly, <code>list.get(i)</code> on a linked list inside a loop. This turns a method which should take linear time into a method which takes quadratic time. Secondly, the cast: this would be unnecessary if the argument were properly typed (as <code>CustomDoubleLinkedList<? extends E></code>).</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public void clear() {\n /*\n * Realmente podríamos eliminar el primero, el último y poner el tamaño a 0,\n * pero de esta forma nos aseguramos liberar memoria\n */\n CustomNode<E> cn = this.first;\n for (int i = 0; i < this.length; i++) {\n CustomNode<E> next = cn.nextItem;\n cn.item = null;\n cn.nextItem = null;\n cn.prevItem = null;\n cn = next;\n }\n this.first = null;\n this.last = null;\n this.length = 0;\n }\n</code></pre>\n</blockquote>\n\n<p>The reasoning in the comment assumes either that the class is somehow leaking its nodes (in which case you should fix that problem instead) or that the garbage collector is broken (which is highly unlikely). So this turns a method which should take constant time into a method which takes linear time for no good reason.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> /**\n * Elimina todos los elementos que coincidan\n *\n * @param element\n */\n public void remove(Object element) {\n for (int i = 0; i < this.length; i++) {\n CustomNode<E> node = searchNode(i);\n</code></pre>\n</blockquote>\n\n<p>Was this really what the spec asked for? <code>java.util.Collection.remove</code> removes one instance (and returns a <code>bool</code> indicating whether it found one to remove or not).</p>\n\n<p>Also, this has the same problem of turning a linear method into a quadratic one by using <code>searchNode</code> inside a loop.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public int indexOf(E element) {\n int index = -1;\n for (int i = 0; i < this.length; i++) {\n // for (CustomNode<E> node = first; node != null; node = node.nextItem) {\n CustomNode<E> node = searchNode(i);\n</code></pre>\n</blockquote>\n\n<p>Same problem. In fact, worse: it seems that you commented out the correct solution, which might make the interviewer think that you couldn't get it to work.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> CustomNode<E> aux = last;\n return aux;\n</code></pre>\n</blockquote>\n\n<p>Why not just <code>return last;</code>?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private void deleteNode(CustomNode<E> node) {\n final E element = node.item;\n</code></pre>\n</blockquote>\n\n<p>What's <code>element</code> for?</p>\n\n<hr>\n\n<p>While I can't be sure what the interviewer meant by \"academic\", I think it's very probable that they expected to see every method implemented with the best possible asymptotic complexity.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:58:58.377",
"Id": "227012",
"ParentId": "226921",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "226977",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:07:43.753",
"Id": "226921",
"Score": "12",
"Tags": [
"java",
"linked-list",
"junit"
],
"Title": "Find most \"academic\" implementation of doubly linked list"
}
|
226921
|
<p>I wrote this console rock-paper-scissors game. I'm new to C++. I'd appreciate any suggestions to improve the code below. Thanks.</p>
<p><strong>RPSCore.h</strong></p>
<pre><code>#ifndef RPS_CORE_H
#define RPS_CORE_H
class RPSCore
{
public:
static int rpsWinner(char& playerChoice, char& computerChoice);
static char getComputerChoice();
};
#endif // !RPS_CORE_H
</code></pre>
<p><strong>RPSCore.cc</strong></p>
<pre><code>#include <random>
#include <chrono>
#include <cstdint>
#include <map>
#include <sstream>
#include <string>
#include <algorithm>
#include "RPSCore.h"
// private helper function
char getValueIfKeyExists(std::map<std::string, char>& dict, std::string& key)
{
char ret = '\0';
for (std::map<std::string, char>::iterator it = dict.begin(); it != dict.end(); it++)
{
if (it->first.compare(key) == 0)
{
ret = it->second;
break;
}
}
return ret;
}
int RPSCore::rpsWinner(char& playerChoice, char& computerChoice)
{
std::map<std::string, char> rules = { {"rs", 'r'}, {"rp", 'p'}, {"sp", 's'} };
std::stringstream ss;
ss << playerChoice << computerChoice;
std::string combination = ss.str();
std::string combinationCopy{ combination };
std::reverse(combinationCopy.begin(), combinationCopy.end());
char p = getValueIfKeyExists(rules, combination) == '\0' ? getValueIfKeyExists(rules, combinationCopy) : getValueIfKeyExists(rules, combination);
return p == playerChoice && p != computerChoice ? 1 : p == computerChoice && p != playerChoice ? 2 : -1; // 1-> player wins, 2-> computer wins, -1-> draw
}
char RPSCore::getComputerChoice()
{
std::string options = "rps";
uint32_t seed = static_cast<uint32_t>(std::chrono::system_clock::now().time_since_epoch().count());
std::minstd_rand0 range(seed);
std::uniform_int_distribution<std::minstd_rand0::result_type> dist(0, 2);
return options[dist(range)];
}
</code></pre>
<p><strong>main.cc</strong></p>
<pre><code>#include <iostream>
#include <string>
#include <cctype>
#include "RPSCore.h"
std::string input(std::string prompt="")
{
std::string temp;
std::cout << prompt;
std::getline(std::cin, temp);
return temp;
}
int main(int argc, char* argv[])
{
char playerChoice = []() {
std::string ret = "";
do
{
ret = input("Your weapon >>> ");
if (std::tolower(ret[0]) == 'r' || std::tolower(ret[0]) == 'p' || std::tolower(ret[0]) == 's') break;
} while (1);
return ret[0];
}();
char computerChoice = RPSCore::getComputerChoice();
int winner = RPSCore::rpsWinner(playerChoice, computerChoice);
std::cout << "Your choice: " << (playerChoice == 'r' ? "Rock" : playerChoice == 'p' ? "Paper" : "Scissors") << " Computer's choice: " << (computerChoice == 'r' ? "Rock" : computerChoice == 'p' ? "Paper" : "Scissors") << " And " << (winner == 1 ? "You WIN!!!" : winner == 2 ? "Computer Wins :(" : "It's a draw :)");
std::cin.get();
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T22:10:39.423",
"Id": "441460",
"Score": "0",
"body": "Where is my Lizard/Spock? https://iwastesomuchtime.com/21448"
}
] |
[
{
"body": "<p>I'm thinking you named <code>ret</code> as in short for <code>return</code>.\nDon't shorten variable names. Also try to give varaible names that are meaningful. Naming it return because you return it is silly.</p>\n\n<pre><code>char ret = '\\0';\n</code></pre>\n\n<p>Same here:</p>\n\n<pre><code>std::string temp;\n</code></pre>\n\n<p>This line looks very odd and is a sign of poorly named variables:</p>\n\n<pre><code>ret = it->second;\n</code></pre>\n\n<p><code>r</code>, <code>p</code> <code>s</code> these are a good example of when you should be using an ENUM.</p>\n\n<p>Try to avoid 1 letter variable names.</p>\n\n<p>You can use <code>const</code> when variables should never change. For example: <code>rules</code>.</p>\n\n<p>I suggest putting the condition inside the while instead.\nFor example:</p>\n\n<pre><code>} while (std::tolower(ret[0]) != 'r' || std::tolower(ret[0]) != 'p' || std::tolower(ret[0]) != 's');\n</code></pre>\n\n<p>If you had an ENUM, you could check the entered value against all the values in the ENUM. This would look much better, and be easier to maintain. (E.g adding <code>Lizard</code> <code>Spock</code>)</p>\n\n<p>The ENUM would also help for printing the values. (No more if <code>r</code> print <code>rock</code> etc)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T23:20:06.240",
"Id": "226961",
"ParentId": "226922",
"Score": "1"
}
},
{
"body": "<p>I don't understand why you would do this:</p>\n\n<pre><code>char playerChoice = []() {\n std::string ret = \"\";\n do\n {\n ret = input(\"Your weapon >>> \");\n if (std::tolower(ret[0]) == 'r' || std::tolower(ret[0]) == 'p' || std::tolower(ret[0]) == 's') break;\n } while (1);\n return ret[0];\n}();\n</code></pre>\n\n<p>Creating an inline function and calling it!</p>\n\n<p>That could should be in its own named function.</p>\n\n<pre><code>char getPlayerChoice()\n{\n std::string ret = \"\";\n do\n {\n ret = input(\"Your weapon >>> \");\n if (std::tolower(ret[0]) == 'r' || std::tolower(ret[0]) == 'p' || std::tolower(ret[0]) == 's') break;\n } while (1);\n return ret[0];\n}\n</code></pre>\n\n<p>Then simply call it like normal.</p>\n\n<pre><code>char playerChoice = getPlayerChoice();\n</code></pre>\n\n<hr>\n\n<p>This line is excessively long:</p>\n\n<pre><code>std::cout << \"Your choice: \" << (playerChoice == 'r' ? \"Rock\" : playerChoice == 'p' ? \"Paper\" : \"Scissors\") << \" Computer's choice: \" << (computerChoice == 'r' ? \"Rock\" : computerChoice == 'p' ? \"Paper\" : \"Scissors\") << \" And \" << (winner == 1 ? \"You WIN!!!\" : winner == 2 ? \"Computer Wins :(\" : \"It's a draw :)\");\n</code></pre>\n\n<p>Make it readable:</p>\n\n<pre><code>std::cout << \"Your choice: \"\n << (playerChoice == 'r' ? \"Rock\" : playerChoice == 'p' ? \"Paper\" : \"Scissors\")\n << \" Computer's choice: \"\n << (computerChoice == 'r' ? \"Rock\" : computerChoice == 'p' ? \"Paper\" : \"Scissors\")\n << \" And \"\n << (winner == 1\n ? \"You WIN!!!\" \n : winner == 2 \n ? \"Computer Wins \n :(\" : \"It's a draw :)\");\n</code></pre>\n\n<p>Would be even better if you used some named functions:</p>\n\n<pre><code>std::cout << \"Your choice: \" << choiceToOutput(playerChoice)\n << \" Computer's choice: \" << choiceToOutput(computerChoice)\n << \" And \" << winnerToOutput(winner)\n << \"\\n\";\n</code></pre>\n\n<hr>\n\n<p>Are you trying to draw smiley faces in the code:</p>\n\n<pre><code> :(\" : \"It's a draw :)\");\n</code></pre>\n\n<p>Fun. But stop it.</p>\n\n<pre><code> : \" : \"It's a draw :)\";\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T00:36:05.680",
"Id": "441470",
"Score": "0",
"body": "Practicing Immediately Invoked Initializing Lambda, perhaps?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T00:29:35.277",
"Id": "226967",
"ParentId": "226922",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:12:36.010",
"Id": "226922",
"Score": "1",
"Tags": [
"c++",
"beginner",
"game",
"rock-paper-scissors"
],
"Title": "Rock–paper–scissors console game"
}
|
226922
|
<p>I have a single table inheritance type on a class (Resource) that can be one of 3 classes:</p>
<p>SingleDay<br>
MultiDay<br>
Accommodation</p>
<p>SingleDay has properties:</p>
<p>QTY<br>
<code>hours_offset</code><br>
<code>minutes_offset</code><br>
<strong>hours_duration</strong><br>
<strong>minutes_duration</strong></p>
<p>MultiDay has properties:</p>
<p>QTY<br>
<em>start_day</em><br>
<em>start_time</em><br>
<strong>hours_duration</strong><br>
<strong>minutes_duration</strong></p>
<p>Accommodation has properties:</p>
<p>QTY<br>
<em>start_day</em><br>
<code>end_day</code><br>
<em>start_time</em><br>
<code>end_time</code></p>
<p>As I've highlighted above, some properties are shared between ALL classes, some properties are shared between <strong>SingleDay and MultiDay</strong>, some properties are shared between <em>MultiDay and Accommodation</em> and some properties are <code>not shared</code></p>
<p>I wondered how best to deal with this?</p>
<p>I was thinking on the top class (Resource) to have the shared properties as protected, and then on <strong>each</strong> of the classes that use the property to have the same getter and setter?</p>
<pre class="lang-php prettyprint-override"><code>/*
* @InheritanceType("SINGLE_TABLE")
* @DiscriminatorColumn(name="multi_day", type="integer")
* @DiscriminatorMap({"M" = "MultiDay", "S" = "SingleDay", "A" = "Accommodation"})
*/
class Resource {
/*
* @var integer $qty
* @Column(name="qty", type="integer", nullable=false, unique=false)
*/
private $qty;
/**
* @var integer $hoursDuration
*
* @Column(name="hours_duration", type="integer", nullable=false, unique=false)
*/
protected $hoursDuration;
/**
* @var integer $minutesDuration
*
* @Column(name="minutes_duration", type="integer", nullable=false, unique=false)
*/
protected $minutesDuration;
...
}
</code></pre>
<pre class="lang-php prettyprint-override"><code>class SingleDay extends Resource {
/**
* @var integer $hoursOffset
*
* @Column(name="hours_offset", type="integer", nullable=false, unique=false)
*/
private $hoursOffset;
/**
* @var integer $minutesOffset
*
* @Column(name="minutes_offset", type="integer", nullable=false, unique=false)
*/
private $minutesOffset;
/**
* @return int
*/
public function getHoursOffset()
{
return $this->hoursOffset;
}
/**
* @param int $hoursOffset
*/
public function setHoursOffset($hoursOffset)
{
$this->hoursOffset = $hoursOffset;
}
/**
* @return int
*/
public function getMinutesOffset()
{
return $this->minutesOffset;
}
/**
* @param int $minutesOffset
*/
public function setMinutesOffset($minutesOffset)
{
$this->minutesOffset = $minutesOffset;
}
/**
* @return int
*/
public function getHoursDuration()
{
return $this->hoursDuration;
}
/**
* @param int $hoursDuration
*/
public function setHoursDuration($hoursDuration)
{
$this->hoursDuration = $hoursDuration;
}
/**
* @return int
*/
public function getMinutesDuration()
{
return $this->minutesDuration;
}
/**
* @param int $minutesDuration
*/
public function setMinutesDuration($minutesDuration)
{
$this->minutesDuration = $minutesDuration;
}
...
}
</code></pre>
<p>Is this the best way to go about this? Is protected properties OK in this situation? Should I also have private properties on each class as well as the getters and setters and would Doctrine be able to deal with multiple declarations of the same column OK?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T07:26:41.010",
"Id": "442744",
"Score": "0",
"body": "It's a bit hard since we do not know what all those properties are for. For instance, what is the difference between start_time and the pair hours_offset, minutes_offset? Could they be merged? What is an accommodation exactly and how is it different from MultiDay?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T08:47:00.273",
"Id": "442762",
"Score": "0",
"body": "Everything that can be shared is being shared (as highlighted), so unfortunately start_time and hours_offset, minutes offset can't be merged. Start time will be entered as 10:30am for example, and the offset will be entered as 2 hours, 30 minutes, which will offset a time of a course set elsewhere. so an offset of 2 hours 30 minutes against 10am (set outside these classes) will be 12:30pm. It's a little more in-depth to explain what the classes do exactly, it's more the design pattern I'm querying"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:12:38.593",
"Id": "226923",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"inheritance",
"doctrine"
],
"Title": "PHP Doctrine - shared properties between discriminator classes"
}
|
226923
|
<p>I am trying to make a very simple error handler that would catch and handle all kinds of errors in both development and production environments. The idea is to keep it as simple as possible yet useful in the production environment.</p>
<p>In order to do so I am converting all errors into exceptions. Then I will need just a single function to handle both errors and exceptions.</p>
<p>Then, according to <a href="https://phpdelusions.net/articles/error_reporting#rules" rel="nofollow noreferrer">my principles of error handling</a></p>
<ul>
<li>in the dev environment, it should just echo the error information out, and</li>
<li>in the prod environment, the error information has to be logged and a generalized error message has to be shown on-screen.</li>
</ul>
<p>It am going to distinguish the modes using <code>display_errors</code> php.ini parameter and also consider all CLI scripts to be in the dev mode too. </p>
<pre><code>set_error_handler(function ($level, $message, $file = '', $line = 0)
{
throw new ErrorException($message, 0, $level, $file, $line);
});
set_exception_handler(function ($e)
{
if (ini_get('display_errors') || php_sapi_name() === 'cli') {
echo $e;
} else {
error_log($e);
header('HTTP/1.1 500 Internal Server Error', TRUE, 500);
echo "<h1>500 Internal Server Error</h1>
An internal server error has been occurred.<br>
Please try again later.";
}
});
</code></pre>
<p>There is vast room for improvement, like to create distinct exception classes for each error type (such as <code>DeprecatedErrorException</code>, <code>NoticeErrorException</code> etc.) or, based on the severity, to decide whether the script execution has to be terminated or not. Or a more creative/user-friendly error message. But I am not sure if I should include all that in a simple demonstration example. What are essential additions or modifications could be made to this code? </p>
|
[] |
[
{
"body": "<p>Perhaps a more \"friendly\" message would be nice and/or a way to customize it. As an example the generic catcher we're using right now reads: </p>\n\n<pre><code>echo '<div style=\"width: 700px;\">\n<h3>Sorry but we ran into an unexpected problem.</h3>\nThe problem has been logged and support staff have been notified.\n<h6>Please try again.</h6>\n</div>';\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T17:30:45.500",
"Id": "226937",
"ParentId": "226925",
"Score": "4"
}
},
{
"body": "<p>\"<code>been occurred</code>\" is grammatically incorrect, and I don't think this line makes any sense:</p>\n\n<blockquote>\n<pre><code>if (ini_get('display_errors') || php_sapi_name() === 'cli')\n</code></pre>\n</blockquote>\n\n<p><code>php_sapi_name()</code> will always return either a 1 or a 0, depending on what method the server is using to access the php script[internally]. It has nothing to do with client side whether you are in development or production..</p>\n\n<p><code>ini_get()</code> will return a boolean value or an empty string, \nas stated in the <a href=\"https://www.php.net/manual/en/function.php-sapi-name.php\" rel=\"nofollow noreferrer\"><code>php_sapi_name</code> manual</a>:</p>\n\n<blockquote>\n <p>A boolean ini value of off will be returned as an empty string or \"0\"\n while a boolean ini value of on will be returned as \"1\".</p>\n</blockquote>\n\n<p>So your <code>if</code> statement is basically saying \"if 0, 1 or an empty string, run the code below,\" which is useless. That has no logical use to error reporting.</p>\n\n<p>What is the purpose of checking what type of interface the server is using to access PHP in this scenario?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T16:16:39.250",
"Id": "467987",
"Score": "3",
"body": "We're *Code* Review, not *post* review - if you can improve the spelling of the non-code part of the post, you're encouraged to propose an edit. It's a shame to spoil this otherwise good answer with rants such as (ironically) \"*If your[sic] gonna keep spamming my post's[sic] atleast[sic] learn to spell in your own.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T20:03:32.653",
"Id": "467995",
"Score": "1",
"body": "Someones already done it, I was just pointing out the fact that he keeps stalking all my questions & answers & leaving negative comments, not usefull critism, when he has only two questions both with errors & not very much code to actually review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T21:29:05.610",
"Id": "468004",
"Score": "4",
"body": "If you have a problem with a user, please leave a moderator flag on *any* post of that user, or take it to [meta.CR](https://codereview.meta.stackexchange.com/). Regardless of the user's actions, this is not the way to handle it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T13:39:17.620",
"Id": "238620",
"ParentId": "226925",
"Score": "-4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:33:40.917",
"Id": "226925",
"Score": "5",
"Tags": [
"php",
"error-handling"
],
"Title": "A simple but useful error handler"
}
|
226925
|
<p>I feel quite slow in the understanding of graph representations. So, please, I'd like you to verify that I did understand, at least, the Adjacency List correctly.</p>
<p>So here I'm trying to implement unweighted graph, that supports parallel edges. Whether graph is directed or not, I don't understand how that might affect an implementation, as I will still add edges by pair (start, end) in any case.</p>
<p>-- Update:</p>
<p>To be more specific, I'd like to get a review, of possible problems that my implementation might have, eg:</p>
<p>1) extra operations</p>
<p>2) extra memory</p>
<p>3) incorrect data structure</p>
<p>... and so on, thank you.</p>
<p>--</p>
<p>Here is my code in JavaScript:</p>
<p>1) data format. Below, in the implementation, you'll see a util <code>formatDataToAdjacencyList</code>. Just assume that it returns such shape of the data (from tests):</p>
<pre><code>const result = formatDataToAdjacencyList(data)
expect(result).toEqual({
edges: [
['0', '4'],
['1', '2'],
['1', '3'],
['1', '4'],
['2', '3'],
['3', '4'],
['3', '3'],
['0', '1'],
['1', '2'],
['2', '0'],
],
vertices: [
'0',
'4',
'1',
'2',
'3',
]
})
</code></pre>
<p>2) implementation</p>
<pre><code>function GraphAdjacencyList(data) {
if (data) {
const formattedData = formatDataToAdjacencyList(data)
this.adjacencyList = formattedData.edges
this.vertices = formattedData.vertices
} else {
this.adjacencyList = []
this.vertices = []
}
}
GraphAdjacencyList.prototype.addVertex = function(nodeLabel) {
if (this.vertices.indexOf(nodeLabel) !== -1) {
throw new Error('vertex already exist')
}
this.vertices.push(nodeLabel)
}
GraphAdjacencyList.prototype.removeVertex = function(nodeLabel) {
const index = this.vertices.indexOf(nodeLabel);
if (index === -1) {
throw new Error('vertex not found')
}
this.vertices.splice(index, 1)
}
GraphAdjacencyList.prototype.addEdge = function(startLabel, endLabel) {
this.adjacencyList.push([startLabel, endLabel])
}
GraphAdjacencyList.prototype.removeEdge = function(inputStartLabel, inputEndLabel) {
const index = this.adjacencyList.findIndex(([startLabel, endLabel]) => {
return startLabel === inputStartLabel || endLabel === inputEndLabel
})
if (index === -1) {
throw new Error('edge doesn\'t exist')
}
this.adjacencyList.splice(index, 1)
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:48:34.813",
"Id": "441342",
"Score": "1",
"body": "But what does it do? What is this code for? Does it solve any problem? It's difficult to review something without context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:49:57.420",
"Id": "441343",
"Score": "0",
"body": "it represents a graph"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:55:45.670",
"Id": "441347",
"Score": "1",
"body": "You only provide methods to add arcs to the graph, not to traverse the graph or perform lookup. And your test shows us expected results, but no input date. The question can not be properly reviewed lacking all this context. Could you include more code to make this a graph and example code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:57:26.883",
"Id": "441348",
"Score": "0",
"body": "I'd like to know that I do understand the pattern of graph representation correctly. I don't have any issues with incorrectly working code, I think I might have an issue with the representation of the idea of how graphs should be implemented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T14:17:14.383",
"Id": "441358",
"Score": "0",
"body": "I find your comment confusing. You know how a graph works but don't know how to represent it. In which context would you like to represent it, can you give a non-trivial example?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T14:21:47.143",
"Id": "441359",
"Score": "0",
"body": "I'd like to represent it as an adjacency list. As far as I understand, for that, I don't need anything more than described methods, if it is incorrect, then it'd be nice to know why."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T16:31:08.530",
"Id": "441372",
"Score": "0",
"body": "There are many types of graph: directed vs undirected, weighted vs unweighted, simple vs variants of non-simple. Which do you want to implement?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T06:21:39.737",
"Id": "441507",
"Score": "0",
"body": "@PeterTaylor, added new information about graph type to description, and I don't know what do you mean by simple and non-simple variants. Thanks"
}
] |
[
{
"body": "<p>Strictly speaking, the list of vertices is not neccessary because the adjacency list already contains all (connected) vertices and disconnected ones can be represented as <code>[x, null]</code>. If you prefer to keep <code>vertices</code>, you'll have to synchronize them with edges:</p>\n\n<ul>\n<li>in <code>removeVertex</code> you not only remove the vertex but also all edges connected to it</li>\n<li>in <code>addEdge</code> you add input labels to the vertices list, if not already there (which makes one think that <code>vertices</code> should be a <code>Set</code>)</li>\n</ul>\n\n<p>Minor notes:</p>\n\n<p>In general, as of 2018, it's cleaner to use the <code>class</code> syntax to define classes.</p>\n\n<p>In <code>removeEdge</code> you'd probably want <code>&&</code>, not <code>||</code>: <code>return startLabel === inputStartLabel && endLabel === inputEndLabel</code>. If the graph is undirected, you also have to check for reversed edges (<code>start == inputEnd && end == inputStart</code>)</p>\n\n<p>You didn't share the input data format and <code>formatDataToAdjacencyList</code>, but anyways, it would look better as a class member, not as an extra function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T10:22:14.317",
"Id": "441528",
"Score": "0",
"body": "thank you for the answer. If I don't store vertices, does that mean that to get the list of vertices, for example, to iterate through it, I'll need to do O(n+m) loop to get all the vertices? And `removeEdge` is a good catch, thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T11:09:00.433",
"Id": "441539",
"Score": "0",
"body": "@Undefitied: yes, that would be the price for not having to synchronize them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T12:39:51.793",
"Id": "441553",
"Score": "0",
"body": "I see, nice to have this part clear. And what do you think about data format, am I using the correct structure for adjacency list?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:02:33.037",
"Id": "441559",
"Score": "0",
"body": "@Undefitied: there's no \"best\" or \"correct\" data structure. It all depends on the type of the graph and what the most frequent operation (build vs query) is. The list of pairs, which you're using, has an advantage of being simple to program."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T07:58:14.060",
"Id": "226986",
"ParentId": "226926",
"Score": "2"
}
},
{
"body": "<pre><code>edges: [\n ['0', '4'],\n ['1', '2'],\n ['1', '3'],\n ['1', '4'],\n ['2', '3'],\n ['3', '4'],\n ['3', '3'],\n ['0', '1'],\n ['1', '2'],\n ['2', '0'],\n]\n</code></pre>\n\n<p>is not an adjacency list representation. That would be</p>\n\n<pre><code>edges: {\n '0': ['1', '4'],\n '1': ['2', '2', '3', '4'],\n '2': ['0', '3'],\n '3': ['4', '3'],\n '4': []\n}\n</code></pre>\n\n<p><code>vertices</code> is unnecessary, because the keys of <code>edges</code> give you the vertices.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T10:17:48.990",
"Id": "441525",
"Score": "0",
"body": "Thank you for the response, @PeterTaylor. I was thinking the same as you say before I've got an answer on StackOverflow about it: https://stackoverflow.com/questions/57645065/why-not-just-use-objectmap-for-adjacency-list-edges-representation-if-instead . The guy there says, such structure is adjacency matrix and not the list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T10:20:26.310",
"Id": "441526",
"Score": "1",
"body": "@Undefitied, no, that's wrong too. An adjacency matrix would be `[[0, 1, 0, 0, 1], [0, 0, 2, 1, 1], [1, 0, 0, 1, 0], [0, 0, 0, 1, 1], [0, 0, 0, 0, 0]]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T12:06:26.140",
"Id": "441550",
"Score": "0",
"body": "Then, do you think we can go further and replace the second level array with an object? So it would be `edges: { '0': { '1': 1, '4': 1 }, '1': { '2': 2, '3': 1, '4': 1 } }`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:16:11.553",
"Id": "441565",
"Score": "1",
"body": "Sure. It's at least as good as an adjacency list in everything except memory usage, where it's probably a constant factor worse."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T09:53:29.997",
"Id": "226992",
"ParentId": "226926",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:42:54.593",
"Id": "226926",
"Score": "0",
"Tags": [
"javascript",
"algorithm"
],
"Title": "Representation graph as Adjacency List in JavaScript"
}
|
226926
|
<p>Easing functions specify the rate of change of a parameter over time.</p>
<p>Objects in real life don’t just start and stop instantly, and almost never move at a constant speed. When we open a drawer, we first move it quickly, and slow it down as it comes out. Drop something on the floor, and it will first accelerate downwards, and then bounce back up after hitting the floor.</p>
<p>Links</p>
<ul>
<li><a href="https://easings.net/" rel="nofollow noreferrer">Common Easing Functions</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T14:03:17.913",
"Id": "226927",
"Score": "0",
"Tags": null,
"Title": null
}
|
226927
|
Easing functions specify the rate of change of a parameter over time. Use this tag when you are using a function to transition the state of an object over a period of time.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T14:03:17.913",
"Id": "226928",
"Score": "0",
"Tags": null,
"Title": null
}
|
226928
|
<p>I am creating a web application using Angular 8. This application is all about talking to the stock markets server and getting the Live updates every second.
I have one query here. Below is my code:</p>
<pre><code>setInterval(()=> {
this.GETDATA_NSE_EQ_LIVE();},
1000);
GETDATA_NSE_EQ_LIVE():void{
this._NSELiveFeedComponent.getData_nse_eq_live(this.stockSymbol)
.subscribe((nse_eq_live_symbol_data) => this.Nse_Eq_Live_Symbol_data = nse_eq_live_symbol_data,
(err) => console.log(err));
}
</code></pre>
<p>As we can see that i am using setInterval() method and i am calling GETDATA_NSE_EQ_LIVE() function in every second.
This means that i am subscribing to getData_nse_eq_live(this.stockSymbol) method every second.
How can i reuse the object once it is subscribed for the first time rather than subscribing it for every second?
Also, is there any better approach than using setInterval() function for getting the stock updates every second?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T14:42:13.123",
"Id": "226929",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"asp.net-web-api",
"angular-2+"
],
"Title": "Subscribe once and reuse the Angular Subscription each second"
}
|
226929
|
<p>I am implementing a Queue class in C# using a Node/LinkedList class that I also implemented, and I wonder if there is a way to implement the enqueue and the dequeue methods, both in algorithmic efficiency of <span class="math-container">\$O(1)\$</span>.</p>
<p>In the <code>Queue</code> class I have a field of the tail and the head, and I managed to implement the enqueue method in <span class="math-container">\$O(1)\$</span>, but the dequeue is <span class="math-container">\$O(n)\$</span>.</p>
<p>This is the code for the <code>Node</code> and the <code>Queue</code> classes:</p>
<pre><code>public class Node<T>
{
#region Fields
private Node<T> next;
private T data;
#endregion Fields
#region Constructors
public Node(T data, Node<T> next)
{
this.data = data;
this.next = next;
}
public Node(T data) : this(data, null)
{
}
#endregion Constructors
#region Properties
public Node<T> Next
{
get { return next; }
set { next = value; }
}
public T Data
{
get { return data; }
set { data = value; }
}
#endregion Properties
#region Methods
public bool HasNext()
{
return next != null;
}
#endregion Methods
}
public class Queue<T>
{
private Node<T> head;
private Node<T> tail;
public Queue()
{
head = null;
tail = null;
}
public void Enqueue(T data)
{
if (IsEmpty())
head = new Node<T>(data);
else if (tail == null) // There is only one element in the queue
tail = new Node<T>(data, head);
else
tail = new Node<T>(data, tail);
}
public T Dequeue()
{
if (IsEmpty())
throw new InvalidOperationException("The queue is empty");
T data = head.Data;
if (tail == null) // There is only one element in the queue
{
head = null;
return data;
}
Node<T> temp = tail;
while (temp.Next != head) // Get the previous Node of the head
temp = temp.Next;
temp.Next = null;
head = temp;
if (tail == head)
tail = null;
return data;
}
public T Head()
{
if (IsEmpty())
throw new InvalidOperationException("The queue is empty");
return head.Data;
}
public bool IsEmpty()
{
return head == null;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T18:28:51.517",
"Id": "441808",
"Score": "0",
"body": "Have you tested this? Does it actually do something yet?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T17:19:34.723",
"Id": "442128",
"Score": "0",
"body": "@Mast yes, it works, but I want to find out if there is a way for the `Dequeue` method to be \\$O(1)\\$ instead of \\$O(n)\\$."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T12:12:59.873",
"Id": "442560",
"Score": "0",
"body": "Welcome to 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."
}
] |
[
{
"body": "<p>This is your bottleneck in retrieving the new head at removal, which can not be avoided in a Singly-Linked structure, so it's <span class=\"math-container\">\\$O(n)\\$</span>.</p>\n\n<blockquote>\n<pre><code>while (temp.Next != head) // Get the previous Node of the head\n temp = temp.Next;\n</code></pre>\n</blockquote>\n\n<h2>Doubly-Linked</h2>\n\n<p>If you want fast removal <span class=\"math-container\">\\$O(1)\\$</span>, you can do so at the cost of slightly slower insertion. You'd need to augment the queue to a doubly linked queue:</p>\n\n<pre><code>var previous = head.Previous;\nhead.Previous = null;\nhead = previous;\nhead.Next = null;\n</code></pre>\n\n<p>Make sure at insertion, you'll set both <code>Previous</code> as <code>Next</code> references on the relevant nodes.</p>\n\n<h2>Circular Doubly-Linked</h2>\n\n<p>If you make the queue circular, you don't even need to store the <code>tail</code>, only the <code>head</code>. The <code>tail</code> would be <code>head.Previous</code>; In case of a single element, since it's circular, <code>head.Previous</code> would point to <code>head</code>. Make sure in iterators to terminate at <code>head</code>, instead of at <code>null</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T10:44:53.970",
"Id": "441532",
"Score": "2",
"body": "Cheater! Writing off-topic reviews and restoring them when the question is fixed :-P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T10:57:46.263",
"Id": "441538",
"Score": "0",
"body": "Who could have seen that missing _Node_ class? :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T18:47:16.040",
"Id": "441640",
"Score": "0",
"body": "@dfhwze Why the line `head.Previous = null;` is needed? The line `head.Next = null;` won't delete the reference to the old head? (so the garbage collector will delete it anyway, even if I didn't set the previous to null)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T18:49:36.030",
"Id": "441644",
"Score": "0",
"body": "You are right, it's just a proper way to clean references. By not clearing the previous reference on the former head, you'd might want to reuse that head later on. There is a thing called 'cloacking' in which a 'removed' node could put itself back in the list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T19:31:47.270",
"Id": "441649",
"Score": "0",
"body": "Be careful though by asserting it will be garbage collected. Even though the queue no longer references the old head, a consumer may still hold a reference to it. So removing the reference to Previous is required."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T20:52:29.840",
"Id": "226949",
"ParentId": "226932",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T15:32:02.363",
"Id": "226932",
"Score": "0",
"Tags": [
"c#",
"linked-list",
"queue",
"complexity"
],
"Title": "Create custom Queue class with O(1) Enqueue and O(1) Dequeue"
}
|
226932
|
<p>VB.NET has a <a href="https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/like-operator" rel="nofollow noreferrer"><code>Like</code> operator</a> with a paradigm similar to the standard SQL <code>LIKE</code> expression (<a href="https://docs.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql?view=sql-server-2017" rel="nofollow noreferrer">SQL Server</a>, <a href="https://www.sqlite.org/lang_expr.html#like" rel="nofollow noreferrer">SQLite</a>, <a href="https://dev.mysql.com/doc/refman/8.0/en/string-comparison-functions.html#operator_like" rel="nofollow noreferrer">MySQL</a>), but with a different syntax:</p>
<pre><code>Dim result As Boolean = "abcd" Like "a*"
</code></pre>
<p>It supports:</p>
<ul>
<li>multiple-character matches -- <code>"abcd" Like "a*"</code></li>
<li>single-character matches -- <code>"abcd" Like "a??d"</code></li>
<li>digit matches -- <code>"ab12cd" Like "ab##cd"</code></li>
<li>alternate character matches -- <code>"abcd" Like "[aeiou]bcd"</code></li>
<li>ranges within the alternate character matches -- <code>"abcd" Like "[a-n]bcd"</code></li>
<li>negation of alternate characters -- <code>"abcd" Like "[!e-z]bcd"</code></li>
</ul>
<p>I've written code that tokenizes these patterns into a data structure, using the <a href="https://github.com/mcintyre321/OneOf" rel="nofollow noreferrer">OneOf library</a> which provides discriminated unions for C#. (The ultimate purpose is to convert the VB Like syntax to SQL LIKE syntax.)</p>
<p>I'm looking for feedback in the following areas:</p>
<ul>
<li>correctness, even in edge cases</li>
<li>clarity / readability</li>
</ul>
<hr>
<p>The function returns a <code>List<T></code>; each element in the list represents a token that consists of one of the following:</p>
<ul>
<li><code>char</code></li>
<li><code>Wildcards</code> enum value (defined below)</li>
<li>an instance of <code>PatternGrouping</code> -- an alternates grouping</li>
</ul>
<p>Each alternates grouping contains one or more ranges, represented using a value tuple; a single character is represented as a range with the same start and end character.</p>
<hr>
<pre><code>using OneOf;
using System;
using System.Collections.Generic;
namespace Shared {
public enum Wildcards {
SingleCharacter,
MultipleCharacter
}
// Single characters within a group are represented by a group with the same start and end character
public class PatternGroup : List<(char start, char end)> {
public PatternGroup(bool isPositive = true) => IsPositive = isPositive;
public bool IsPositive { get; set; } = true;
}
public class LikePattern : List<OneOfBase<char, Wildcards, PatternGroup>> {
public static LikePattern ParseVBLike(string pattern) {
var ret = new LikePattern();
int pos = -1;
int lastPos = pattern.Length - 1;
PatternGroup currentGroup = null;
char ch;
while (pos < lastPos) {
advanceChar();
if (currentGroup == null) {
if (ch == '?') {
ret.Add(Wildcards.SingleCharacter);
} else if (ch == '*') {
ret.Add(Wildcards.MultipleCharacter);
} else if (ch == '#') {
ret.Add(new PatternGroup() {
{'0','9' }
});
} else if (ch == '[') {
currentGroup = new PatternGroup();
if (nextChar() == '!') {
advanceChar();
currentGroup.IsPositive = false;
}
} else {
ret.Add(ch);
}
} else {
var start = ch;
if (ch == ']') {
ret.Add(currentGroup);
currentGroup = null;
} else if (nextChar() == '-' && nextChar(2) != ']') {
advanceChar();
advanceChar();
currentGroup.Add(start, ch);
} else {
currentGroup.Add(ch, ch);
}
}
}
if (currentGroup != null) {
throw new ArgumentException("Missing group end.");
}
return ret;
void advanceChar(bool ignoreEnd = false) {
pos += 1;
if (pos <= lastPos) {
ch = pattern[pos];
} else if (ignoreEnd) {
ch = '\x0';
} else {
throw new ArgumentException("Unexpected end of text");
}
}
char nextChar(int offset = 1) => pos + offset > lastPos ? '\x0' : pattern[pos + offset];
}
}
}
</code></pre>
<p><strong>Usage</strong></p>
<p>Usage looks like this (source of <a href="https://github.com/zspitz/ExpressionTreesInVBandCS/blob/master/Shared/LikePatternClasses.cs#L88" rel="nofollow noreferrer">functions</a>, <a href="https://github.com/zspitz/ExpressionTreesInVBandCS/blob/master/CSharp_LikeVisitor/LikeVisitor.cs#L32" rel="nofollow noreferrer">usage</a>):</p>
<pre><code>private static string MapSqlSpecialCharacters(char ch) {
switch (ch) {
case '%':
case '_':
case '[':
return "[" + ch + "]";
default:
return ch.ToString();
}
}
public static string GetSQLLike(LikePattern pattern) => pattern.Joined("", x => x.Match(
ch => MapSqlSpecialCharacters(ch),
wildcard => (wildcard == Wildcards.SingleCharacter ? '_' : '%').ToString(),
patternGroup => {
string ret = "";
if (patternGroup.IsPositive) { ret += '^'; }
return ret + String.Join("",
patternGroup.Select(range =>
range.start == range.end ?
$"{range.start}" :
$"{range.start}-{range.end}"
);
}
));
var tokenized = ParseVBLike(oldPattern);
var newPattern = GetSQLLike(tokenized);
</code></pre>
<p>The following XUnit test passes:</p>
<pre><code>[Fact]
public void Test1() {
var pattern = "a[L-P]#[!c-e]";
var result = ParseVBLike(pattern);
Assert.Collection(
result,
item => Assert.Equal('a', item),
item => {
PatternGroup grp = item.AsT2;
Assert.True(grp.IsPositive);
Assert.Equal(
new List<(char,char)> { ('L', 'P') },
grp.ToList()
);
},
item => {
PatternGroup grp = item.AsT2;
Assert.True(grp.IsPositive);
Assert.Equal(
new List<(char, char)> { ('0', '9') },
grp.ToList()
);
},
item => {
PatternGroup grp = item.AsT2;
Assert.False(grp.IsPositive);
Assert.Equal(
new List<(char, char)> { ('c', 'e') },
grp.ToList()
);
}
);
}
</code></pre>
<p>as does this one:</p>
<pre><code>[Fact]
public void TestWithAsterisk() {
var pattern = "a*b";
var result = ParseVBLike(pattern);
Assert.Collection(
result,
item => Assert.Equal('a', item),
item => Assert.Equal(Wildcards.MultipleCharacter, item),
item => Assert.Equal('b', item)
);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T21:41:37.450",
"Id": "441456",
"Score": "0",
"body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/97956/discussion-on-question-by-zev-spitz-function-to-parse-vb-net-like-pattern)."
}
] |
[
{
"body": "<p>IMO the use of <code>OneOfBase</code> as a kind of imitation of discriminated unions makes a lot of noise in your code and makes it more difficult to read than it has to be.</p>\n\n<p>Instead I would define a more traditional class structure, where each class holds information about each pattern or token type:</p>\n\n<pre><code> abstract class LikeToken\n {\n public abstract bool Match(string value, ref int start);\n public abstract string ToSQL();\n public abstract string ToVB();\n\n internal LikeToken Next { get; set; }\n }\n\n // Any constant char eg: 'a'\n class SingleChar : LikeToken\n {\n public SingleChar(char value)\n {\n Value = value;\n }\n\n public char Value { get; }\n\n public override bool Match(string value, ref int start)\n {\n if (start < value.Length && value[start] == Value)\n {\n start++;\n return Next.Match(value, ref start);\n }\n\n return false;\n }\n }\n\n // ?\n class AnySingleChar : LikeToken\n {\n // TODO implement the behavior\n }\n\n // *\n class ZeroOrMoreChars : LikeToken\n {\n // TODO implement the behavior\n }\n\n // 0 - 9\n class DigitChar : LikeToken\n {\n // TODO implement the behavior\n }\n\n // [a-z0-9] or [^a-z0-9]\n class CharList : LikeToken\n {\n public CharList(string charList)\n {\n }\n\n public bool IsPositive { get; private set; }\n\n // TODO implement the behavior\n }\n</code></pre>\n\n<p>As shown above the <code>Match()</code> method can be used to match each char in the string to test, and it will be independent of if the pattern originally was a VB or SQL pattern.\nThe methods <code>ToSQL()</code> and <code>ToVB()</code> should be used to reconstruct the pattern and hence act as a conversion mechanism between the two languages.</p>\n\n<p>The <code>Next</code> member can be used to chain the tokens in a linked list which can be useful in the match process, because some of the patterns have to look ahead to find the optimal match - but you have surely already a design for that.</p>\n\n<hr>\n\n<p>Parsing the pattern could then for VB be something like:</p>\n\n<pre><code> public class LikePattern\n {\n internal LikePattern(IReadOnlyList<LikeToken> tokens)\n {\n // TODO Initialize the tokens Next member to form a linked list and the head member with the first token\n }\n\n public string Message { get; private set; }\n private readonly LikeToken head\n\n public bool Match(string value)\n {\n // TOD Implement\n }\n\n public static LikePattern Parse(string pattern)\n {\n if (string.IsNullOrEmpty(pattern))\n throw new ArgumentException(\"Can not be an empty string\", nameof(pattern));\n\n List<LikeToken> tokens = new List<LikeToken>();\n int index = 0;\n\n while (index < pattern.Length)\n {\n char current = pattern[index];\n\n switch (current)\n {\n case '?':\n tokens.Add(new AnySingleChar());\n break;\n case '*':\n tokens.Add(new ZeroOrMoreChars());\n break;\n case '#':\n tokens.Add(new DigitChar());\n break;\n case '[':\n int start = index;\n while (index < pattern.Length && pattern[index] != ']')\n {\n index++;\n }\n if (index >= pattern.Length)\n throw new InvalidOperationException(\"Missing a closing square bracket for last char list\");\n tokens.Add(new CharList(pattern.Substring(start, index - start + 1)));\n break;\n default:\n tokens.Add(new SingleChar(pattern[index]));\n break;\n }\n\n index++;\n }\n\n return new LikePattern(tokens);\n }\n }\n</code></pre>\n\n<p>And a similar method could easily be made for SQL.</p>\n\n<hr>\n\n<p>Some convenient extension methods could be:</p>\n\n<pre><code> public static class LikeExtensions\n {\n public static bool Like(this string value, string pattern, out string message)\n {\n LikePattern likePattern = LikePattern.Parse(pattern);\n bool result = likePattern.Match(value);\n if (!result)\n message = likePattern.Message;\n else\n message = \"\";\n return result;\n }\n\n public static bool Like(this string value, LikePattern pattern)\n {\n return pattern.Match(value);\n }\n }\n</code></pre>\n\n<hr>\n\n<p>And usage:</p>\n\n<pre><code> LikePattern likePattern = LikePattern.Parse(\"[!e-z]bcd\");\n\n string value = \"abcd\";\n bool result = value.Like(likePattern);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T10:33:01.473",
"Id": "227070",
"ParentId": "226938",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T17:51:04.700",
"Id": "226938",
"Score": "3",
"Tags": [
"c#",
"parsing",
"lexical-analysis"
],
"Title": "Function to parse VB.NET Like pattern"
}
|
226938
|
<p>I have a specs file:</p>
<pre class="lang-none prettyprint-override"><code>Name: program
Version: 2.3.3
Release: 0
...
</code></pre>
<p>I want to update the version number every time it's built. I perform the build from a bash script so I'm calling <code>sed</code> to update the SPECS file and a "version" file which holds the version number.</p>
<p>I am using the following sed script to perform the update:</p>
<pre class="lang-sh prettyprint-override"><code>sed -ri 's/^(Version:\s+)([0-9.]+)/\1$version/g' SPECS/*.spec
</code></pre>
<p>with the <code>$version</code> being provided by the bash script.</p>
<p>It's designed to look for the correct line and replace the version portion while preserving whatever whitespace has been used. I use <code>*.spec</code> so that it will work with a spec file of any name.</p>
<p>I felt that a sed one-liner made the most sense given the requirement.</p>
|
[] |
[
{
"body": "<p>Variables don't interpolate inside single quotes. You need double quotes.</p>\n\n<p>No need to capture the old version that we're throwing away. The <code>/g</code> is redundant since the pattern can never match more than once per line (being anchored to start-of-line).</p>\n\n<p>What happens with <code>Version: 0.9a</code>? <code>Version:1</code>? <code>Version:</code>? Better to take the whole line, possibly excluding comments, and relax the space requirement. </p>\n\n<pre><code>sed -ri \"s/^(Version:\\s*)[^#]*/\\1$version/\" SPECS/*.spec\n</code></pre>\n\n<p>It's possible for the description or another section to contain the trigger text, and we probably don't want to change that. Use sed's <code>start,stop</code> addressing to limit replacement to the top block only, stopping at the first <code>%whatever</code> header:</p>\n\n<pre><code>sed -ri \"1,/^\\s*%/s/^(Version:\\s*)[^#]*/\\1$version/\" SPECS/*.spec\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T10:55:13.837",
"Id": "227390",
"ParentId": "226940",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227390",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T18:28:35.367",
"Id": "226940",
"Score": "1",
"Tags": [
"bash",
"sed"
],
"Title": "Sed script to update a version number in an RPM SPECS file"
}
|
226940
|
<p>I am coming from PHP OOP background so just want to find out if what I do with Go is common/acceptable practise or not (<em>I am newbie in Go</em>). It is to do with Dependency Injection.</p>
<p>In OOP it is ideal to Dependency Inject object X into object Y rather than directly instantiating object X in object Y. I won't list the reasons because I believe most of you know general OOP practises etc. Given that Go is not an OOP language and I've seen both versions being used, which version below wins over another an why?</p>
<p><strong>api/internal/config/config.go</strong></p>
<pre><code>package config
type Config struct
{
Locale string
}
func NewConfig() Config {
return Config{"en"}
}
</code></pre>
<p><strong>VER 1</strong></p>
<p><strong>api/internal/app/app.go</strong></p>
<pre><code>package app
func Start(c config.Config) {
fmt.Println(c.Locale)
}
</code></pre>
<p><strong>cmd/main.go</strong></p>
<pre><code>package main
import (
"api/internal/app"
"api/internal/config"
)
func main() {
c := config.NewConfig()
app.Start(c)
}
</code></pre>
<p><strong>VER 2</strong></p>
<p><strong>api/internal/app/app.go</strong></p>
<pre><code>package app
import (
"fmt"
"api/internal/config"
)
func Start() {
c := config.NewConfig()
fmt.Println(c.Locale)
}
</code></pre>
<p><strong>cmd/main.go</strong></p>
<pre><code>package main
import "api/internal/app"
func main() {
app.Start()
}
</code></pre>
|
[] |
[
{
"body": "<p>Version 1 wins hands down.</p>\n\n<p>Because, as you say yourself, go isn't an OO language, you kind of have to treat your entry point (e.g. <code>main</code> func) as your injection point. The main function loads up the global config (usually from flags and/or environment variables), and then passes them on the the various components you'll use (or packages if you like).</p>\n\n<p>Go is a great language to write tests in quickly. If I see code like the second snippet:</p>\n\n<pre><code>func Start() {\n c := config.New()\n // do stuff with c\n}\n</code></pre>\n\n<p>I will rewrite it. The config value is created in that function, so it's safe to assume that this function will need to check the config values. How am I going to reliably unit-test the package, if I can't pass in all possible combinations of config?</p>\n\n<p>Sure, I could write a ton of code setting/unsetting environment variables, and call this <code>Start</code> function over and over again, but am I really <em>unit</em>-testing the code then? Surely, if the config package is broken, then all other tests become unreliable to say the least. What about a change to the config package? How awful it'd be to rewrite all the tests just to make sure the changes to the config are reflected there, too? It's going to be a PITA, and an enormous waste of time and resources.</p>\n\n<p>PS: code like <code>config.NewConfig()</code> will also get rewritten by a lot of gophers. This is referred to as <em>stuttering</em> code (read <a href=\"https://blog.golang.org/package-names\" rel=\"nofollow noreferrer\">this</a>).</p>\n\n<p>I now I'm getting config, because I'm using the <code>config</code> package. The function name <code>New</code> is enough information, surely. <code>config.NewConfig</code> reads like <em>\"from config, get me new config\"</em> as opposed to <em>\"hey, config, give me a new value\"</em>.<br>\nThis might be personal preference, but I generally find it better to use the function <code>Get</code> for config, rather than <code>New</code>. Config is, IMO, an immutable set of data, not something that <em>does</em> something, not something that needs <em>constructing</em>, it needs to be fetched/loaded. For that reason, I'd write <code>config.Get()</code> and that func would looks something like this:</p>\n\n<pre><code>package config\n\n// Conf - global config struct\ntype Conf struct {\n App // config per package\n}\n\n// App - config specific to the App package\ntype App struct {\n Locale string\n}\n\nfunc Get() (*Conf, error) {\n // get values, return...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T16:55:15.957",
"Id": "441613",
"Score": "0",
"body": "Thanks for the answer. Assume that the `config` is needed in an another package but the package is not bootstrapped when we stated the `app` in `main()`. I guess it is ok to create/fetch `config` with `config.Get()` in the package?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T10:31:54.077",
"Id": "441708",
"Score": "0",
"body": "@BentCoder: No it wouldn't be. The whole point of DI is that dependencies are created and _injected_ into whatever component depends on them. If you create the deps in `app.New()`, then you're no longer injecting. `config.Get()` should be called once, _before_ you create any instance that requires values from config"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T10:53:31.253",
"Id": "226996",
"ParentId": "226946",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "226996",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T20:27:13.537",
"Id": "226946",
"Score": "1",
"Tags": [
"go"
],
"Title": "Dependency injecting or manually instantiating structs in others with go"
}
|
226946
|
<p>I'm following a tutorial on merging two bubble-sorted Single Linked Lists in Python. </p>
<ul>
<li><code>merge1</code> creates a new list and does the merging. </li>
</ul>
<hr>
<p>Other than naming conventions which are not the best and I'm just following the tutorial, any feedback would be appreciated. OOP, practical time-complexity, algorithms, and others. </p>
<pre><code>class Node:
# Instantiates the node class
def __init__(self, value):
self.info = value
self.link = None
class SingleLinkedList:
# Instantiates the single linked list class
def __init__(self):
self.start = None
# Creates the single linked list
def create_list(self):
n = int(input("Enter the number of nodes in the list you wish to create: "))
if n == 0:
return
for i in range(n):
data = int(input("Enter the element to be inserted: "))
self.insert_at_end(data)
# Counts the nodes of the single linked list
def count_nodes(self):
p = self.start
n = 0
while p is not None:
n += 1
p = p.link
print(" The number of nodes in single linked list is: " + str(n))
# Searches the x integer in the linked list
def search(self, x):
position = 1
p = self.start
while p is not None:
if p.info == x:
print(" YAAAY! We found " + str(x) + " at position " + str(position))
return True
# Increment the position
position += 1
# Assign the next node to the current node
p = p.link
else:
print(" Sorry! We couldn't find " + str(x) + " at any position. Maybe, try again later!")
return False
# Displays the list
def display_list(self):
if self.start is None:
print(" Single linked list is empty!")
return
else:
print(" Single linked list includes: ")
p = self.start
while p is not None:
print(p.info, " ", end=' ')
p = p.link
print()
# Inserts an integer in the beginning of the linked list
def insert_in_beginning(self, data):
temp = Node(data)
temp.link = self.start
self.start = temp
# Inserts an integer at the end of the linked list
def insert_at_end(self, data):
temp = Node(data)
if self.start is None:
self.start = temp
return
p = self.start
while p.link is not None:
p = p.link
p.link = temp
# Inserts an integer after the x node
def insert_after(self, data, x):
p = self.start
while p is not None:
if p.info == x:
break
p = p.link
if p is None:
print(" Sorry! " + str(x) + " is not in the list.")
else:
temp = Node(data)
temp.link = p.link
p.link = temp
# Inserts an integer before the x node
def insert_before(self, data, x):
# If list is empty
if self.start is None:
print(" Sorry! The list is empty.")
return
# If x is the first node, and new node should be inserted before the first node
if x == self.start.info:
temp = Node(data)
temp.link = p.link
p.link = temp
# Finding the reference to the prior node containing x
p = self.start
while p.link is not None:
if p.link.info == x:
break
p = p.link
if p.link is not None:
print(" Sorry! " + str(x) + " is not in the list.")
else:
temp = Node(data)
temp.link = p.link
p.link = temp
# Inserts an integer in k position of the linked list
def insert_at_position(self, data, k):
# if we wish to insert at the first node
if k == 1:
temp = Node(data)
temp.link = self.start
self.start = temp
return
p = self.start
i = 1
while i < k-1 and p is not None:
p = p.link
i += 1
if p is None:
print(" The max position is: " + i)
else:
temp = Node(data)
temp.link = self.start
self.start = temp
# Deletes a node of a linked list
def delete_node(self, x):
# If list is empty
if self.start is None:
print(" Sorry! The list is empty.")
return
# If there is only one node
if self.start.info == x:
self.start = self.start.link
# If more than one node exists
p = self.start
while p.link is not None:
if p.link.info == x:
break
p = p.link
if p.link is None:
print(" Sorry! " + str(x) + " is not in the list.")
else:
p.link = p.link.link
# Deletes the first node of a linked list
def delete_first_node(self):
if self.start is None:
return
self.start = self.start.link
# Deletes the last node of a linked list
def delete_last_node(self):
# If the list is empty
if self.start is None:
return
# If there is only one node
if self.start.link is None:
self.start = None
return
# If there is more than one node
p = self.start
# Increment until we find the node prior to the last node
while p.link.link is not None:
p = p.link
p.link = None
# Reverses the linked list
def reverse_list(self):
prev = None
p = self.start
while p is not None:
next = p.link
p.link = prev
prev = p
p = next
self.start = prev
# Bubble sorts the linked list with respect to data
def bubble_sort_exdata(self):
# If the list is empty or there is only one node
if self.start is None or self.start.link is None:
print(" The list has no or only one node and sorting is not required.")
end = None
while end != self.start.link:
p = self.start
while p.link != end:
q = p.link
if p.info > q.info:
p.info, q.info = q.info, p.info
p = p.link
end = p
# Bubble sorts the linked list with respect to links
def bubble_sort_exlinks(self):
# If the list is empty or there is only one node
if self.start is None or self.start.link is None:
print(" The list has no or only one node and sorting is not required.")
end = None
while end != self.start.link:
r = p = self.start
while p.link != end:
q = p.link
if p.info > q.info:
p.link = q.link
q.link = p
if p != self.start:
r.link = q.link
else:
self.start = q
p, q = q, p
r = p
p = p.link
end = p
#Merges two already sorted single linked lists by creating new lists
def merge1(self, list2):
merge_list = SingleLinkedList()
merge_list.start = self._merge1(self.start, list2.start)
return merge_list
def _merge1(self, p1, p2):
if p1.info <= p2.info:
StartM = Node(p1.info)
p1 = p1.link
else:
StartM = Node(p2.info)
p2 = p2.link
pM = StartM
while p1 is not None and p2 is not None:
if p1.info <= p2.info:
pM.link = Node(p1.info)
p1 = p1.link
else:
pM.link = Node(p2.info)
p2 = p2.link
pM = pM.link
# If the second list is finished, yet the first list has some nodes
while p1 is not None:
pM.link = Node(p1.info)
p1 = p1.link
pM = pM.link
# If the second list is finished, yet the first list has some nodes
while p2 is not None:
pM.link = Node(p2.info)
p2 = p2.link
pM = pM.link
return StartM
# Testing
list1 = SingleLinkedList()
list2 = SingleLinkedList()
list1.create_list()
list2.create_list()
list1.bubble_sort_exdata()
list2.bubble_sort_exdata()
print("1️⃣ The first list is: ")
list1.display_list()
print("2️⃣ The second list is: ")
list2.display_list()
list3 = list1.merge1(list2)
print("The merged list by creating a new list is: ")
list3.display_list()
</code></pre>
<h3>Output</h3>
<pre><code>1️⃣ The first list is:
Single linked list includes:
1 1 1 2 3
2️⃣ The second list is:
Single linked list includes:
1 3 6 6
The merged list by creating a new list is:
Single linked list includes:
1 1 1 1 2 3 3 6 6
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T21:14:07.560",
"Id": "441444",
"Score": "1",
"body": "where is merge2 ? :( "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T21:17:32.470",
"Id": "441446",
"Score": "2",
"body": "Ah ok, I was about to add the _comparative review_ tag, but it's no longer required. By the way, I'm out of votes :s"
}
] |
[
{
"body": "<h1>Docstrings</h1>\n\n<p>You should have a <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\"><code>docstring</code></a> at the beginning of every module, class, and method you write. This will allow documentation to identify what your code is supposed to do. You're on the right track, having comments above the classes and methods. Now, just move those comments <em>inside</em> these classes and methods at the very beginning, inside triple quote comments (<code>\"\"\" ... \"\"\"</code>). I've gone and done this for you.</p>\n\n<h1>Meaningful Variable Naming</h1>\n\n<p>You have many variables like <code>p</code>, <code>q</code>, <code>x</code>, <code>k</code>, etc. While this may be convenient for sorting algorithms, you should provide more meaningful names for these variables.</p>\n\n<h1><code>_</code> for unused loop variable(s)</h1>\n\n<p>You have this code:</p>\n\n<pre><code>for i in range(n):\n data = int(input(\"Enter the element to be inserted: \"))\n self.insert_at_end(data)\n</code></pre>\n\n<p>You don't use the <code>i</code> at all in this loop. You should use a <code>_</code> instead. This makes it clear that the loop variable is to be ignored. The loop should now look like this:</p>\n\n<pre><code>for _ in range(n):\n data = int(input(\"Enter the element to be inserted: \"))\n self.insert_at_end(data)\n</code></pre>\n\n<h1>String Concatenation / Formatting</h1>\n\n<p>You have this code all throughout your program:</p>\n\n<pre><code>print(\" The number of nodes in single linked list is: \" + str(n))\nprint(\" YAAAY! We found \" + str(x) + \" at position \" + str(position))\nprint(\" Sorry! \" + str(x) + \" is not in the list.\")\n...\n</code></pre>\n\n<p>Changing the type of the variable to a string, then adding it to the string, is unnecessary. You can simply use <code>f\"\"</code> or <code>\"\".format()</code> to directly incorporate these variables into your strings, without having to type cast them. Here are both ways:</p>\n\n<p><strong><code>f\"\"</code></strong></p>\n\n<pre><code>print(f\" The number of nodes in single linked list is: {n}\")\nprint(f\" YAAAY! We found {x} at position {position}\")\nprint(f\" Sorry! {x} is not in the list.\")\n</code></pre>\n\n<p><strong><code>\"\".format()</code></strong></p>\n\n<pre><code>print(\" The number of nodes in single linked list is: {}\".format(n))\nprint(\" YAAAY! We found {} at position {}\".format(x, position))\nprint(\" Sorry! {} is not in the list.\".format(x))\n</code></pre>\n\n<p>Personally, I go with <code>f\"\"</code> because it makes the code cleaner, and allows me to see exactly what variables are in the string, without having to call <code>.format()</code> at the end. I use this in the updated version of your code at the bottom of this answer, but you can choose.</p>\n\n<h1>Unreachable Code</h1>\n\n<p>Here is your <code>search</code> method:</p>\n\n<pre><code>def search(self, x):\n position = 1\n p = self.start\n while p is not None:\n if p.info == x:\n print(\" YAAAY! We found \" + str(x) + \" at position \" + str(position))\n return True\n\n # Increment the position\n position += 1 \n # Assign the next node to the current node\n p = p.link\n else:\n print(\" Sorry! We couldn't find \" + str(x) + \" at any position. Maybe, try again later!\")\n return False\n</code></pre>\n\n<p>After you return <code>True</code>, it exits this method. So, the four lines of code after never get run. Ever. This code should be removed. The <code>else</code> is also unnecessary; I speak on that in the next section.</p>\n\n<h1>Unnecessary else after return</h1>\n\n<p>After you return something in a body of an <code>if</code>, you don't need an <code>else</code>. If the <code>if</code> isn't executed, it will automatically go to the next code, which will execute that code. Take your <code>display_list</code> method:</p>\n\n<pre><code>def display_list(self):\n if self.start is None:\n print(\" Single linked list is empty!\")\n return\n else:\n print(\" Single linked list includes: \")\n p = self.start\n while p is not None:\n print(p.info, \" \", end=' ')\n p = p.link\n print()\n</code></pre>\n\n<p>Since you return in the initial <code>if</code> statement, the <code>else</code> is unnecessary. That code won't be run if the <code>if</code> is <code>True</code>, since the method will be exited after the <code>return</code> statement. This method should now look like this:</p>\n\n<pre><code>def display_list(self):\n if self.start is None:\n print(\" Single linked list is empty!\")\n return\n print(\" Single linked list includes: \")\n p = self.start\n while p is not None:\n print(p.info, \" \", end=' ')\n p = p.link\n print()\n</code></pre>\n\n<h1>Redefining built in keywords</h1>\n\n<p>You have a variable named <code>next</code> in your code. Since this is a name of a function in the <a href=\"https://www.programiz.com/python-programming/methods/built-in/next\" rel=\"nofollow noreferrer\">Python Standard Library</a>, it should be avoided. You shouldn't use built in keywords as variable names. They can cause collision and other errors in your code. You can use a text editor such as Sublime Text 3, which will highlight these words at built in keywords.</p>\n\n<h1>Constant Variable Naming</h1>\n\n<p>Constants in your program should be UPPER_CASE, to identify them as such.</p>\n\n<p><strong><em>Updated Code</em></strong></p>\n\n<pre><code>\"\"\"\nMethod Docstring\nA description of your program goes here\n\"\"\"\n\nclass Node:\n \"\"\"\n Node Class Docstring\n A description of this class goes here\n \"\"\"\n\n def __init__(self, value):\n \"\"\"\n Instantiates the node class\n \"\"\"\n self.info = value\n self.link = None\n\nclass SingleLinkedList:\n \"\"\"\n SingleLinkedList Class Docstring\n A description of this class goes here\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Instantiates the single linked list class\n \"\"\"\n self.start = None\n\n\n def create_list(self):\n \"\"\"\n Creates the single linked list\n \"\"\"\n num_nodes = int(input(\"Enter the number of nodes in the list you wish to create: \"))\n\n if num_nodes == 0:\n return\n for _ in range(num_nodes):\n data = int(input(\"Enter the element to be inserted: \"))\n self.insert_at_end(data)\n\n\n def count_nodes(self):\n \"\"\"\n Counts the nodes of the single linked list\n \"\"\"\n start = self.start\n count = 0\n while start is not None:\n count += 1\n start = start.link\n print(f\" The number of nodes in single linked list is: {count}\")\n\n\n def search(self, number):\n \"\"\"\n Searches the x integer in the linked list\n \"\"\"\n position = 1\n start = self.start\n while start is not None:\n if start.info == number:\n print(f\" YAAAY! We found {number} at position {position}\")\n return True\n print(f\" Sorry! We couldn't find {number} at any position. Maybe, try again later!\")\n return False\n\n\n\n def display_list(self):\n \"\"\"\n Displays the list\n \"\"\"\n if self.start is None:\n print(\" Single linked list is empty!\")\n return\n print(\" Single linked list includes: \")\n start = self.start\n while start is not None:\n print(start.info, \" \", end=' ')\n start = start.link\n print()\n\n def insert_in_beginning(self, data):\n \"\"\"\n Inserts an integer in the beginning of the linked list\n \"\"\"\n temp = Node(data)\n temp.link = self.start\n self.start = temp\n\n def insert_at_end(self, data):\n \"\"\"\n Inserts an integer at the end of the linked list\n \"\"\"\n temp = Node(data)\n if self.start is None:\n self.start = temp\n return\n\n start = self.start\n while start.link is not None:\n start = start.link\n start.link = temp\n\n def insert_after(self, data, number):\n \"\"\"\n Inserts an integer after the x node\n \"\"\"\n start = self.start\n\n while start is not None:\n if start.info == number:\n break\n start = start.link\n\n if start is None:\n print(f\" Sorry! {number} is not in the list.\")\n else:\n temp = Node(data)\n temp.link = start.link\n start.link = temp\n\n def insert_before(self, data, number):\n \"\"\"\n Inserts an integer before the x node\n \"\"\"\n\n # If list is empty\n if self.start is None:\n print(\" Sorry! The list is empty.\")\n return\n\n # If x is the first node, and new node should be inserted before the first node\n if number == self.start.info:\n temp = Node(data)\n temp.link = number.link\n number.link = temp\n\n # Finding the reference to the prior node containing x\n start = self.start\n while start.link is not None:\n if start.link.info == number:\n break\n start = start.link\n\n if start.link is not None:\n print(f\" Sorry! {number} is not in the list.\")\n else:\n temp = Node(data)\n temp.link = start.link\n start.link = temp\n\n def insert_at_position(self, data, pos):\n \"\"\"\n Inserts an integer in k position of the linked list\n \"\"\"\n # if we wish to insert at the first node\n if pos == 1:\n temp = Node(data)\n temp.link = self.start\n self.start = temp\n return\n\n start = self.start\n i = 1\n\n while i < pos - 1 and start is not None:\n start = start.link\n i += 1\n\n if start is None:\n print(\" The max position is: \" + i)\n else:\n temp = Node(data)\n temp.link = self.start\n self.start = temp\n\n def delete_node(self, node):\n \"\"\"\n Deletes a node of a linked list\n \"\"\"\n # If list is empty\n if self.start is None:\n print(\" Sorry! The list is empty.\")\n return\n\n # If there is only one node\n if self.start.info == node:\n self.start = self.start.link\n\n # If more than one node exists\n start = self.start\n while start.link is not None:\n if start.link.info == node:\n break\n start = start.link\n\n if start.link is None:\n print(f\" Sorry! {node} is not in the list.\")\n else:\n start.link = start.link.link\n\n def delete_first_node(self):\n \"\"\"\n Deletes the first node of a linked list\n \"\"\"\n if self.start is None:\n return\n self.start = self.start.link\n\n def delete_last_node(self):\n \"\"\"\n Deletes the last node of a linked list\n \"\"\"\n # If the list is empty\n if self.start is None:\n return\n\n # If there is only one node\n if self.start.link is None:\n self.start = None\n return\n\n # If there is more than one node\n start = self.start\n\n # Increment until we find the node prior to the last node\n while start.link.link is not None:\n start = start.link\n\n start.link = None\n\n def reverse_list(self):\n \"\"\"\n Reverses the linked list\n \"\"\"\n prev = None\n start = self.start\n while start is not None:\n next_ = start.link\n start.link = prev\n prev = start\n start = next_\n self.start = prev\n\n def bubble_sort_exdata(self):\n \"\"\"\n Bubble sorts the linked list with respect to data\n \"\"\"\n # If the list is empty or there is only one node\n if self.start is None or self.start.link is None:\n print(\" The list has no or only one node and sorting is not required.\")\n end = None\n\n while end != self.start.link:\n start = self.start\n while start.link != end:\n q = start.link\n if start.info > q.info:\n start.info, q.info = q.info, start.info\n start = start.link\n end = start\n\n def bubble_sort_exlinks(self):\n \"\"\"\n Bubble sorts the linked list with respect to links\n \"\"\"\n # If the list is empty or there is only one node\n if self.start is None or self.start.link is None:\n print(\" The list has no or only one node and sorting is not required.\")\n end = None\n\n while end != self.start.link:\n r = p = self.start\n while p.link != end:\n q = p.link\n if p.info > q.info:\n p.link = q.link\n q.link = p\n if p != self.start:\n r.link = q.link\n else:\n self.start = q\n p, q = q, p\n r = p\n p = p.link\n end = p\n\n def merge1(self, list_two):\n \"\"\"\n Merges two already sorted single linked lists by creating new lists\n \"\"\"\n merge_list = SingleLinkedList()\n merge_list.start = self._merge1(self.start, list_two.start)\n return merge_list\n\n def _merge1(self, p1, p2):\n \"\"\"\n A description of this method goes here\n \"\"\"\n if p1.info <= p2.info:\n start_m = Node(p1.info)\n p1 = p1.link\n else:\n start_m = Node(p2.info)\n p2 = p2.link\n p_m = start_m\n\n while p1 is not None and p2 is not None:\n if p1.info <= p2.info:\n p_m.link = Node(p1.info)\n p1 = p1.link\n else:\n p_m.link = Node(p2.info)\n p2 = p2.link\n p_m = p_m.link\n\n # If the second list is finished, yet the first list has some nodes\n while p1 is not None:\n p_m.link = Node(p1.info)\n p1 = p1.link\n p_m = p_m.link\n\n # If the second list is finished, yet the first list has some nodes\n while p2 is not None:\n p_m.link = Node(p2.info)\n p2 = p2.link\n p_m = p_m.link\n\n return start_m\n\n\n# Testing\n\nif __name__ == '__main__':\n\n LIST_ONE = SingleLinkedList()\n LIST_TWO = SingleLinkedList()\n\n LIST_ONE.create_list()\n LIST_TWO.create_list()\n\n LIST_ONE.bubble_sort_exdata()\n LIST_TWO.bubble_sort_exdata()\n\n print(\"1️⃣ The first list is: \")\n LIST_ONE.display_list()\n\n print(\"2️⃣ The second list is: \")\n LIST_TWO.display_list()\n\n LIST_THREE = LIST_ONE.merge1(LIST_TWO)\n\n print(\"The merged list by creating a new list is: \")\n LIST_THREE.display_list()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T22:14:54.303",
"Id": "226960",
"ParentId": "226951",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226960",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T21:05:17.247",
"Id": "226951",
"Score": "2",
"Tags": [
"python",
"beginner",
"algorithm",
"object-oriented",
"complexity"
],
"Title": "Merging Two Bubble Sorted Linked Lists (Python)"
}
|
226951
|
<p>I'm following a tutorial on merging two bubble-sorted Single Linked Lists in Python. </p>
<ul>
<li><code>merge1</code> does the merging by creating a new list with maybe <span class="math-container">\$O(N+M)\$</span> memory complexity that I'm guessing, and <a href="https://codereview.stackexchange.com/questions/226951/merging-two-bubble-sorted-linked-lists">has been also reviewed here</a>. </li>
<li><code>merge2</code> does an in-place merging with <span class="math-container">\$O(1)\$</span> constant space complexity that I'm guessing. </li>
</ul>
<hr>
<p>Other than naming conventions which are not the best here and is not a concern and I have to just follow the tutorial, any feedback would be appreciated, especially about the best practices in object-orinted programming, practical as opposed to theoretical time and complexities, and algorithms. </p>
<pre><code>"""
Module Docstring
This is a simple object-oriented implementation of merging two Single Linked Lists with some associated methods,
such as bubble sorting, create list, and such.
"""
class Node:
def __init__(self, value):
"""
Instantiates the node class
"""
self.info = value
self.link = None
class SingleLinkedList:
def __init__(self):
"""
Instantiates the single linked list class
"""
self.start = None
def create_list(self):
"""
Creates the single linked list
"""
n = int(input("Enter the number of nodes in the list you wish to create: "))
if n == 0:
return
for _ in range(n):
data = int(input("Enter the element to be inserted: "))
self.insert_at_end(data)
def display_list(self):
"""
Displays the list
"""
if self.start is None:
print(" Single linked list is empty!")
return
print(" Single linked list includes: ")
p = self.start
while p is not None:
print(p.info, " ", end=' ')
p = p.link
print()
def insert_in_beginning(self, data):
"""
Inserts an integer in the beginning of the linked list
"""
temp = Node(data)
temp.link = self.start
self.start = temp
def insert_at_end(self, data):
"""
Inserts an integer at the end of the linked list
"""
temp = Node(data)
if self.start is None:
self.start = temp
return
p = self.start
while p.link is not None:
p = p.link
p.link = temp
def insert_after(self, data, x):
"""
Inserts an integer after the x node
"""
p = self.start
while p is not None:
if p.info == x:
break
p = p.link
if p is None:
print(f" Sorry! {x} is not in the list.")
else:
temp = Node(data)
temp.link = p.link
p.link = temp
def insert_before(self, data, x):
"""
Inserts an integer before the x node
"""
#If list is empty
if self.start is None:
print(" Sorry! The list is empty.")
return
#If x is the first node, and new node should be inserted before the first node
if x == self.start.info:
temp = Node(data)
temp.link = p.link
p.link = temp
#Finding the reference to the prior node containing x
p = self.start
while p.link is not None:
if p.link.info == x:
break
p = p.link
if p.link is not None:
print(f" Sorry! {x} is not in the list.")
else:
temp = Node(data)
temp.link = p.link
p.link = temp
def insert_at_position(self, data, k):
"""
Inserts an integer in k position of the linked list
"""
#if we wish to insert at the first node
if k == 1:
temp = Node(data)
temp.link = self.start
self.start = temp
return
p = self.start
i = 1
while i < k-1 and p is not None:
p = p.link
i += 1
if p is None:
print(" The max position is: " + i)
else:
temp = Node(data)
temp.link = self.start
self.start = temp
def delete_node(self, x):
"""
Deletes a node of a linked list
"""
#If list is empty
if self.start is None:
print(" Sorry! The list is empty.")
return
#If there is only one node
if self.start.info == x:
self.start = self.start.link
#If more than one node exists
p = self.start
while p.link is not None:
if p.link.info == x:
break
p = p.link
if p.link is None:
print(f" Sorry! {x} is not in the list.")
else:
p.link = p.link.link
def delete_first_node(self):
"""
Deletes the first node of a linked list
"""
if self.start is None:
return
self.start = self.start.link
def delete_last_node(self):
"""
Deletes the last node of a linked list
"""
#If the list is empty
if self.start is None:
return
#If there is only one node
if self.start.link is None:
self.start = None
return
#If there is more than one node
p = self.start
#Increment until we find the node prior to the last node
while p.link.link is not None:
p = p.link
p.link = None
def reverse_list(self):
"""
Reverses the linked list
"""
prev = None
p = self.start
while p is not None:
next = p.link
p.link = prev
prev = p
p = next
self.start = prev
def bubble_sort_exdata(self):
"""
Bubble sorts the linked list with respect to data
"""
#If the list is empty or there is only one node
if self.start is None or self.start.link is None:
print(" The list has no or only one node and sorting is not required.")
end = None
while end != self.start.link:
p = self.start
while p.link != end:
q = p.link
if p.info > q.info:
p.info, q.info = q.info, p.info
p = p.link
end = p
def bubble_sort_exlinks(self):
"""
Bubble sorts the linked list with respect to links
"""
#If the list is empty or there is only one node
if self.start is None or self.start.link is None:
print(" The list has no or only one node and sorting is not required.")
end = None
while end != self.start.link:
r = p = self.start
while p.link != end:
q = p.link
if p.info > q.info:
p.link = q.link
q.link = p
if p != self.start:
r.link = q.link
else:
self.start = q
p, q = q, p
r = p
p = p.link
end = p
def merge1(self, list2):
"""
Merges two already sorted single linked lists by creating new lists
"""
merge_list = SingleLinkedList()
merge_list.start = self._merge1(self.start, list2.start)
return merge_list
def _merge1(self, p1, p2):
"""
Private method of merge1
"""
if p1.info <= p2.info:
StartM = Node(p1.info)
p1 = p1.link
else:
StartM = Node(p2.info)
p2 = p2.link
pM = StartM
while p1 is not None and p2 is not None:
if p1.info <= p2.info:
pM.link = Node(p1.info)
p1 = p1.link
else:
pM.link = Node(p2.info)
p2 = p2.link
pM = pM.link
#If the second list is finished, yet the first list has some nodes
while p1 is not None:
pM.link = Node(p1.info)
p1 = p1.link
pM = pM.link
#If the second list is finished, yet the first list has some nodes
while p2 is not None:
pM.link = Node(p2.info)
p2 = p2.link
pM = pM.link
return StartM
def merge2(self, list2):
"""
Merges two already sorted single linked lists in place in O(1) of space
"""
merge_list = SingleLinkedList()
merge_list.start = self._merge2(self.start, list2.start)
return merge_list
def _merge2(self, p1, p2):
"""
Merges two already sorted single linked lists in place in O(1) of space
"""
if p1.info <= p2.info:
StartM = p1
p1 = p1.link
else:
StartM = p2
p2 = p2.link
pM = StartM
while p1 is not None and p2 is not None:
if p1.info <= p2.info:
pM.link = p1
pM = pM.link
p1 = p1.link
else:
pM.link = p2
pM = pM.link
p2 = p2.link
if p1 is None:
pM.link = p2
else:
pM.link = p1
return StartM
# Testing
if __name__ == '__main__':
LIST_ONE = SingleLinkedList()
LIST_TWO = SingleLinkedList()
LIST_ONE.create_list()
LIST_TWO.create_list()
print("1️⃣ The unsorted first list is: ")
LIST_ONE.display_list()
print("2️⃣ The unsorted second list is: ")
LIST_TWO.display_list()
LIST_ONE.bubble_sort_exdata()
LIST_TWO.bubble_sort_exdata()
print("1️⃣ The sorted first list is: ")
LIST_ONE.display_list()
print("2️⃣ The sorted second list is: ")
LIST_TWO.display_list()
LIST_THREE = LIST_ONE.merge1(LIST_TWO)
print("The merged list by creating a new list is: ")
LIST_THREE.display_list()
LIST_FOUR = LIST_ONE.merge2(LIST_TWO)
print("The in-place merged list is: ")
LIST_FOUR.display_list()
</code></pre>
<h3>Output</h3>
<pre><code>Enter the number of nodes in the list you wish to create: 6
Enter the element to be inserted: -1
Enter the element to be inserted: 0
Enter the element to be inserted: 47
Enter the element to be inserted: 30
Enter the element to be inserted: -4
Enter the element to be inserted: 26
Enter the number of nodes in the list you wish to create: 9
Enter the element to be inserted: -3
Enter the element to be inserted: 19
Enter the element to be inserted: 24
Enter the element to be inserted: -120
Enter the element to be inserted: -120
Enter the element to be inserted: 84
Enter the element to be inserted: 40
Enter the element to be inserted: -50
Enter the element to be inserted: 0
1️⃣ The unsorted first list is:
Single linked list includes:
-1 0 47 30 -4 26
2️⃣ The unsorted second list is:
Single linked list includes:
-3 19 24 -120 -120 84 40 -50 0
1️⃣ The sorted first list is:
Single linked list includes:
-4 -1 0 26 30 47
2️⃣ The sorted second list is:
Single linked list includes:
-120 -120 -50 -3 0 19 24 40 84
The merged list by creating a new list is:
Single linked list includes:
-120 -120 -50 -4 -3 -1 0 0 19 24 26 30 40 47 84
The in-place merged list is:
Single linked list includes:
-120 -120 -50 -4 -3 -1 0 0 19 24 26 30 40 47 84
</code></pre>
|
[] |
[
{
"body": "<pre><code>\"\"\"\nModule Docstring\nThis is a simple object-oriented implementation of merging two Single Linked Lists with some associated methods, \nsuch as bubble sorting, create list, and such. \n\n\"\"\"\n</code></pre>\n\n<p>The line <code>Module Docstring</code> is probably a placeholder which you're meant to remove, but it's good to see that the methods are documented.</p>\n\n<hr>\n\n<pre><code> def create_list(self):\n \"\"\"\n Creates the single linked list\n \"\"\"\n</code></pre>\n\n<p>What's the difference between <em>create</em> and <em>instantiate</em>? I think this is best described as <code>Reads values from stdin and appends them to this list</code>.</p>\n\n<hr>\n\n<pre><code> def insert_in_beginning(self, data):\n \"\"\"\n Inserts an integer in the beginning of the linked list\n \"\"\"\n temp = Node(data)\n temp.link = self.start\n self.start = temp\n</code></pre>\n\n<p>There's an <code>insert_at_position</code> below: why not just call that with position <code>0</code>?</p>\n\n<hr>\n\n<pre><code> if self.start is None:\n</code></pre>\n\n<p>Thumbs up for using the right comparison operator.</p>\n\n<hr>\n\n<pre><code> def insert_before(self, data, x):\n \"\"\"\n Inserts an integer before the x node\n \"\"\"\n\n #If list is empty\n if self.start is None:\n print(\" Sorry! The list is empty.\")\n return \n</code></pre>\n\n<p>In general, raising an exception is more useful than printing something to stdout.</p>\n\n<pre><code> #If x is the first node, and new node should be inserted before the first node\n if x == self.start.info:\n temp = Node(data)\n temp.link = p.link\n p.link = temp\n</code></pre>\n\n<p>I think this is extremely buggy. <code>p</code> doesn't exist yet, <code>self.start</code> should be updated to <code>temp</code>, and it shouldn't fall through and potentially insert the value twice.</p>\n\n<hr>\n\n<pre><code> def insert_at_position(self, data, k):\n \"\"\"\n Inserts an integer in k position of the linked list\n \"\"\" \n\n #if we wish to insert at the first node\n if k == 1:\n</code></pre>\n\n<p>1-indexing in Python? That's going to confuse people...</p>\n\n<hr>\n\n<pre><code> p = self.start\n i = 1\n\n while i < k-1 and p is not None:\n p = p.link\n i += 1\n</code></pre>\n\n<p>I suggest refactoring this to decrement <code>k</code> and eliminate the variable <code>i</code> entirely.</p>\n\n<hr>\n\n<pre><code> def delete_node(self, x):\n ...\n #If there is only one node\n if self.start.info == x:\n self.start = self.start.link\n</code></pre>\n\n<p>The comment describes a different condition to the one which the code actually tests. This would be clearer without the comment.</p>\n\n<hr>\n\n<pre><code> def reverse_list(self):\n ...\n prev = p\n p = next\n</code></pre>\n\n<p>Here Python's simultaneous assignment <code>prev, p = p, next</code> can be useful.</p>\n\n<hr>\n\n<p>This seems like a good point to ask the question: do you know what a <em>sentinel</em> is? A linked list using a sentinel node for <code>start</code> could avoid the special cases of most of the methods above.</p>\n\n<hr>\n\n<pre><code> def bubble_sort_exdata(self):\n \"\"\"\n Bubble sorts the linked list with respect to data\n \"\"\"\n</code></pre>\n\n<p>The meaning of \"<em>with respect to data</em>\" is not transparent to me. I only figured it out once I looked at the implementation.</p>\n\n<pre><code> while end != self.start.link:\n p = self.start\n while p.link != end:\n q = p.link\n if p.info > q.info:\n p.info, q.info = q.info, p.info\n p = p.link\n end = p\n</code></pre>\n\n<p>So far I've resisted the temptation to comment on names, because you said that they're following the tutorial, but I find <code>end</code> to be very misleading. I would expect it to be the last node in the list, whereas in effect it's a sentinel for the end of the <em>unsorted</em> portion of the list.</p>\n\n<hr>\n\n<pre><code> def bubble_sort_exlinks(self):\n ...\n while end != self.start.link:\n r = p = self.start\n while p.link != end:\n q = p.link\n if p.info > q.info:\n p.link = q.link\n q.link = p\n if p != self.start:\n r.link = q.link\n else:\n self.start = q\n p, q = q, p\n r = p\n p = p.link\n end = p\n</code></pre>\n\n<p>This is rather complex. I could use some comments to explain the loop invariants and the meanings of <code>p,q,r</code>.</p>\n\n<hr>\n\n<pre><code> def merge1(self, list2):\n \"\"\"\n Merges two already sorted single linked lists by creating new lists\n \"\"\"\n merge_list = SingleLinkedList()\n merge_list.start = self._merge1(self.start, list2.start)\n return merge_list\n\n def _merge1(self, p1, p2):\n \"\"\"\n Private method of merge1\n \"\"\"\n if p1.info <= p2.info:\n</code></pre>\n\n<p>What if <code>p1 is None</code> or <code>p2 is None</code>? I don't see anything which would prevent those cases arising.</p>\n\n<pre><code> StartM = Node(p1.info)\n</code></pre>\n\n<p>This could be just <code>self.start</code> instead of <code>StartM</code> if called with a different <code>self</code>. At present the method doesn't use <code>self</code> at all.</p>\n\n<hr>\n\n<pre><code> def merge2(self, list2):\n \"\"\"\n Merges two already sorted single linked lists in place in O(1) of space\n \"\"\"\n</code></pre>\n\n<p>This should say something about the process being destructive to <code>this</code> and <code>list2</code>. And it would arguably make more sense to merge <code>list2</code> into <code>self</code> and not return anything.</p>\n\n<pre><code> def _merge2(self, p1, p2):\n \"\"\"\n Merges two already sorted single linked lists in place in O(1) of space\n \"\"\"\n if p1.info <= p2.info:\n</code></pre>\n\n<p>Same bug as <code>_merge1</code>.</p>\n\n<hr>\n\n<pre><code># Testing\n\nif __name__ == '__main__':\n</code></pre>\n\n<p>That's good, but it might be better to use <code>doctest</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T11:02:08.020",
"Id": "226998",
"ParentId": "226955",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "226998",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T21:34:46.960",
"Id": "226955",
"Score": "2",
"Tags": [
"python",
"beginner",
"algorithm",
"sorting",
"complexity"
],
"Title": "In-Place Merging of Two Bubble Sorted Linked Lists (Python)"
}
|
226955
|
<p>One function of a program I'm working with benefits from using all available openMP threads. The rest of the program has issues with the env variable <code>OMP_NUM_THREADS</code> being unequal to 1.</p>
<p>I'm currently using the following solution to that, and was wondering whether there were any caveats or room for improvement here. I haven't worked much with context managers yet, and greatly appreciate any help/pointers. Thanks!</p>
<pre class="lang-py prettyprint-override"><code>import os
import multiprocessing as mp
class MaxOMP:
def __enter__(self):
os.environ["OMP_NUM_THREADS"] = str(mp.cpu_count())
def __exit__(self, exc_type, exc_val, exc_tb):
os.environ["OMP_NUM_THREADS"] = "1"
def main():
with MaxOMP():
run_omp_intensive_job()
</code></pre>
|
[] |
[
{
"body": "<p>Instead of <code>MaxOMP</code> as a name, I like <code>MaxOmp</code> - in general still CamelCase your names even if they include an acronym.</p>\n\n<p>Additionally, there isn't any reason why this needs to be restricted to any particular environment variable. As such, I would probably make this:</p>\n\n<pre><code>class EnvironmentVariableContextManager:\n\n _base_value = None\n _variable = None\n\n def __init__(self, variable_name, value):\n self.variable = variable_name\n self.target_value = value\n\n @property\n def variable(self):\n return self._variable\n\n @variable.setter\n def variable(self, name):\n self._base_value = os.environ.get(name, None)\n\n if self._base_value is None:\n raise Exception(f\"{name} is not a valid environment variable\")\n\n self._variable = name\n\n @property\n def original_value(self):\n return self._base_value\n\n def __enter__(self):\n os.environ[self.variable] = self.target_value\n\n def __exit__(self, *):\n os.environ[self.variable] = self.original_value\n</code></pre>\n\n<p>This has a few benefits:</p>\n\n<ul>\n<li>We use properties to properly encapsulate access and add some extra validation (if you don't care about invalid environment variables feel free to remove that)</li>\n<li>We restore it to the original value, not some hardcoded value. You could also provide a way to specify an \"after\" value if that was desirable.</li>\n</ul>\n\n<p>As suggested in the comments, we may have a valid use-case for an environment variable that doesn't currently have a value. In that case, we would remove the exception, and instead do this:</p>\n\n<pre><code>@variable.setter\ndef variable(self, name):\n self._base_value = os.environ.get(name, None)\n self._variable = name\n\ndef __exit__(self, *):\n if self.original_value is None:\n os.environ.pop(self.variable)\n else:\n os.environ[self.variable] = self.original_value\n</code></pre>\n\n<p>Once we have that, then we just inherit.</p>\n\n<pre><code>class MaxOmpThreads(EnvironmentVariableContextManager):\n\n def __init__(self, max_threads=None):\n max_threads = max_threads or mp.cpu_count()\n super().__init__(\"OMP_NUM_THREADS\", max_threads)\n</code></pre>\n\n<p>Another thing to note, is that <a href=\"https://docs.python.org/3/library/os.html#os.environ\" rel=\"nofollow noreferrer\"><code>os.environ</code></a> only reflects the environment variables at the time of Python startup. If this is not what you want then you'll likely need a different solution.</p>\n\n<p>This also may not be thread-safe; if you might have multiple processes working on something at once, and some need one setting and some need another, then you're likely to run into issues. If your program is overall serial, and the pieces that use OMP are well defined and contained, you're probably fine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T10:52:30.347",
"Id": "441534",
"Score": "1",
"body": "Instead of raising an exception, I would find it more intuitive if the context manager would set it on entry and delete it on exit (instead of resetting) in case the variable doesn't exist prior to entry."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T22:04:08.300",
"Id": "226959",
"ParentId": "226956",
"Score": "4"
}
},
{
"body": "<p>You don't need multiprocessing as <code>os</code> already have what you need : <a href=\"https://docs.python.org/3/library/os.html#os.cpu_count\" rel=\"nofollow noreferrer\"><code>os.cpu_count</code></a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T10:23:58.577",
"Id": "226994",
"ParentId": "226956",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226959",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T21:38:53.657",
"Id": "226956",
"Score": "3",
"Tags": [
"python",
"python-3.x"
],
"Title": "Temporary modifying env variables with context manager"
}
|
226956
|
<p>I'm new to Python and want to develop good habits at the beginning. This class takes a string, and then counts the number of vowels and consonants in the word(s). Any advice on how to improve? </p>
<pre><code>class CntVowels:
def __init__(self,string):
self.string = string
self.vowels = [ "a", "e", "i", "o", "u"]
def vowel_count(self):
strings = self.string.lower()
vowels = self.vowels
counter = 0
for letter in strings:
for vowel in vowels:
if letter == vowel:
counter += 1
print("There are {} vowels in this string.".format(counter))
def constant_count(self):
strings = self.string.lower()
vowels = self.vowels
length = len(strings)
counter = 0
for letter in self.string:
for vowel in vowels:
if letter == vowel:
counter += 1
results = length - counter
print("There are {} constants in this string.".format(results))
a = input("enter a string")
CntVowels(a).vowel_count()
CntVowels(a).constant_count()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T00:34:00.667",
"Id": "441469",
"Score": "0",
"body": "Note: You mean “consonants”, not “constants”. I’ve edited the title & question text, but I’ve left the code unchanged."
}
] |
[
{
"body": "<p>Welcome to Python, and welcome to Code Review.</p>\n\n<h2>Classes</h2>\n\n<p>An instance of a class, where only one method is ever called, is not a good class. Instead, use functions.</p>\n\n<pre><code>a = input(\"Enter a string: \")\nvowel_count(a)\nconstant_count(a)\n</code></pre>\n\n<h2>Class Constants & Members</h2>\n\n<p>If you do create a class, and that class has some global constant data, store that on the <code>class</code> itself, not on the instances of the <code>class</code>.</p>\n\n<p>Constants should have <code>UPPERCASE_NAMES</code>, to distinguish them from non-constant data. Moreover, if the data is constant, where possible use non-mutable objects, such as <code>tuple</code> (eg, <code>(..., ..., ...)</code>) over <code>list</code> (eg, <code>[..., ..., ...]</code>).</p>\n\n<p>Non-public members of a class should begin with a single underscore.</p>\n\n<pre><code>class CntVowels:\n\n VOWELS = (\"a\", \"e\", \"i\", \"o\", \"u\")\n\n def __init__(self, string):\n self._string = string\n\n # ...\n</code></pre>\n\n<h2>Eschew <code>.lower()</code></h2>\n\n<p>When attempting to compare strings (or characters) case-insensitively, use <code>.casefold()</code> instead of <code>.lower()</code>. This properly handles many additional oddities, such as the German <code>ß</code> which is equivalent to <code>ss</code>.</p>\n\n<h2><code>x in y</code></h2>\n\n<p>Testing for existence of an item in a container is easily done with the <code>in</code> operator. For example, this code:</p>\n\n<pre><code>for vowel in vowels:\n if letter == vowel:\n counter += 1\n</code></pre>\n\n<p>can be re-written more efficiently as:</p>\n\n<pre><code>if letter in vowels:\n count += 1\n</code></pre>\n\n<h2>A String is a Container</h2>\n\n<p>It could even be re-written as:</p>\n\n<pre><code>if letter in \"aeiou\":\n count += 1\n</code></pre>\n\n<p>since a string is simply a container of letters.</p>\n\n<h2>Non-Vowels are not necessarily Consonants</h2>\n\n<p>Many characters which are not vowels are also not consonants, such as <code>4</code>, <code>&</code>, <code></code> and <code>.</code> to name a few.</p>\n\n<h2>Avoid Name Shadowing</h2>\n\n<p><code>string</code> is not a good variable name, because a module named <code>string</code> exists, and can be imported, and doing so results in the meaning of <code>string</code> changing depending on what is in scope.</p>\n\n<p>It is even reasonable that you’d <code>import string</code> in this program, to get convenient access to all of the <code>string.ascii_lowercase</code> letters.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T05:49:47.630",
"Id": "441504",
"Score": "0",
"body": "Would it be more conventional to count `ß` as one consonant or two?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T15:59:16.670",
"Id": "441596",
"Score": "0",
"body": "@200_success from my limited understanding of German it is one letter. However, Wikipedia says \"The grapheme has an intermediate position between letter and ligature.\" https://en.wikipedia.org/wiki/%C3%9F"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T18:31:34.027",
"Id": "441631",
"Score": "0",
"body": "[Rocket Languages](https://www.rocketlanguages.com/german/lessons/german-consonants) states it (``) is a consonant, which means `.foldcase`, while great for equivalents tests, isn’t so good for consonant counting."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T00:20:58.343",
"Id": "226965",
"ParentId": "226962",
"Score": "4"
}
},
{
"body": "<pre><code>if __name__ == '__main__':\n</code></pre>\n\n<p>use this guard to test your functions at the end of the script in the following way:</p>\n\n<pre><code>if __name__ == '__main__':\n a = input(\"enter a string\")\n CntVowels(a).vowel_count()\n CntVowels(a).constant_count()\n</code></pre>\n\n<p><strong>Functions do not print:</strong> your functions should return values and these values should be indicated in the docstrings example:</p>\n\n<pre><code>def vowel_count(self):\n \"\"\"Return vowel count.\"\"\"\n return len([letter for letter in self.string if letter in self.vowels])\n\ndef consonant_count(self):\n \"\"\"Return consonant count.\"\"\"\n return len([letter for letter in self.string if letter not in self.vowels])\n</code></pre>\n\n<p>There is no need to use a class, for such simple tasks a function is sufficient and the whole code might look like this:</p>\n\n<pre><code>def get_total_count(word):\n \"\"\"Return vowel and consonant count in a word.\"\"\"\n vowels = [letter for letter in word if letter in 'aeiou']\n consonants = [letter for letter in word if letter not in 'aeiou']\n return len(vowels), len(consonants)\n\n\nif __name__ == '__main__':\n word = input('Enter a word: ').lower()\n while not word.isalpha():\n print('Invalid word! Please enter letters only.')\n word = input('Enter a word: ').lower()\n vowel_count, consonant_count = get_total_count(word)\n print(f\"There are ({vowel_count}) vowels and ({consonant_count} consonants) in '{word}'.\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T00:29:01.443",
"Id": "441467",
"Score": "2",
"body": "No. Do not use `len( [ ... ] )`. This is unnecessarily creating a new object (a list), simply to determine the length of said object. `sum(1 for letter in self.string if letter in self.vowels)` while slightly cryptic is a better alternative. More efficient (and even more cryptic) would be `sum(letter in self.vowels for letter in self.string)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T00:30:30.613",
"Id": "441468",
"Score": "0",
"body": "Thank you for pointing this out, a lot of times I feel like I'm over relying on lists and memory to do the work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T08:35:58.847",
"Id": "441513",
"Score": "0",
"body": "@AJNeufeld The second one is actually less efficient (because it sums also the zeros/`False`)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T00:21:00.320",
"Id": "226966",
"ParentId": "226962",
"Score": "3"
}
},
{
"body": "<p>If your class counts not only vowels but also consonants, why call it <code>CntVowels</code>? <code>CntSounds</code> or <code>CntLetters</code> might be more suitable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T02:03:40.317",
"Id": "226971",
"ParentId": "226962",
"Score": "2"
}
},
{
"body": "<p>If you are starting out in Python, you should have a look at it's <a href=\"https://docs.python.org/3/library/\" rel=\"nofollow noreferrer\">standard library</a>. It has many helpful modules. One of them is the <code>[collections][2]</code> module, which contains a <code>[Counter][2]</code> object that, well, counts stuff. You could use it here to count the occurrence of each letter in the given string and calculate the number of consonants and vowels from that. In addition, have a look at the <code>[string][2]</code> module that contains some useful constants.</p>\n\n<p>As said in the other answers, a simple function is enough for this task, no need to make it a class.</p>\n\n<pre><code>import string\nfrom collections import Counter\n\nVOWELS = set(\"aeiou\")\nCONSONANTS = set(string.ascii_lowercase) - VOWELS\n\ndef count_vowels_consonants(s):\n counts = Counter(s.casefold())\n vowels = sum(counts[c] for c in VOWELS)\n consonants = sum(counts[c] for c in CONSONANTS)\n return vowels, consonants\n\nif __name__ == \"__main__\":\n a = input(\"Enter a string: \")\n vowels, consonants = count_vowels_consonants(a)\n other = len(a.casefold()) - vowels - consonants\n print(f\"{vowels} vowels, {consonants} consonants and {other} other characters\")\n</code></pre>\n\n<p>Some other concepts which are useful and contained in this short function:</p>\n\n<ul>\n<li><a href=\"https://wiki.python.org/moin/TimeComplexity\" rel=\"nofollow noreferrer\"><code>in</code> is <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> for <code>list</code>, <code>tuple</code>, <code>str</code> and <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> for <code>set</code> and <code>dict</code></a>. Here it does not matter too much, because <code>len(CONSONANTS) == 21</code>.</li>\n<li><a href=\"https://wiki.python.org/moin/Generators\" rel=\"nofollow noreferrer\">Generator expressions</a> are as easy to use as list comprehensions, but avoid creating a temporary list in memory. Useful if you do something with the items right away (like summing them up, as I am doing here).</li>\n<li><a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\"><code>f-string</code>s, or format strings</a>, are a nice way to easily format output.</li>\n<li>Putting the calling code with the user in-/output behind a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> allows you to import from this script without running the code.</li>\n<li>Tuple unpacking let's you easily return multiple return values from a function and assign them to separate variables. This can get very fancy with <a href=\"https://stackoverflow.com/a/6968451/4042267\">advanced tuple unpacking</a>.</li>\n<li><p>You should always think about edge cases. Here there are several. Some characters convert to multiple characters when being case-folded (e.g. <code>ß</code>), for some characters it might depend on the locale if they are vowels, like <code>äâàãá</code> and some characters are definitely neither vowels, nor consonants, at least all of <code>\\t\\n\\x0b\\x0c\\r !\"#$%&\\'()*+,-./0123456789:;<=>?@[\\\\]^_{|}~</code>. The last category is even larger than the standard alphabet. It contains whitespace, punctuation, digits and other miscellaneous symbols. You can get it with <code>\"\".join(sorted(set(string.printable) - set(string.ascii_letters)))</code>. And this is just ASCII. Since Python strings are unicode strings, this list is actually quite a lot bigger.</p>\n\n<p>Your code currently treats all non-vowels as consonants, which is probably not correct, unless you guarantee that the user-entered string contains only ASCII letters. My code specifically counts the number of consonants via a whitelist of consonants. This way you can at least add a third category <code>other</code>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T09:06:49.977",
"Id": "226987",
"ParentId": "226962",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T23:48:07.860",
"Id": "226962",
"Score": "5",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Counting consonants and vowels"
}
|
226962
|
<p>I've been trying to make a work-around for global usage; however, I can't seem to find an alternative.</p>
<p>I'd like to create a C++ suffix function which converts pixels to millimeters. A custom gui library I've been developing separates OS calls and the actual widget system in two separate headers (IoC); therefore, I do not have access to system-level DPI calls when creating widgets (which is when I'd want to use the suffix function). A kludgey work-around I've considered is maintaining a global variable / singleton. For example:</p>
<pre><code>// widgets.h
...
class SystemProperties { // ! << SINGLETON CLASS HERE
std::pair<double, double> dpi = {1, 1};
SystemProperties() {}
static auto self() -> SystemProperties& {
static SystemProperties system_properties;
return system_properties;
}
public:
static auto set_dpi(const decltype(dpi)& dpi) {
SystemProperties::self().dpi = dpi;
}
static auto get_dpi_x() { return SystemProperties::self().dpi.first; }
static auto get_dpi_x() { return SystemProperties::self().dpi.second; }
};
double operator"" _inch_x(long double value) {
return value * SystemProperties::get_dpi_x(); // ! << GLOBAL USAGE HERE
}
double operator"" _inch_y(long double value) {
return value * SystemProperties::get_dpi_y(); // ! << GLOBAL USAGE HERE
}
...
</code></pre>
<pre><code>
// win32_implementation.h
#include "widgets.h"
...
auto init() {
UINT dpiX, dpiY;
GetDpiForMonitor(
::MonitorFromWindow(::GetDesktopWindow(), MONITOR_DEFAULTTOPRIMARY),
MDT_EFFECTIVE_DPI, &dpiX, &dpiY);
SystemProperties::set_dpi({dpiX, dpiY}); // ! << GLOBAL USAGE HERE
}
...
</code></pre>
<p>Of course I could implement some kind of additional IoC that does dpi conversion, but that would miss the point of being able to use the suffix operator. Perhaps I am getting too hung up on that function? What are some other work-arounds if possible?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:00:16.163",
"Id": "441556",
"Score": "1",
"body": "Just a warning about code review, any time the code contains `...` the question is likely to be closed as off topic. It is very difficult to review partial code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:00:49.230",
"Id": "441557",
"Score": "0",
"body": "This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. [Questions should include a description of what the code does](//codereview.meta.stackexchange.com/q/1226) and the code should be complete enough to be reviewable. This is currently missing too much context I think, although clarification of the post may alleviate that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:02:56.243",
"Id": "441560",
"Score": "0",
"body": "If you're using classes, why don't you instantiate the class and only access the member variables? What made you pick this solution instead? If you need to set global settings that you can't workaround because they're external, well, tough luck, there is no alternative for global usage. But that would be obvious, so I suppose you got another problem somewhere."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T17:31:34.037",
"Id": "441621",
"Score": "0",
"body": "@pacmaninbw I see I'll be working on an edit later tonight, appreciate the advice."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T00:07:01.663",
"Id": "226964",
"Score": "1",
"Tags": [
"c++",
"dependency-injection",
"singleton"
],
"Title": "Usage of global variable for dynamic value that must be declared compile time"
}
|
226964
|
<p>I need to select "random" elements from a collection. Random is quoted because I must assign a weight to each element; elements with higher weights have a greater chance of being selected.</p>
<p>To achieve this, I wrote the classes described below. I'd like to have my code reviewed in order to feel more secure that it is working as intended*</p>
<p>Obs: I store the accumulated probabilities as a field, making the class non-static, because I often need to choose multiple items (always with replacement) from a given pair (items, weights); and performing all the checks / computations is costly.</p>
<p>By the way, I just asked this same question a few moments ago, but I was using floats (that ranged from 0 to 1 and had to sum to 1) to model the weights; and someone asked in a comment why not use ints... I scratched my head and rewrote the whole thing using ints; it made such a big difference (the code became far simpler and cleaner) that I decided to re-ask the question, but now using ints.</p>
<pre><code>namespace Minotaur.Random {
using System;
using System.Linq;
public sealed class BiasedOptionChooser<T> {
private readonly T[] _options;
private readonly int[] _weights;
private readonly int _sumOfWeights;
private BiasedOptionChooser(T[] options, int[] weights, int sumOfWeights) {
_options = options;
_weights = weights;
_sumOfWeights = sumOfWeights;
}
public static BiasedOptionChooser<T> Create(T[] options, int[] weights) {
if (options is null)
throw new ArgumentNullException(nameof(options));
if (weights is null)
throw new ArgumentNullException(nameof(weights));
if (options.Length != weights.Length)
throw new ArgumentException(nameof(options) + " and " + nameof(weights) + " must have the same length.");
if (options.Length == 0)
throw new ArgumentException(nameof(options) + " can't be empty.");
for (int i = 0; i < weights.Length; i++) {
if (weights[i] <= 0)
throw new ArgumentException(nameof(weights) + " can't contain non-positive values.");
}
var optionsAndProbabilities = new (T option, int weight)[options.Length];
for (int i = 0; i < optionsAndProbabilities.Length; i++)
optionsAndProbabilities[i] = (option: options[i], weight: weights[i]);
return FromWeightedOptions(optionsAndProbabilities);
}
private static BiasedOptionChooser<T> FromWeightedOptions((T option, int weight)[] weightedOptions) {
var sortedWeightedOptions = weightedOptions
.OrderBy(op => op.weight)
.ToList();
var options = new T[sortedWeightedOptions.Count];
var weights = new int[sortedWeightedOptions.Count];
var sumOfWeights = 0;
/* option A, weight 10
* option B, weight 10
* option C, weight 30
*
* weights are stored in this way
* [10, 20, 50]
*
* We then roll a dice between 0 and 50
* if dice < 10, we choose option a
* if dice < 20, we choose option b
* else we chose option c
*/
for (int i = 0; i < sortedWeightedOptions.Count; i++) {
var (option, weight) = sortedWeightedOptions[i];
sumOfWeights += weight;
options[i] = option;
weights[i] = sumOfWeights;
}
return new BiasedOptionChooser<T>(
options: options,
weights: weights,
sumOfWeights: sumOfWeights);
}
public T GetRandomChoice() {
var probability = ThreadStaticRandom.Int(
inclusiveMin: 0,
exclusiveMax: _sumOfWeights);
// @Improve performance by utilizing BinarySearch
for (int i = 0; i < _weights.Length - 1; i++) {
if (probability < _weights[i])
return _options[i];
}
return _options[_options.Length - 1];
}
}
}
</code></pre>
<p>The code for the <a href="https://codereview.stackexchange.com/questions/226485/thread-safe-convenient-and-performant-random-number-generator/226489#226489">ThreadStaticRandom</a> can be found here (another codereview post).</p>
<p>Usage example:</p>
<pre><code>private CategoricalFeatureTest FromCategorical(CategoricalDimensionInterval cat) {
var featureIndex = cat.DimensionIndex;
var possibleValues = cat.SortedValues;
var weights = new int[possibleValues.Length];
for (int i = 0; i < weights.Length; i++) {
var frequency = Dataset.GetFeatureValueFrequency(
featureIndex: featureIndex,
featureValue: possibleValues[i]);
weights[i] = frequency;
}
var chooser = BiasedOptionChooser<float>.Create(
options: possibleValues,
weights: weights);
var value = chooser.GetRandomChoice();
return new CategoricalFeatureTest(
featureIndex: cat.DimensionIndex,
value: value);
}
</code></pre>
<p>Poorly-written test example</p>
<pre><code>public static int Main(string[] args) {
var total = 1000 * 1000 * 1000;
var chooser = BiasedOptionChooser<char>.Create(
options: new char[] { 'a', 'b', 'c' },
weights: new int[] { 37, 13, 50 });
var aCount = 0;
var bCount = 0;
var cCount = 0;
for (int i = 0; i < total; i++) {
var choosen = chooser.GetRandomChoice();
if (choosen == 'a')
aCount += 1;
else if (choosen == 'b')
bCount += 1;
else if (choosen == 'c')
cCount += 1;
else
throw new InvalidOperationException();
}
Console.WriteLine($"a ratio: {(double) aCount / total}");
Console.WriteLine($"b ratio: {(double) bCount / total}");
Console.WriteLine($"c ratio: {(double) cCount / total}");
return 0;
}
</code></pre>
<p>Test output:</p>
<pre><code>a ratio: 0.369988021
b ratio: 0.129995958
c ratio: 0.500016021
C:\Program Files\dotnet\dotnet.exe (process 8232) exited with code 0.
Press any key to close this window . .
</code></pre>
<p>.</p>
<p>*I'm also writing tests, but having others read and discuss the code is quite nice / reassuring.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T04:47:51.650",
"Id": "441501",
"Score": "1",
"body": "_I'm also writing tests, but having others read and discuss the code is quite nice / reassuring_ Feel free to include the unit tests you have written, that would also make it easier for us to verify your code :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T05:47:55.253",
"Id": "441503",
"Score": "1",
"body": "Your tests would also help us to understand how you are going to use this and maybe try this out ourselfes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T05:51:44.940",
"Id": "441505",
"Score": "1",
"body": "Could you include `ThreadStaticRandom`? This one is missing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T12:02:07.440",
"Id": "441548",
"Score": "0",
"body": "@t3chb0t I have edited the question to include a link to ThreadStaticRandom"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T13:30:07.637",
"Id": "441737",
"Score": "1",
"body": "@dfhwze I added one of the tests I wrote and its outpout to the question."
}
] |
[
{
"body": "<p>I don't have a whole lot to say. It looks sound and is easy to read.</p>\n\n<p>I'm not sure the big comment explaining how it works is necessarily in the right place, but that doesn't really bother me since the method is compact enough already.</p>\n\n<h2>API</h2>\n\n<p>It would be nice to provide a method like <code>FromWeightedOptions</code> as part of the public API. Personally I wouldn't use a tuple for the public part, but this would allow you to accept an <code>IEnumerable/IReadOnlyList<WeightedChoice<T>></code> or something which would reduce the effort of using the type.</p>\n\n<p>The validation in <code>Create</code> looks good, though you might want to provide the argument name to the <code>ArgumentException</code>s: it just makes it a little quicker to scan when it's thrown. One more thing worth checking is overflows: if the total weight is too large, then the class will fail in an unhelpful way.</p>\n\n<p>Everything that should be hidden is hidden, and using <code>ThreadStaticRandom</code> it should work fine from multiple threads. I would really expect a class like this to take a <code>Random</code> instance in the constructor, but clearly you don't want this for your purposes, and I think providing both options in the exact same class would be a bad idea.</p>\n\n<p>Inline documentation would of course be nice. The decision to not support zero-weight options seems fine to me (though I probably would if I were writing this for general use), but definitely needs to be documented.</p>\n\n<h2>Efficiency</h2>\n\n<p>There is no need to sort your options before building the data-structure. In fact, by sorting in ascending order, you are maximising the number of comparisons required to sample from choices with the linear scan, so if anything it is counter productive.</p>\n\n<p>In case you are not aware, <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.array.binarysearch?view=netframework-4.8\" rel=\"nofollow noreferrer\"><code>Array.BinarySearch</code></a> is a thing, so it's little effort to make the sampling time complexity logarithmic in the number of choices.</p>\n\n<p>An alternative method that will give you sort-of constant time sampling is the <a href=\"https://en.wikipedia.org/wiki/Alias_method\" rel=\"nofollow noreferrer\">Alias Method</a>. It's a Monte-Carlo method, so you can't know how many random number you will need to sample, but for very large collections it could be important.</p>\n\n<h2>Misc</h2>\n\n<ul>\n<li><p>You can simplify <code>optionsAndProbabilities</code> to <code>optionsAndProbabilities = options.Zip(weight, (o, w) => (option: options[i], weight: weights[i])).ToArray()</code> (or something like that, I haven't tested it)</p></li>\n<li><p>I'd be inclined to remove <code>_sumOfWeights</code> from the constuctor: it's strictly redundant with the last element of <code>weights</code>, so I would just acquire it from there.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:43:39.873",
"Id": "441573",
"Score": "0",
"body": "Removing sorting would change the behaviour because `GetRandomChoice` is falling back to _max_ or _last_ item when there was no hit. I think without sorting it would require to rework this method too which currently should be called `GetRandomOrMax` or `GetRandomOrLast`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:55:26.460",
"Id": "441578",
"Score": "1",
"body": "It's returning the last options (coincidentally the one with max chance) not because there's is no hit, but because it must me it, since it's not any of the other options. Notice that I'm not iterating over the entire array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T14:15:15.317",
"Id": "441583",
"Score": "0",
"body": "@Trauer yeah... I considered mentioning that: I'd probably prefer to remove the last-element special case, and instead throw if I exit the loop. That way if the loop is broken, the code throws instead of pretending it is still working."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T15:05:02.663",
"Id": "441586",
"Score": "0",
"body": "But ._. isn't it guaranteed to work? If I'm generating a number between X and Y; am I not guaranteed that the number is between X and Y?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T15:11:06.790",
"Id": "441588",
"Score": "0",
"body": "@Trauer if the code works, yes. But if someone comes along and breaks the code so that it no longer does so, the return at the end will quietly return the last entry. If instead you removed the special case and throw, the code will be simpler (so less likely to go wrong) and if the code is broken in such a way that it doesn't always return from within the loop, then it will throw and immediately tell you that it is broken. I don't think this is a very day/night matter, which is why I didn't put it in the answer, but I'd hope if I were writing the code I would go with the throw."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T13:33:16.610",
"Id": "441740",
"Score": "0",
"body": "I'm aware of the BinarySearch existence (and implementation in the framework), but I'm not sure if for small arrays it will out-perform a linear search. I oughta benchmark it.\nAnyway, I totally forgot (or was unware of) the Alias Method. Thank you a ton for the suggestion!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T09:47:21.483",
"Id": "226990",
"ParentId": "226968",
"Score": "4"
}
},
{
"body": "<h3>Addendum</h3>\n\n<p>I noticed VisualMelon also suggested this:</p>\n\n<blockquote>\n <p><em>Personally I wouldn't use a tuple for the public part, but this would allow you to accept an <code>IEnumerable</code>/<code>IReadOnlyList<WeightedChoice<T>></code> or\n something which would reduce the effort of using the type.</em></p>\n</blockquote>\n\n<p>I would just like to express why I think this is an important point, both from the view as a consumer, and as a maintenance developer of the API.</p>\n\n<h2>Usability</h2>\n\n<p>As consumer of your API, I need to create two lists and have to manage that the items across lists are synchronized.</p>\n\n<pre><code>var chooser = BiasedOptionChooser<char>.Create(\n options: new char[] { 'a', 'b', 'c' },\n weights: new int[] { 37, 13, 50 });\n</code></pre>\n\n<p>In my object-oriented world, I would rather have related data grouped together in a class.</p>\n\n<pre><code>var chooser = BiasedOptionChooser<char>.Create(\n new[] { \n new Option<char>('a', 37), \n new Option<char>('b', 13), \n new Option<char>('c', 50) });\n</code></pre>\n\n<h2>Maintenance</h2>\n\n<p>As developer maintaining your code, I like the idea of this class <code>Option</code>. If ever we need to extend the functionality of the algorithm, we'd only have to add a property to the class, without having to change the signature! This makes versioning and handling compatibility issues easier.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T14:11:47.197",
"Id": "227090",
"ParentId": "226968",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226990",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T00:43:06.633",
"Id": "226968",
"Score": "3",
"Tags": [
"c#",
"random",
"statistics"
],
"Title": "BiasedOptionChooser<T>: a class to do “weighted random choices”"
}
|
226968
|
<p>Until today, in the few cases where I needed something like this, it had been in simple programs which only I used, and where I didn't care about security, so I used the simple <code>atoi()</code>.</p>
<p>However, today I needed to do that for a some more serious program, and I researched about the many different forms that are out there to go from a string to a number: <a href="https://stackoverflow.com/q/22865622/6872717">atoi vs atol vs strtol vs strtoul vs sscanf</a></p>
<p>None of those pleased me. <code>strtol()</code> (and its family) is the safest standard one and also a very fast one, but it is incredibly difficult to use, so I decided to write a safe and simple interface to it. <code>strtoi()</code> (libbsd) is easier to use than <code>strtol()</code>, but still a bit complicated. I decided to use fixed-width integers, as I do in all my code. I also did an interface for <code>strtof()</code> and company.</p>
<p>Requisites:</p>
<ul>
<li><strong>libbsd</strong> (The following code can be written in terms of <code>strtol()</code> instead of <code>strtoi()</code> if libbsd is not available, but it is more complex, and has a problem with <code>errno</code> which <code>strtoi()</code> hasn't).</li>
<li>GNU C11 (not actually needed, but I use it for added safety/optimizations).</li>
</ul>
<hr>
<p>Signed integers:</p>
<p><code>strtoi_s.h</code>:</p>
<pre><code>#pragma once /* libalx/base/stdlib/strto/strtoi_s.h */
#include <errno.h>
#include <inttypes.h>
#include <stddef.h>
#include <stdint.h>
__attribute__((nonnull, warn_unused_result))
inline
int strtoi8_s (int8_t *restrict num, const char *restrict str,
int base);
__attribute__((nonnull, warn_unused_result))
inline
int strtoi16_s (int16_t *restrict num, const char *restrict str,
int base);
__attribute__((nonnull, warn_unused_result))
inline
int strtoi32_s (int32_t *restrict num, const char *restrict str,
int base);
__attribute__((nonnull, warn_unused_result))
inline
int strtoi64_s (int64_t *restrict num, const char *restrict str,
int base);
inline
int strtoi8_s (int8_t *restrict num, const char *restrict str,
int base)
{
int rstatus;
*num = strtoi(str, NULL, base, INT8_MIN, INT8_MAX, &rstatus);
switch (rstatus) {
case 0:
return 0;
case ENOTSUP:
return rstatus;
case ECANCELED:
case EINVAL:
case ERANGE:
default:
return -rstatus;
}
}
inline
int strtoi16_s (int16_t *restrict num, const char *restrict str,
int base)
{
int rstatus;
*num = strtoi(str, NULL, base, INT16_MIN, INT16_MAX, &rstatus);
switch (rstatus) {
case 0:
return 0;
case ENOTSUP:
return rstatus;
case ECANCELED:
case EINVAL:
case ERANGE:
default:
return -rstatus;
}
}
inline
int strtoi32_s (int32_t *restrict num, const char *restrict str,
int base)
{
int rstatus;
*num = strtoi(str, NULL, base, INT32_MIN, INT32_MAX, &rstatus);
switch (rstatus) {
case 0:
return 0;
case ENOTSUP:
return rstatus;
case ECANCELED:
case EINVAL:
case ERANGE:
default:
return -rstatus;
}
}
inline
int strtoi64_s (int64_t *restrict num, const char *restrict str,
int base)
{
int rstatus;
*num = strtoi(str, NULL, base, INT64_MIN, INT64_MAX, &rstatus);
switch (rstatus) {
case 0:
return 0;
case ENOTSUP:
return rstatus;
case ECANCELED:
case EINVAL:
case ERANGE:
default:
return -rstatus;
}
}
</code></pre>
<p>Unsigned integers:</p>
<p>It's mostly the same as the previous one, so I'll post only a function</p>
<p><code>strtou_s.h</code>:</p>
<pre><code>inline
int strtou8_s (uint8_t *restrict num, const char *restrict str,
int base)
{
int rstatus;
*num = strtou(str, NULL, base, 0, UINT8_MAX, &rstatus);
switch (rstatus) {
case 0:
return 0;
case ENOTSUP:
return rstatus;
case ECANCELED:
case EINVAL:
case ERANGE:
default:
return -rstatus;
}
}
</code></pre>
<p>Floating-point:</p>
<p><code>strtof_s.h</code>:</p>
<pre><code>#pragma once /* libalx/base/stdlib/strto/strtof_s.h */
#include <errno.h>
#include <stdlib.h>
/*
* `errno` needs to be cleared before calling these functions. If not, false
* negatives could happen (the function succeds, but it reports error).
*/
__attribute__((nonnull, warn_unused_result))
inline
int strtod_s (double *restrict num, const char *restrict str);
__attribute__((nonnull, warn_unused_result))
inline
int strtof_s (float *restrict num, const char *restrict str);
__attribute__((nonnull, warn_unused_result))
inline
int strtold_s (long double *restrict num, const char *restrict str);
inline
int strtod_s (double *restrict num, const char *restrict str)
{
char *endptr;
*num = strtod(str, &endptr);
if (*endptr != '\0')
return ENOTSUP;
if (errno == ERANGE)
return ERANGE;
if (str == endptr)
return -ECANCELED;
return 0;
}
inline
int strtof_s (float *restrict num, const char *restrict str)
{
char *endptr;
*num = strtof(str, &endptr);
if (*endptr != '\0')
return ENOTSUP;
if (errno == ERANGE)
return ERANGE;
if (str == endptr)
return -ECANCELED;
return 0;
}
inline
int strtold_s (long double *restrict num, const char *restrict str)
{
char *endptr;
*num = strtold(str, &endptr);
if (*endptr != '\0')
return ENOTSUP;
if (errno == ERANGE)
return ERANGE;
if (str == endptr)
return -ECANCELED;
return 0;
}
</code></pre>
<hr>
<p>The functions take two pointers: the first one to the variable where the number has to be stored; and the second one to the string to be read. The integer functions also require the base, which follows the same rules as in <code>strtol()</code>.</p>
<p>The return value is simply an error code:</p>
<p><code>0</code> is OK as always,</p>
<p><code>> 0</code> means a valid conversion with some error (partial conversion, 0 or inf in floating-point, ...).</p>
<p><code>< 0</code> means an invalid conversion, or no conversion at all.</p>
<p>Example:</p>
<pre><code>char buf[BUFSIZ];
int64_t num;
if (!fgets(buf, ARRAY_SIZE(buf), stdin))
goto err;
if (strtoi64_s(&num, buf, 0))
goto err;
/* num is safe to be used now*/
</code></pre>
<p>Do you think the interface can be improved in any way? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T23:42:37.180",
"Id": "442477",
"Score": "0",
"body": "\"(strtol) is more complex, and has a problem with errno\" and \"I also did an interface for strtof() and company.\" is curious. `strtof()` and family is harder/more complex to use than `strtol()`. If code can well handle `strofd()` with all its issues, `strtol()` is relatively easy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T10:57:03.637",
"Id": "442542",
"Score": "0",
"body": "@chux By more complex I meant that you have to handle more than one variable, as with `strtof()`, not extremely more complex. And it has the added problem that I already have with `strtof_s()`: if `errno` isn't reset, the return value is wrong, but it's also a minor problem. Not something very problematic, of course, but I prefer to avoid it even if it means using less portable code."
}
] |
[
{
"body": "<ul>\n<li><p>The main advantage of <code>strtol</code> and family is that they compute (for free!) the point where the conversion ended. It is a very valuable information, because usually after extracting the number you want to continue parsing. Your wrappers throw it away.</p></li>\n<li><p>DRY. The switches (which compute <code>result</code>) for integral types is identical. Factor it out into a function.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T19:44:49.713",
"Id": "441650",
"Score": "0",
"body": "Good points. For the first point, I could add a parameter `ptrdiff_t *read` at the end and use `nonnull(1, 2)`, so that the user can read it or ignore it passing `NULL` (a `char **` would be another possibility, but I prefer the length, and they're easily interchangeable)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T00:27:42.193",
"Id": "441674",
"Score": "0",
"body": "For the second one, I will use a helper `int strtoi_status(int rstatus);`. BTW, for the floating point status computation I will also write a helper: `int strtof_status(const char *restrict str,\n const char *restrict endptr, int _errno);`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T18:15:29.767",
"Id": "227032",
"ParentId": "226969",
"Score": "3"
}
},
{
"body": "<p><strong>Portability</strong></p>\n\n<p>To be clear, <code>strtoi()</code> and <code>strtou()</code> that OP's code relies on is not in the standard C library. OP's code is limited to the requisites.</p>\n\n<p><code>strtol()</code> may be more complex, yet it is portable throughout all compliant C implementations.</p>\n\n<p><strong>Bug - failure to clear <code>errno</code></strong></p>\n\n<p>When <code>strtod()</code> succeeds, it does not change <code>errno</code>, so the tests on <code>errno</code> are testing the prior state. Add <code>errno = 0;</code> before calling <code>strtod()</code>, <code>strtof()</code>, <code>strtold()</code>.</p>\n\n<pre><code> errno = 0; // add\n *num = strtod(str, &endptr);\n if (*endptr != '\\0') return ENOTSUP;\n if (errno == ERANGE) return ERANGE;\n ...\n</code></pre>\n\n<p><strong>Questionable error</strong></p>\n\n<p>With floating point conversions, input like <code>\"z\"</code>, the functions indicate <code>ENOTSUP</code>. I'd expect <code>ECANCELED</code></p>\n\n<p>Rather than</p>\n\n<pre><code> if (*endptr != '\\0') return ENOTSUP;\n if (errno == ERANGE) return ERANGE;\n if (str == endptr) return -ECANCELED;\n</code></pre>\n\n<p>Consider </p>\n\n<pre><code> if (str == endptr) return -ECANCELED;\n if (*endptr != '\\0') return ENOTSUP;\n if (errno == ERANGE) return ERANGE;\n</code></pre>\n\n<p><strong>Questionable cases</strong></p>\n\n<p>With <code>\"1.0e100000\"</code>? A floating point value with infinity with an <code>ERANGE</code> error?</p>\n\n<p>With <code>\"INF\"</code>? A floating point value with infinity with an no error?</p>\n\n<p><strong>Careful about <code>ERANGE</code> on the small side</strong></p>\n\n<p>When the string indicates a small value like <code>1e-100000</code>, this may or may not set <code>errno = ERANGE</code>.</p>\n\n<p>C allows that. C also allows <code>errno</code> to not be set on <em>underflow</em>.</p>\n\n<p><a href=\"https://linux.die.net/man/3/strtod\" rel=\"nofollow noreferrer\">Linux man</a> has \"If the correct value would cause underflow, zero is returned and ERANGE is stored in errno.\"</p>\n\n<p>It is unclear to me what <code>libbsd</code> or OP wants in this case.</p>\n\n<hr>\n\n<p>There are additional issues anytime the string would convert to a value smaller in magnitude than <code>DBL_MIN</code>. This lack of crispness in <code>strtod()</code> specification renders <em>string</em> in the converted range of <code>DBL_MIN</code> and <code>DBL_TRUE_MIN</code> troublesome.</p>\n\n<p><strong>String to number design</strong></p>\n\n<p>Most string to number functions tolerate leading spaces. I find it curious that most such functions do not well tolerate trailing white-space.</p>\n\n<p>IMO, such functions should - very convenient for reading and converting a <em>line</em> of input like <code>\"123\\n\"</code>. Perhaps as:</p>\n\n<pre><code>number = strto*(string, &endptr);\n\nif (string == endptr) return fail_no_conversion;\nwhile (isspace((unsigned char) *endptr)) {\n endptr++;\n}\n// Now test for null character\nif (*endptr) return fail_junk_at_the_end;\n...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T11:07:28.277",
"Id": "442543",
"Score": "0",
"body": "*Bug - failure to clear `errno`*: I prefer to not clear `errno` in any of my library functions, just as standard library functions do. For that reason I wrote the note acknowledging the bug. Nevertheless, it's unlikely to find `errno` already with the value `ERANGE` without knowing just before calling this function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T11:10:49.277",
"Id": "442544",
"Score": "0",
"body": "*Questionable error*: Very good point!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T11:13:43.910",
"Id": "442545",
"Score": "0",
"body": "*Questionable cases*: My point there is that is you wrote `\"INF\"` the variable stores exactly what you meant, but if you wrote `\"1.0e100000\"` it has lost some important information, so a positive return value indicates that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T11:28:47.737",
"Id": "442548",
"Score": "0",
"body": "*Trailing white-space:* very good point!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T13:31:56.240",
"Id": "442570",
"Score": "0",
"body": "@CacahueteFrito Re: [unlikely to find errno already with the value `ERANGE`](https://codereview.stackexchange.com/questions/226969/safe-and-simple-strtol/227362#comment442543_227362) If one calls `strtod_s(too_big)` and it sets `errno=ERANGE`, then next calls to `strtod_s(in_range)` will still have `ERANGE` set. Sounds like you are obliging the caller to clear `errno` with the FP functions, yet not the integer ones - asymmetric functionality. Your call."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T13:51:35.027",
"Id": "442574",
"Score": "0",
"body": "Re:Re: `ERANGE`: Ok, a solution would be to store the value of `errno` in a local variable, and restore it later if it hasn't been set during the call. Would you agree?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T14:24:39.047",
"Id": "442579",
"Score": "0",
"body": "*Careful about `ERANGE` on small side*: POSIX makes it mandatory to set `errno` on underflow: https://pubs.opengroup.org/onlinepubs/009695399/functions/strtof.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T10:55:51.613",
"Id": "442786",
"Score": "1",
"body": "BTW, I did that of the trailing space, and for that it was easier to use good old `strtol()`, so as a side effect it is more portable now :) Also, now all of the functions share the same error handling function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T08:21:20.310",
"Id": "507991",
"Score": "0",
"body": "Also note that fuzzers like to fail in strtol() with non zro-terminated strings. Before calling strtol or sscanf ensure that your string is really a string, i.e. it is zero-terminated. All string functions are unsafe if so."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T23:09:01.653",
"Id": "227362",
"ParentId": "226969",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227362",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T01:30:03.483",
"Id": "226969",
"Score": "6",
"Tags": [
"c",
"formatting",
"api"
],
"Title": "Safe and simple strtol()"
}
|
226969
|
<p>Is there a better way to do this? Assuming very long lists, is this slow and wasteful?</p>
<pre><code>flavors = ['chocolate', 'vanilla', 'caramel', 'strawberry', 'coffee']
for flavor in flavors:
print(flavor, end = ', ' if (flavors.index(flavor) != len(flavors) -1) else '.')
</code></pre>
<p>Output:</p>
<p><code>chocolate, vanilla, caramel, strawberry, coffee.</code></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T10:50:04.790",
"Id": "441533",
"Score": "10",
"body": "Note that it outputs `a, a, a, ` for `[a, a, a]`."
}
] |
[
{
"body": "<p>There is indeed a better way.</p>\n\n<pre><code>flavours = ('chocolate', 'vanilla', 'caramel', 'strawberry', 'coffee')\n\nfor i, flavour in enumerate(flavours):\n if i == len(flavours) - 1:\n end = '.'\n else:\n end = ', '\n print(flavour, end=end)\n</code></pre>\n\n<p>Even better:</p>\n\n<pre><code>print(', '.join(flavours) + '.')\n</code></pre>\n\n<p>The most expensive part of your solution is the call to <code>index</code>. That needs to be avoided because it does a search for the current item on each iteration.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T02:21:32.637",
"Id": "441474",
"Score": "1",
"body": "So index has to do a linear search through the entire list every time, such that the number of operations would be n/2 * (n+1) ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T02:32:44.377",
"Id": "441476",
"Score": "6",
"body": "Correct, but computer scientists instead call that O(n²)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T10:54:53.933",
"Id": "441535",
"Score": "0",
"body": "Between both solutions you proposed, it's possible to use a loop without if. Here's an [example](https://tio.run/##VYxBCsIwEEX3OcWQTVqIgrgr9CTFxRgnNBAzZRIrPX1sJS7cPf7j/WUrM6drrT7iyi/JMEJn3MyOIxYyFsyKKcSIBzoUfFI8MBfB951Etq9g74lMr5RngfYFIf0wT8PpchsUACwSUunaboHSY9QW9J7@mTztQdNn3df6AQ)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:27:02.700",
"Id": "441569",
"Score": "0",
"body": "@EricDuminil Yum, \\$O(n)\\$ memory, doesn't support lists of nothing and it doesn't support iterators! For \\$O(1)\\$ memory, no if and to support iterators you can do it [this way](https://gist.github.com/Peilonrayz/fd7c43f17754406cb85ff004ff5321c7). You can get rid of the if outside the loop with a try if you think that still counts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:44:22.833",
"Id": "441574",
"Score": "1",
"body": "@Peilonrayz: Not my proudest piece of code, I'll give you that :D. It has the merit of being simple and short, and not asking at every iteration \"Are we there yet?\". I'd never use it though, for the reasons you mentioned."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T02:14:42.947",
"Id": "226973",
"ParentId": "226970",
"Score": "10"
}
},
{
"body": "<p>The best solution is to use <a href=\"https://docs.python.org/3/library/stdtypes.html#str.join\" rel=\"nofollow noreferrer\"><code>str.join()</code></a>, using <code>', '</code> as the joining string.</p>\n\n<pre><code>def display(flavours):\n print(', '.join(flavours) + '.')\n</code></pre>\n\n<p>Outputting:</p>\n\n\n\n<pre><code>>>> display(['chocolate', 'vanilla', 'caramel', 'strawberry', 'coffee'])\nchocolate, vanilla, caramel, strawberry, coffee.\n</code></pre>\n\n<p>Comparing this to the two adaptions of my approach, and against AJNeufeld in one of the graphs:</p>\n\n<p><img src=\"https://raw.githubusercontent.com/Peilonrayz/Stack-Exchange-contributions/master/code-review/226974/static/figs/plot-aj.svg?sanitize=true\" alt=\"image\"></p>\n\n<p><img src=\"https://raw.githubusercontent.com/Peilonrayz/Stack-Exchange-contributions/master/code-review/226974/static/figs/plot.svg?sanitize=true\" alt=\"image\"></p>\n\n<p><strong>NOTE</strong>: Code to <a href=\"https://github.com/Peilonrayz/Stack-Exchange-contributions/blob/master/code-review/226974/tests/test_plot.py\" rel=\"nofollow noreferrer\">plot the graphs</a>, <a href=\"https://github.com/Peilonrayz/Stack-Exchange-contributions/tree/master/code-review/226974\" rel=\"nofollow noreferrer\">complete changes</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T02:15:58.593",
"Id": "226974",
"ParentId": "226970",
"Score": "42"
}
},
{
"body": "<h2>TL;DR:</h2>\n\n<p>Despite this being the currently accepted & highest voted answer, these methods from this <a href=\"https://codereview.stackexchange.com/a/226974/100620\">answer</a> and variations (<a href=\"https://codereview.stackexchange.com/a/227026/100620\">1</a>, <a href=\"https://codereview.stackexchange.com/questions/226970/printing-a-list-as-a-b-c-using-python/226976#comment441720_226976\">2</a>) of it:</p>\n\n<pre><code>print(\", \".join(flavours) + \".\") # Peilonrayz\nprint(\", \".join(flavours), end=\".\\n\") # Maarten Fabré\nprint(f'{\", \".join(flavors)}.') # Andy\n</code></pre>\n\n<p>are all faster than the solution originally proposed in this answer:</p>\n\n<pre><code>print(*flavours, sep=', ', end='.\\n')\n</code></pre>\n\n<hr>\n\n<h2>Original Answer, Plus Explanation & Timing Analysis:</h2>\n\n<p>Consider also:</p>\n\n<pre><code>flavours = ['chocolate', 'vanilla', 'caramel', 'strawberry', 'coffee']\nprint(*flavours, sep=', ', end='.\\n')\n</code></pre>\n\n<p>This does not perform any unnecessary string concatenation, nor does it require a loop variable to test for the final index. </p>\n\n<hr>\n\n<p>How does this work?</p>\n\n<p>The print function takes a variable number of arguments, and so would be defined something like:</p>\n\n<pre><code>def print(*args, sep=' ', end='\\n', file=sys.stdout, flush=False):\n # ...\n</code></pre>\n\n<p>except it is a built-in function.</p>\n\n<p>The <code>*args</code> parameter consumes all of the unnamed arguments into one list for processing by the function, allowing the function to take a variable number of arguments.</p>\n\n<p>In the statement,</p>\n\n<pre><code>print(*flavours, sep=', ', end='.\\n')\n</code></pre>\n\n<p>The \"splat operator\" (<code>*</code>) takes the iterable <code>flavours</code> and expands it into a list of arguments for the function, allowing the caller to pass a variable number of arguments to a function, taken from the contents of a container (list, tuple, etc).</p>\n\n<p>The Python interpreter <em>could</em> match the <code>*flavours</code> splat operator with the <code>*args</code> variable argument list of the print function, and simply pass the <code>flavours</code> list into the <code>args</code>.</p>\n\n<p>But does it? I got worried. Perhaps, because a list is given, and the variable argument list (in <code>CPython</code>) is passed as a tuple, the list actually must be copied. How much time does it take.</p>\n\n<p>After creating a <code>class Null</code> output stream, to speed up the printing, I began passing variable sized lists to the various answers, and profiling the results. While my solution is one of the least amounts of code, it turns out that @Peilonrayz's solution of <code>\", \".join(flavours)</code> seems to be the fastest.</p>\n\n<p><a href=\"https://i.stack.imgur.com/6iQKb.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/6iQKb.png\" alt=\"profile results\"></a></p>\n\n<p>Using tuples or lists doesn't seem to affect the performance much, so any thought that splatting a <code>tuple</code> instead of a <code>list</code>, to be collected into a <code>*args</code> variable argument <code>tuple</code> may be optimized to a no-op, seems to have been squashed.</p>\n\n<hr>\n\n<p>Since <code>print</code> will automatically convert objects to strings for printing, the above will work for all object types in a list. The <code>\", \".join(flavours)</code> will only work for strings; it would have to be modified to convert non-strings to strings to be truly equivalent:</p>\n\n<pre><code>print(\", \".join(map(str, flavours)) + \".\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T17:37:05.233",
"Id": "441622",
"Score": "8",
"body": "wow that is some serious science for a list glueing task"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T11:35:47.483",
"Id": "441720",
"Score": "3",
"body": "Wouldn't `print(', '.join(flavours), end='.\\n')` work slightly better, since it wouldn't need to make 2 long strings?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T14:45:58.950",
"Id": "441751",
"Score": "0",
"body": "@MaartenFabré Yes, that would be slightly better. But that comment should be on Peilonrayz's answer. When they update _their answer_ to include your improvement, I'll update the last statement of my answer to keep it _equivalent to theirs_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T15:16:38.033",
"Id": "441763",
"Score": "1",
"body": "Great answer. https://stackoverflow.com/help/how-to-answer should redirect here. Every answer should have an _\"How does this work?\"_ section."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T10:17:31.073",
"Id": "441918",
"Score": "0",
"body": "@tjt263 That's a Stack Overflow link, this is Code Review ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T15:37:17.787",
"Id": "441980",
"Score": "0",
"body": "@Mast It's relevant to all the things, but here: https://codereview.stackexchange.com/help/how-to-answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T02:43:25.157",
"Id": "442039",
"Score": "0",
"body": "When printing, I'm generally not concerned with performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T02:46:02.030",
"Id": "442040",
"Score": "0",
"body": "@I.J.Kennedy The OP asked, “Assuming very long lists, is this slow and wasteful?” so clearly they were concerned with performance."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T04:49:35.980",
"Id": "226976",
"ParentId": "226970",
"Score": "73"
}
},
{
"body": "<p>Using f-strings, which are pretty fast:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>flavors = ['chocolate', 'vanilla', 'caramel', 'strawberry', 'coffee']\n\nprint(f'{\", \".join(flavors)}.')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T18:09:29.543",
"Id": "441627",
"Score": "0",
"body": "Is this really faster than writing `print(\", \".join(flavors) + \".\")` as others have already suggested?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T18:45:52.163",
"Id": "441639",
"Score": "0",
"body": "A tiny bit, yeah. https://imgur.com/JwNJjtp"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T18:47:40.380",
"Id": "441642",
"Score": "1",
"body": "With those error margins it's hard to say."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T18:48:00.907",
"Id": "441643",
"Score": "1",
"body": "That's why I said a *tiny* bit. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T19:58:19.490",
"Id": "441653",
"Score": "2",
"body": "I do not trust a single timeit call, please look at AJNeufeld's edits to see why (those peaks that mean nothing). You should make a graph like AJNeufeld."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T13:32:14.473",
"Id": "441739",
"Score": "3",
"body": "Yeah @Andy you should make graphs like AJNeufeld. Be more like him."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T14:48:17.497",
"Id": "441754",
"Score": "3",
"body": "I've added your answer to my time-plots. Performance seems effectively identical."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T14:57:26.947",
"Id": "441755",
"Score": "0",
"body": "@AJNeufeld makes sense -- the extra speed in f-strings comes from opcodes for the final string format, so the bottleneck is the join."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T14:58:16.323",
"Id": "441756",
"Score": "5",
"body": "@user14492 are you... are you one of my coworkers?"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T17:31:02.653",
"Id": "227026",
"ParentId": "226970",
"Score": "4"
}
},
{
"body": "<p>The built-in print function (in Python 3+) has a <code>sep</code> (separator) argument. Performance is not as good as with <code>str.join</code>, but I just thought I'd mention it. In combination with <code>*</code> argument unpacking:</p>\n\n<p><code>print(*flavours, sep=', ', end='.\\n')</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T15:04:37.240",
"Id": "442259",
"Score": "0",
"body": "Interesting. Do you have any performance numbers to back up this claim, like [here](https://codereview.stackexchange.com/a/226976/100620) or [here](https://codereview.stackexchange.com/a/226974/100620)?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T09:17:50.297",
"Id": "227213",
"ParentId": "226970",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226976",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T02:00:49.887",
"Id": "226970",
"Score": "17",
"Tags": [
"python",
"performance",
"formatting"
],
"Title": "Printing a list as \"a, b, c.\" using Python"
}
|
226970
|
<p>For a long time I've been using Angular "Layout" components so their role is basically to define layout, like padding, margin, fonts and so on.</p>
<p>For instance, page header component:</p>
<pre><code><my-header>My super page</my-header>
</code></pre>
<p>So now this component will have SCSS:</p>
<pre><code>:host {
width: 100%;
display: block;
padding:10px
}
</code></pre>
<p>But it's kind of the same I can achieve with SASS mixins:</p>
<pre><code>@mixin page-header(){
width: 100%;
display: block;
padding:10px
}
</code></pre>
<p>and then I can use it on the page:</p>
<pre><code><div class="page-header">My super page</div>
</code></pre>
<p>and SCSS:</p>
<pre><code>div.page-header{
@include page-header();
}
</code></pre>
<p>I don't see much difference. The only benefit of components would be bundle size, since if mixins are "big" and used in many places then size will be bigger.</p>
<p>My question is, what is the best way to make structural/Layout components? I appreciate any thoughts/recommendation they usually lead to better decisions :)</p>
<p>It's not a question for components like <code><my-header [image]="cat.jpg" [header]="text"></my-header></code>. The questions how it's better to make components which contains mostly CSS.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T09:20:25.120",
"Id": "441518",
"Score": "0",
"body": "Could you include a non-trivial example so we get an idea for which components you would to get a review?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T02:03:42.957",
"Id": "226972",
"Score": "1",
"Tags": [
"angular-2+",
"sass"
],
"Title": "Sass mixins vs Angular layout components"
}
|
226972
|
<p>I'm writing a ctrl+f function so to speak in React that allows a user to search for a term in a list of words, and if the term matches any of the words in the list then it highlights it. To do this, I'm currently using <code>document.querySelectorAll</code> to retrieve all of the words in the list and manipulate them (highlight) if there is a match. Because this is React I feel very bad about using the querySelector to grab the words and feel I should be using refs perhaps, but not sure how comparable that is or if that works in this particular scenario. Here is my code:</p>
<pre><code>const HighlightSearchTerm = () => {
const [searchTerm, setSearchTerm] = React.useState("");
React.useEffect(() => {
const regex = new RegExp(searchTerm, "gi");
const labels = document.querySelectorAll(".label"); // use refs??
labels.forEach(label => {
label.innerHTML = label.innerText.replace(regex, match =>
`<span class="highlight">${match}</span>`
);
});
}, [searchTerm]);
return (
<div>
<input
type="text"
value={searchTerm}
placeholder="Search Labels"
onChange={event => setSearchTerm(event.target.value)}
/>
</div>
);
};
</code></pre>
<p>As you can see, implementing it this way has to also call <code>document.querySelectorAll</code> each time the user types a letter or makes a change which isn't very efficient and is causing <code>[Violation] 'setTimeout' handler took <N>ms</code> to appear in the console many times when working with large lists. Instead, I would like to </p>
<ol>
<li>Not use <code>document.querySelectorAll</code> to retrieve the words in the list (use refs if possible?)</li>
<li>Not fetch the list of words each time I type due to the fact the list won't change once the component is rendered (possibly render them when the component mounts, although it seems I can't do this currently when using querySelector)</li>
</ol>
<p>Any other optimization suggestions would also be very much appreciated.</p>
<p>Current working example: <a href="https://codepen.io/andrewgarrison/pen/eYOWjZB" rel="nofollow noreferrer">https://codepen.io/andrewgarrison/pen/eYOWjZB</a></p>
|
[] |
[
{
"body": "<p>Rather than extract the Search input in to a different component I would suggest you keep the input and list in the same component.</p>\n\n<p>This way when printing the list you can highlight the search term directly.</p>\n\n<pre><code>const HighlightableList = (props) => {\n const [searchTerm, setSearchTerm] = React.useState(\"\");\n const regex = new RegExp(searchTerm, \"gi\");\n\n const items = props.terms.map((term, index) => (\n <div\n className=\"label\"\n key={index}\n dangerouslySetInnerHTML={{\n __html: term.replace(regex, match => `<span class=\"highlight\">${match}</span>`)\n }}\n />\n ));\n\n return (\n <>\n <input \n type=\"text\"\n value={searchTerm}\n placeholder=\"Search Labels\"\n onChange={event => setSearchTerm(event.target.value)}\n />\n <div className=\"label-container\">\n {items}\n </div>\n </>\n );\n}\n</code></pre>\n\n<p><a href=\"https://codepen.io/rockingskier/pen/YzKrGNR\" rel=\"nofollow noreferrer\">https://codepen.io/rockingskier/pen/YzKrGNR</a></p>\n\n<p><em>Side notes:</em></p>\n\n<p>Don't make each list item a <code>label</code>. From <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label\" rel=\"nofollow noreferrer\">MDN</a></p>\n\n<blockquote>\n <p>The HTML element represents a caption for an item in a user interface.</p>\n</blockquote>\n\n<p>That would suggest that each item in the list has its own user input. In fact there is only one input (search) and that should really have a label of its own. I'll let you implement that.</p>\n\n<p>Additionally due the the \"list-iness\" of the data I have converted it to a <code>ul</code> with each item as an <code>li</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T14:21:09.067",
"Id": "227331",
"ParentId": "226975",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227331",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T03:00:57.693",
"Id": "226975",
"Score": "2",
"Tags": [
"performance",
"react.js",
"jsx"
],
"Title": "Highlight strings that match a search term"
}
|
226975
|
<p>I've been searching the internet and cannot find a proper answer as when one should user "Parent" and "Child". I see these two used all over, I have not used them myself in my programs, and now I'm wondering if I have missed something in creating my software. I am wondering why and when should they be used. I've only gathered that they should be used when one class controls another. Only thing I have done in that sense is call another class/window, from a class. Example below.</p>
<pre><code>class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.doSomething
class Child(QtWidgets.QWidget)
def __init__(self, Parent)
super(Child, self).__init__(Parent)
self.doSomething
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T08:35:44.297",
"Id": "441512",
"Score": "1",
"body": "This is more of a question for [Software Engineering Stack Exchange](https://softwareengineering.stackexchange.com/) (if it's about parent/child classes in general) or [Stack Overflow](https://stackoverflow.com/) if it's about these classes specifically in QT."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T09:23:33.830",
"Id": "441519",
"Score": "1",
"body": "We only review real working code. Details matter! In order to give good advice, we need to see real, concrete code, and understand the context in which the code is used. Visit our help center to find out more how to ask a question: https://codereview.stackexchange.com/help/on-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T05:11:13.803",
"Id": "441683",
"Score": "0",
"body": "Thanks anyways. I did not know about Software Engineering Stack Exchange. Only just started using any Stack Exchange."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T05:31:26.867",
"Id": "226978",
"Score": "2",
"Tags": [
"python",
"pyqt"
],
"Title": "Using Parent and Child in PyQt and Python"
}
|
226978
|
<p>I solved this problem from a challenge.The problem is as below:-</p>
<p><strong>Problem Statement:</strong></p>
<p>Given N activities with their start and finish times. Select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a time.</p>
<p><strong>Note :</strong> The start time and end time of two activities may coincide.</p>
<p>Input:
The first line contains T denoting the number of testcases. Then follows description of testcases. First line is N number of activities then second line contains N numbers which are starting time of activies.Third line contains N finishing time of activities.</p>
<p>Output:
For each test case, output a single number denoting maximum activities which can be performed in new line.</p>
<p><strong>Constraints:</strong></p>
<pre><code>1<=T<=50
1<=N<=1000
1<=A[i]<=100
</code></pre>
<p><strong>Example:</strong></p>
<p><strong>Input:</strong></p>
<pre><code>2
6
1 3 2 5 8 5
2 4 6 7 9 9
4
1 3 2 5
2 4 3 6
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>4
4
</code></pre>
<p>C++ code for the problem:-</p>
<pre><code>#include<iostream>
void swap(int a[],int i,int j)
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
int activitySelection(int start[], int end[], int n){
long i,j,count=1,pointer;
for(i=0;i<n;i++) //sorting both arrays in the order of the end array
{
for(j=i+1;j<n;j++)
if(end[j]<end[i])
{
swap(end,i,j);
swap(start,i,j);
}
}
pointer=end[0]; //pointer set to end time of the first activity
for(i=1;i<n;i++)
{
if(start[i]>=pointer) //if
{
count++;
pointer=end[i];
}
}
return count;
}
int main()
{
int t;
std::cin>>t; /*number of testcases*/
while(t--)
{
int n;
std::cin >> n;
int start[n], end[n];
for(int i=0;i<n;i++)
std::cin>>start[i];
for(int i=0;i<n;i++)
std::cin>>end[i];
std:: cout << activitySelection(start, end, n) << std::endl;
}
}
</code></pre>
<p>The code works as I intended to.But there are few openings that i feel could be improved in the code.The above code basically sorts the both arrays according to the end[] array.Then it checks if the starting time of the current activity is greater or equal to the end time of the previous activity,if yes then count increments and the pointer is set to the end time of the current activity for comparing the next activity.Two things i want to know:</p>
<p>1.Is there a better approach than sorting arrays and comparing?</p>
<p>2.What is a better way to sort the two arrays on the basis of the second array?</p>
<p>Please suggest changes to improve.Thanks for reading ;-)</p>
|
[] |
[
{
"body": "<p><strong>Note:</strong> your code doesn't currently compile for at least two reasons: you are not telling the compiler <code>cout</code> and <code>endl</code> live in the <code>std</code> namespace, and you can't declare your arrays <code>start</code> and <code>end</code> because <code>n</code> is not known at compile-time (instead, you'd have to use dynamic memory allocations).</p>\n\n<p>In any case, your code smells like your background might be in C (but then you'd probably also know about dynamic memory... well, anyway). Indeed, with C++, you typically define variables as close to their site of usage. Moreover, you could take advantage of the algorithms and data structures provided by the language.</p>\n\n<blockquote>\n <ol>\n <li>Is there a better approach than sorting arrays and comparing?</li>\n </ol>\n</blockquote>\n\n<p>Essentially no: you must sort the arrays (with no additional knowledge, you can't beat the log-linear bound). This dominates your runtime, but it is scalable and practical enough that you don't have to worry about it.</p>\n\n<blockquote>\n <ol start=\"2\">\n <li>What is a better way to sort the two arrays on the basis of the second array?</li>\n </ol>\n</blockquote>\n\n<p>Because start and end times are logically and tightly coupled (i.e., something is wrong if we suddenly lose the correspondence), it's a good idea to tie them together. For that reason, we can use <a href=\"https://en.cppreference.com/w/cpp/utility/pair\" rel=\"nofollow noreferrer\"><code>std::pair</code></a>. To store such objects, we can use a dynamic array, i.e., <a href=\"https://en.cppreference.com/w/cpp/header/vector\" rel=\"nofollow noreferrer\"><code>std::vector</code></a>. For sorting that according to the second element, we can use <a href=\"https://en.cppreference.com/w/cpp/algorithm/sort\" rel=\"nofollow noreferrer\"><code>std::sort</code></a>.</p>\n\n<p>To summarize, we could proceed along the following lines (I'm taking the liberty to omit reading input to avoid clutter):</p>\n\n<pre><code>#include <iostream>\n#include <algorithm>\n#include <vector>\n\ntypedef std::vector<std::pair<int, int> > PairList;\n\nint activitySelection(const PairList& p) \n{\n PairList s(p);\n std::sort(s.begin(), s.end(), [](const auto& x, const auto& y) {\n return x.second < y.second;\n });\n\n int end = s[0].second;\n int count = 1;\n\n for (int i = 1; i < s.size(); ++i)\n {\n if (s[i].first >= end)\n {\n ++count;\n end = s[i].second;\n }\n }\n\n return count;\n}\n\nint main()\n{\n PairList v{ {1,2},{3,4},{2,6},{5,7},{8,9},{5,9} };\n std::cout << activitySelection(v) << \"\\n\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T19:29:30.533",
"Id": "441813",
"Score": "0",
"body": "Thank you for the answer and the cout and endl part was my mistake while editing(I corrected them now) and the variable array size was not written by me, infact the whole main function was provided by the platform and there was no rewrite permission.I just copied it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T18:07:03.040",
"Id": "227116",
"ParentId": "226979",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227116",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T05:35:07.470",
"Id": "226979",
"Score": "1",
"Tags": [
"c++",
"algorithm",
"array"
],
"Title": "Activity Selection to maximize the number of activity executions"
}
|
226979
|
<p>I have written the code for credit card number validation and it works correctly but I feel that the code could be reduce to fewer lines.</p>
<pre><code>#include <stdio.h>
int main()
{
long long int no;
do
{
printf("Card number: ");
scanf("%lld", &no);
}
while(no<10);
int d_1,d_2,d_3,d_4,d_5,d_6,d_7,d_8,d_9,d_10,d_11,d_12,d_13,d_14,d_15,d_16;
d_16 = no%10;
d_15 = ((no%100)/10)*2;
d_14 = (no%1000)/100;
d_13 = ((no%10000)/1000)*2;
d_12 = (no%100000)/10000;
d_11 = ((no%1000000)/100000)*2;
d_10 = (no%10000000)/1000000;
d_9 = ((no%100000000)/10000000)*2;
d_8 = (no%1000000000)/100000000;
d_7 = ((no%10000000000)/1000000000)*2;
d_6 = (no%100000000000)/10000000000;
d_5 = ((no%1000000000000)/100000000000)*2;
d_4 = (no%10000000000000)/1000000000000;
d_3 = ((no%100000000000000)/10000000000000)*2;
d_2 = (no%1000000000000000)/100000000000000;
d_1 = ((no%10000000000000000)/1000000000000000)*2;
int od[] = {d_1,d_3,d_5,d_7,d_9,d_11,d_13,d_15};
int ed[] = {d_2,d_4,d_6,d_8,d_10,d_12,d_14,d_16};
int i,add=0;
for (i=1;i<=8;i++)
{
if(od[i] >= 10)
{
int nod = (od[i]%10)+(od[i]/10);
od[i] = nod;
}
}
for (int j=0;j<8;j++)
{
add = add + od[j];
}
for (i=1;i<=8;i++)
{
if(ed[i] >= 10)
{
int ood = (ed[i]%10)+(ed[i]/10);
ed[i] = ood;
}
}
for (int j=0;j<8;j++)
{
add = add + ed[j];
}
if ((add%10)==0)
{
printf("The card is valid");
}
else
{
printf("The card is invalid");
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T09:18:06.347",
"Id": "441517",
"Score": "0",
"body": "Could you provide the specification of a valid credit card number and some unit tests?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T09:39:49.217",
"Id": "441521",
"Score": "0",
"body": "Did you make a typo d3 has 2 different variable names?"
}
] |
[
{
"body": "<pre><code>d_16 = no%10;\nd_15 = ((no%100)/10)*2;\nd_14 = (no%1000)/100;\nd_13 = ((no%10000)/1000)*2;\nd_12 = (no%100000)/10000;\nd_11 = ((no%1000000)/100000)*2;\nd_10 = (no%10000000)/1000000;\nd_9 = ((no%100000000)/10000000)*2;\nd_8 = (no%1000000000)/100000000;\nd_7 = ((no%10000000000)/1000000000)*2;\nd_6 = (no%100000000000)/10000000000;\nd_5 = ((no%1000000000000)/100000000000)*2;\nd_4 = (no%10000000000000)/1000000000000;\nd__3 = ((no%100000000000000)/10000000000000)*2;\nd_2 = (no%1000000000000000)/100000000000000;\nd_1 = ((no%10000000000000000)/1000000000000000)*2;\n</code></pre>\n\n<p>You're using too many <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">magic numbers</a> in your program, and they are prone to error. Instead, you could use a loop for this calculation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T06:32:22.530",
"Id": "226983",
"ParentId": "226982",
"Score": "3"
}
},
{
"body": "<p>I don't like this:</p>\n\n<blockquote>\n<pre><code>do\n{\n printf(\"Card number: \");\n scanf(\"%lld\", &no);\n}\n\nwhile(no<10);\n</code></pre>\n</blockquote>\n\n<p>That blank line makes it look like the <code>while ();</code> is a separate (possibly infinite) loop. I recommend writing the <code>while</code> keyword straight after the closing brace, like this:</p>\n\n<pre><code>do {\n printf(\"Card number: \");\n} while (scanf(\"%lld\", &no) != 1);\n</code></pre>\n\n<p>(I've also changed the test so that we don't access an uninitialised <code>no</code> if the <code>scanf()</code> fails - it's still flawed, though, as any permanent <code>stdin</code> failure will lead to an infinite loop).</p>\n\n<hr>\n\n<p>It's not clear why we have <code>d_1</code>, <code>d_2</code>, ..., etc. when all we do with them is to copy them into array members - why not just assign to the array members directly?</p>\n\n<hr>\n\n<p>Instead of dividing <code>no</code> by successively bigger numbers each time, we could modify it as we go, like this:</p>\n\n<pre><code>d_16 = no % 10;\nno /= 10;\nd_15 = no % 10 * 2;\nno /= 10;\nd_14 = no % 10;\n</code></pre>\n\n<p>It's starting to become clear how to transform this into a loop. The missing part is whether to multiply by 2 at each step; we can tell whether the loop index is even or odd, by considering it modulo 2.</p>\n\n<p>Once we are considering the digits in a loop, we can perform the addition as we go, meaning that we no longer need all those local variables.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T07:29:35.403",
"Id": "226984",
"ParentId": "226982",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T06:04:19.700",
"Id": "226982",
"Score": "1",
"Tags": [
"algorithm",
"c",
"checksum"
],
"Title": "Validation of credit card number"
}
|
226982
|
<p>To better learn templates, I have dabbled with a simple linked list implementing the class with a private member compare function (<code>cmp</code>) that is used when adding nodes in sort-order, or when sorting an unsorted list. Here I have simply bitten the bullet and put the entire class implementation in the header file, rather than splitting between a source and header and having to explicityly instantiate for anticipated types at the bottom of the source file.</p>
<p>As a result, I have also included the default <code>compare</code> function that will compare nodes for where <code>>, >=, <, and <=</code> are overloaded to provide the comparison. I have the ascending sort as the default, but ran into problems considering how I would also include a descending version. there is currently a "setter" function that takes the compare function name as an argument and assigns to the private compare function pointer. Would it be better to require both ascending and descending functions defined allowing setters for <code>setcmpascending</code> and <code>setcmpdescending</code>?</p>
<p>So far I have the constructors overloaded to accept compare function and then a separate setter for the compare function as well.</p>
<blockquote>
<p>Is this in-header compare function in the right place and is the
<code>setcmp</code> setter fine, or should I look to wrap two setter member
functions (such as <code>setascending</code> and <code>setdescending</code> that could serve
as wrappers for setting the default compare function that make use of
the overloads above?</p>
</blockquote>
<pre><code>#ifndef _ll_template_full_h_
#define _ll_template_full_h_ 1
#include <iostream>
template <class T>
struct node_t {
T data;
node_t<T> *next;
};
/* default compare function for types w/overload (ascending) */
template <typename T>
int compare_asc (const node_t<T> *a, const node_t<T> *b)
{
return (a->data > b->data) - (a->data < b->data);
}
template <class T>
class list_t {
node_t<T> *head, *tail;
int (*cmp)(const node_t<T>*, const node_t<T>*);
public:
list_t (void); /* constructors */
list_t (int(*f)(const node_t<T>*, const node_t<T>*));
~list_t (void); /* destructor */
list_t (const list_t&); /* copy constructor */
/* setter for compare function */
void setcmp (int (*f)(const node_t<T>*, const node_t<T>*));
node_t<T> *addnode (T data); /* simple add at end */
node_t<T> *addinorder (T data); /* add in order */
void delnode (T data); /* delete node */
void prnlist (void); /* print space separated */
void insertionsort (void); /* sort list */
list_t split (void); /* split list ~ 1/2 */
};
/* constructor (default) */
template <class T>
list_t<T>::list_t (void)
{
head = tail = nullptr;
cmp = compare_asc;
}
/* constructor taking compare function as argument */
template <class T>
list_t<T>::list_t (int(*f)(const node_t<T>*, const node_t<T>*))
{
head = tail = nullptr;
cmp = f;
}
/* destructor free all list memory */
template <class T>
list_t<T>::~list_t (void)
{
node_t<T> *pn = head;
while (pn) {
node_t<T> *victim = pn;
pn = pn->next;
delete victim;
}
}
/* copy ctor - copy exising list */
template <class T>
list_t<T>::list_t (const list_t& l)
{
cmp = l.cmp; /* assign compare function ptr */
head = tail = nullptr; /* initialize head/tail */
/* copy data to new list */
for (node_t<T> *pn = l.head; pn; pn = pn->next)
this->addnode (pn->data);
}
/* setter compare function */
template <class T>
void list_t<T>::setcmp (int(*f)(const node_t<T>*, const node_t<T>*))
{
cmp = f;
}
</code></pre>
<p>My question here is (1) is there a better way to factor the compare functions rather than having them as part of the class header (they are needed for default contructing the class with the ascending function), but that still doesn't mean they shouldn't be in a difference header/source and included in this class file. Regadless where they go they will need some forward-type declaration of <code>node_t<T></code> to make sense. If in separate files, how best to provide that? Lastly (2) does it make sense worrying about it, or is just having the compare functions as part of the class header fine?</p>
<p>Then in my <code>insertionsort</code> I make use of pointers as I would normally do in C to iterate over the list nodes to finally end up wtih the list in sort order. Since this is a list and natively handled by pointers, I didn't know whether using references in some fashoin may not be the preferred approach? I currently have:</p>
<pre><code>/** insertion sort of linked list.
* re-orders list in sorted order.
*/
template <class T>
void list_t<T>::insertionsort (void)
{
node_t<T> *sorted = head, /* initialize sorted list to 1st node */
*pn = head->next; /* advance original list node to next */
sorted->next = NULL; /* initialize sorted->next to NULL */
while (pn) { /* iterate over existing from 2nd node */
node_t<T> **pps = &sorted, /* ptr-to-ptr to sorted list */
*ps = *pps, /* ptr to sorted list */
*next = pn->next; /* save list next as separate pointer */
while (ps && cmp(ps, pn) < 0) { /* loop until sorted */
pps = &ps->next; /* get address of next node */
ps = ps->next; /* get next node pointer */
}
*pps = pn; /* insert existing in sort order as current */
pn->next = ps; /* set next as sorted next */
pn = next; /* reinitialize existing pointer to next */
}
head = sorted; /* update head to sorted head */
/* set tail pointer to last node after sort */
for (pn = head; pn; pn = pn->next)
tail = pn;
}
</code></pre>
<p>Lastly, my <code>split</code> function which takes roughly 1/2 the nodes from the list and moves them to a new instance of the class. Here if feels like an awkward way to factor the function as a member function returning a new instance of the class. Only the original class instance holds pointers to the list, but the second instance created within the function allows nodes to be divied up among the now two instances of the class. Here also it just feels a bit awkward with all the pointer use, and left me wondering it there may be a more C++ way to approach this operation. The split function is:</p>
<pre><code>/* split list l into lists a & b */
template <class T>
list_t<T> list_t<T>::split (void)
{
list_t<T> s; /* new instance of class */
node_t<T> *pa = head, /* pointer to current head */
*pb = pa->next; /* 2nd pointer to double-advance */
while (pb) { /* while not end of list */
pb = pb->next; /* advance 2nd ptr */
if (pb) { /* if not nullptr */
pa = pa->next; /* advance current ptr */
pb = pb->next; /* advance 2nd ptr again */
}
}
s.tail = tail; /* 2nd half tail will be current tail */
tail = pa; /* current tail is at pa */
s.head = pa->next; /* 2nd half head is next ptr */
pa->next = nullptr; /* set next ptr NULL to end 1st 1/2 */
return s; /* return new instance */
}
#endif
</code></pre>
<blockquote>
<p>Is this a reasonable way to put the <code>split</code> funtion together using
pointers, and instantiating a second list class within and returing it
as the 2nd half of the list -- is that a reasonable approach?</p>
</blockquote>
<p>A MCVE for the header is:</p>
<pre><code>#ifndef _ll_template_full_h_
#define _ll_template_full_h_ 1
#include <iostream>
template <class T>
struct node_t {
T data;
node_t<T> *next;
};
/* default compare function for types w/overload (ascending) */
template <typename T>
int compare_asc (const node_t<T> *a, const node_t<T> *b)
{
return (a->data > b->data) - (a->data < b->data);
}
template <class T>
class list_t {
node_t<T> *head, *tail;
int (*cmp)(const node_t<T>*, const node_t<T>*);
public:
list_t (void); /* constructors */
list_t (int(*f)(const node_t<T>*, const node_t<T>*));
~list_t (void); /* destructor */
list_t (const list_t&); /* copy constructor */
/* setter for compare function */
void setcmp (int (*f)(const node_t<T>*, const node_t<T>*));
node_t<T> *addnode (T data); /* simple add at end */
node_t<T> *addinorder (T data); /* add in order */
void delnode (T data); /* delete node */
void prnlist (void); /* print space separated */
void insertionsort (void); /* sort list */
list_t split (void); /* split list ~ 1/2 */
};
/* constructor (default) */
template <class T>
list_t<T>::list_t (void)
{
head = tail = nullptr;
cmp = compare_asc;
}
/* constructor taking compare function as argument */
template <class T>
list_t<T>::list_t (int(*f)(const node_t<T>*, const node_t<T>*))
{
head = tail = nullptr;
cmp = f;
}
/* destructor free all list memory */
template <class T>
list_t<T>::~list_t (void)
{
node_t<T> *pn = head;
while (pn) {
node_t<T> *victim = pn;
pn = pn->next;
delete victim;
}
}
/* copy ctor - copy exising list */
template <class T>
list_t<T>::list_t (const list_t& l)
{
cmp = l.cmp; /* assign compare function ptr */
head = tail = nullptr; /* initialize head/tail */
/* copy data to new list */
for (node_t<T> *pn = l.head; pn; pn = pn->next)
this->addnode (pn->data);
}
/* setter compare function */
template <class T>
void list_t<T>::setcmp (int(*f)(const node_t<T>*, const node_t<T>*))
{
cmp = f;
}
/* add using tail ptr */
template <class T>
node_t<T> *list_t<T>::addnode (T data)
{
node_t<T> *node = new node_t<T>; /* allocate/initialize node */
node->data = data;
node->next = nullptr;
if (!head)
head = tail = node;
else {
tail->next = node;
tail = node;
}
return node;
}
template <class T>
node_t<T> *list_t<T>::addinorder (T data)
{
if (!cmp) { /* validate compare function not nullptr */
std::cerr << "error: compare is nullptr.\n";
return nullptr;
}
node_t<T> *node = new node_t<T>; /* allocate/initialize node */
node->data = data;
node->next = nullptr;
node_t<T> **ppn = &head, /* ptr-to-ptr to head */
*pn = head; /* ptr to head */
while (pn && cmp (node, pn) > 0) { /* node sorts after current */
ppn = &pn->next; /* ppn to address of next */
pn = pn->next; /* advance pointer to next */
}
node->next = pn; /* set node->next to next */
if (pn == nullptr)
tail = node;
*ppn = node; /* set current to node */
return node; /* return node */
}
template <class T>
void list_t<T>::delnode (T data)
{
node_t<T> **ppn = &head; /* pointer to pointer to node */
node_t<T> *pn = head; /* pointer to node */
for (; pn; ppn = &pn->next, pn = pn->next) {
if (pn->data == data) {
*ppn = pn->next; /* set address to next */
delete pn;
break;
}
}
}
template <class T>
void list_t<T>::prnlist (void)
{
if (!head) {
std::cout << "empty-list\n";
return;
}
for (node_t<T> *pn = head; pn; pn = pn->next)
std::cout << " " << pn->data;
std::cout << '\n';
}
/** insertion sort of linked list.
* re-orders list in sorted order.
*/
template <class T>
void list_t<T>::insertionsort (void)
{
node_t<T> *sorted = head, /* initialize sorted list to 1st node */
*pn = head->next; /* advance original list node to next */
sorted->next = NULL; /* initialize sorted->next to NULL */
while (pn) { /* iterate over existing from 2nd node */
node_t<T> **pps = &sorted, /* ptr-to-ptr to sorted list */
*ps = *pps, /* ptr to sorted list */
*next = pn->next; /* save list next as separate pointer */
while (ps && cmp(ps, pn) < 0) { /* loop until sorted */
pps = &ps->next; /* get address of next node */
ps = ps->next; /* get next node pointer */
}
*pps = pn; /* insert existing in sort order as current */
pn->next = ps; /* set next as sorted next */
pn = next; /* reinitialize existing pointer to next */
}
head = sorted; /* update head to sorted head */
/* set tail pointer to last node after sort */
for (pn = head; pn; pn = pn->next)
tail = pn;
}
/* split list l into lists a & b */
template <class T>
list_t<T> list_t<T>::split (void)
{
list_t<T> s; /* new instance of class */
node_t<T> *pa = head, /* pointer to current head */
*pb = pa->next; /* 2nd pointer to double-advance */
while (pb) { /* while not end of list */
pb = pb->next; /* advance 2nd ptr */
if (pb) { /* if not nullptr */
pa = pa->next; /* advance current ptr */
pb = pb->next; /* advance 2nd ptr again */
}
}
s.tail = tail; /* 2nd half tail will be current tail */
tail = pa; /* current tail is at pa */
s.head = pa->next; /* 2nd half head is next ptr */
pa->next = nullptr; /* set next ptr NULL to end 1st 1/2 */
return s; /* return new instance */
}
#endif
</code></pre>
<p>I have a couple simple example programs as well, one <code>int</code> and the other <code>string</code>.</p>
<p><strong>Integer Test Program</strong></p>
<p>Here I also include other compare functions for testing the setter, etc..</p>
<pre><code>#include <iostream>
#include "ll_template_full.h"
/* compare function for numeric types (ascending) */
template <typename T>
int cmpnumeric (const node_t<T> *a, const node_t<T> *b)
{
return (a->data > b->data) - (a->data < b->data);
}
/* compare function for types w/overload (descending) */
template <typename T>
int compare_desc (const node_t<T> *a, const node_t<T> *b)
{
return (a->data < b->data) - (a->data > b->data);
}
int main (void) {
list_t<int> l (cmpnumeric);
int arr[] = {12, 11, 10, 7, 4, 14, 8, 16, 20, 19,
2, 9, 1, 13, 17, 6, 15, 5, 3, 18};
unsigned asz = sizeof arr / sizeof *arr;
for (unsigned i = 0; i < asz; i++)
l.addnode (arr[i]);
l.prnlist();
l.insertionsort();
l.prnlist();
l.setcmp (compare_desc);
l.insertionsort();
l.prnlist();
list_t<int>s = l.split();
l.prnlist();
s.prnlist();
}
</code></pre>
<p><strong>String Test Program</strong></p>
<pre><code>#include <iostream>
#include <vector>
#include <string>
#include "ll_template_full.h"
/* compare function for types w/overload (descending) */
template <typename T>
int compare_desc (const node_t<T> *a, const node_t<T> *b)
{
return (a->data < b->data) - (a->data > b->data);
}
int main (void) {
list_t<std::string> l;
std::vector<std::string> vs = { "my", "dog", "has", "fleas" };
for (auto& s : vs)
l.addnode (s);
l.prnlist();
l.insertionsort();
l.prnlist();
l.setcmp (compare_desc);
l.insertionsort();
l.prnlist();
list_t<std::string>s = l.split();
l.prnlist();
s.prnlist();
}
</code></pre>
<p>Any other points you find are welcome as well. That was intentionally done without any of the STL containers as the purpose was to take a known quantity that has a reasonable set of functions and then to template them to manage various types providing comparison on nodes rather than data so a sort function could be written to handle sorting on any member of an aggregate type. If there are pointers that could better be references, or if for instance the <code>split</code> function should take an existing instance as a parameter rather than creating the class instance inside -- anything along those lines would help (and the why as well).</p>
|
[] |
[
{
"body": "<ul>\n<li><p>A standard way out of your problems is to </p>\n\n<ul>\n<li><p>Define few comparators, such as <code>operator<</code> and the family, e.g.</p>\n\n<pre><code>friend bool operator<(const Node& a, const Node& b) {\n return a.data < b.data;\n}\n\nfriend bool operator>=(const Node& a, const Node& b) {\n return !(a < b);\n}\n</code></pre></li>\n</ul>\n\n<p>etc;</p>\n\n<ul>\n<li><p>Define the iterator over your list;</p></li>\n<li><p>Do not implement the methods which are already implemented in STL <code><algorithm></code> library, but enjoy them for free. That includes <code>insertionsort</code> and <code>prnlist</code> for example, and greatly simplifies <code>addinorder</code> (just call <code>std::lower_bound</code> and notice that it returns exactly an insertion point you need).</p></li>\n</ul></li>\n<li><p>Except that iterators are preferred to raw pointers, I see nothing wrong with your <code>split</code>. A few nitpicks though. I would call it <code>split_in_half</code>, and define another <code>split_at</code> method with an iterator parameter telling <em>where</em> to split.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T17:39:31.350",
"Id": "441623",
"Score": "0",
"body": "Yes, thank you. All good points. My descriptive names -- aren't. I do take advantage of STL at every turn in normal programming. Here, the intent was to broaden my understanding of templates, so my re-inventing the wheel was intentional. I'll work further on comparators, but I suppose I would have to implement one for each aggregate type of `node_t<T>` that does not already have an overloaded `<, <=, >, >=`. Thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T16:36:16.223",
"Id": "227022",
"ParentId": "226985",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T07:54:45.880",
"Id": "226985",
"Score": "0",
"Tags": [
"c++",
"linked-list",
"template"
],
"Title": "C++ Linked List Template Implementation, Howto Default Compare Function, and Split?"
}
|
226985
|
<p>I need a fully asynchronous single-threaded server written using .Net Core. Searched for options and, surprisingly, did't find any. So I decided to write a simple prototype. Borrowed idea from python's selectors module.</p>
<p>Idea is simple. We have <code>SocketSelector</code> class to whom we register sockets for desired events (Read, Write, Error) and provide callbacks, which selector will call. Selector once every loop iteration (server just runs infinite loop) checks what sockets are ready by calling <code>Socket.Select</code> and then adds callbacks of ready sockets to <code>readyQueue</code>. Server every iteration dequeues all callbacks from this queue and calls them.</p>
<p>Each socket (listener and client sockets) are all set to be non-blocking. Say we accepted some new connection and now want to read a message from it asynchronously. We don't call <code>socket.Receive</code> outright because we don't know whether there are bytes to read or not. First we create <code>TaskCompletionSource</code>, call <code>selector.Register(socket, SocketEvent.Read, tcs.SetResult)</code>, and then <code>await tcs.Task</code>. Eventually socket becomes ready to read, so selector will put <code>tcs.SetResult</code> into the <code>readyQueue</code>, and server will call it with <code>null</code> as an argument. This will complete awaited task. At this point we can start actually reading from socket knowing that <code>socket.Receive</code> will not block. Same for sending messages.</p>
<p>Code it straightforward. The only strange thing is <code>ListForPolling</code>. This class is needed to alleviate some of <code>Socket.Select</code>'s problems. This method takes 3 lists of sockets (1 for each event) and removes (using <code>RemoveAt</code>) from provided lists all sockets that are not yet ready. That means that on every iteration we have to populate lists again. So instead of actually removing sockets I just mark them as removed. <code>Socket.Select</code> implementation uses only <code>Count</code>, <code>Clear</code>, indexer and <code>RemoveAt</code>, so all other <code>IList</code> methods are not required. Unix implementation internally uses poll instead of select and it iterates over lists from back to front, so code is different a little bit. <code>ListForPolling</code> works with <code>Socket.Select</code> and <code>Socket.Select</code> only, so don't use it for anything else, it will break :)</p>
<p>First, I don't really want to reinvent the wheel if some robust solution already exists. So please provide some links if you have any. <strong>I don't need servers that use thread pool behind the scenes</strong>, I want a single-threaded asynchronous solution. And I don't want to learn NodeJS :)</p>
<p>Second, is this code viable? I tested it with simple client. It works well. Tested with 150k concurrent clients (not really concurrent of course). I didn't test it on Linux, but it should work even better. Poll is much better then Select after all.</p>
<p>There are problems with current solution of course, after all it is just a prototype, but concept works, I think.</p>
<pre class="lang-cs prettyprint-override"><code>#define WINDOWS
using System;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Text;
class Program {
private static void Main() {
var server = new Server(7894);
server.Run();
}
}
public class Server {
private ushort port;
private Socket listener;
private SocketSelector selector;
private int numClients = 0;
private Queue<Action<object>> readyQueue = new Queue<Action<object>>(50);
private Dictionary<string, string> requestToResponse =
new Dictionary<string, string>() {
["hello"] = "bye",
["how are you?"] = "I am fine",
["what's up?"] = "nothing",
["what do you think about god?"] = "I don't think about him",
["I love GoT's final season"] = "maniac",
["Answer is always lasers and/or duck tape"] = "true wisdom"
};
public Server(ushort port) {
this.port = port;
listener = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
listener.Blocking = false;
listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
listener.Bind(new IPEndPoint(IPAddress.IPv6Any, port));
listener.Listen(2000);
selector = new SocketSelector(readyQueue);
selector.Register(listener, SocketEvent.Read, _ => acceptConnection());
}
private void acceptConnection() {
var clientSocket = listener.Accept();
clientSocket.Blocking = false;
++numClients;
serveClient(clientSocket);
}
private async void serveClient(Socket socket) {
Console.WriteLine($"Started serving client { socket.RemoteEndPoint }.");
byte[] buffer = new byte[1024];
try {
int messageLength = await readMessage(socket, buffer);
var request = Encoding.UTF8.GetString(buffer, 0, messageLength);
string response = requestToResponse[request];
messageLength = Encoding.UTF8.GetBytes(response, 0, response.Length, buffer, 0);
await sendMessage(socket, buffer, messageLength);
} catch (Exception e) {
Console.WriteLine(e);
selector.Unregister(socket);
}
Console.WriteLine($"Finished serving client { socket.RemoteEndPoint }.");
selector.Unregister(socket);
socket.Shutdown(SocketShutdown.Both);
socket.Close();
--numClients;
}
private async Task read(Socket socket, byte[] buffer, int bytesToRead) {
int n = 0, offset = 0;
while (bytesToRead > 0) {
var tcs = new TaskCompletionSource<object>();
if (offset == 0) {
selector.Register(socket, SocketEvent.Read, tcs.SetResult);
} else {
selector.SwitchCallbackForRegisteredEvent(socket, tcs.SetResult);
}
await tcs.Task;
try {
n = socket.Receive(buffer, offset, bytesToRead, 0);
} catch (SocketException e) {
// ...
}
if (n == 0 && bytesToRead > 0) {
throw new Exception("Client disconnected before sending the whole message.");
}
bytesToRead -= n;
offset += n;
}
selector.Unregister(socket, SocketEvent.Read);
}
private async Task<int> readMessage(Socket socket, byte[] buffer) {
await read(socket, buffer, 2);
var messageLength = Utils.UnpackUshort(buffer, 0);
if (messageLength > buffer.Length) {
throw new Exception("Incoming message is too long.");
}
await read(socket, buffer, messageLength);
return messageLength;
}
private async Task sendAll(Socket socket, byte[] buffer, int bytesTotal) {
int bytesSent = 0;
while (bytesSent < bytesTotal) {
var tcs = new TaskCompletionSource<object>();
if (bytesSent == 0)
selector.Register(socket, SocketEvent.Write, tcs.SetResult);
else
selector.SwitchCallbackForRegisteredEvent(socket, tcs.SetResult);
await tcs.Task;
try {
bytesSent += socket.Send(buffer, bytesSent, bytesTotal - bytesSent, 0);
} catch (SocketException e) {
// ...
}
}
selector.Unregister(socket, SocketEvent.Write);
}
private async Task sendMessage(Socket socket, byte[] buffer, int messageLength) {
byte b0 = buffer[0];
byte b1 = buffer[1];
Utils.PackUshort(buffer, 0, (ushort) messageLength);
await sendAll(socket, buffer, 2);
buffer[0] = b0;
buffer[1] = b1;
await sendAll(socket, buffer, messageLength);
}
public void Run() {
while (true) {
selector.Poll();
while (readyQueue.Count > 0) {
var action = readyQueue.Dequeue();
action(null);
}
}
}
}
internal enum SocketEvent {
Read, Write, Error
}
internal class SocketSelector {
private ListForPolling[] lists = {
new ListForPolling(), // read list
new ListForPolling(), // write list
new ListForPolling() // error list
};
private Dictionary<IntPtr, (SocketEvent SocketEvent, Action<object> Callback)> handleToSocketEventAndCallback =
new Dictionary<IntPtr, (SocketEvent SocketEvent, Action<object> Callback)>();
private Queue<Action<object>> readyQueue;
public SocketSelector(Queue<Action<object>> readyQueue) {
this.readyQueue = readyQueue;
}
private void addCallbacksToReadyQueue(int index) {
var lst = lists[index];
lst.ResetRemovedCount();
for (int i = 0; i < lst.Count; ++i) {
if (!lst.IsRemoved(i)) {
IntPtr handle = ((Socket) lst[i]).Handle;
var callback = handleToSocketEventAndCallback[handle].Callback;
if (callback != null)
readyQueue.Enqueue(callback);
}
}
lst.ResetRemovedSet();
}
public void Poll() {
if (lists[0].Count > 0 || lists[1].Count > 0 || lists[2].Count > 0) {
Socket.Select(lists[0], lists[1], lists[2], -1);
addCallbacksToReadyQueue(0);
addCallbacksToReadyQueue(1);
addCallbacksToReadyQueue(2);
}
}
public void SwitchCallbackForRegisteredEvent(Socket socket, Action<object> callback) {
IntPtr handle = socket.Handle;
if (handleToSocketEventAndCallback.ContainsKey(handle)) {
var socketEvent = handleToSocketEventAndCallback[handle].SocketEvent;
handleToSocketEventAndCallback[handle] = (socketEvent, callback);
} else {
throw new Exception("Cannot switch callback for unregistered socket.");
}
}
public void Register(Socket socket, SocketEvent socketEvent, Action<object> callback) {
IntPtr handle = socket.Handle;
if (!handleToSocketEventAndCallback.ContainsKey(handle)) {
lists[(int) socketEvent].Add(socket);
handleToSocketEventAndCallback[handle] = (socketEvent, callback);
} else {
throw new Exception("Socket can be registered to listen to only one event at a time.");
}
}
public void Unregister(Socket socket, SocketEvent socketEvent) {
IntPtr handle = socket.Handle;
if (
handleToSocketEventAndCallback.ContainsKey(handle) &&
handleToSocketEventAndCallback[handle].SocketEvent == socketEvent
) {
handleToSocketEventAndCallback.Remove(handle);
lists[(int) socketEvent].Remove(socket);
} else {
throw new Exception("Cannot unregister not registered event.");
}
}
public void Unregister(Socket socket) {
IntPtr handle = socket.Handle;
if (handleToSocketEventAndCallback.ContainsKey(handle)) {
Unregister(socket, handleToSocketEventAndCallback[handle].SocketEvent);
}
}
}
internal class ListForPolling : IList {
private List<object> list;
private HashSet<int> removed = new HashSet<int>();
private int removedCount = 0; // always 0 for Unix
public int Count => list.Count - removedCount;
public object this[int index] {
get { return list[index + removedCount]; }
set { }
}
public ListForPolling(int capacity = 100) {
list = new List<object>(capacity);
}
public int Add(object item) {
list.Add(item);
return list.Count - 1;
}
public void Clear() {
removedCount = 0;
for (int i = 0; i < Count; ++i) {
removed.Add(i);
}
}
public void Remove(object item) => list.Remove(item);
public void RemoveAt(int index) {
removed.Add(index + removedCount);
#if WINDOWS
++removedCount;
#endif
}
public bool IsRemoved(int index) {
return removed.Contains(index);
}
public void ResetRemovedSet() {
removed.Clear();
}
public void ResetRemovedCount() {
removedCount = 0;
}
public bool IsFixedSize { get { throw new NotSupportedException(); } }
public bool IsReadOnly { get { throw new NotSupportedException(); } }
public bool IsSynchronized { get { throw new NotSupportedException(); } }
public object SyncRoot { get { throw new NotSupportedException(); } }
public bool Contains(object item) { throw new NotSupportedException(); }
public void CopyTo(Array array, int index) { throw new NotSupportedException(); }
public IEnumerator GetEnumerator() { throw new NotSupportedException(); }
public int IndexOf(object item) { throw new NotSupportedException(); }
public void Insert(int index, object item) { throw new NotSupportedException(); }
}
internal static class Utils {
public static ushort UnpackUshort(byte[] buffer, int offset) {
if (BitConverter.IsLittleEndian) {
byte temp = buffer[offset];
buffer[offset] = buffer[offset + 1];
buffer[offset + 1] = temp;
}
return BitConverter.ToUInt16(buffer, offset);
}
public static void PackUshort(byte[] buffer, int offset, ushort num) {
unsafe {
byte* p = (byte*) &num;
buffer[offset] = *p++;
buffer[offset + 1] = *p;
}
if (BitConverter.IsLittleEndian) {
byte temp = buffer[offset];
buffer[offset] = buffer[offset + 1];
buffer[offset + 1] = temp;
}
}
}
</code></pre>
<p>Here is simple client.</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
class Client {
private static int serverPort = 7894;
private static string[] requests = {
"hello",
"how are you?",
"what's up?",
"what do you think about god?",
"I love GoT's final season",
"Answer is always lasers and/or duck tape"
};
private static void packUshort(byte[] buffer, int offset, ushort num) {
unsafe {
byte* p = (byte*) &num;
buffer[offset] = *p++;
buffer[offset + 1] = *p;
}
if (BitConverter.IsLittleEndian) {
byte temp = buffer[offset];
buffer[offset] = buffer[offset + 1];
buffer[offset + 1] = temp;
}
}
private static int readUntilClosedOrBufferFilled(Socket socket, byte[] buffer, int offset = 0) {
int n = -1, initialOffset = offset;
int availableRoom = buffer.Length - offset;
while (availableRoom > 0 && n != 0) {
n = socket.Receive(buffer, offset, availableRoom, 0);
availableRoom -= n;
offset += n;
}
return buffer.Length - availableRoom - initialOffset;
}
private static void sendMessage(Socket socket, string msg, byte[] buffer) {
int msgLength = Encoding.UTF8.GetByteCount(msg);
packUshort(buffer, 0, (ushort) msgLength);
socket.Send(buffer, 0, 2, 0);
int n = Encoding.UTF8.GetBytes(msg, 0, msg.Length, buffer, 0);
socket.Send(buffer, 0, n, 0);
}
private static async Task startClient(int cc) {
var hostEntry = Dns.GetHostEntry("localhost");
EndPoint remoteEndPoint = new IPEndPoint(hostEntry.AddressList[0], serverPort);
var tasks = new Task[cc];
for (int i = 0; i < cc; ++i) {
int j = i;
var task = Task.Run(() => {
var socket = new Socket(remoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(remoteEndPoint);
byte[] buffer = new byte[1024];
sendMessage(socket, requests[j % 6], buffer);
int n = readUntilClosedOrBufferFilled(socket, buffer);
Console.WriteLine($"Response { j }: { Encoding.UTF8.GetString(buffer, 2, n - 2) }");
socket.Close();
});
tasks[i] = task;
}
await Task.WhenAll(tasks);
}
private static async Task Main(string[] args) {
await startClient(int.Parse(args[0]));
}
}
</code></pre>
<p>Just provide client count as command line argument.</p>
<p>And by the way, communication is performed with very simple protocol: 2 bytes message length and then payload.</p>
<p>Test it please and tell me your thoughts. Don't forget to remove define if you are not on Windows.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T10:59:04.717",
"Id": "226997",
"Score": "6",
"Tags": [
"c#",
"socket",
"async-await",
".net-core"
],
"Title": "Single-threaded fully asynchronous server, with a SocketSelector that dispatches events"
}
|
226997
|
<p>Not please with this outcome, function works as is, but would love to simplify and prettify it. Use of one for-loop would be great and limit the use of the conditional operator.</p>
<pre><code>private void checkForOverage(List<GoogleUsageMapping> records) {
Long sumOfAllocatedSize = 0L;
Long sumOfLogicalSize = 0L;
for (GoogleUsageMapping record : records) {
// initially all records are set to GoogleTrackingState.UNPROCESSED
if (record.getUsage().getMeasuredType() == MeasuredType.ALLOCATED_SIZE) {
sumOfAllocatedSize += record.getUsage().getQuantity().longValue();
} else if (record.getUsage().getMeasuredType() == MeasuredType.LOGICAL_SIZE) {
sumOfLogicalSize += record.getUsage().getQuantity().longValue();
}
}
for (GoogleUsageMapping record : records) {
if (sumOfAllocatedSize >= sumOfLogicalSize && record.getUsage().getMeasuredType() == MeasuredType.LOGICAL_SIZE) {
record.setState(GoogleTrackingState.IGNORED_OVERAGE);
} else if (sumOfLogicalSize > sumOfAllocatedSize && record.getUsage().getMeasuredType() == MeasuredType.ALLOCATED_SIZE) {
record.setState(GoogleTrackingState.IGNORED_OVERAGE);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T18:49:54.593",
"Id": "441645",
"Score": "1",
"body": "Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 2 → 1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T21:03:02.157",
"Id": "441658",
"Score": "2",
"body": "You should really add more context so that we can give you proper advice. What class does this method appear in, and what does the code for the `GoogleUsageMapping` class look like? See [ask]. (Our rules allow adding code for contextual information, but not revising the code that you have already posted.)"
}
] |
[
{
"body": "<p>If you have not done so. I recommend picking up the book <a href=\"https://martinfowler.com/books/refactoring.html\" rel=\"nofollow noreferrer\">Refactoring: Improving the Design of Existing Code</a> by Martin Fowler. It is an excellent book on exactly this topic.</p>\n\n<p>One thing you can start with is to split the method by extracting each operation into a separate method. So that instead of doing everything at once you end up with a method per operation.</p>\n\n<p>Doing so will let you examine what your code is actually doing and helps you see the patterns. Something like this:</p>\n\n<pre><code>private void checkForOverage(List<GoogleUsageMapping> records) {\n long allocatedSize = sumAllocated(records);\n long logicalSize = sumLogical(records);\n checkAllocated(records,allocatedSize, logicalSize);\n checkLogical(records,allocatedSize, logicalSize);\n}\n\nprivate long sumAllocated(List<GoogleUsageMapping> records) {\n long sumOfAllocatedSize = 0L;\n for (GoogleUsageMapping record : records) {\n if (record.getUsage().getMeasuredType() == MeasuredType.ALLOCATED_SIZE) {\n sumOfAllocatedSize += record.getUsage().getQuantity().longValue();\n }\n }\n return sumOfAllocatedSize;\n}\n\nprivate long sumLogical(List<GoogleUsageMapping> records) {\n long sumOfLogicalSize = 0L;\n for (GoogleUsageMapping record : records) {\n if (record.getUsage().getMeasuredType() == MeasuredType.LOGICAL_SIZE) {\n sumOfLogicalSize += record.getUsage().getQuantity().longValue();\n }\n }\n return sumOfLogicalSize;\n}\n\nprivate void checkAllocated(List<GoogleUsageMapping> records, long allocatedSize, long logicalSize) {\n for (GoogleUsageMapping record : records) {\n if (allocatedSize >= logicalSize && record.getUsage().getMeasuredType() == MeasuredType.LOGICAL_SIZE) {\n record.setState(GoogleTrackingState.IGNORED_OVERAGE);\n }\n }\n}\n\nprivate void checkLogical(List<GoogleUsageMapping> records, long allocatedSize, long logicalSize) {\n for (GoogleUsageMapping record : records) {\n if (logicalSize > allocatedSize && record.getUsage().getMeasuredType() == MeasuredType.ALLOCATED_SIZE) {\n record.setState(GoogleTrackingState.IGNORED_OVERAGE);\n }\n }\n}\n</code></pre>\n\n<p>As you can see both pairs of methods are nearly identical. All you have to do to unify them is to extract the difference as parameter.</p>\n\n<pre><code>private void checkForOverage(List<GoogleUsageMapping> records) {\n long allocatedSize = sumByType(records, MeasuredType.ALLOCATED_SIZE);\n long logicalSize = sumByType(records, MeasuredType.LOGICAL_SIZE);\n check(records, allocatedSize >= logicalSize, MeasuredType.ALLOCATED_SIZE);\n check(records, logicalSize > allocatedSize, MeasuredType.LOGICAL_SIZE);\n}\n\nprivate long sumByType(List<GoogleUsageMapping> records, MeasuredType type) {\n long sumOfAllocatedSize = 0L;\n for (GoogleUsageMapping record : records) {\n if (record.getUsage().getMeasuredType() == type) {\n sumOfAllocatedSize += record.getUsage().getQuantity().longValue();\n }\n }\n return sumOfAllocatedSize;\n}\n\nprivate void check(List<GoogleUsageMapping> records, boolean condition, MeasuredType type) {\n for (GoogleUsageMapping record : records) {\n if (condition && record.getUsage().getMeasuredType() == type) {\n record.setState(GoogleTrackingState.IGNORED_OVERAGE);\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:33:21.160",
"Id": "441570",
"Score": "2",
"body": "This is definitely less efficient. At the very least I would move the condition check in `check` outside of the loop, if the condition is false, nothing needs to be done at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:53:46.643",
"Id": "441577",
"Score": "5",
"body": "@konijn Sure. Minor optimizations can be done all over the place, but that was not the point of this example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T14:04:27.153",
"Id": "441581",
"Score": "2",
"body": "The difference is substantial for large data volumes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T16:24:07.063",
"Id": "441604",
"Score": "0",
"body": "thank you both for you contribution, very helpful, please see my newest editing, where I'm at a solution that I really like."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:13:53.617",
"Id": "227007",
"ParentId": "227000",
"Score": "2"
}
},
{
"body": "<p>After around of iterations I have come up with this solution, and I'm pretty please with it.\nI had introduced a static class as a some kind of data container for <strong>min</strong>, <strong>max</strong> and <strong>MeasuredType</strong> variables, but when completed with that iteration I saw clearly that code could be more simplified.\nSo by abstracting code to more functions lead me to my final solution.</p>\n\n<pre><code>private void checkForOverage(List<GoogleUsageMapping> records) {\n MeasuredType measuredType = sumByMeasuredType(records);\n for (GoogleUsageMapping record : records) {\n if (record.getUsage().getMeasuredType() == measuredType) {\n record.setState(GoogleTrackingState.IGNORED_OVERAGE);\n }\n }\n}\n\nprivate MeasuredType sumByMeasuredType(List<GoogleUsageMapping> records) {\n long allocatedSize = 0L;\n long logicalSize = 0L;\n for (GoogleUsageMapping record : records) {\n if (record.getUsage().getMeasuredType() == MeasuredType.ALLOCATED_SIZE) {\n allocatedSize += record.getUsage().getQuantity().longValue();\n } else if (record.getUsage().getMeasuredType() == MeasuredType.LOGICAL_SIZE) {\n logicalSize += record.getUsage().getQuantity().longValue();\n }\n }\n return (allocatedSize >= logicalSize) ? MeasuredType.LOGICAL_SIZE : MeasuredType.ALLOCATED_SIZE;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T19:18:59.493",
"Id": "227036",
"ParentId": "227000",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T11:20:39.203",
"Id": "227000",
"Score": "0",
"Tags": [
"java"
],
"Title": "Too many for-loops and conditional operators"
}
|
227000
|
<h2>Prerequisites</h2>
<p>The <code>unsigned long</code> type has a size of 64 bits.</p>
<p>The following macros are defined.</p>
<pre><code>/* all 3^n for n < 41 fits into 64-bit unsigned long */
#define LUT_SIZE 41
/* any reasonably high number */
#define LUT_SIZEMPZ 512
</code></pre>
<p>The following array is defined and properly initialized with corresponding values.</p>
<pre><code>/* lut[n] contains 3^n */
mpz_t lut[LUT_SIZEMPZ];
</code></pre>
<p>Additionally, the following auxiliary function is defined.</p>
<pre><code>/* count trailing zeros */
mp_bitcnt_t mpz_ctz(const mpz_t n)
{
return mpz_scan1(n, 0);
}
</code></pre>
<h2>Problem</h2>
<p>This code review request follows my previous request <a href="https://codereview.stackexchange.com/questions/226835/computational-verification-of-collatz-conjecture">Computational verification of Collatz conjecture</a>. The implementation in this request should handle the numbers which cannot be handled with the code in previous post.</p>
<p>In short: My program verifies the convergence of the <a href="https://en.wikipedia.org/wiki/Collatz_conjecture" rel="nofollow noreferrer">Collatz problem</a>, using <a href="https://math.stackexchange.com/questions/3330085/computational-verification-of-collatz-problem">this algorithm</a>. The convergence for all values <code>n</code> ≤ 87 × 2<sup>60</sup> has already been proven.</p>
<p>The following function is called for <code>n</code> of the form <span class="math-container">\$4n+3\$</span>, in order from the smallest one to the largest one, only if all preceding calls returned zero.</p>
<p>This function should either</p>
<ul>
<li>return <code>0</code> if the problem for the <code>n</code> is convergent, or</li>
<li>loop infinitely if the trajectory for the <code>n</code> is cyclic.</li>
</ul>
<h1>Code</h1>
<p>The 128-bit input <code>n</code> is split into two 64-bit parts <code>nh</code> and <code>nl</code> such that <code>n = nh * 2^64 + nl</code>.</p>
<pre><code>int check_convergence(unsigned long nh, unsigned long nl)
{
mpz_t n;
mpz_t n0;
mpz_t n_max;
mp_bitcnt_t e;
mpz_init_set_ui(n, nh);
mpz_mul_2exp(n, n, (mp_bitcnt_t)64);
mpz_add_ui(n, n, nl);
mpz_init_set_ui(n_max, 87UL);
mpz_mul_2exp(n_max, n_max, (mp_bitcnt_t)60);
mpz_init_set(n0, n);
do {
if (mpz_cmp(n, n_max) <= 0) {
mpz_clear(n);
mpz_clear(n0);
mpz_clear(n_max);
return 0;
}
mpz_add_ui(n, n, 1UL);
e = mpz_ctz(n);
mpz_fdiv_q_2exp(n, n, e);
assert( e < LUT_SIZEMPZ );
mpz_mul(n, n, lut[e]);
mpz_sub_ui(n, n, 1UL);
mpz_fdiv_q_2exp(n, n, mpz_ctz(n));
if (mpz_cmp(n, n0) < 0) {
mpz_clear(n);
mpz_clear(n0);
mpz_clear(n_max);
return 0;
}
} while (1);
}
</code></pre>
|
[] |
[
{
"body": "<p>If you need a type with exactly 64 bits, use <code>uint64_t</code> (from <code><stdint.h></code>). That will give a clear compilation error if no such type is available.</p>\n\n<p>Given that the function never returns anything other than zero, we can move the cleanup of <code>n</code>, <code>n0</code> and <code>n_max</code> outside the loop, and simply <code>break</code> to reach them.</p>\n\n<p>Is indefinite looping really a good output if a cycle is detected? How is that distinguishable from an arbitrarily long (but finite) chain? Look up the standard algorithms for cycle detection in your graph theory textbook.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:04:47.733",
"Id": "441562",
"Score": "0",
"body": "The problem with gmplib is that it does not support `uint64_t`. It only supports standard C types like `unsigned int`: https://gmplib.org/manual/Assigning-Integers.html#Assigning-Integers"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:11:32.907",
"Id": "441563",
"Score": "0",
"body": "The program is part of distributed computing project. I cannot distinguish these two situations. I can however focus on particular assignments that have not been returned for a long time or that have not been returned from several different nodes."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T12:54:02.523",
"Id": "227004",
"ParentId": "227002",
"Score": "3"
}
},
{
"body": "<p>I would use <code>uint64_t</code> even if the API asks for an <code>unsigned long</code>. It's far more precise about what it is, and you can always ensure that both are the same.</p>\n\n<p>Assuming your C version is >= GNU C11 you can use the following code just below your <code>#include</code>s (actually anywhere, but I like it on top):</p>\n\n<pre><code>_Static_assert(__builtin_types_compatible_p(uint64_t, unsigned long),\n \"uint64_t != unsigned long\");\n</code></pre>\n\n<p>This code doesn't need to go inside a function.</p>\n\n<p>If you just have C99 (Edit: GNU C99), you can do something similar:</p>\n\n<pre><code>#if (sizeof(uint64_t) != sizeof(unsigned long))\n#error \"uint64_t != unsigned long\"\n#endif\n</code></pre>\n\n<p>You could even write your own wrapper around GMP functions that uses <code><stdint.h></code> types.</p>\n\n<p>If for whatever reason <code>unsigned long</code> changed suddenly to <code>uint32_t</code> or <code>uint128_t</code>, you would notice, instead of having new bugs everywhere.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T12:54:54.100",
"Id": "441732",
"Score": "1",
"body": "I have received similar feedback through github today. I'll make over wrappers for ligmp functions. Anyhow, I use the C89 standard (+ GNU extensions), but it shouldn't matter so much. You should be however aware of that the `#if (sizeof(uint64_t) != sizeof(unsigned long))` is compiler extension. The C preprocessor does not know the unary operator `sizeof`. The fact that these constructs work is just due to extensions of compilers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T12:56:31.963",
"Id": "441733",
"Score": "0",
"body": "Anyway, good feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T13:19:15.550",
"Id": "441735",
"Score": "0",
"body": "@DaBler Yes, it was me in GitHub :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T13:21:56.877",
"Id": "441736",
"Score": "0",
"body": "@DaBler Good to know that about `sizeof`. I thought it was standard. I found this interesting: https://stackoverflow.com/q/4079243/6872717"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T15:16:03.110",
"Id": "441762",
"Score": "0",
"body": "I posted a comment in GitHub to you..."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T12:16:20.067",
"Id": "227083",
"ParentId": "227002",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227004",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T11:53:49.040",
"Id": "227002",
"Score": "3",
"Tags": [
"c",
"mathematics",
"integer",
"collatz-sequence"
],
"Title": "Computational verification of Collatz conjecture using gmplib"
}
|
227002
|
<h1>Objective</h1>
<p>I have following array and would like to group by each child and get its smallest <code>Id</code>:-</p>
<pre><code>var list = new[]
{
new { Id = 1, Childs = new [] { 'a', 'b' } },
new { Id = 2, Childs = new [] { 'a' } },
new { Id = 3, Childs = new [] { 'a', 'c' } },
new { Id = 4, Childs = new [] { 'b' } },
new { Id = 5, Childs = new [] { 'b' } },
new { Id = 6, Childs = new [] { 'b', 'c' } },
};
</code></pre>
<h1>Attempt</h1>
<pre><code>var groups = list
.SelectMany(item => item.Childs)
.Distinct() // for each unique child
.ToDictionary(
child => child, // with each child as key
child => list.Where(item =>
item.Childs.Any(c =>
c == child)) // get items with corresponding child
.Min(item => item.Id)); // extract min Id
foreach (var g in groups)
{
Console.WriteLine($"{ g.Key }: { g.Value }");
}
// Prints
// a: 1
// b: 1
// c: 3
</code></pre>
<h1>Rationale</h1>
<p><strong>a</strong> contains in <code>Id</code> 1, 2 and 3 and the smallest is 1.</p>
<h1>Improvement</h1>
<p>I'm trying to solve it with LINQ and thinking <code>GroupBy</code> would be the go-to solution but I'm stuck with splitting each child element as the key.</p>
<p>I would really appreciate if someone have any idea to solve it in a more elegant way! </p>
|
[] |
[
{
"body": "<p>Indeed, you could use <code>GroupBy</code> but I think it's easier to solve with the query syntax because we also need the <code>item</code> from the first list to sort by its <code>Id</code>. Without it, we would need to do additional lookups like you do.</p>\n\n<pre><code>var result = \n from item in items // from + from = SelectMany\n from child in item.Children\n orderby item.Id // sort in ascending order\n group item.Id by child into g // group by child\n select (Child: g.Key, MinId: g.First()); // the first item in each group is the min-id\n</code></pre>\n\n<p>If you use <code>select g</code> instead, you'll get <code>IGrouping<char, int></code> which you can easily turn into a dictionary or a lookup.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:28:33.943",
"Id": "227008",
"ParentId": "227003",
"Score": "4"
}
},
{
"body": "<p>First, you're going through the list of items to find all distinct children. Then, for each child, you're going through the list again to find all items that it belongs to, and then you take the lowest item ID. That's <span class=\"math-container\">\\$O(n^2)\\$</span> in worst-case scenarios, though in practice it'll be closer to <span class=\"math-container\">\\$O(n)\\$</span> if you don't have too many distinct children.</p>\n\n<p>A more efficient approach would be to create ID-child pairs, which allows you to group item IDs per child, and then extract the lowest ID from each group:</p>\n\n<pre><code>list.SelectMany(item => item.Childs.Select(child => new { Id = item.Id, Child = child }))\n .GroupBy(item => item.Child, item => item.Id)\n .ToDictionary(\n group => group.Key,\n group => group.Min(id => id));\n</code></pre>\n\n<p>However, creating a dictionary with a nested loop is still several times faster, and less GC-intensive, while taking about the same 'amount' of code, so I'm not so sure about Linq being the best choice here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:47:10.160",
"Id": "227010",
"ParentId": "227003",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "227010",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T12:06:21.923",
"Id": "227003",
"Score": "4",
"Tags": [
"c#",
"linq",
"hash-map"
],
"Title": "Reverse Dictionary: Group from child array elements and get its minimum key"
}
|
227003
|
<p>Recently, I started reading image processing via opencv library in python.</p>
<p>I create a minio object storage and upload some photos into it. After that, I wrote a program which reads every image in each bucket in minio and watermark it with a simple logo. I read each image with <code>imread</code> and finally (after inserting a watermark), save it with <code>imwrite</code> (on the same image).</p>
<p>But when testing my code, I saw that for each image it took about 0.4 seconds. Since I want to do this simple operation for a lot of images, this time is not acceptable.</p>
<p>Here is a part of my simple code:</p>
<pre><code>import cv2
import numpy as np
logo_img = cv2.imread('logo.png', cv2.IMREAD_UNCHANGED)
scl = 50
w = int(logo_img.shape[1] * scl / 100)
h = int(logo_img.shape[0] * scl / 100)
dim = (w, h)
logo = cv2.resize(logo_img, dim, interpolation=cv2.INTER_AREA)
logo_height, logo_width = logo.shape[:2]
def watermark_image(image_name):
image = cv2.imread(image_name)
image_height, image_width = image.shape[:2]
image = np.dstack([image, np.ones((image_height, image_width), dtype="uint8") * 255])
# Blend
ovr = np.zeros((image_height, image_width, 4), dtype="uint8")
x_pos = int(random() * (image_height - 10 - logo_width))
y_pos = int(random() * (image_width - 10 - logo_height))
ovr[x_pos:x_pos + logo_height, y_pos:y_pos + logo_width] = logo
image = cv2.addWeighted(ovr, 0.6, image, 1.0, 0, image)
cv2.imwrite(image_name, image)
import time
start = time.time()
for bucket in buckets:
objects = minioClient.list_objects(bucket.name, prefix=None, recursive=True)
for current_object in objects:
watermark_image('./test/' + current_object.object_name)
end = time.time()
print(end - start)
</code></pre>
<p>How can I improve my code and optimize it in order to need less runtime?</p>
<p>Suppose that I have a object storage which contains a lot of image. Actually I want to prepare an API, for people to request a watermark for every image and then I want to show them requested image after watermarking it online.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:14:55.733",
"Id": "441564",
"Score": "0",
"body": "did you check whether most time was spent in the downloading/uploading, or the watermarking?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:20:03.940",
"Id": "441567",
"Score": "0",
"body": "@maartenFabre most of time is for watermarking. i test it again and just for calling watermark, it is spent about 0.4 second, as seen before."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T16:37:29.170",
"Id": "441608",
"Score": "1",
"body": "How large are the images you are using to test this?"
}
] |
[
{
"body": "<p>I'll focus more on the</p>\n\n<blockquote>\n <p>How can I improve my code</p>\n</blockquote>\n\n<p>part of your question.</p>\n\n<h2>Imports at the top</h2>\n\n<p>Move your <code>import time</code> to the top of the file, which is standard in Python.</p>\n\n<h2>Code in functions</h2>\n\n<p>Your logo dimension calculation should be in a function instead of global scope. The code at the bottom should be in a top-level <code>main</code> function.</p>\n\n<h2>Integer division</h2>\n\n<pre><code>w = int(logo_img.shape[1] * scl / 100)\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>w = logo_img.shape[1] * scl // 100\n</code></pre>\n\n<h2>Use pathlib</h2>\n\n<p>...so that this:</p>\n\n<pre><code>'./test/' + current_object.object_name\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>Path('test') / current_object.object_name\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T14:02:51.680",
"Id": "441579",
"Score": "0",
"body": "thank you but my means was improve duration time not style code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T16:35:17.800",
"Id": "441607",
"Score": "2",
"body": "@cutename, by asking on Code Review, you should expect reviewers to assess *any and all aspects of your code* - askers don't get to constrain reviewers like that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:30:08.527",
"Id": "227009",
"ParentId": "227006",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:05:21.673",
"Id": "227006",
"Score": "1",
"Tags": [
"python",
"performance",
"image",
"opencv"
],
"Title": "Add watermark to images"
}
|
227006
|
<p>We have a macro that updates all dates/years in all our pivottables (around 100 of them pulling out data from our OLAP cube) based off of a "Master Date" at the top of our sheet (which is being updated monthly).
The problem is, that the way we're doing it, takes up a lot of space, and we've been forced to split the macro into multiple subs since it started exceeding the compile limit.</p>
<p>As you can see in the code example, its a very primitive way of updating the dates.</p>
<p>The next big problem is that the "YearMonth" filter that is being used to show the year and month is different, because some PT are looking at order quantity (QtyOrdered) and some are looking at sales quantity (QtyCustPackSlip), whihch are using a separate "YearMonth" filter.</p>
<pre><code>Sub UpDateAllPivots()
' UpDateAllPivots Macro, nr.1
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
'These ranges are the "Master Date
D1 = Sheets("DATA").Range("B6").Value
D2 = Sheets("DATA").Range("C6").Value
D3 = Sheets("DATA").Range("D6").Value
D4 = Sheets("DATA").Range("E6").Value
D5 = Sheets("DATA").Range("F6").Value
D6 = Sheets("DATA").Range("G6").Value
D7 = Sheets("DATA").Range("H6").Value
D8 = Sheets("DATA").Range("I6").Value
D9 = Sheets("DATA").Range("J6").Value
D10 = Sheets("DATA").Range("K6").Value
D11 = Sheets("DATA").Range("L6").Value
D12 = Sheets("DATA").Range("M6").Value
'This is a PT looking at QtyOrdered, using the Date.YearMonth
ActiveSheet.PivotTables("PivotTable1").PivotFields( _
"[Date].[YearMonth].[YearMonth]").VisibleItemsList = Array("", _
"[Date].[YearMonth].&[" & D1 & "]", "[Date].[YearMonth].&[" & D2 & "]", "[Date].[YearMonth].&[" & D3 & "]", _
"[Date].[YearMonth].&[" & D4 & "]", "[Date].[YearMonth].&[" & D5 & "]", "[Date].[YearMonth].&[" & D6 & "]", _
"[Date].[YearMonth].&[" & D7 & "]", "[Date].[YearMonth].&[" & D8 & "]", "[Date].[YearMonth].&[" & D9 & "]", _
"[Date].[YearMonth].&[" & D10 & "]", "[Date].[YearMonth].&[" & D11 & "]", "[Date].[YearMonth].&[" & D12 & "]")
'This is a PT looking at QtyCustPackSlip, using the StatusPickedDatetimeKey
ActiveSheet.PivotTables("PivotTable3").PivotFields( _
"[StatusPickedDatetimeKey].[YearMonth].[YearMonth]").VisibleItemsList = Array("", _
"[StatusPickedDatetimeKey].[YearMonth].&[" & D1 & "]", "[StatusPickedDatetimeKey].[YearMonth].&[" & D2 & "]", "[StatusPickedDatetimeKey].[YearMonth].&[" & D3 & "]", _
"[StatusPickedDatetimeKey].[YearMonth].&[" & D4 & "]", "[StatusPickedDatetimeKey].[YearMonth].&[" & D5 & "]", "[StatusPickedDatetimeKey].[YearMonth].&[" & D6 & "]", _
"[StatusPickedDatetimeKey].[YearMonth].&[" & D7 & "]", "[StatusPickedDatetimeKey].[YearMonth].&[" & D8 & "]", "[StatusPickedDatetimeKey].[YearMonth].&[" & D9 & "]", _
"[StatusPickedDatetimeKey].[YearMonth].&[" & D10 & "]", "[StatusPickedDatetimeKey].[YearMonth].&[" & D11 & "]", "[StatusPickedDatetimeKey].[YearMonth].&[" & D12 & "]")
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
</code></pre>
<p>What we ultimately want is to compress it into something that isn't as big, since we're only getting more data. You can imagine how big this is with 100+ PT's and growing.</p>
<p>I was wondering if you could make a loop that looks through all used rows, looking for pivottable1-pivottable(n+1), seing if it exist. If it does exist, then it goes through a switch with two cases being that it either uses QtyOrdered ot QtyCustPackSlip, and updates the .YearMonth accordingly.</p>
|
[] |
[
{
"body": "<p>Comepletely forgot to post an answer to this, that i found a little after asking this question. Hopefully someone can use it</p>\n\n<p>The code we used before was not optimal and messy, since you had to write those six lines of code for each PT, and every time you added a new PT.</p>\n\n<p>I then realised you could just add some <code>for each ... then</code> loops that would go through not only every PT, but also each field in the PT, and then I could add the <code>If / elsif</code> that would check which field each PT is using, and have it correct the dates accordingly. </p>\n\n<p>I had to set the pt anme as a string <code>pts = pt</code> for it to recognize it as a name (I don't know why exactly), but just having it as <code>ActiveSheet.PivotTables(pt).PivotFields( _ ....</code> Didn't work as it thought the name was \"pt\" and not the actualt name like \"PivotTable1\"..</p>\n\n<p>It works as intended, the process takes about 1 min to complete. I suspect you can make it faster, but I havn't looked at it.</p>\n\n<pre><code>Sub UpdateAllPivots_new()\n'\n'Looks through all pivots in the sheet and updates the dates accordingly\n'\n'Update time is approx. 1 min (How can this be improved)\n'\n\nDim ws As Worksheet\nDim pt As PivotTable\nDim pf As PivotField\nDim pi As PivotItem\nDim pts As String\n\n D1 = Sheets(\"DATA\").Range(\"B6\").Value\n D2 = Sheets(\"DATA\").Range(\"C6\").Value\n D3 = Sheets(\"DATA\").Range(\"D6\").Value\n D4 = Sheets(\"DATA\").Range(\"E6\").Value\n D5 = Sheets(\"DATA\").Range(\"F6\").Value\n D6 = Sheets(\"DATA\").Range(\"G6\").Value\n D7 = Sheets(\"DATA\").Range(\"H6\").Value\n D8 = Sheets(\"DATA\").Range(\"I6\").Value\n D9 = Sheets(\"DATA\").Range(\"J6\").Value\n D10 = Sheets(\"DATA\").Range(\"K6\").Value\n D11 = Sheets(\"DATA\").Range(\"L6\").Value\n D12 = Sheets(\"DATA\").Range(\"M6\").Value\n\n\nApplication.Calculation = xlCalculationManual\nApplication.ScreenUpdating = False\nApplication.DisplayStatusBar = False\nApplication.EnableEvents = False\n\nSet ws = ActiveSheet\n\n For Each pt In ws.PivotTables\n pts = pt \n\n For Each pf In pt.PivotFields\n\n\n If pf.Name = \"[StatusPickedDatetimeKey].[YearMonth].[YearMonth]\" Then\n ActiveSheet.PivotTables(pts).PivotFields( _\n \"[StatusPickedDatetimeKey].[YearMonth].[YearMonth]\").VisibleItemsList = Array(\"\", _\n \"[StatusPickedDatetimeKey].[YearMonth].&[\" & D1 & \"]\", \"[StatusPickedDatetimeKey].[YearMonth].&[\" & D2 & \"]\", \"[StatusPickedDatetimeKey].[YearMonth].&[\" & D3 & \"]\", _\n \"[StatusPickedDatetimeKey].[YearMonth].&[\" & D4 & \"]\", \"[StatusPickedDatetimeKey].[YearMonth].&[\" & D5 & \"]\", \"[StatusPickedDatetimeKey].[YearMonth].&[\" & D6 & \"]\", _\n \"[StatusPickedDatetimeKey].[YearMonth].&[\" & D7 & \"]\", \"[StatusPickedDatetimeKey].[YearMonth].&[\" & D8 & \"]\", \"[StatusPickedDatetimeKey].[YearMonth].&[\" & D9 & \"]\", _\n \"[StatusPickedDatetimeKey].[YearMonth].&[\" & D10 & \"]\", \"[StatusPickedDatetimeKey].[YearMonth].&[\" & D11 & \"]\", \"[StatusPickedDatetimeKey].[YearMonth].&[\" & D12 & \"]\")\n\n ElseIf pf.Name = \"[Date].[YearMonth].[YearMonth]\" Then\n ActiveSheet.PivotTables(pts).PivotFields( _\n \"[Date].[YearMonth].[YearMonth]\").VisibleItemsList = Array(\"\", _\n \"[Date].[YearMonth].&[\" & D1 & \"]\", \"[Date].[YearMonth].&[\" & D2 & \"]\", \"[Date].[YearMonth].&[\" & D3 & \"]\", _\n \"[Date].[YearMonth].&[\" & D4 & \"]\", \"[Date].[YearMonth].&[\" & D5 & \"]\", \"[Date].[YearMonth].&[\" & D6 & \"]\", _\n \"[Date].[YearMonth].&[\" & D7 & \"]\", \"[Date].[YearMonth].&[\" & D8 & \"]\", \"[Date].[YearMonth].&[\" & D9 & \"]\", _\n \"[Date].[YearMonth].&[\" & D10 & \"]\", \"[Date].[YearMonth].&[\" & D11 & \"]\", \"[Date].[YearMonth].&[\" & D12 & \"]\")\n\n End If\n\n\n Next pf\n\n Next pt\n\n\nApplication.Calculation = xlCalculationAutomatic\nApplication.ScreenUpdating = True\nApplication.DisplayStatusBar = True\nApplication.EnableEvents = True\n\nEnd Sub\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T06:57:22.333",
"Id": "229892",
"ParentId": "227011",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "229892",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T13:50:26.520",
"Id": "227011",
"Score": "1",
"Tags": [
"vba",
"excel"
],
"Title": "Look for existing pivottables and change date/year colums based off the “Value” filter"
}
|
227011
|
<p>The problem I'm solving is:</p>
<blockquote>
<p>given a length of an arithmetic progression, and a limit to the
terms (see below), find all progressions that work.</p>
<p>All terms of the progressions must be of the form a²+b², and
0 ≤ a²+b² ≤ limit.</p>
</blockquote>
<p>I have the following code:</p>
<pre class="lang-py prettyprint-override"><code>from math import ceil
with open('ariprog.in') as fin:
ariLen = int(fin.readline().strip())
ariLim = int(fin.readline().strip())
def generate(bound):
max_len=((bound**2)*2)+1
parity = [0]*max_len
for i in range(bound+1):
for j in range(bound+1):
parity[i**2+j**2] = 1
return parity
parity = generate(ariLim)
lenpar = len(parity)
big_mama_ar = []
# print(lenpar)
for a in range(lenpar-1):
if parity[a] == 1:
for d in range(1, ceil((lenpar-a)/(ariLen-1))):
for n in range(1, ariLen):
# print('a:', a)
# print('d:', d)
# print('n:', n)
if parity[a+n*d] != 1:
break
else:
big_mama_ar.append((a,d))
pass
big_mama_ar.sort(key=lambda x: x[1])
with open('ariprog.out', 'w') as fout:
if big_mama_ar == []:
fout.write('NONE\n')
else:
for i in big_mama_ar:
fout.write(str(i[0])+' '+str(i[1])+'\n')
</code></pre>
<p>This code times out on my grader when <code>ariLen</code> is 21 and <code>ariLim</code> is 200. The time limit is 5 seconds, and on my computer, it takes 22 seconds.
ariprog.in is</p>
<blockquote>
<p>21</p>
<p>200</p>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T18:29:47.413",
"Id": "441629",
"Score": "2",
"body": "How can we run this code? What's in that *ariprog.in* file?"
}
] |
[
{
"body": "<p>Welcome to CodeReview!</p>\n\n<h2>Whitespace</h2>\n\n<p>The PEP8 standard, and consequently most Python linting tools, will recommend that you add another linebreak before your function definitions, plus some whitespace around your operators, etc. I won't detail this exhaustively; you're best to use the IDE of your choice - PyCharm is a reasonable one that is helpful for this.</p>\n\n<h2>Type hinting</h2>\n\n<p><code>bound</code> is probably an integer, so add <code>: int</code> after it. It probably returns an <code>int</code> as well.</p>\n\n<h2>Subroutines</h2>\n\n<p>Put your global-scoped code into subroutines for ease of maintenance, legibility and testing.</p>\n\n<h2>Redundant <code>pass</code></h2>\n\n<p>That <code>pass</code> isn't needed.</p>\n\n<h2>Use format strings</h2>\n\n<p>This:</p>\n\n<pre><code>str(i[0])+' '+str(i[1])+'\\n'\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>f'{i[0]} {i[1]}\\n'\n</code></pre>\n\n<h2>Simplify some math</h2>\n\n<p>This:</p>\n\n<pre><code>((bound**2)*2)+1\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>2 * bound**2 + 1\n</code></pre>\n\n<p>due to operator precedence.</p>\n\n<h2>Truthiness</h2>\n\n<p>This:</p>\n\n<pre><code>if parity[a+n*d] != 1:\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>if not parity[a + n*d]:\n</code></pre>\n\n<p>because 0 is falsey.</p>\n\n<h2>camel_case</h2>\n\n<p><code>ariLen</code> is more commonly written <code>ari_len</code> in Python.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T07:35:27.173",
"Id": "441693",
"Score": "2",
"body": "Not just \"because 0 is falsey\" - but because 1 is the only truthy value we'll get. If `parity` could be 2, for example, then those tests wouldn't be equivalent."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T01:12:13.410",
"Id": "227053",
"ParentId": "227020",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "227053",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T16:04:28.483",
"Id": "227020",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"time-limit-exceeded"
],
"Title": "USACO Arithmetic Progressions"
}
|
227020
|
<p>Converting words to morse code and vice versa using dictionaries and that's it.</p>
<pre><code>morse_code = {'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....',
'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.',
'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-',
'Y': '-.--', 'Z': '--..', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....',
'6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----', ' ': ' '}
def convert_to_morse_code(word):
string = ''
for letternum in word:
if letternum.isalnum():
string += f'{morse_code[letternum.upper()]} '
else:
string += ' '
return string
def convert_to_word(word):
string = ''
if ' ' in word:
word = word.replace(' ', '</<')
if ' ' in word:
word = word.replace(' ', '<')
for code in word:
if code == '/':
word = word.replace(code, ' ')
word = word.split('<')
for code in word:
for key in morse_code.keys():
if morse_code[key] == code:
string += key
return string
print(convert_to_morse_code('HI MICHAEL'))
print(convert_to_word('.... .. -- .. -.-. .... .- . .-..'))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T17:08:14.293",
"Id": "441615",
"Score": "2",
"body": "Do you want any specific aspects of your code reviewd?"
}
] |
[
{
"body": "<p>The question could benefit from some context. You don't need to answer every one of the following, but it would be helpful for reviewers.</p>\n\n<ol>\n<li>Why have you written a morse code converter?</li>\n<li>Is this going to be used by anyone else or is it a personal project? Is it a homework question? From this we can tell if the review should focus on finding security holes, or just annoying bugs.</li>\n<li>What will the input look like? Can we assume nobody is going to call convert_to_word with a letters that aren't dot, dash, or space?</li>\n</ol>\n\n<hr>\n\n<pre><code>def convert_to_morse_code(word):\n ...\n\ndef convert_to_word(word):\n ...\n</code></pre>\n\n<p>This looks a little funny, as they both take a \"word\", yet neither does. One takes a string which may have complete sentences, and the other takes a string containing morse code. I'd suggest adding a docstring for these functions which gives a brief explanation about the expected input.</p>\n\n<hr>\n\n<pre><code>if letternum.isalnum():\n string += f'{morse_code[letternum.upper()]} '\nelse:\n string += ' '\n</code></pre>\n\n<p>What happens if somebody comes along and helpfully adds some international morse code symbols such as \"?\" or \"+\" to the dictionary? This code will ignore those. I think the dictionary should be the source of truth, not isalnum.</p>\n\n<pre><code>if letternum.upper() in morse_code:\n string += morse_code[letternum.upper()] + ' '\nelse:\n string += ' '\n</code></pre>\n\n<p>The above possibility shows that letternum is no longer an appropriate name. Lets update it the name to c or char, short for character, which is what it is. The other change I would propose here is to use the dictionary method <a href=\"https://www.tutorialspoint.com/python3/dictionary_get.htm\" rel=\"nofollow noreferrer\">.get</a> as it has a handy parameter 'default value'. If we set the default value as ' ' (for when the character is not a symbol we know how to write in morse code) this takes the place of the else branch.</p>\n\n<pre><code>for char in word:\n string += morse_code.get(char, ' ') + ' '\n</code></pre>\n\n<p>I think it would be worth noting in the docstring for this function that unrecognised characters are skipped, and this is the line responsible.</p>\n\n<hr>\n\n<pre><code>for code in word:\n if code == '/':\n word = word.replace(code, ' ')\n</code></pre>\n\n<p>In general it is a bad idea to modify the thing you are looping over. It can lead to hard to spot bugs. The other thing to note is that the first time '/' is encountered, all occurrences of it are replaced. This doesn't need to be in a loop.</p>\n\n<hr>\n\n<pre><code> for key in morse_code.keys():\n if morse_code[key] == code:\n string += key\n</code></pre>\n\n<p>This loop does a little more work than is necessary. It will get slower and slower each time a new symbol is added to the dictionary. The performance loss will honestly not be noticeable, but if you think the solution sounds nicer you can try implementing it.</p>\n\n<p>The solution is to build a new map which is the inverse of morse_code, where all the keys become values and all the values become keys.</p>\n\n<pre><code>morse_code = {...}\ncode_to_char = {code: char for char, code in morse_code.items()}\n...\n\n if code in code_to_char:\n string += code_to_char[code]\n</code></pre>\n\n<hr>\n\n<p>There are some small problems to which you will need to decide on the answer.</p>\n\n<ol>\n<li><code>convert_to_word(convert_to_morse_code(\"Hello, world!\"))</code> outputs <code>'HELLO WORLD '</code>. Is that ok? Should the output match the input more closely? Why is there trailing space?</li>\n<li><code>convert_to_morse_code(\"HI LOW\")</code> outputs <code>'.... .. .-.. --- .-- '</code>. Some variations exist, such as using a slash to indicate a space (<code>'.... .. / .-.. --- .--'</code>) or seven dots (<code>.... .. ....... .-.. --- .--</code>). Could your code have that as an optional feature?</li>\n<li><code>convert_to_word</code> works on some weird input, and not on others. But it does not ever tell the user when something is wrong. I'd prefer if <code>convert_to_word('--- -, .')</code> failed in some way rather than returning <code>'OE'</code>.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T17:40:29.413",
"Id": "227027",
"ParentId": "227021",
"Score": "3"
}
},
{
"body": "<pre><code>if __name__ == '__main__':\n</code></pre>\n\n<p>use this guard that allows you to import from this script without running the code.</p>\n\n<pre><code>if __name__ == '__main__':\n print(convert_to_morse_code('HI MICHAEL'))\n print(convert_to_word('.... .. -- .. -.-. .... .- . .-..'))\n</code></pre>\n\n<h1>Style</h1>\n\n<p>check PEP0008 <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0008/</a> the official Python style guide and here are a few comments:</p>\n\n<ul>\n<li><p><strong>Docstrings:</strong> Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. An object's docstring is defined by including a string constant as the first statement in the object's definition. Use docstrings in the following way to indicate what your functions do:</p>\n\n<pre><code>def convert_to_morse(text):\n \"\"\"Convert text to Morse code.\"\"\"\n # code goes here\n\ndef convert_morse_to_word(morse_code):\n \"\"\"Convert Morse code to alphanumeric words.\"\"\"\n # code goes here\n</code></pre></li>\n<li><p><strong>Blank lines</strong> use blank lines sparingly (too many blank lines in your script)</p>\n\n<pre><code>string = ''\n\nif ' ' in word:\n word = word.replace(' ', '</<')\nif ' ' in word:\n word = word.replace(' ', '<')\nfor code in word:\n if code == '/':\n word = word.replace(code, ' ')\n\nword = word.split('<')\n\nfor code in word:\n for key in morse_code.keys():\n if morse_code[key] == code:\n string += key\n\nreturn string\n</code></pre></li>\n</ul>\n\n<h1>Code</h1>\n\n<ul>\n<li><p>f- strings provide a way to embed expressions inside string literals, using a minimal syntax and are not supposed to be used this way:</p>\n\n<pre><code>string += f'{morse_code[letternum.upper()]} '\n</code></pre>\n\n<p>could be written:</p>\n\n<pre><code>string += morse_code[letternum.upper()]\n</code></pre></li>\n<li><p>isalnum() a bad idea if you want to include punctuation and spaces\nand Morse code does not exclude punctuation btw.</p></li>\n<li>string += this is inefficient because strings cannot be changed in place so each time you add to the string, a new string is created. A better approach is to use list comprehensions and join the results.\nWe have to reconstruct dictionary based on the following international Morse code:</li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/D3BWJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/D3BWJ.png\" alt=\"International Morse code.\"></a></p>\n\n<p>and the code looks like:</p>\n\n<pre><code>def get_translation(translate_to):\n \"\"\"\n Return a dictionary from to (Morse code-text)\n assuming translate_to a string:\n m for translation to Morse\n t for translation to text.\n \"\"\"\n morse_code = {\n 'a': '·-', 'b': '-···', 'c': '-·-·', 'd': '-··', 'e': '.', 'f': '..-.', 'g': '--.',\n 'h': '····', 'i': '··', 'j': '·---', 'k': '-.-', 'l': '.-..', 'm': '--',\n 'n': '-·', 'o': '---', 'p': '·--.', 'q': '--.-', 'r': '·-.', 's': '...', 't': '-',\n 'u': '..-', 'v': '···-', 'w': '·--', 'x': '-..-', 'y': '-.--', 'z': '--..',\n 'á': '.--.-', 'ä': '.-.-', 'é': '..-..', 'ñ': '--.--', 'ö': '---.', 'ü': '..--', \"'\": '·----·',\n '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....',\n '6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----', '!': '-·-·--',\n '.': '.-.-.-', ',': '--..--', '?': '..--..', ':': '---...', \"\\\"\": '.-..-.',\n '-': '-....-', '/': '-..-.', '(': '-.--.', ')': '-.--.-', ' ': '\\t', '\\n': '\\t', '_': '··--·-'\n }\n morse_to_letter = {code: letter for letter, code in morse_code.items()}\n if translate_to == 'm':\n return morse_code\n if translate_to == 't':\n return morse_to_letter\n else:\n raise ValueError(f'Invalid input{translate_to} expected m or t')\n\n\ndef convert_to_morse_code(text):\n \"\"\"Translate text to Morse code.\"\"\"\n morse_code = get_translation('m')\n return ' '.join([morse_code[letter] for letter in text.lower()])\n\n\ndef convert_morse_code_to_text(morse_code):\n \"\"\"Translate from Morse code to text.\"\"\"\n morse_to_letter = get_translation('t')\n text = []\n words = morse_code.split('\\t')\n for word in words:\n letters = word.split()\n to_text = [morse_to_letter[letter] for letter in letters]\n text.append(''.join(to_text))\n return ' '.join(text)\n\n\nif __name__ == '__main__':\n print(convert_to_morse_code('Hello Michael! How are you doing today?'))\n print(convert_morse_code_to_text('·· ·----· -- ..-. ·· -· . - ···· ·- -· -.- ... .-.-.-'))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T21:30:31.357",
"Id": "441661",
"Score": "0",
"body": "I am not the most familiar with the single-line list comprehensions could you dissect the code a little more, please? Additionally, I derived this from CodeWars where spaces between words are 3, and for letters, are 1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T21:30:47.330",
"Id": "441662",
"Score": "0",
"body": "Might want to check this link: https://www.programiz.com/python-programming/list-comprehension"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T21:33:25.873",
"Id": "441663",
"Score": "0",
"body": "You should've indicated the 3 spaces thing in the description above and a link to the problem indicating input and desired output if you want the results to be exact. However the code I provided does the same functionality using a tab for words '\\t' and 1 space for letters."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T21:09:01.340",
"Id": "227043",
"ParentId": "227021",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T16:29:05.600",
"Id": "227021",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"programming-challenge",
"morse-code"
],
"Title": "Challenge: MORSE_CODE.PY"
}
|
227021
|
<h1>Building on previous reviews</h1>
<p>Whilst not an <a href="https://codereview.meta.stackexchange.com/q/1763">iterative review</a> I have tried to follow the advice provided to some of my older questions:</p>
<ol>
<li><p>KISS, in some of my previous questions I've over complicated the design.</p>
<p>Even though I'm doing quite a lot I've tried to keep everything as simple as possible.
I think I achieved this in the majority of my code, where only my coroutines may have been a bit heavy handed.
Even then I think the design still is fairly simple as the magic is hidden away in a fully documented wrapper.</p></li>
<li><p>Lack of documentation / comments.</p>
<p>In this program I feel that only one function required comments as it performs some magic that I didn't really understand when implementing it.</p>
<p>I've also added docstrings to everything, which removes the need for most comments.
I feel some of my docstrings are good and achieve their goal of saying what the program does.
However the majority I feel are somewhat underwhelming, as they're pretty much just a single comment echoing the name of the function/class/method they're 'documenting'.</p></li>
<li><p>PEP 8 violations.</p>
<p>I've run a rather large amount of static analysis tools over the code. Most issues raised by these tools are, as far as I know, no longer PEP 8 issues. The majority are that mypy and pylint can't import the libraries I've used.</p></li>
</ol>
<p>And so if my code exhibits any of these problems it would be great to know, with how to fix it.<br>
Don't forget that <strong><a href="https://codereview.stackexchange.com/help/how-to-answer">an answer only needs to make one insightful observation</a></strong>.</p>
<h1>What my program does</h1>
<p>My <a href="https://github.com/Peilonrayz/stack_exchange_graph_data/tree/03c530547f10aa858e5a485b51da8c018eee57b0" rel="noreferrer">full code can be seen on Git Hub</a> and the documentation can be built using <code>tox -e docs</code>. Alternately you can <a href="https://peilonrayz.github.io/stack_exchange_graph_data/index.html" rel="noreferrer">view the documentation online</a>. Whilst <a href="https://peilonrayz.github.io/stack_exchange_graph_data/docs/stack_exchange_graph_data.html#module-stack_exchange_graph_data" rel="noreferrer">this page</a> explains the entire code in greater depth the following is a short description.</p>
<p>Running <code>segd meta.codereview</code> does:</p>
<ol>
<li>Download the <a href="https://archive.org/download/stackexchange/" rel="noreferrer">stack exchange data dump</a> for the wanted site, caching the archive in <code>.cache/</code>.</li>
<li>Extract the 7z archive, caching the files in <code>.cache/meta.codereview</code>.</li>
<li>Read the XML data for comments and posts.</li>
<li>Extract all links from the posts and comments. Using docutils to convert comments to html, and using beautiful soup to extract the hyperlinks.</li>
<li>Save all links in <code>meta.codereview.edges.csv</code> and post information in <code>meta.codereview.nodes.csv</code>.</li>
</ol>
<h1>My code</h1>
<p>To keep my question from becoming humungus, I have included only the code in the <a href="https://github.com/Peilonrayz/stack_exchange_graph_data/tree/03c530547f10aa858e5a485b51da8c018eee57b0/src/stack_exchange_graph_data/helpers" rel="noreferrer">helpers package</a>. These run independantly of the rest of the code, but can depend on each other.</p>
<h2>SI</h2>
<p>Converts a number, like 100000, into a short form, such as <code>' 97.66KiB'</code>. The functions in the <code>Magnitude</code> class are used to convert the value to be at most the base's size. For <code>Magnitude.ibyte</code> this means it'd be at most 1023. <code>display</code> is then used to display the number to a certain amount of decimal places. This makes an easy to use library when displaying quantities of data.</p>
<pre><code>"""Simplify a number to a wanted base."""
import math
from typing import Callable, Tuple
def si_magnitude(
base: int,
suffix: str,
prefixes: str,
) -> Callable[[int], Tuple[int, str]]:
"""
SI base converter builder.
:param base: Base to truncate values to.
:param suffix: Suffix used to denote the type of information.
:param prefixes: Prefixes before the suffix to denote magnitude.
:return: A function to change a value by the above parameters.
"""
prefixes = ' '.join(prefixes.split('|')[::-1])
prefixes_ = prefixes.split(' ')
def inner(value: int) -> Tuple[int, str]:
"""
Convert a number to a truncated base form.
:param value: Value to adjust.
:return: Truncated value and unit.
"""
logged = math.log(value, base)
if -1 < value < 1:
logged -= 1
remainder = value / base ** int(logged)
return remainder, prefixes_[int(logged)] + suffix
return inner
_MAGNITUDE = 'f p n μ m| k M G T P E Z Y'
class Magnitude:
"""Magnitude conversions."""
ibyte = si_magnitude(
1024,
'B',
'| Ki Mi Gi Ti Pi Ei Zi Yi',
)
byte = si_magnitude(
1000,
'B',
_MAGNITUDE,
)
number = si_magnitude(
1000,
'',
_MAGNITUDE,
)
def display(values: Tuple[int, str], decimal_places: int = 2) -> str:
"""
Display a truncated number to a wanted DP.
:param values: Value and unit to display.
:param decimal_places: Amount of decimal places to display the value to.
:return: Right aligned display value.
"""
value, unit = values
decimal_places = int(decimal_places)
width = 4 + decimal_places
if decimal_places > 0:
return f'{value:>{width}.{decimal_places}f}{unit}'
value = int(value)
return f'{value:>3}{unit}'
</code></pre>
<h2>Progress</h2>
<p>This wraps an iterator and displays how far into the iterator you are, with some extra information like total size and speed. It displays it's numbers using the SI module, so they're in a human readable form.</p>
<pre><code>"""Display progress of a stream."""
import time
import warnings
from typing import Callable, Generic, Iterator, Optional, Tuple, TypeVar
from .si import Magnitude, display
# nosa(1): pylint[:Class name "T" doesn't conform to PascalCase naming style]
T = TypeVar('T')
# nosa(1): pylint[:Too many instance attributes]
class BaseProgressStream(Generic[T]):
"""Display the progress of a stream."""
# nosa(1): pylint[:Too many arguments]
def __init__(
self,
stream: Iterator[T],
size: Optional[int],
si: Callable[[int], Tuple[int, str]],
progress: Callable[[T], int],
width: int = 20,
prefix: str = '',
start: int = 0,
message: Optional[str] = None,
):
"""Initialize BaseProgressStream."""
self.stream = stream
self.size = size
self.width = width
self.progress_bar = '=' * (width - 1) + '>'
self.prefix = prefix
self.to_readable = si
self.progress_fn = progress
self._start = start
self.message = message
def _get_progress(self, current: int) -> str:
"""
Get the progress of the stream.
:param current: Current progress - not in percentage.
:return: Progress bar and file size.
"""
if not self.size:
return ''
amount = self.width * current // self.size
progress = self.progress_bar[-amount:] if amount else ''
disp_size = display(self.to_readable(self.size))
return f'[{progress:<{self.width}}] {disp_size} '
def __iter__(self) -> Iterator[T]:
"""
Echo the stream, and update progress.
Catches all warnings raised whilst processing the stream to be
displayed afterwards. This keeps the UI tidy and prevents the
progress bar traveling over multiple lines.
:return: An echo of the input stream.
"""
with warnings.catch_warnings(record=True) as warnings_:
current = self._start
if self.message:
print(self.message)
start = time.clock()
for chunk in self.stream:
current += self.progress_fn(chunk)
progress = self._get_progress(current)
rate = current // max(int(time.clock() - start), 1)
disp_rate = display(self.to_readable(rate))
print(
f'\r{self.prefix}{progress}{disp_rate}/s',
end='',
flush=True,
)
yield chunk
print()
for warning in warnings_:
warnings.showwarning(
warning.message,
warning.category,
warning.filename,
warning.lineno,
)
class DataProgressStream(BaseProgressStream[T]):
"""Display progress of a data stream."""
def __init__(
self,
stream: Iterator[T],
size: Optional[int],
width: int = 20,
prefix: str = '',
message: Optional[str] = None,
):
"""Initialize DataProgressStream."""
super().__init__(
stream,
size,
Magnitude.ibyte,
len,
width,
prefix,
0,
message,
)
class ItemProgressStream(BaseProgressStream[T]):
"""Display progress of an item stream."""
def __init__(
self,
stream: Iterator[T],
size: Optional[int],
width: int = 20,
prefix: str = '',
message: Optional[str] = None,
):
"""Initialize ItemProgressStream."""
super().__init__(
stream,
size,
Magnitude.number,
lambda _: 1,
width,
prefix,
1,
message,
)
</code></pre>
<h2>Curl</h2>
<p>A small library that mimics <code>curl</code>, it displays information about the download by using the Progress module.</p>
<pre><code>"""Copy URL."""
import os
import pathlib
from typing import Any
# nosa(1): pylint
import requests
from . import progress
def curl(
path: pathlib.Path,
*args: Any,
**kwargs: Any,
) -> None:
"""
Download file to system.
Provides a progress bar of the file being downloaded and some
statistics around the file and download.
:param path: Local path to save the file to.
:param args&kwargs: Passed to :code:`request.get`.
"""
response = requests.get(*args, stream=True, **kwargs)
response.raise_for_status()
length_ = response.headers.get('content-length')
length = int(length_) if length_ else None
path.parent.mkdir(parents=True, exist_ok=True)
print(f'Downloading: {response.url}')
try:
with path.open('wb') as output:
for chunk in progress.DataProgressStream(
response.iter_content(chunk_size=512),
length,
prefix=' ',
):
output.write(chunk)
except BaseException:
os.remove(path)
raise
</code></pre>
<h2>Cache</h2>
<p>Exposes a very simple cache. The objects returned all expose an <code>ensure</code> method to allow the action to happen at a later point, and means that a cache can rely on another cache. So the archive can rely on the file downloader if the 7z archive it needs doesn't exist.</p>
<pre><code>"""
Simple file cache.
Exposes two forms of cache:
1. A file that is downloaded from a website.
2. A 7z archive cache - files that are extracted from a 7z archive.
"""
import pathlib
# nosa(1): pylint,mypy
import py7zlib
from . import curl, si
class CacheMethod:
"""Base cache object."""
def __init__(self, cache_path: pathlib.Path) -> None:
"""Initialize CacheMethod."""
self.cache_path = cache_path
def _is_cached(self, use_cache: bool) -> bool:
"""
Check if the target exist in the cache.
:param use_cache: Set to false to force redownload the data.
:return: True if we should use the cache.
"""
return use_cache and self.cache_path.exists()
def ensure(self, use_cache: bool = True) -> pathlib.Path:
"""
Ensure target file exists.
This should be overwritten in child classes.
:param use_cache: Set to false to force redownload the data.
:return: Location of file.
"""
raise NotImplementedError('Should be overwritten in subclass.')
class FileCache(CacheMethod):
"""Exposes a cache that allows downloading files."""
def __init__(self, cache_path: pathlib.Path, url: str) -> None:
"""Initialize FileCache."""
super().__init__(cache_path)
self.url = url
def ensure(self, use_cache: bool = True) -> pathlib.Path:
"""
Ensure target file exists.
This curls the file from the web to cache, providing a progress
bar whilst downloading.
:param use_cache: Set to false to force redownload the data.
:return: Location of file.
"""
if not self._is_cached(use_cache):
curl.curl(self.cache_path, self.url)
return self.cache_path
class Archive7zCache(CacheMethod):
"""Exposes a cache that allows unzipping 7z archives."""
def __init__(
self,
cache_path: pathlib.Path,
archive_cache: CacheMethod,
) -> None:
"""Initialize Archive7zCache."""
super().__init__(cache_path)
self.archive_cache = archive_cache
def ensure(self, use_cache: bool = True) -> pathlib.Path:
"""
Ensure target file exists.
Unzips the 7z archive showing the name and size of each file
being extracted.
:param use_cache: Set to false to force reunarchiving of the data.
:return: Location of file.
"""
if not self._is_cached(use_cache):
with self.archive_cache.ensure(use_cache).open('rb') as input_file:
print(f'Unziping: {input_file.name}')
archive = py7zlib.Archive7z(input_file)
directory = self.cache_path.parent
directory.mkdir(parents=True, exist_ok=True)
for name in archive.getnames():
output = directory / name
member = archive.getmember(name)
size = si.display(si.Magnitude.ibyte(member.size))
print(f' Unpacking[{size}] {name}')
with output.open('wb') as output_file:
output_file.write(archive.getmember(name).read())
return self.cache_path
class Cache:
"""Interface to make cache instances."""
def __init__(self, cache_dir: pathlib.Path) -> None:
"""Initialize Cache."""
self.cache_dir = cache_dir
def file(self, cache_path: str, url: str) -> FileCache:
"""
Get a file cache endpoint.
:param cache_path: Location of file relative to the cache directory.
:param url: URL location of the file to download from if not cached.
:return: A file cache endpoint.
"""
return FileCache(self.cache_dir / cache_path, url)
def archive_7z(
self,
cache_path: pathlib.Path,
archive_cache: CacheMethod,
) -> Archive7zCache:
"""
Get an archive cache endpoint.
:param cache_path: Location of file relative to the cache directory.
:param archive_cache: A cache endpoint to get the 7z archive from.
:return: An archive cache endpoint.
"""
return Archive7zCache(self.cache_dir / cache_path, archive_cache)
</code></pre>
<h2>XRef</h2>
<p>This expands Sphinx partial_xref objects to be full urls. This is as you can link to posts using <code>[link description](/q/1)</code>. Secondly Simon once didn't wrap an example link in back ticks and it makes the code blow up otherwise, so we handle that too. An example is <code>[link description](target)</code>.</p>
<pre><code>"""Expand partial xrefs."""
# nosa: pylint,mypy
from typing import List, Type
import docutils.core
import docutils.nodes
import docutils.parsers
import docutils.transforms
from recommonmark.parser import CommonMarkParser
import sphinx.addnodes
__all__ = [
'custom_parser',
]
def custom_parser(prefix: str) -> Type[docutils.parsers.Parser]:
"""
Markdown parser with partial xref support.
Extends :code:`recommonmark.parser.CommonMarkParser` with to include
the :code:`custom_parser.PendingXRefTransform` transform.
:param prefix: Http base to prepend to partial hyperlinks.
:return: A custom parser to parse Markdown.
"""
class PendingXRefTransform(docutils.transforms.Transform):
"""
Expands partial links.
Some links are provided like :code:`[text](/a/2)``.
This expands the link to include the basename like:
.. :
http://codereview.meta.stackexchange.com
"""
default_priority = 999
@staticmethod
def handle_xref(
node: sphinx.addnodes.pending_xref,
) -> docutils.nodes.Node:
"""Convert partial_xref to desired output."""
referance, = node.children
ref = node.attributes['reftarget']
if ref != referance.attributes['refuri']:
print(
'target not the same',
node.attributes['reftarget'],
referance.attributes['refuri'],
)
if ref.startswith('/'):
referance['refuri'] = prefix + ref
return referance
# Handles 'links' like [this other thing](link)
text, = referance.children
if not isinstance(text, docutils.nodes.Text):
print('Referance text is not text.')
return docutils.nodes.Text(f'[{text.rawsource}]({ref})')
def traverse(self, node: docutils.nodes.Node) -> None:
"""Traverse the tree updating partial_xref nodes."""
transforms = []
children = []
for child in getattr(node, 'children', [])[:]:
if isinstance(child, sphinx.addnodes.pending_xref):
new_child = self.handle_xref(child)
transforms.append((child, new_child))
child = new_child
children.append(child)
replace = getattr(node, 'replace', None)
if replace is not None:
for old, new in transforms:
replace(old, new)
for child in children:
self.traverse(child)
def apply(self) -> None:
"""Docutils entry."""
self.traverse(self.document)
class CustomParser(CommonMarkParser):
"""Subclass of CommonMark to add XRef transform."""
def get_transforms(self) -> List[Type[docutils.transforms.Transform]]:
"""Get transformations used for this passer."""
return [PendingXRefTransform]
return CustomParser
</code></pre>
<h2>Coroutines</h2>
<p>The main function <code>coroutine</code> adds a lot of magic, that's better described in the code. For the most part it doesn't do much unless the control flow enters a bad state.</p>
<pre><code>"""
Coroutine helpers.
A lot of this module is based on the assumption that Python doesn't
seamlessly handle the destruction of coroutines when using multiplexing
or broadcasting. It also helps ease interactions when coroutines enter
closed states prematurely.
"""
import functools
import itertools
import types
from typing import (
Any, Callable, Generator, Iterable, Iterator, List, Optional, Tuple, Union,
)
NEW_SOURCE = object()
EXIT = object()
IIter = Union[Iterator, Iterable]
class CoroutineDelegator:
"""Helper class for delegating to coroutines."""
_queue: List[Tuple[IIter, Generator]]
def __init__(self) -> None:
"""Initialize CoroutineDelegator."""
self._queue = []
def send_to(
self,
source: IIter,
target: Generator,
) -> None:
"""
Add a source and target to send data to.
This does not send any data into the target, to do that use the
:meth:`CoroutineDelegator.run` function.
:param source: Input data, can be any iterable. Each is passed
straight unaltered to target.
:param target: This is the coroutine the data enters into to get
into the coroutine control flow.
"""
self._queue.append((source, target))
def _increment_coroutine_refs(self) -> None:
"""Increment the amount of sources for the coroutines."""
for _, target in self._queue:
if _is_magic_coroutine(target):
target.send(NEW_SOURCE)
def _run(self, source: IIter, target: Generator) -> Optional[Iterator]:
item = sentinel = object()
source_ = iter(source)
try:
for item in source_:
target.send(item)
except StopIteration:
if item is sentinel:
return source_
return itertools.chain([item], source_)
else:
if _is_magic_coroutine(target):
target.send(EXIT)
return None
def run(self) -> List[Iterator]:
"""
Send all data into the coroutine control flow.
:return: If a coroutine is closed prematurely the data that
hasn't been entered into the control flow will be
returned. Otherwise an empty list is.
"""
self._increment_coroutine_refs()
output: List[Optional[Iterator]] = [
None for _ in range(len(self._queue))
]
for i, (source, target) in enumerate(self._queue):
output[i] = self._run(source, target)
self._queue = []
if any(output):
return [iter(o or []) for o in output]
return []
def primed_coroutine(function: Callable[..., Generator]) -> Callable:
"""
Primes a coroutine at creation.
:param function: A coroutine function.
:return: The coroutine function wrapped to prime the coroutine at creation.
"""
function = types.coroutine(function)
def inner(*args: Any, **kwargs: Any) -> Generator:
output = function(*args, **kwargs)
next(output)
return output
return inner
def _is_magic_coroutine(target: Any) -> bool:
"""
Check if target is a magic coroutine.
:param target: An object to check against.
:return: If the object is a magic coroutine.
"""
try:
return bool(
target
and target.__qualname__.endswith('coroutine.<locals>.magic'),
)
except Exception:
return False
def coroutine(function: Callable) -> Callable:
"""
Wrap a coroutine generating function to make magic coroutines.
A magic coroutine is wrapped in a protective coroutine that eases
the destruction of coroutine pipelines. This is because the
coroutine is wrapped in a 'bubble' that:
1. Primes the coroutine when the first element of data is passed to it.
2. Sends information about the creation and destruction of other
coroutines in the pipeline. This allows a coroutine to destroy
itself when all providers have exited.
3. Handles when a coroutine is being prematurely closed, if this is
the case all target coroutines will be notified that some data
sources are no longer available allowing them to deallocate
themselves if needed.
4. Handles situations where a target coroutine has been prematurely
closed. In such a situation the current coroutine will be closed
and exit with a StopIteration error, as if the coroutine has been
closed with the :code:`.close`.
It should be noted that these coroutine pipelines should be started via the
:class:`stack_exchange_graph_data.helpers.coroutines.CoroutineDelegator`.
This is as it correctly initializes the entry coroutine, and handles
when the coroutine has been prematurely closed.
:param function: Standard coroutine generator function.
:return: Function that generates magic coroutines.
"""
self: Generator
@primed_coroutine
def magic(*args: Any, **kwargs: Any) -> Generator:
# Get magic coroutine targets
targets_ = itertools.chain(args, kwargs.values())
targets = [
t
for t in targets_
if _is_magic_coroutine(t)
]
# Create wrapped coroutine
wrapped = function(*args, **kwargs)
# Broadcast the creation of a new source to the targets
for target in targets:
target.send(NEW_SOURCE)
sources = 0
generator_exit_flag = False
generator_iteration_flag = False
active = False
try:
# Main coroutine loop handles adding and removing source counters.
while True:
item = yield
if item is NEW_SOURCE:
sources += 1
elif item is EXIT:
sources -= 1
if not sources:
break
else:
# Allows coroutines to be uninitialized until
# they're needed to be active.
if not active:
next(wrapped)
active = True
wrapped.send(item)
# Raised when a anything above parent has been killed
except RuntimeError:
pass
# Raised when a parent has been killed
except StopIteration:
generator_iteration_flag = True
# Raised when this is being killed via `.close`.
except GeneratorExit:
generator_exit_flag = True
finally:
# Close the wrapped coroutine
# This happens first, so any code in a `finally` can
# propagate correctly
try:
wrapped.close()
except RuntimeError:
pass
# Decrement target coroutine's source counters
if targets and not generator_iteration_flag:
for target in targets:
try:
for _ in range(sources):
target.send(EXIT)
except StopIteration:
pass
# Coroutine must yield when it's being killed. IDK why but it does.
# But it's illegal to yield when a GeneratorExit has been raised.
if not generator_exit_flag:
yield
@functools.wraps(function)
def inner(*args: Any, **kwargs: Any) -> Generator:
nonlocal self
self = magic(*args, **kwargs)
return self
return inner
@coroutine
def broadcast(*targets: Generator) -> Generator:
"""Broadcast items to targets."""
while True:
item = yield
for target in targets:
target.send(item)
@coroutine
def file_sink(*args: Any, **kwargs: Any) -> Generator:
"""Send all data to a file."""
with open(*args, **kwargs) as file_obj:
while True:
file_obj.write((yield))
</code></pre>
|
[] |
[
{
"body": "<p>You're storing the magnitudes like this:</p>\n\n<pre><code>_MAGNITUDE = 'f p n μ m| k M G T P E Z Y'\n</code></pre>\n\n<p>This is a serialized format that requires parsing. This is inconvenient and complicates your code. Just store a tuple of tuples, or maybe a dictionary, storing the prefix string and its magnitude. A couple of options are:</p>\n\n<pre><code>(\n ('f', -15),\n ('p', -12),\n ('n', -9),\n # ...\n\n(\n 'mμnpf', # Negative prefixes\n 'kMGTPEZY' # Positive prefixes\n)\n</code></pre>\n\n<p>Otherwise... wow, this is a lot of code. It's not written terribly, but for what this is - a data-processing tool - I think it's suffering from some feature bloat. The coroutine implementation is interesting, but you don't really need this pile of code - seeing anything described as magic always gives me a sinking feeling, particularly in Python. For instance, for generic broadcasting, you can just store an iterable of function references.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T00:48:20.920",
"Id": "441675",
"Score": "2",
"body": "Yeah that second way looks much better! I'm gunna have to have a think about your solution for broadcasting, my first response was \"how could I be so stupid?!\" but I need all the output data to perform some of the operations. When posting the question I started doubting if coroutines were the way to go, so I'll look into this more tomorrow. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T00:19:52.370",
"Id": "227052",
"ParentId": "227035",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T19:10:26.420",
"Id": "227035",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"console",
"stream",
"stackexchange"
],
"Title": "Stack Exchange graph data - helper modules"
}
|
227035
|
<p>I've been working on writing data structures and methods from scratch (with minimal reference) and I'm looking for assistance on my coding style/if there's any way to optimize the methods I've included.</p>
<p>Below is my singular linked list code, all of its methods, and the output of my tests from main. This is also my first time on the board, so let me know if this isn't an appropriate venue for these kinds of questions.</p>
<pre><code>class MySingularlyLinkedList {
// Writing java Linked List singular from scratch (memory)
// Make head node
private Node head;
// Variable to keep track of size of linked list
private int size;
// Function to remove element at end of list
private void removeEnd() {
if (head == null) {
throw new IllegalArgumentException("No list exists to remove an element from");
}
Node current = head;
// Node variable to store node before current
Node prev = null;
// Iterate to end of list (current, prev is one before end)
while (current.next != null) {
prev = current;
current = current.next;
}
// Unlink end node from linked list
prev.next = current.next;
// Decrement size
size--;
}
// Function to remove element at front of list
private void removeFront() {
head = head.next;
size--;
}
// Function to remove element at given index
private void removeAt(int index) {
// I know this is the wrong exception, but couldn't think of how else to do this
if (head == null) {
throw new IllegalArgumentException("No list exists to remove an element from");
}
Node current = head;
Node prev = null;
for (int i = 0; i < index; i++) {
prev = current;
current = current.next;
}
prev.next = current.next;
size--;
}
// Function to remove first instance of a given value
private void removeData(int value) {
Node current = head;
Node prev = null;
// I know this is the wrong exception, but couldn't think of how else to do this
if (head == null) {
throw new IllegalArgumentException("No list exists to remove an element from");
}
if(current.data == value) {
current = current.next;
}
while (current.next != null && current.data != value) {
prev = current;
current = current.next;
}
// return if value not present in linked list
if (current.next == null) {
System.out.println("Value " + value + " not in linked list");
return;
}
prev.next = current.next;
size--;
}
// Function to return data at given index
public int getData(int index) {
Node current = head;
for (int i = 0; i < index; i++) {
current = current.next;
}
// Not sure the best way to do this statement, in main, or in the function? Main because it's not always
// necessary is my assumption?
System.out.println("The data at index: " + index + " is: " + (current.data));
return(current.data);
}
// Function to return index at first instance of data
public int getIndex(int element) {
Node current = head;
int index = 0;
while (current.next != null) {
if(current.data == (element)) {
return index;
}
index++;
}
return -1;
}
// Function to add element to end of linked list
private void insertEnd(int newData) {
Node newNode = new Node(newData);
newNode.next = null;
// if Linked List is empty, make new node head
if (head == null) {
head = newNode;
}
else {
// Traverse until current = null
Node current = head;
while (current.next != null) {
current = current.next;
}
// Once end of list is reached, insert new Node
current.next = newNode;
}
// Increment size of list
size++;
}
// Function to insert node at beginning of list
private void insertFront(int newData) {
Node newNode = new Node(newData);
// If list is initally empty insert node at head
if (head == null) {
head = newNode;
}
else {
// Set newNode to point to node in front of head
newNode.next = head;
// Set head to point to newNode
head = newNode;
}
size++;
}
// Function to insert new node at given index
private void insertAt(int newData, int index) {
indexCheck(index);
Node newNode = new Node(newData);
Node current = head;
// Iterate until current is node before node at index
for(int i = 0; i < index - 1; i ++) {
current = current.next;
}
// Set newNode's pointer to node after current (node at specified index)
newNode.next = current.next;
// Set current's pointer to newNode
current.next = newNode;
// Increment size
size++;
}
// Function to check if index is within bounds of list
private void indexCheck(int index) {
if(index < 0 || index > size - 1) {
throw new IndexOutOfBoundsException("The following index is out of bounds: " + index);
}
}
private class Node {
int data;
Node next;
// Default Constructor
Node(int newData) {
data = newData;
}
}
private static void printLinkedList(MySingularlyLinkedList list) {
Node current = list.head;
System.out.println("Linked List: ");
while (current != null) {
System.out.println(current.data);
current = current.next;
}
System.out.println("The size of the list is now: " + list.size);
}
public static void main(String args[]) {
MySingularlyLinkedList newList = new MySingularlyLinkedList();
newList.insertEnd(5);
newList.insertEnd(2);
newList.insertEnd(66);
newList.insertEnd(1);
System.out.println("Adding elements 5 2 66 and 1 to linked list ");
printLinkedList(newList);
System.out.println("Insert 22 at front of linked list ");
newList.insertFront(22);
printLinkedList(newList);
System.out.println("Insert 50 at index 3 of linked list ");
newList.insertAt(50,3);
printLinkedList(newList);
System.out.println("Removing end node of of linked list ");
newList.removeEnd();
printLinkedList(newList);
System.out.println("Removing front node of of linked list ");
newList.removeFront();
printLinkedList(newList);
System.out.println("Removing node at index 2 of of linked list ");
newList.removeAt(2);
printLinkedList(newList);
System.out.println("Getting data at index 0 ");
newList.getData(0);
System.out.println("Removing node at first instance of value 2 ");
newList.removeData(2);
printLinkedList(newList);
System.out.println("Removing node at first instance of value -55");
newList.removeData(-55);
printLinkedList(newList);
// Test indexCheck
// newList.insertAt(1,-1);
}
</code></pre>
<p><strong>Output</strong></p>
<pre class="lang-none prettyprint-override"><code>Adding elements 5 2 66 and 1 to linked list
Linked List:
5
2
66
1
The size of the list is now: 4
Insert 22 at front of linked list
Linked List:
22
5
2
66
1
The size of the list is now: 5
Insert 50 at index 3 of linked list
Linked List:
22
5
2
50
66
1
The size of the list is now: 6
Removing end node of of linked list
Linked List:
22
5
2
50
66
The size of the list is now: 5
Removing front node of of linked list
Linked List:
5
2
50
66
The size of the list is now: 4
Removing node at index 2 of of linked list
Linked List:
5
2
66
The size of the list is now: 3
Getting data at index 0
The data at index: 0 is: 5
Removing node at first instance of value 2
Linked List:
5
66
The size of the list is now: 2
Removing node at first instance of value -55
Value-55 not in linked list
Linked List:
5
66
The size of the list is now: 2
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T13:40:17.843",
"Id": "441742",
"Score": "0",
"body": "Accepting an answer very quickly discourages further answers."
}
] |
[
{
"body": "<p>It's good that you have tests (and great to get them reviewed!), but including all the output is probably unnecessary, <strong>unless</strong> you're including it because some tests are failing and you don't understand why. </p>\n\n<p>As to your question</p>\n\n<blockquote>\n <p>I'm looking for assistance on my coding style/if there's any way to optimize the methods I've included</p>\n</blockquote>\n\n<p>I'll write my comments inline:</p>\n\n<pre><code>class MySingularlyLinkedList {\n// Writing java Linked List singular from scratch (memory)\n\n// Make head node\nprivate Node head;\n// Variable to keep track of size of linked list\nprivate int size;\n\n// Function to remove element at end of list\nprivate void removeEnd() {\n\n if (head == null) {\n throw new IllegalArgumentException(\"No list exists to remove an element from\");\n</code></pre>\n\n<p>Careful here: is this the case (no list exists) or is the list just empty? Remember, this code is inside the list itself. Would you want an object you're using after instantiating to tell you it doesn't exist?</p>\n\n<pre><code> }\n Node current = head;\n // Node variable to store node before current\n Node prev = null;\n // Iterate to end of list (current, prev is one before end)\n while (current.next != null) {\n prev = current;\n current = current.next;\n }\n\n // Unlink end node from linked list\n prev.next = current.next;\n // Decrement size\n size--;\n}\n\n// Function to remove element at front of list\nprivate void removeFront() {\n\n head = head.next;\n size--;\n}\n\n// Function to remove element at given index\nprivate void removeAt(int index) {\n\n // I know this is the wrong exception, but couldn't think of how else to do this\n if (head == null) {\n throw new IllegalArgumentException(\"No list exists to remove an element from\");\n</code></pre>\n\n<p>Same as above - the list exists, it's just empty. You probably want the No Such Element Exception, which is what <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html#remove%28%29\" rel=\"nofollow noreferrer\">Java's LinkedList</a> uses.</p>\n\n<pre><code> }\n Node current = head;\n Node prev = null;\n\n for (int i = 0; i < index; i++) {\n prev = current;\n current = current.next;\n }\n\n prev.next = current.next;\n size--;\n</code></pre>\n\n<p>Careful - if your list has 5 elements and you're asked to remove the 99th element, what happens?</p>\n\n<pre><code>}\n\n// Function to remove first instance of a given value\nprivate void removeData(int value) {\n\n Node current = head;\n Node prev = null;\n\n // I know this is the wrong exception, but couldn't think of how else to do this\n if (head == null) {\n throw new IllegalArgumentException(\"No list exists to remove an element from\");\n }\n\n if(current.data == value) {\n current = current.next;\n }\n\n while (current.next != null && current.data != value) {\n\n prev = current;\n current = current.next;\n }\n\n // return if value not present in linked list\n if (current.next == null) {\n System.out.println(\"Value \" + value + \" not in linked list\");\n return;\n }\n\n prev.next = current.next;\n size--;\n}\n\n// Function to return data at given index\npublic int getData(int index) {\n</code></pre>\n\n<p>The convention is for this method to be called <code>get()</code></p>\n\n<pre><code> Node current = head;\n for (int i = 0; i < index; i++) {\n current = current.next;\n }\n // Not sure the best way to do this statement, in main, or in the function? Main because it's not always\n // necessary is my assumption?\n System.out.println(\"The data at index: \" + index + \" is: \" + (current.data));\n return(current.data);\n}\n\n// Function to return index at first instance of data\npublic int getIndex(int element) {\n</code></pre>\n\n<p>Similarly, this is usually <code>indexOf()</code></p>\n\n<pre><code> Node current = head;\n int index = 0;\n while (current.next != null) {\n\n if(current.data == (element)) {\n return index;\n }\n index++;\n }\n return -1;\n}\n\n// Function to add element to end of linked list\n</code></pre>\n\n<p>This comment doesn't tell me anything I don't know from the method signature itself</p>\n\n<pre><code>private void insertEnd(int newData) {\n\n Node newNode = new Node(newData);\n newNode.next = null;\n\n // if Linked List is empty, make new node head\n if (head == null) {\n head = newNode;\n }\n else {\n // Traverse until current = null\n Node current = head;\n while (current.next != null) {\n current = current.next;\n }\n // Once end of list is reached, insert new Node\n current.next = newNode;\n }\n\n // Increment size of list\n size++;\n}\n\n// Function to insert node at beginning of list\n</code></pre>\n\n<p>Same as above</p>\n\n<pre><code>private void insertFront(int newData) {\n\n Node newNode = new Node(newData);\n // If list is initally empty insert node at head\n if (head == null) {\n head = newNode;\n }\n else {\n // Set newNode to point to node in front of head\n newNode.next = head;\n // Set head to point to newNode\n head = newNode;\n }\n size++;\n}\n\n// Function to insert new node at given index\nprivate void insertAt(int newData, int index) {\n\n indexCheck(index);\n Node newNode = new Node(newData);\n Node current = head;\n // Iterate until current is node before node at index\n for(int i = 0; i < index - 1; i ++) {\n current = current.next;\n }\n // Set newNode's pointer to node after current (node at specified index)\n newNode.next = current.next;\n // Set current's pointer to newNode\n current.next = newNode;\n // Increment size\n size++;\n</code></pre>\n\n<p>Seems like this doesn't work if index = 0</p>\n\n<pre><code>}\n\n// Function to check if index is within bounds of list\nprivate void indexCheck(int index) {\n\n if(index < 0 || index > size - 1) {\n throw new IndexOutOfBoundsException(\"The following index is out of bounds: \" + index);\n }\n}\n\n private class Node {\n\n int data;\n Node next;\n\n // Default Constructor\n Node(int newData) {\n\n data = newData;\n }\n}\n\nprivate static void printLinkedList(MySingularlyLinkedList list) {\n\n Node current = list.head;\n System.out.println(\"Linked List: \");\n while (current != null) {\n System.out.println(current.data);\n current = current.next;\n }\n System.out.println(\"The size of the list is now: \" + list.size);\n}\n\n\npublic static void main(String args[]) {\n\n MySingularlyLinkedList newList = new MySingularlyLinkedList();\n\n newList.insertEnd(5);\n newList.insertEnd(2);\n newList.insertEnd(66);\n newList.insertEnd(1);\n\n System.out.println(\"Adding elements 5 2 66 and 1 to linked list \");\n printLinkedList(newList);\n\n System.out.println(\"Insert 22 at front of linked list \");\n newList.insertFront(22);\n printLinkedList(newList);\n\n System.out.println(\"Insert 50 at index 3 of linked list \");\n newList.insertAt(50,3);\n printLinkedList(newList);\n\n System.out.println(\"Removing end node of of linked list \");\n newList.removeEnd();\n printLinkedList(newList);\n\n System.out.println(\"Removing front node of of linked list \");\n newList.removeFront();\n printLinkedList(newList);\n\n System.out.println(\"Removing node at index 2 of of linked list \");\n newList.removeAt(2);\n printLinkedList(newList);\n\n System.out.println(\"Getting data at index 0 \");\n newList.getData(0);\n\n System.out.println(\"Removing node at first instance of value 2 \");\n newList.removeData(2);\n printLinkedList(newList);\n\n System.out.println(\"Removing node at first instance of value -55\");\n newList.removeData(-55);\n printLinkedList(newList);\n\n // Test indexCheck\n // newList.insertAt(1,-1);\n</code></pre>\n\n<p>These tests are a good start, but you could do a better job of testing edge cases. I.e. there should be tests for calling <code>size</code> and <code>remove</code> on an empty list, adding elements to an empty list, adding elements to the start, end, and middle of a full list, etc. Consider using a unit testing framework, like <code>junit</code>, instead of putting tests in a main method. It'll give you much better visibility and separation between tests.<br>\n }</p>\n\n<p><strong>Overall notes:</strong></p>\n\n<p>Your code is pretty clean, and easy to understand. However, it's missing a couple things that would make it clean<strong>er</strong>. First: some of your methods are public, and some private, but there doesn't seem to be a logical separation between the two - think about which methods actually <strong>belong</strong> to the API of a linked list, and make those public, and make the rest private. A public method that's definitely needed that you don't have yet is <code>size()</code>.</p>\n\n<p>Stylistically: </p>\n\n<p>Methods should be ordered top to bottom: constructors -> public methods -> private methods. (Public) constructors and public methods should have javadoc explaining what they do. Methods can have inline or block comments, but they should be used <em>sparsely</em>, and only where the code itself is tricky to understand or potentially confusing. Comments should not be redundant, so if the code explains itself leave them out. If the code doesn't explain itself, first ask <strong>why</strong>: it's likely possible to change it to be easier to follow, and not require commenting. Only if the answer is \"because of something that can't be changed\" should you add a comment to explain it.</p>\n\n<p>Logically:</p>\n\n<p>Be careful of edge cases, especially for public methods. Private methods will only be called by <em>you</em> - you can assume some things about your input based on how you use the methods in your other code. Public methods will be used by <em>everyone</em>, and you can't be sure what they'll pass. Be sure to account for potentially erroneous input.</p>\n\n<p>Overall, nice job and good attempt. A suite of unit tests and clarification on the interface will go a long way to make this production-quality.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T22:34:49.010",
"Id": "441668",
"Score": "0",
"body": "Thank you! This is incredibly helpful"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T21:41:38.467",
"Id": "227047",
"ParentId": "227042",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227047",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T20:45:20.373",
"Id": "227042",
"Score": "3",
"Tags": [
"java",
"linked-list"
],
"Title": "Singular linked list check and assistance"
}
|
227042
|
<p>I'm trying to a write super simple task runner with asyncio. </p>
<p>Basically, my goal is to run 100 requests to google as tasks, whilst also being be able to handle tasks being added at a later time.</p>
<pre><code>from abc import ABC, abstractmethod
import asyncio
import socket
import time
import aiohttp
import requests
class MyScheduler:
def __init__(self, wait=2):
self.work = []
self.wait = wait
def set_initial_callback(self, callback, **kwargs):
self.initial_callback = callback
self.initial_callback_args = kwargs
async def add_task(self, callback, **kwargs):
task = asyncio.create_task(callback(**kwargs))
self.work.append(task)
async def _run(self):
while self.work:
task = self.work.pop()
await task
if len(self.work) == 0:
await asyncio.sleep(self.wait)
async def set_things_up(self, callback, **kwargs):
task = asyncio.create_task(callback(**kwargs))
self.work.append(task)
await self._run()
def go(self):
asyncio.run(self.set_things_up(self.initial_callback, **self.initial_callback_args))
async def google(n):
if n == 100:
return None
await s.add_task(google, n=n + 1)
async with aiohttp.ClientSession() as session:
async with session.get('http://h...content-available-to-author-only...n.org/get') as resp:
print(resp.status)
t = time.time()
s = MyScheduler(wait=1)
s.set_initial_callback(google, n=1)
s.go()
print(time.time() - t)
</code></pre>
<p>I benchmarked this against sequentally running requests, and I did see a massive speed up. It's still super rough, but I'd love some pointers on how I could improve my code in terms of readability/exploiting async stuff better.</p>
|
[] |
[
{
"body": "<p>I actually just started learning <code>asyncio</code> a couple days ago, so I won't be able to comment too deeply. I do see a few things though:</p>\n\n<p>Disregarding asyncio for a sec, I think <code>google</code> could be set up better. You have the base case of the recursion as <code>n == 100</code>, and are incrementing <code>n</code> in each recursive call. To easily allow the caller to decide how many time to run, I'd reverse how <code>n</code> is being handled. I would decrement it each call, and set the base case as <code>n <= 0</code>. With how you have it now, say the caller wanted it to run 1000 times, they would need to call it as</p>\n\n<pre><code>google(-900)\n</code></pre>\n\n<p>which is a little wonky. I'd change the first bit to:</p>\n\n<pre><code>async def google(n):\n if n <= 0:\n return None\n\n await s.add_task(google, n=n - 1)\n\n. . .\n</code></pre>\n\n<hr>\n\n<p>I'm not sure recursion is the cleanest tool for the job here. I'm also not sure entirely why you're using a job queue or why you're using a elaborate class here unless the goal is to be able to handle jobs being added at a later time.</p>\n\n<p>If your goal is just to initiate many requests and wait on them at the same time, you could just <a href=\"https://docs.python.org/3/library/asyncio-task.html?highlight=gather#asyncio.gather\" rel=\"nofollow noreferrer\"><code>gather</code></a> them:</p>\n\n<pre><code>import aiohttp\nimport asyncio as a\n\n# google no longer cares about how many times it runs\n# That is arguably beyond the responsibilities of a function intended to make requests\nasync def google():\n async with aiohttp.ClientSession() as session:\n async with session.get('http://h...content-available-to-author-only...n.org/get') as resp:\n print(resp.status)\n\nasync def start_requests(n_requests: int):\n routines = [google() for _ in range(n_requests)] # Create a list of reqeust-making coroutines\n await a.gather(*routines) # Unpack the routines into gather (since gather is var-arg)\n</code></pre>\n\n<hr>\n\n<p>Also, instead of doing timing using a single attempt and plain subtraction, it would be more accurate to use <code>timeit</code>:</p>\n\n<pre><code>from timeit import timeit\n\nprint(\"t:\", timeit(lambda: a.run(start_requests(10)), number=20)) # number is the amount of tests to do\n</code></pre>\n\n<p>I'm assuming there's no issue using <code>timeit</code> for async code. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T08:15:22.297",
"Id": "441699",
"Score": "0",
"body": "thanks for the feedback! I should have added, yes the goal is to be able to handle jobs being added at a later time, as it offers more flexibility. :) Do you have any recommendations for how I could implement a graceful shutdown?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T23:11:24.493",
"Id": "227051",
"ParentId": "227044",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T21:20:23.760",
"Id": "227044",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"asynchronous",
"async-await"
],
"Title": "Python task runner with asyncio"
}
|
227044
|
<p>I am using Angular 8.x. I have a table with two columns that can be sorted. You can only sort one column at a time. I have conditions that display an up and down sort icon if neither column is being sorted, or a up or down sort icon depending on the sort direction. Is there a better way to write this condition?</p>
<p>html</p>
<pre><code> <th scope="col"> Issue Opened At
<i class="fa fa-fw"
[ngClass]="{'fa-sort': (!sortCol || sortCol == 'last_commit_date'),
'fa-sort-up': (sortCol && sortCol != 'last_commit_date' && !isDescSort),
'fa-sort-down': (sortCol && sortCol != 'last_commit_date' && isDescSort)}"
(click)="onSort('created')">
</i>
</th>
<th scope="col"> Issue Updated At
<i class="fa fa-fw"
[ngClass]="{'fa-sort': (!sortCol || sortCol == 'created_at'),
'fa-sort-up': (sortCol && sortCol != 'created_at' && !isDescSort),
'fa-sort-down': (sortCol && sortCol != 'created_at' && isDescSort)}"
(click)="onSort('updated')">
</i>
</th>
</code></pre>
<p>component </p>
<pre><code>sortCol = '';
onSort = (col) => {
this.sortCol = col;
this.isDescSort = !this.isDescSort;
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T21:36:49.167",
"Id": "227046",
"Score": "1",
"Tags": [
"html",
"angular-2+"
],
"Title": "Better way to apply class based on multiple conditions"
}
|
227046
|
<p>I have implemented Python-style generators within Java. I <em>might</em> be reinventing the wheel here, but I feel that the ability to define a Generator with an anonymous class is the most flexible approach. Here's the relevant code:</p>
<blockquote>
<p>generator/Generator.java</p>
</blockquote>
<pre><code>public abstract class Generator<T> implements Iterable<T>, Iterator<T>
{
private Lock lock = null;
private Lock lock2 = null;
private Semaphore semaphore = null;
private T curr;
private Thread execution;
private Runnable onTermination = null;
private Consumer<? super T> forEachAction = null;
public Generator(Object... params)
{
execution = new Thread(() ->
{
try
{
T t = get(params);
onTermination = ThrowingRunnable.of(execution::join);
yield(t);
getPermit();
}
catch(Exception unexpected)
{
onTermination = ThrowingRunnable.of(() ->
{
Exception e = new NoSuchElementException("Failed to retrieve element!");
e.initCause(unexpected);
throw e;
});
semaphore.release();
}
});
execution.setDaemon(true);
}
@Override
public final Iterator<T> iterator()
{
return this;
}
@Override
public final boolean hasNext()
{
return onTermination == null;
}
@Override
public final T next()
{
if(!hasNext())
throw new NoSuchElementException(
"There are no more elements to be generated by this Generator!");
if(semaphore == null && lock == null)
{
lock = new ReentrantLock();
lock2 = new ReentrantLock();
lock.lock();
semaphore = new Semaphore(0);
execution.start();
getPermit();
return curr;
}
lock2.lock();
lock.unlock();
getPermit();
lock.lock();
lock2.unlock();
getPermit();
if(onTermination != null)
{
lock.unlock();
onTermination.run();
}
return curr;
}
protected final void yield(T t)
{
if(forEachAction != null)
{
forEachAction.accept(t);
return;
}
curr = t;
semaphore.release();
lock.lock();
lock.unlock();
semaphore.release();
lock2.lock();
lock2.unlock();
}
private final void getPermit()
{
try
{
if(semaphore != null)
semaphore.acquire();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
/**
* Consumes all remaining elements possible. Obviously, don't use on
* infinite Generators.
*/
@Override
public void forEach(Consumer<? super T> action)
{
Objects.requireNonNull(action);
if(!hasNext())
throw new IllegalStateException("Exhausted elements before calling forEach!");
forEachAction = action;
if(execution.isAlive())
{
lock.unlock();
}
else
{
try
{
execution.start();
}
catch(IllegalThreadStateException itse)
{
itse.initCause(// double checking
new IllegalStateException("Can't exhaust elements and then call forEach!"));
throw itse;
}
}
ThrowingRunnable.of(execution::join).run();
onTermination.run();
}
protected abstract T get(Object... objs);
}
</code></pre>
<p>This is the code that I use for ignoring compile-time exceptions from lambdas (which should be thrown at runtime, with the default handler).</p>
<blockquote>
<p>throwing/ThrowingRunnable.java</p>
</blockquote>
<pre><code>@FunctionalInterface
public interface ThrowingRunnable extends Runnable, ExceptionFlowController
{
public abstract void run_() throws Exception;
@Override
default void run()
{
try
{
run_();
}
catch (Exception e)
{
handle(e);
}
}
static Runnable of(ThrowingRunnable tr, Consumer<Exception> h)
{
return new ThrowingRunnable()
{
public void run_() throws Exception
{
tr.run_();
}
public void handle(Exception e)
{
h.accept(e);
}
};
}
static Runnable of(ThrowingRunnable tr)
{
return tr;
}
}
</code></pre>
<blockquote>
<p>throwing/ExceptionFlowController.java</p>
</blockquote>
<pre><code>/**
* Controls exception flow by piping it into a handler.
*/
public interface ExceptionFlowController
{
public default void handle(Exception e)
{
ThrowingUtil.raise(e);
}
}
</code></pre>
<blockquote>
<p>throwing/ThrowingUtil.java</p>
</blockquote>
<pre><code>public class ThrowingUtil
{
@SuppressWarnings("unchecked")
static <E extends Exception> void raise(Exception e) throws E
{
throw (E) e;// sneakyThrow if you google it, restricted to exceptions only
}
}
</code></pre>
<p>Here's an example of using a Generator to print the first 92 Fibonacci numbers (until 64 bits is no longer enough):</p>
<blockquote>
<p>Main.java</p>
</blockquote>
<pre><code>public class Main
{
public static void main(String[] args)
{
Generator<Number> g = new Generator<>()
{
public Number get(Object[] o)
{
return get(0, 1);
}
private Number get(long fib0, long fib1)
{
yield(fib0);
fib0 += fib1;
yield(fib1);
fib1 += fib0;
if(fib0 < 0 || fib1 < 0)
return null;
return get(fib0, fib1);
}
};
StreamSupport.stream(g.spliterator(),false)
.takeWhile(Objects::nonNull)
.forEach(System.out::println);
}
}
</code></pre>
<p><strong>Output:</strong></p>
<blockquote>
<p>0<br>
1<br>
1<br>
2<br>
...<br>
4660046610375530309 </p>
</blockquote>
<p>I was a bit disappointed with the amount of concurrent primitive vomit that I had to use in order to ensure Generators were synchronized properly. Keeping this in mind, here's what I'd like to know:</p>
<ol>
<li>Any generic code quality suggestions/opinions/revisions.</li>
<li>How can I cut down on the number of Locks and Semaphores/usages of Locks and Semaphores (maybe using well-named condition variables)?</li>
</ol>
<p><strong>Edit:</strong><br>
Here's an example where using a Generator is massively convenient compared to creating a stateful Supplier/Iterator to do the same thing:</p>
<pre><code>public static void main(String[] args)
{
// 0
// 1 2
// _ 6 3 4
//_ _ 8 9 5 _ 7 _
Node n0 = new Node(), n1 = new Node(), n2 = new Node(),
n3 = new Node(), n4 = new Node(), n5 = new Node(),
n6 = new Node(), n7 = new Node(), n8 = new Node(),
n9 = new Node();
n0.left = n1;
n0.right = n2;
n2.left = n3;
n2.right = n4;
n3.left = n5;
n1.right = n6;
n4.left = n7;
n6.left = n8;
n6.right = n9;
Generator<Node> g = new Generator<>()
{
public Node get(Object[] o)
{
return get(n0);
}
private Node get(Node n)
{
if(n.left != null)
get(n.left);
yield(n);
if(n.right != null)
get(n.right);
return null;
}
};
Generator<Node> rightMost7Nodes = new Generator<Node>()
{
int count = 0;
int target = 7;
public Node get(Object[] o)
{
return get(n0);
}
private Node get(Node n)
{
if(n.right != null)
get(n.right);
if(count++ >= target)
return null;
yield(n);
if(n.left != null)
get(n.left);
return null;
}
};
System.out.println("Nodes in-order:");
StreamSupport.stream(g.spliterator(),false)
.takeWhile(o -> g.hasNext()) //ignore last element
.forEach(System.out::println);
System.out.println("Right-most 7 nodes in reverse order:");
StreamSupport.stream(rightMost7Nodes.spliterator(),false)
.takeWhile(o -> g.hasNext()) //ignore last element
.forEach(System.out::println);
}
</code></pre>
<p><strong>Output:</strong> </p>
<blockquote>
<p>Nodes in-order:<br>
Node(1)<br>
Node(8)<br>
Node(6)<br>
...<br>
Node(2)<br>
Node(7)<br>
Node(4)<br>
Right-most 7 nodes in reverse order:<br>
Node(4)<br>
Node(7)<br>
Node(2)<br>
Node(3)<br>
Node(5)<br>
Node(0)<br>
Node(9) </p>
</blockquote>
<p>The flexibility provided by being able to <code>yield</code> mid-logic makes it extremely simple for the programmer to modify the ordering and stored state during stream creation. If the same were to be done with a Supplier/Iterator, the need to correctly modify stored state during the traversal could be unnecessarily complex (using <a href="https://www.geeksforgeeks.org/inorder-tree-traversal-without-recursion-and-without-stack/" rel="nofollow noreferrer">Morris Traversal</a> or a stack-based approach is fine for full iteration, but can get complicated when you stop midway). Furthermore, the code would be inflexible to modify for other types of traversals (pre-order/post-order). For this reason, I plan to use my Generator implementation relatively frequently - which is why I'd like for it to be reviewed as per questions 1 and 2 :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T23:30:40.777",
"Id": "441669",
"Score": "5",
"body": "I don't know about Python generators but I find the use of threading here to be pretty dubious. Can you explain why you think a separate thread is needed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T23:34:01.140",
"Id": "441670",
"Score": "1",
"body": "Also c.f. `Stream.generate()` which seems a good deal simpler than your implementation: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/stream/Stream.html#generate(java.util.function.Supplier)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T00:59:16.353",
"Id": "441676",
"Score": "0",
"body": "@markspace I need threading to support Python generator behavior, as `yield` statements will pause a function, save all state (context), and continue from the last `yield` on successive calls to `next()`. `Stream::generate` is insufficiently powerful for my desired use cases, as it provides *only* an infinite, unordered stream of elements, whereas my Generator intends to provide (in/)finite, ordered, stateful stream of elements. According to Stream's Javadoc: behavioral parameters \"in most cases must be stateless (their result should not depend on any state that might change ...)\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T01:05:15.330",
"Id": "441677",
"Score": "0",
"body": "Furthermore, I need control flow to go from the thread calling `next()` to switch to the Generator's `get` logic until such time as the Generator `yield`s or `returns`, at which point control flow should resume in the thread that called `next()` with the correct return value. This sounds extremely similar to a [context switch](https://en.wikipedia.org/wiki/Context_switch) to me, which is why I used threads."
}
] |
[
{
"body": "<p>Ok, so, per @markspace, you've made this a lot more complicated than it has to be. In Python, <code>yield</code> is being used to save the state of a function. In Java, you'd just use a stateful object that executes the desired function. I'm pretty sure you could either create a <code>FibonacciIterator</code> or a <code>FibonacciSupplier</code> and meet your requirements.</p>\n\n<p>In either case, every time you call <code>get()</code>/<code>next()</code>, the code runs until it hits a <code>return</code> (yield). Then state is preserved and control flow returns to the calling code. The next time <code>get()</code>/<code>next()</code> is called, execution continues from the preserved state. Both classes provide an infinite, ordered, stateful stream of elements. <code>Supplier</code> can be plugged into <code>Stream::generate</code>, while <code>Iterable</code> can be iterated over.</p>\n\n<p>It is my (limited) understanding that a Python <code>Generator function</code> is just syntactic sugar that creates a Python <code>Iterator</code> which tracks execution state. This is a convenience so you can work with a function instead of an object. In your Java code, you're already tracking state yourself in your client method - by creating an infinitely deep call stack recursing on <code>get</code> with the new arguments.</p>\n\n<p>If you think I'm mistaken, can you please provide a specific case that the classes below do not solve?</p>\n\n<pre><code>public final class FibonnaciSupplier implements Supplier<Integer> {\n\n private int currentNumber = 0;\n private int nextNumber = 1;\n\n @Override\n public Integer get() {\n final int result = this.currentNumber;\n final int sum = this.currentNumber + this.nextNumber;\n\n this.currentNumber = this.nextNumber;\n this.nextNumber = sum;\n return Integer.valueOf(result);\n }\n\n}\n\npublic final class FibonnaciIterator implements Iterator<Integer> {\n\n private int currentNumber = 0;\n private int nextNumber = 1;\n\n @Override\n public boolean hasNext() {\n return true;\n }\n\n @Override\n public Integer next() {\n final int result = this.currentNumber;\n final int sum = this.currentNumber + this.nextNumber;\n\n this.currentNumber = this.nextNumber;\n this.nextNumber = sum;\n return Integer.valueOf(result);\n }\n\n}\n</code></pre>\n\n<p>To see an example of the stack overflow issue, try the following generator. </p>\n\n<pre><code> Generator<Number> g = new Generator<Number>() {\n public Number get(Object[] o) {\n return get(0);\n }\n\n private Number get(long currentNumber) {\n yield(currentNumber);\n currentNumber += 1;\n if (currentNumber < 0)\n return null;\n return get(currentNumber);\n }\n };\n</code></pre>\n\n<p>You can also put a breakpoint on the line <code>yield(currentNumber)</code>, run your debugger through a few calls to <code>get()</code>, and look at the call stack. It'll look something like:</p>\n\n<blockquote>\n <p>Daemon Thread [Thread-0] (Suspended (breakpoint at line 18 in Main$1))<br>\n Main$1.get(long) line: 18<br>\n Main$1.get(long) line: 22<br>\n Main$1.get(long) line: 22<br>\n Main$1.get(long) line: 22<br>\n Main$1.get(Object[]) line: 14<br>\n Main$1.get(Object[]) line: 1<br>\n Main$1(Generator).lambda$0(Object[]) line: 25<br>\n 232824863.run() line: not available \n Thread.run() line: 745 </p>\n</blockquote>\n\n<p>Those repeated <code>get()</code> calls on line 22 are you stepping into a new stack frame every time <code>get()</code> is invoked recursively.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T16:26:26.383",
"Id": "441775",
"Score": "0",
"body": "I now realize that using `Supplier` and `Stream::generate` is the best way to go about simple element stream generation (possibly in conjunction with `limit(n)` to make the stream finite). However, I would argue that persisting state explicitly would be increasingly difficult for increasingly complex states (unlike Fibonacci). For example, providing an reverse in-order stream of elements from a binary tree (e.g. right-most n elements in a tree) would be simple using a recursive generator, whereas an iterative state-based approach would be far more complicated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T16:47:04.543",
"Id": "441778",
"Score": "0",
"body": "I'm not saying don't use recursion. I'm saying don't wrap a recursive method call in an unboundedly-increasing call stack with totally unnecessary concurrency checking. The `Supplier`/`Iterator` implementation can use recursion as necessary, and still remember state as part of the object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T16:54:42.763",
"Id": "441780",
"Score": "0",
"body": "@Avi Would you mind adding a new generator implementation to your question which shows the issue you're talking about, and how you think your generator solves a problem that a simple iterator/supplier cannot?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T16:56:06.453",
"Id": "441781",
"Score": "0",
"body": "I'm saying that the `Supplier/Iterator` implementation makes recursion unnecessarily complicated. The Fibonacci generator could have easily contained this: `for(int i = 0; i < 46; i++) { yield(fib0); fib0 += fib1; yield(fib1); fib1 += fib0; } return null;` in its `get(int, int)` method and produced the same results. Iterative implementations with state are relatively easy in all `Supplier/Iterator/Generator` approachs. w.r.t your latest request, I'll post a generator for a binary tree once I have it complete."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T15:20:37.783",
"Id": "227097",
"ParentId": "227049",
"Score": "2"
}
},
{
"body": "<p>Implementing both Iterable and Iterator at the same time is a bit weird choice and while the API documentation for Iterator makes no claims about the implementation, I think most people would assume that subsequent calls to iterator() return a different object each time and those objects, if used for reading only, do not interfere with each other.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T16:16:06.897",
"Id": "441773",
"Score": "0",
"body": "Thanks! You're right that it seems weird. I'll probably end up removing the Iterable functionality (`iterator()` method) and rename `forEach` to `forEachRemaining` as per the Iterator API (which makes more sense per my comment \"Consumes all remaining elements possible\")."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T16:09:50.963",
"Id": "227104",
"ParentId": "227049",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T22:17:39.413",
"Id": "227049",
"Score": "8",
"Tags": [
"python",
"java",
"multithreading",
"iterator",
"generator"
],
"Title": "Python-style Generator in Java"
}
|
227049
|
<p><a href="https://en.wikipedia.org/wiki/A/B_testing" rel="nofollow noreferrer">The definition of ABtest</a></p>
<p>Goal:</p>
<p>For input data, each pair row is a group such as 0 and 1, 2 and 3. I want to test whether each group is significant using chi-square. </p>
<ul>
<li>If result is significant and any value in group is more than or equals 5 , it returns p-value, else it returns 'not significant'.</li>
<li>If any value in group is less than 5, it returns 'sample size too small'.</li>
</ul>
<p>My question is:</p>
<ul>
<li>My code seems so long and not so elegant and want to be more simple.</li>
</ul>
<p>Notice: please don't use column <code>grp</code> as raw input to rewrite like <code>groupby</code> method because the raw data is not named <code>a1 ca1, b1 cb1</code> . But I make sure each pair row (e.g. 0 and 1, 2 and 3) is a group.</p>
<p>Code:</p>
<pre><code>import numpy as np
from scipy.stats import chi2_contingency
from itertools import chain, repeat
def abtest(df,tot,convert):
df = df.copy()
df['nonconvert'] = df[tot] - df[convert]
grp = np.split(df.index.values,df.index.size//2)
rst = []
for g in grp:
obs = df.loc[g][[convert,'nonconvert']].values
if (obs>=5).all():
_, p, _, _=chi2_contingency(obs)
if p<0.05:
rst.append(p)
else:
rst.append('not significant')
else:
rst.append('sample size too small')
rate = tot + '_' + convert + '_'+'test'
df[rate] = list(chain.from_iterable(zip(*repeat(rst, 2))))
del df['nonconvert']
return df
df = abtest(df=df,tot='tot',convert='read')
df = abtest(df=df,tot='tot',convert='lgn')
df = abtest(df=df,tot='lgn',convert='read')
</code></pre>
<p>Input:</p>
<pre><code> grp tot lgn read
0 a1 6300 360 30
1 ca1 2300 60 7
2 b1 26300 148 6
3 cb1 10501 15 3
4 c1 74600 36 2
5 cc1 26000 6 1
</code></pre>
<p>Output:</p>
<pre><code> grp tot lgn read tot_read_test tot_lgn_test \
0 a1 6300 360 30 not significant 4.68208e-09
1 ca1 2300 60 7 not significant 4.68208e-09
2 b1 26300 148 6 sample size too small 7.01275e-08
3 cb1 10501 15 3 sample size too small 7.01275e-08
4 c1 74600 36 2 sample size too small not significant
5 cc1 26000 6 1 sample size too small not significant
lgn_read_test
0 not significant
1 not significant
2 sample size too small
3 sample size too small
4 sample size too small
5 sample size too small
</code></pre>
|
[] |
[
{
"body": "<p>When you have a finite number of members in a group A and B. Instead of split into groups, hstack the DataFrame like this:</p>\n\n<pre><code>pd.concat(\n [\n df[df.index % 2 == 0].add_prefix('a_').reset_index(),\n df[df.index % 2 == 1].add_prefix('b_').reset_index()\n ], axis=1\n)\n</code></pre>\n\n<pre><code> a_grp a_tot a_lgn a_read index b_grp b_tot b_lgn b_read\n0 0 a1 6300 360 30 1 ca1 2300 60 7\n1 2 b1 26300 148 6 3 cb1 10501 15 3\n2 4 c1 74600 36 2 5 cc1 26000 6 1\n</code></pre>\n\n<p>Now you can replace the for-loop with 'a_' and 'b_' and <code>df.apply()</code> like</p>\n\n<pre><code>df.apply(apply_chi2)\n\ndef apply_chi2(df_ab):\n if df_ab['a_'+convert] > df_ab['a_'+'nonconvert']:\n return ...\n obs = df_ab.a\n return _, p, _, _=chi2_contingency(obs)\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T11:39:12.170",
"Id": "441722",
"Score": "0",
"body": "read it carefully, the grp is not used"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T11:41:06.893",
"Id": "441723",
"Score": "0",
"body": "sorry, but it doesn't seem more elegant than my code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T11:32:48.710",
"Id": "227077",
"ParentId": "227054",
"Score": "2"
}
},
{
"body": "<p>One minor thing that you can do is make your function <code>reduce</code>-friendly:</p>\n\n<pre><code>import numpy as np\nfrom scipy.stats import chi2_contingency\nfrom functools import reduce\nfrom itertools import chain, repeat\n\ndef abtest(df, args):\n tot, convert = args\n df = df.copy()\n df['nonconvert'] = df[tot] - df[convert]\n grp = np.split(df.index.values,df.index.size//2)\n rst = []\n\n for g in grp:\n obs = df.loc[g][[convert,'nonconvert']].values\n if (obs>=5).all():\n _, p, _, _=chi2_contingency(obs)\n if p<0.05:\n rst.append(p)\n else:\n rst.append('not significant')\n else:\n rst.append('sample size too small')\n\n rate = tot + '_' + convert + '_'+'test'\n df[rate] = list(chain.from_iterable(zip(*repeat(rst, 2))))\n del df['nonconvert']\n return df \n\ndf = reduce(abtest,\n (\n ('tot', 'read'),\n ('tot', 'lgn'),\n ('lgn', 'read')\n ),\n df\n)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T01:54:49.823",
"Id": "442718",
"Score": "0",
"body": "great,but it there any way to rewrite abtest function more simple"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T14:39:07.083",
"Id": "227334",
"ParentId": "227054",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T02:43:03.133",
"Id": "227054",
"Score": "5",
"Tags": [
"python",
"pandas",
"statistics",
"scipy"
],
"Title": "A/B testing using chi-square to calculate the significance in an elegant way"
}
|
227054
|
<p>The app grabs 10 questions from an API, displays them one by one with 4 multiple choice answers. These answers are clickable buttons that alert to whether the answer is correct or not. Finally the last screen shows the amount write and wrong (via wrongCount) and the percentage score as well as a retry that wipes it as restarts. I'm hoping for some good feedback on how bad my new, self taught coding style.</p>
<pre><code>
var questionsdata = null;
var wrongCount = 0;
var questionCount = 0;
var answers = [];
var questions = [];
const url = 'https://opentdb.com/api.php?amount=10&type=multiple';
function getData() {
fetch(url)
.then((resp) => resp.json())
.then(function(data){
questionsdata = data.results;
})
.catch(function(error){
alert("Could not get any questions!");
})
// add start button creation to load
}
function getQuestion () {
var correct = []
var incorrect = []
for(var i = 0; i < questionsdata.length; i++){
questions[i] = questionsdata[i].question;
incorrect[i] = questionsdata[i].incorrect_answers;
var characters = ['&amp;;', '&quot;', '&#039;', '&rsquo;', '&ldquo;', '&rdquo;', '&eacute;', '&shy;', "&Uuml;", "&Aacute;", '&aacute;'];
var actual = ['&', '"', "'", "'", '"', '"', 'é', '-', 'Ü', 'Á', 'á'];
for (var j = 0; j < incorrect[i].length; j++) {
for(var h = 0; h < characters.length; h++) {
incorrect[i][j] = incorrect[i][j].replace(new RegExp(characters[h], 'g'), actual[h]);
}
}
correct[i] = questionsdata[i].correct_answer;
for (var j = 0; j < characters.length; j++) {
correct[i] = correct[i].replace(new RegExp(characters[j], 'g'), actual[j]);
}
answers[i] = [{"answer" : correct[i], "correct" : "correct"},
{"answer" : incorrect[i][0], "correct" : "incorrect"},
{"answer" : incorrect[i][1], "correct" : "incorrect"},
{"answer" : incorrect[i][2], "correct" : "incorrect"}];
shuffle(answers[i]);
for(var j = 0; j < characters.length; j++) {
questions[i] = questions[i].replace(new RegExp(characters[j], 'g'), actual[j]);
}
}
}
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle
while (0 !== currentIndex) {
// Pick a remaining element
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function createQuestionElements(question){
if(questionCount < 10){
var container = document.getElementById("testcontainer");
container.innerHTML = "";
var addId = document.createAttribute("id");
addId.value = "questiontitle";
var questionTitle = document.createElement("h2");
questionTitle.setAttributeNode(addId);
container.appendChild(questionTitle);
questionTitle.innerText = question;
createButtons(container);
} else {
completionScreen();
}
}
function createButtons(container) {
var questionId = document.createAttribute("id");
questionId.value = "answers";
var buttonDiv = document.createElement("div");
var buttonContainer = container.appendChild(buttonDiv);
buttonContainer.setAttributeNode(questionId);
var count = 0
for(var i = 0; i < answers.length; i++){
var buttons = document.createElement("button");
buttonContainer.appendChild(buttons);
buttons.innerText = answers[i].answer;
buttons.id = "answerbutton" + count;
buttons.classList.add(answers[i].correct);
buttons.onclick = correctness;
count++
}
}
function correctness() {
if (this.className === "correct"){
alert("Correct!");
} else {
alert("Incorrect")
wrongCount++;
}
questionCount++
getQuestion();
pickQuestion();
}
function completionScreen(){
var container = document.getElementById("testcontainer");
container.innerHTML = "";
var resultsId = document.createAttribute("id");
resultsId.value = "results";
var resultsDiv = document.createElement("div");
var resultsContainer = container.appendChild(resultsDiv);
resultsContainer.setAttributeNode(resultsId);
var resultHeader = document.createElement("h2")
resultsContainer.appendChild(resultHeader)
if (wrongCount < 4) {
resultHeader.innerText = "You Passed";
} else {
resultHeader.innerText = "You Failed";
}
var right = 10 - wrongCount;
var wrong = wrongCount;
percent = (right / 10) * 100;
var resultsRight = document.createElement("p");
resultsContainer.appendChild(resultsRight);
resultsRight.innerText = "You got " + right + " questions correct!";
var resultsWrong = document.createElement("p");
resultsContainer.appendChild(resultsWrong);
resultsWrong.innerText = "you got " + wrong + " questions wrong!";
var resultsPercent = document.createElement("p");
resultsContainer.appendChild(resultsPercent);
resultsPercent.innerText = "Your score is " + percent + "%";
var retry = document.createElement("button");
resultsContainer.appendChild(retry);
retry.innerText = "Play Again";
retry.onclick = restart;
getData();
}
function restart(){
location.reload();
}
function start() {
getQuestion();
pickQuestion();
}
function pickQuestion() {
question = questions[questionCount]
answers = answers[questionCount]
question = questions[questionCount]
createQuestionElements(question, answers);
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p><strong>Some notes on readability</strong></p>\n\n<p>I will focus on method <code>getQuestion</code>. The first thing I noticed is that your indentation is very confusing. You start with an outer loop, and it looks it contains only 2 statements. However, the entire remaining method body is part of that loop. This pop in indentation introduced at <code>var characters</code> should never have been there.</p>\n\n<blockquote>\n<pre><code>for(var i = 0; i < questionsdata.length; i++){\n questions[i] = questionsdata[i].question;\n incorrect[i] = questionsdata[i].incorrect_answers;\n\n var characters = ['&amp;;', '&quot;', // .. and so on\n var actual = ['&', '\"', \"'\", \"'\", '\"', '\"', 'é', '-', 'Ü', 'Á', 'á'];\n // .. other code\n</code></pre>\n</blockquote>\n\n<p>To increase readaibility, you migth also want to introduce some whitespace here and there:</p>\n\n<pre><code>for (var i = 0; i < questionsdata.length; i++) {\n</code></pre>\n\n<p>rather than</p>\n\n<blockquote>\n<pre><code>for(var i = 0; i < questionsdata.length; i++){\n</code></pre>\n</blockquote>\n\n<p>But I would use a different syntax than the <code>for (;;)</code> pattern altogether. You have statements deep in the method body that use indexes from both an inner and the outer loop:</p>\n\n<blockquote>\n<pre><code>correct[i].replace(new RegExp(characters[j], 'g'), actual[j])\n</code></pre>\n</blockquote>\n\n<p>I'd have to scroll up to see what <code>j</code> and <code>i</code> represent.</p>\n\n<p>A more readable option is to use the <code>for (. of .)</code> pattern. This would avoid the indexes.</p>\n\n<p>You'd get:</p>\n\n<pre><code>for (const question of questionsdata) {\n</code></pre>\n\n<p>as opposed to:</p>\n\n<blockquote>\n<pre><code>for (var i = 0; i < questionsdata.length; i++) {\n</code></pre>\n</blockquote>\n\n<p>You'd have to refactor some variables though, no longer to use the indexes:</p>\n\n<blockquote>\n<pre><code>incorrect[i][j] = // ..\n</code></pre>\n</blockquote>\n\n<p>To avoid verbose loops you should check out some built-in methods, they might do the trick for you (<code>forEach</code>, <code>filter</code>, <code>map</code>, <code>reduce</code>, ..). I believe many of your inner loops could be rewritten in this style.</p>\n\n<p>You should also be careful using <code>var</code>, it has a <a href=\"https://stackoverflow.com/questions/1470488/what-is-the-purpose-of-the-var-keyword-and-when-should-i-use-it-or-omit-it\">scope</a> broader than the current block, unlike <code>let</code> and <code>const</code>. This could introduce unwanted behavior if you don't take the scope into account.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T01:44:11.820",
"Id": "442485",
"Score": "1",
"body": "Thank you so much for the insight! I have heard reducing the number of loops and if statement is code is advisable so moving to .filter,reduce etc is something I've been meaning to work on."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T04:50:27.963",
"Id": "227058",
"ParentId": "227055",
"Score": "1"
}
},
{
"body": "<p>I agree with the advice in dfhwze's answer. Because <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged 'ecmascript-6'\" rel=\"tag\">ecmascript-6</a> features like arrow functions are used, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for...of</code></a> loops could be used to simplify the loop syntax. And instead of pushing values into <code>questions</code> and <code>incorrect</code> using <code>i</code>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push\" rel=\"nofollow noreferrer\"><code>Array.push()</code></a> could be used.</p>\n\n<p>I see that <code>getData()</code> is called at the end of <code>completionScreen()</code>, which is called at the end of <code>createQuestionElements()</code> if <code>questionCount</code> is not less than 10, and that function is called at the end of <code>pickQuestion()</code>. I haven't seen this code in action but fear there could be a timing issue - i.e. the results might not be loaded from the API before other code attempts to load data from the questions array. </p>\n\n<p>The second promise callback could be simplified to a one-line arrow function:</p>\n\n<pre><code>.then(data => questionsdata = data.results)\n</code></pre>\n\n<p>Though be aware that <code>questionsdata</code> would get returned and any subsequent promise would receive that value.</p>\n\n<p>It looks like the <code>for</code> loops with the regexp replacements decode HTML entities. There are <a href=\"https://stackoverflow.com/questions/1912501/unescape-html-entities-in-javascript\">various other techniques for this</a>. I noticed the first element of <code>characters</code> has two semi-colons at the end. Should it only have one?</p>\n\n<p>Other ES-6 features could be used, like <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">destructuring assignment</a> for <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Swapping_variables\" rel=\"nofollow noreferrer\">swapping variables</a> without the need for a temporary variable.</p>\n\n<p>Inside the <code>shuffle()</code> function the technique used to decrement <code>currentIndex</code> could be simplified to the decrement operator: <code>--</code>. In fact, that could be moved to the previous line after it is used:</p>\n\n<blockquote>\n<pre><code>randomIndex = Math.floor(Math.random() * currentIndex);\ncurrentIndex -= 1;\n</code></pre>\n</blockquote>\n\n<p>could be simplified to: </p>\n\n<pre><code>randomIndex = Math.floor(Math.random() * currentIndex--);\n</code></pre>\n\n<p>The conditional for the <code>while</code> could be reduced to simply <code>currentIndex</code> because it is considered <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Falsy\" rel=\"nofollow noreferrer\"><em>falsey</em></a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T05:30:18.290",
"Id": "227149",
"ParentId": "227055",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T03:19:32.400",
"Id": "227055",
"Score": "3",
"Tags": [
"javascript",
"ecmascript-6",
"iterator",
"shuffle"
],
"Title": "A basic trivia app"
}
|
227055
|
<p>I want to add/remove a class on the html and body tags in the dom when my nav menu is opened or closed. Is this the most optimal way of writing this logic?</p>
<pre><code>$( '#navbarNav' ).on( 'show.bs.collapse', function() {
$( 'html, body' ).addClass( 'noscroll' );
});
$( '#navbarNav' ).on( 'hide.bs.collapse', function() {
$( 'html, body' ).removeClass( 'noscroll' );
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T09:48:51.657",
"Id": "447326",
"Score": "0",
"body": "It would be a good idea to mention that you are using Bootstrap, especially specifially which JS plugins."
}
] |
[
{
"body": "<p>Don't repeat the queries. Store any queries that are called more than once in a variable, and utilize jQuery's chaining:</p>\n\n<pre><code>const navbarNav = $( '#navbarNav' );\nconst htmlBody = $( 'html, body' );\n\nnavbarNav.on( 'show.bs.collapse', function() {\n htmlBody.addClass( 'noscroll' );\n}).on( 'hide.bs.collapse', function() {\n htmlBody.removeClass( 'noscroll' );\n});\n</code></pre>\n\n<hr>\n\n<p>Why are you setting the class on both the <code>html</code> and <code>body</code> elements? Either should be sufficient. </p>\n\n<hr>\n\n<p>Name the class <a href=\"https://maintainablecss.com/chapters/semantics/\" rel=\"nofollow noreferrer\">semantically</a>. Just like you call a class for important text \"<code>important</code>\" and not \"<code>red</code>\", just because it happens to be red, you don't call a class that indicates whether the main navigation is open \"<code>noscroll</code>\" but \"<code>main-nav-open</code>\" (for example).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T10:07:25.057",
"Id": "229841",
"ParentId": "227059",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229841",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T04:55:35.690",
"Id": "227059",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"dom",
"twitter-bootstrap"
],
"Title": "Add or remove a class on two elements when two different events fire"
}
|
227059
|
<h3>Project description</h3>
<p>We have different types of devices like <em>sov</em>, <em>motor</em>, <em>analog</em>, <em>digital</em>, <em>control valves</em> etc. Each type of device has 100 items.</p>
<p>Now our software continuously monitors with the PLC to read some property of each type according to which we need to write some property.</p>
<p>As an example, if motor on command is high then we need to write on feedback at PLC end high. At the moment, I face the problem that it takes too much time to update.</p>
<p>Now I describe my software architecture:</p>
<ol>
<li><p>I make individual class for each types of device. As an example for motor:</p>
<pre><code>class Fn_Motor1D:
def __init__(self,com,df,idxNo):
self._idxNo =idxNo
self.gen = com
self.df = df
self.setup()
self.initilizedigitalinput()
def setup(self):
try:
for tag,col in self.readalltags():
if col==3:
self.cmd = str(tag)
if col == 4:
self.runingFB = str(tag)
if col == 5:
self.remoteFB = str(tag)
if col == 6:
self.healthyFB = str(tag)
if col == 7:
self.readyFB = str(tag)
if col == 8:
self.mccbonFeedBack = str(tag)
if col == 9:
self.overloadFeedBack = str(tag)
if col == 10:
self.faultFB =str(tag)
if col == 11:
self.delaytime = tag
except Exception as e:
print("exception raise",e.args)
log_exception(e)
def initilizedigitalinput(self):
try:
if len(self.healthyFB) > 3:
self.gen.writegeneral.writenodevalue(self.healthyFB, 1)
else:
pass
if len(self.remoteFB) > 3:
self.gen.writegeneral.writenodevalue(self.remoteFB, 1)
else:
pass
if len(self.readyFB) > 3:
self.gen.writegeneral.writenodevalue(self.readyFB, 1)
else:
pass
if len(self.mccbonFeedBack) > 3:
self.gen.writegeneral.writenodevalue(self.mccbonFeedBack, 1)
else:
pass
if len(self.overloadFeedBack) > 3:
self.gen.writegeneral.writenodevalue(self.overloadFeedBack, 0)
else:
pass
if len(self.faultFB) > 3:
self.gen.writegeneral.writenodevalue(self.faultFB, 0)
else:
pass
except Exception as e :
log_exception(e)
def process(self):
try:
oncommandvalue = self.gen.readgeneral.readtagvalue(self.cmd)
if oncommandvalue:
sleep(self.delaytime)
self.gen.writegeneral.writenodevalue(self.runingFB, 1)
else:
self.gen.writegeneral.writenodevalue(self.runingFB, 0)
except Exception as e:
log_exception(e)
def readalltags(self):
n = 3
row, col = self.df.shape
print(col)
while n < col:
data = self.df.iloc[self._idxNo, n]
yield data,n
n = n + 1
</code></pre></li>
<li><p>Call all motor devices at one class and make <code>listofallmotor1d</code> devices.</p>
<pre><code>class Cal_AllMotor1D:
def __init__(self,df,com):
self.df = df
self.com = com
self.listofmotor1D = []
self.setup()
def setup(self):
try:
n =0
self.listofmotor1D.clear()
while n< len(self.df.index):
self.df.iloc[n, 0] = Fn_Motor1D(self.com, self.df, n)
self.listofmotor1D.append(self.df.iloc[n,0])
n = n + 1
except Exception as e :
print(e.args)
log_exception(e)
def process(self):
n = 0
while n < len(self.listofmotor1Dir):
self.listofmotor1Dir[n].process()
n = n + 1
@property
def listofmotor1Dir(self):
if len(self.listofmotor1D) > 0:
return self.listofmotor1D
</code></pre></li>
<li><p>Now I make <code>AllDevices</code> class where I call the all device and write monitoring process:</p>
<pre><code>import callallmotor1D
import callallmotor2D_V1
import callallsov1S_V1
import callallsov2S_V1
import calallanalog_V1
import calallcontrolvalves_V1
import callallvibrofeeder_V1
import callallconveyor_V1
import pandas as pd
class AllDevices:
def __init__(self,comobject):
self._comobject = comobject
dfM1D = pd.read_excel(r'D:\OPCUA\Working_VF1.xls', sheet_name='Motor1D')
dfM2D = pd.read_excel(r'D:\OPCUA\Working_VF1.xls', sheet_name='Motor2D')
dfsov1S = pd.read_excel(r'D:\OPCUA\Working_VF1.xls', sheet_name='Valve1S')
dfsov2S = pd.read_excel(r'D:\OPCUA\Working_VF1.xls', sheet_name='Valve2S')
dfanalog = pd.read_excel(r'D:\OPCUA\Working_VF1.xls', sheet_name='AnalogTx')
dfcontrolvalve = pd.read_excel(r'D:\OPCUA\Working_VF1.xls', sheet_name='ControlValves')
dfvibrofeeder = pd.read_excel(r'D:\OPCUA\Working_VF1.xls', sheet_name='VibroFeeder')
dfconveyor = pd.read_excel(r'D:\OPCUA\Working_VF1.xls', sheet_name='Conveyor')
self.allmotor1dobjects = callallmotor1D.Cal_AllMotor1D(dfM1D, comobject)
self.allmotor2dobjects = callallmotor2D_V1.Cal_AllMotor2D(dfM2D,comobject)
self.allsov1sobjects = callallsov1S_V1.Cal_AllSov1S(dfsov1S,comobject)
self.allsov2sobjects = callallsov2S_V1.Cal_AllSov2S(dfsov2S, comobject)
self.allanalogobjects = calallanalog_V1.Cal_AllAnalogInputs(dfanalog,comobject)
self.allcontrolvalveobjects = calallcontrolvalves_V1.Cal_AllControlValve(dfcontrolvalve,comobject)
self.allvibrofeederobjects = callallvibrofeeder_V1.Cal_AllVibroFeeder(dfvibrofeeder,comobject)
self.allconveyorobjects = callallconveyor_V1.Cal_AllConveyor1D(dfconveyor,comobject)
def allmotor1dprocessing(self):
self.allmotor1dobjects.process()
self.allmotor1dobjects.process()
def allmotor2dprocessing(self):
self.allmotor2dobjects.process()
def allsov1sprocessing(self):
self.allsov1sobjects.process()
def allanalogsprocessing(self):
self.allanalogobjects.process()
def allcontrolvaleprocessing(self):
self.allcontrolvalveobjects.process()
def allvibrofeederprocessing(self):
self.allvibrofeederobjects.process()
def allconveyorprocessing(self):
self.allconveyorobjects.process()
</code></pre></li>
<li><p>At the end I all devices class in my main UI and run seperate thread each device type:-</p>
<pre><code> def allmotor1dprocess():
while True :
self.callalldevices.allmotor1dprocessing()
def allmotor2dprocess():
while True:
self.callalldevices.allmotor2dprocessing()
def allsov1sprocess():
while True:
self.callalldevices.allsov1sprocessing()
def allananlogprocess():
while True:
self.callalldevices.allanalogsprocessing()
def allcontrolvalveprocess():
while True:
self.callalldevices.allcontrolvaleprocessing()
def allconveyorprocess():
while True:
self.callalldevices.allconveyorprocessing()
self.writeallmotor1dthread = threading.Thread(target=allmotor1dprocess)
self.writeallmotor2dthread =threading.Thread(target=allmotor2dprocess)
self.writeallsov1sthread1 = threading.Thread(target=allsov1sprocess)
self.writeallsov1sthread2 = threading.Thread(target=allsov1sprocess2)
self.writeallsov2sthread = threading.Thread(target=allsov2sprocess)
self.writeallanalogthread = threading.Thread(target=allananlogprocess)
self.writeallcontrolvalvethread = threading.Thread(target=allcontrolvalveprocess)
self.writeallconveyorthread = threading.Thread(target=allconveyorprocess)
self.writeallmotor1dthread.start()
self.writeallmotor2dthread.start()
self.writeallsov1sthread1.start()
self.writeallsov1sthread2.start()
self.writeallsov2sthread.start()
self.writeallanalogthread.start()
self.writeallcontrolvalvethread.start()
self.writeallconveyorthread.start()
</code></pre></li>
</ol>
<p>In this software architecture I really face problem to update the plc data.</p>
<p>As an example, let's suppose that I give on command for a motor. This will take time to update its run feedback. So, I need your expert view on this.
Please let me know how I can improve my coding to get process faster.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T09:41:32.420",
"Id": "441707",
"Score": "0",
"body": "Hello all any help?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T14:32:41.667",
"Id": "441748",
"Score": "1",
"body": "You are on Code Review here. It's not unusual that answers take at least few hours to several days, depending on the amount of code and the depth of the review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T15:22:33.280",
"Id": "441767",
"Score": "0",
"body": "It is okye Alex ..Please take your time.Actually my current project is put on hold. I need your help.If you are able to give me some feedback after this weekend, it would be good.please reply if you are interested to review my code.If you need any further information I can help you.Thank you"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T06:07:18.710",
"Id": "227060",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"multithreading",
"device-driver"
],
"Title": "Motor control PLC in Python"
}
|
227060
|
<p>I've created a extension method to count every available descendant starting from a single, given key. </p>
<p>The data is a flat list, there's is no hierarchical structure. (Well, not entirely true. There is an hierarchy in the data-model, but not in the list itself)</p>
<pre><code>self-reference parent-reference some other members
10045 => 0 ..
10046 => 10045 ..
10044 => 10063 ..
10061 => 10044 ..
10063 => 10046 ..
10064 => 10046 ..
10021 => 10061 ..
10028 => 10000 ..
10030 => 10000 ..
10031 => 10000 ..
10000 => 10000 ..
</code></pre>
<p>As an example, counting the descendant of the entry with the self-reference number 10046 would result in 6. </p>
<p>Let's take 10021 as an possible related entry to entry 10046, for example.</p>
<blockquote>
<p>10021 refers to 10061, 10061 refers to 10044, 10044 refers to 10063,
10063 refers to 10046
=> related!</p>
</blockquote>
<hr>
<p>My extension method is actually split up in two different methods.</p>
<pre><code>public static int CountDescendants<TSource, T>(
this IEnumerable<TSource> source,
T startKey,
Func<TSource, T> selfReference,
Func<TSource, T> parentReference)
{
if(source == null) {
throw new ArgumentNullException("source");
}
return Count(source, startKey, selfReference, parentReference);
}
</code></pre>
<p><code>startKey</code> defines our filter, the key we're looking for. In the example above I've used </p>
<blockquote>
<p>10046</p>
</blockquote>
<p><code>selfReference</code> defines a unique key a dataset can be identified with. </p>
<p><code>parentReference</code> defines a unique key which refers to another dataset.</p>
<p>The actual algorithm looks like this.</p>
<pre><code>private static int Count<TSource, T>(
IEnumerable<TSource> source,
T key,
Func<TSource, T> selfReference,
Func<TSource, T> parentReference)
{
// hash-map + .Where is faster than using IEnumerable + .Where
ReadOnlyDictionary<T, T> consolidatedSource =
new ReadOnlyDictionary<T, T>(source.ToDictionary(selfReference, parentReference));
int count = 0;
// to keep track of every reference which is somehow related to "key"
HashSet<T> keys = new HashSet<T> {
key
};
// using a stack instead of recurison
Stack<KeyValuePair<T, T>> stack = new Stack<KeyValuePair<T, T>>();
// get all first level entries with the given key
foreach(KeyValuePair<T,T> item in consolidatedSource.Where(x => x.Value.Equals(key))) {
stack.Push(item);
}
// using .Any over .Count because we don't care how many items we have but rather that the stack is not empty
while (stack.Any()) {
KeyValuePair<T, T> current = stack.Pop();
if (keys.Contains(current.Value)) {
count++;
keys.Add(current.Key);
// get all first level entries with the new key
foreach (KeyValuePair<T, T> item in consolidatedSource.Where(x => x.Value.Equals(current.Key) && !x.Key.Equals(current.Key))){
stack.Push(item);
}
}
}
return count;
}
</code></pre>
<p>The method can be called like this</p>
<p><code>this.AllProfiles.CountDescendants(CurrentProfile.Ref, x => x.Ref, x => x.ParentRef);</code></p>
<p>Is stuff like using a Dictionary to speed up things micro-optimization which I shouldn't worry about? Personally, wherever I can impact performance, I try to get the best out of it. Or at least not make it any worse.</p>
<p>Also, I'm not entirely sure if there are any constraints I can apply to the generic types. I don't think there's one that actually fits and is needed.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T07:44:50.703",
"Id": "441694",
"Score": "0",
"body": "Wouldn't it be more useful to return a tree structure, and then have properties like Count on each Node?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T07:54:38.600",
"Id": "441696",
"Score": "0",
"body": "Using a flat structure greatly simplifies other parts of the application, especially when working with databases. Creating a tree structure would be a way but I wouldn't have any use for. I think it would be 'too much' if I created one just to count the nodes afterwards."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T07:55:52.837",
"Id": "441697",
"Score": "0",
"body": "Understandable... I just figured a method to convert this flat structure to tree might be very reusable :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T17:18:51.550",
"Id": "441787",
"Score": "0",
"body": "Is it a static read only list, or is it dynamic (delete/add)? And what is the expected average size of it?"
}
] |
[
{
"body": "<blockquote>\n<pre><code>public static int CountDescendants<TSource, T>(\n this IEnumerable<TSource> source, \n T startKey, \n Func<TSource, T> selfReference,\n Func<TSource, T> parentReference)\n{\n if(source == null) {\n throw new ArgumentNullException(\"source\");\n }\n\n return Count(source, startKey, selfReference, parentReference);\n}\n</code></pre>\n</blockquote>\n\n<p>Thumbs up for doing the validation in a non-coroutine method, although I wonder why <code>source</code> is the only argument which needs validation.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> // hash-map + .Where is faster than using IEnumerable + .Where\n ReadOnlyDictionary<T, T> consolidatedSource = \n new ReadOnlyDictionary<T, T>(source.ToDictionary(selfReference, parentReference));\n</code></pre>\n</blockquote>\n\n<p>Firstly, why <code>ReadOnlyDictionary</code>? This isn't exposed outside this method, and within the method you should able to trust yourself not to do anything nasty with it.</p>\n\n<p>Secondly, I think the comment is indicative of a misunderstanding. Hash-map + <code>.TryGetValue</code> is faster than <code>IEnumerable</code> + <code>.Where</code>, but a linear search through a hash-map is no faster than a linear search through a list.</p>\n\n<p>What you probably want to use here is <code>source.ToLookup(parentReference)</code>. That <em>will</em> give an asymptotic performance improvement.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> Stack<KeyValuePair<T, T>> stack = new Stack<KeyValuePair<T, T>>();\n</code></pre>\n</blockquote>\n\n<p>If you have C# 7 then it would probably be nicer to use <code>Stack<(T foo, T bar)></code> with suitable names. The ability to have names at all is part of the point here.</p>\n\n<p>Although, FWIW, I'm not convinced that you need anything more than <code>Stack<T></code>, and I don't think <code>keys</code> is necessary at all.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T12:17:24.293",
"Id": "441727",
"Score": "0",
"body": "Thanks for your answer! I already added the validation for the other arguments but forgot to update my post. I used the ```ReadOnlyDictionary``` out of habit because I usually explicitly declare read-only types as such, but I followed your suggestion to use ```.ToLookup``` instead. The ```HashSet``` is useless as you mentioned, I removed it. I also changed the stack to be of the type ```T```. Thanks for your notes, they really helped!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T11:09:48.297",
"Id": "227074",
"ParentId": "227062",
"Score": "5"
}
},
{
"body": "<p>Peter already pointed out the main problem with your code: you're doing linear searches when looking for child-nodes, which will blow up to <span class=\"math-container\">\\$O(n^2)\\$</span> for worst-case inputs (very deep trees). Indeed, a lookup table that maps a parent ID to child IDs is much more efficient, and ensures that your method remains <span class=\"math-container\">\\$O(n)\\$</span> for all sorts of input.</p>\n\n<p>Another problem is that your method does not guard against cyclic inputs - it'll run indefinitely. You may want to throw an exception instead, or otherwise prevent the start item from being added to the stack again. It's also a good idea to document this behavior.</p>\n\n<p>Other notes:</p>\n\n<ul>\n<li>There's no need to perform input validation in a separate method here: <code>Count</code> does not use <code>yield</code>, so the input validation will be performed immediately. Note that a modern alternative is to move the <code>yield</code>ing part to a local function instead of to a separate method.</li>\n<li>When throwing argument-related exceptions, it's better to use <code>nameof(parameterName)</code> instead of <code>\"parameterName\"</code>. This lets the compiler protect you against typos, and works well with code refactoring tools.</li>\n<li>I would rename <code>T</code> to <code>TKey</code>, <code>selfReference</code> to <code>keySelector</code> and <code>parentReference</code> to <code>parentKeySelector</code>. I think that better describes their purpose, and it's consistent with other Linq methods.</li>\n<li>Use <code>var</code> to cut down on type name repetition: <code>var variableName = new LongTypeName(...);</code> is equivalent to <code>LongTypeName variableName = new LongTypeName(...);</code>.</li>\n<li>As Peter already mentioned, there's no need for that <code>keys</code> set: you're only adding items with a known parent ID to the stack, so there's no point in verifying whether their parent ID is known.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T12:31:04.433",
"Id": "441730",
"Score": "1",
"body": "Thanks for pointing out the possible infinite loop. Data-wise it shouldn't be possible, but I'v added a guard. The only reason I've separated those methods because I didn't want the actual algorithm to do 'too much' and mainly because I've been doing it with other methods as well. Using ```nameof``` is a good idea. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T13:43:20.123",
"Id": "441743",
"Score": "0",
"body": "Good point on the cycle detection, but then maybe `keys` is useful after all. It's certainly the most straightforward way of detecting a cycle."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T12:18:06.650",
"Id": "227084",
"ParentId": "227062",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T07:34:35.173",
"Id": "227062",
"Score": "5",
"Tags": [
"c#",
"generics",
"extension-methods"
],
"Title": "Generic Extension Method To Count Descendants"
}
|
227062
|
<h3>Input</h3>
<p>A long string of numbers, A list of numbers in string</p>
<h3>Output</h3>
<p>Minimum space needed in long string to match maximum numbers from list</p>
<h3>Example</h3>
<ul>
<li><code>minSpaces('3141592653589793238462643383279',['314','49','15926535897','14','9323','8462643383279','4','793'])</code> </li>
<li>will return <code>3</code></li>
</ul>
<p>I am using below code to solve it, but I am not able to figure out how can I use DP for more efficient time complexity.</p>
<p>Thanks for your help.</p>
<pre><code>dpArr = {} #empty list for DP
def findMinSpaces(k, piStr, favNumArr):
curr = ''
ans = 0
N = len(piStr)
if( k == N):
return 0
for i in range(k, N):
print(curr)
curr += piStr[i]
if(curr in favNumArr and i != N-1):
if(curr not in dpArr):
ans += 1 + findMinSpaces(i+1, piStr, favNumArr)
dpArr[curr] = ans
else:
print("from dpArr")
return dpArr[curr]
print(dpArr)
return ans
def minSpaces(piStr, favNumArr):
return findMinSpaces(0, piStr, favNumArr)
print(minSpaces('3141592653589793238462643383279',['314','49','15926535897','14','9323','8462643383279','4','793']))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T12:20:01.337",
"Id": "441728",
"Score": "1",
"body": "Could you elaborate on how exactly you get `3` for your example input? I don't really get what that \"minimal space\" means. Also, is this a programming challenge? If so, could you provide a link to it? If not, could you add more context, where does this problem come from?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T18:29:49.783",
"Id": "441809",
"Score": "0",
"body": "The problem is from here. \n https://youtu.be/tOD6g7rF7NA"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-01T13:29:16.540",
"Id": "451994",
"Score": "1",
"body": "Please edit your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!"
}
] |
[
{
"body": "<p>'''\nThe Problem can be thought as string pattern matching, Where output will be minimum no of spaces in bigger string(piStr) to match maximum no of strings from list of smaller strings(favNumArr).\nTo solve this, we take one var \"ans\" to store no spaces and one variable \"curr\" to store the current pattern.\nNow we iterate through the piStr and whenever we encounter(ith pos) that curr pattern is in favNumArr, we use recursion and call findMinSpaces for i+1 and increment ans with 1.\nThere is no need to use DP if we return from the loop with first occurrence of match and hence the loop will not run after it return value of recursion call.\nThe last return statement is to counter when i == N-1 when we reach the end of piStr.\nThe time complexity for this solution is O(n)\nAny suggestion for further enhancement or if breaks any edge case is open.'''</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def findMinSpaces(k, piStr, favNumArr):\n curr = ''\n ans = 0\n N = len(piStr)\n if( k == N):\n return 0\n for i in range(k, N):\n print(curr)\n curr += piStr[i]\n if(curr in favNumArr and i != N-1):\n ans += 1 + findMinSpaces(i+1, piStr, favNumArr)\n return ans\n return ans \n\ndef minSpaces(piStr, favNumArr):\n return findMinSpaces(0, piStr, favNumArr)\n\nprint(minSpaces('',['3149v','40x9','15926535c897','1c4','932c3','84626c43383279','4c793']))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T11:35:22.113",
"Id": "227316",
"ParentId": "227067",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T09:05:34.273",
"Id": "227067",
"Score": "3",
"Tags": [
"python",
"dynamic-programming"
],
"Title": "Using Dynamic Programming to reduce time complexity"
}
|
227067
|
<p>I'm trying to reshape my input arrays in a way that's described below to be able to fit a curve on the data points, plot it, etc.
It works fine, but I'm afraid it's not the most efficient way of doing it, and also it's hard to understand and read. It's part of a bigger function, but I only post here the critical part and not the whole function. I also added little comments to help you understand what's going on. I know it's ugly.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
from itertools import chain
#example inputs
delay = np.array([10,20,30,40,50,60,70,None])
omega = [[1,2,3,4],[1.1,2.2,3.3,None],[1.4,2.4,3.4,None],[1.5,2.8,None,None],
[1.8,2.9,None,None],[1.9,None,None,None],[2.0,None,None,None],[None,None,None,None]]
"""
desired output explained:
with delay's first component 10 I want to assign 1, 2, 3 and 4
so the outputs starts like this: [10,10,10,10] , [1,2,3,4]
then with delay's second component 20 I want to assign 1.1, 2.2, 3.3 and drop the None value.
at the moment the outputs should look like this: [10,10,10,10,20,20,20] , [1,2,3,4,1.1,2.2,3.3]
and so on.
"""
def spp_method(omegas, delays):
#dropping all None values from delays
delays = delays[delays != np.array(None)]
#dropping all the None values from omegas
omegas_ext = []
for element in omegas:
item = [x for x in element if x is not None]
omegas_ext.append(item)
#expand delays with the number of values in omegas_ext appropriate component
delays_exp = []
for idx in range(len(omegas_ext)):
if len(omegas_ext[idx])>1:
value = delays[idx]
item_to_add = [value]*(len(omegas_ext[idx]))
delays_exp.append(item_to_add)
elif len(omegas_ext[idx]) == 1:
value = delays[idx]
delays_exp.append([value])
#put the values into simple array to plot and to fit curve.
delays_unpacked = []
omegas_unpacked = []
for element in omegas_ext:
for item in element:
omegas_unpacked.append(item)
delays_unpacked = list(chain.from_iterable(delays_exp))
return np.array(delays_unpacked), np.array(omegas_unpacked)
y, x = spp_method(omega, delay)
print(x)
#outputs to: [1. 2. 3. 4. 1.1 2.2 3.3 1.4 2.4 3.4 1.5 2.8 1.8 2.9 1.9 2. ]
print(y)
#outputs to: [10 10 10 10 20 20 20 30 30 30 40 40 50 50 60 70]
</code></pre>
<p>which are correct.</p>
<p>Any improvements in the code are well-appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T11:18:32.997",
"Id": "441715",
"Score": "1",
"body": "Welcome to Code Review. Please change your title so that it describes what you are trying to accomplish, not what you expect from the review (see also [ask])."
}
] |
[
{
"body": "<p>You took a curved path to where you want to go :)</p>\n\n<p>It seems you are ill at ease at building flat lists and take long routes at building nested ones then unpacking them. But you can replace :</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> omegas_ext = []\n for element in omegas:\n item = [x for x in element if x is not None]\n omegas_ext.append(item)\n# [...]\n for element in omegas_ext:\n for item in element:\n omegas_unpacked.append(item)\n</code></pre>\n\n<p>By:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> omegas_ext = []\n for element in omegas:\n item = [x for x in element if x is not None]\n omegas_ext.extend(item)\n</code></pre>\n\n<p>Second, this if else is unecessary. <code>[value] * 1</code> is equivalent to <code>[value]</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> if len(omegas_ext[idx])>1:\n value = delays[idx]\n item_to_add = [value]*(len(omegas_ext[idx]))\n delays_exp.append(item_to_add)\n elif len(omegas_ext[idx]) == 1:\n value = delays[idx]\n delays_exp.append([value])\n</code></pre>\n\n<p>Can be replaced by:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> if len(omegas_ext[idx])>=1:\n delays_exp.append([delays[idx]]*(len(omegas_ext[idx])))\n</code></pre>\n\n<p>Again you unpack this later on. So you could extend and this would also make it unecessary to have this check for an element (since extending with an empty list is a no-op)</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> delays_exp.extend([delays[idx]*len(omegas_ext[idx]))\n # itertools.chain no longer needed\n</code></pre>\n\n<p>Finally, you missed the fact you can build the two lists in a single for, by using <code>zip</code>. This would save you the need to use an index to recompute the length of the <code>omegas_ext</code> items.</p>\n\n<p>Here would be the function :</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def spp_method(omegas, delays):\n delays = delays[delays != np.array(None)]\n omegas_ext = []\n delays_exp = []\n for delay, element in zip(delays, omegas):\n item = [x for x in element if x is not None]\n omegas_ext.extend(item)\n delays_exp.extend(len(item) * [delay])\n return np.array(delays_exp), np.array(omegas_ext)\n</code></pre>\n\n<p>Code returns the same output.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T11:29:01.170",
"Id": "441718",
"Score": "0",
"body": "Thank you for the answer, it is much better like this."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T11:18:59.833",
"Id": "227075",
"ParentId": "227069",
"Score": "1"
}
},
{
"body": "<pre><code>In [15]: delay = np.array([10,20,30,40,50,60,70,None]) \n ...: omega = [[1,2,3,4],[1.1,2.2,3.3,None],[1.4,2.4,3.4,None],[1.5,2.8,None,None], \n ...: [1.8,2.9,None,None],[1.9,None,None,None],[2.0,None,None,None],[None,None,None,None]] \n ...: \n</code></pre>\n\n<p>We can use a list comprehension to create a list of tuples. One tuple for each non-None element in <code>omega</code>.</p>\n\n<pre><code>In [16]: [(i,j) for i,k in zip(delay, omega) for j in k if j is not None] \nOut[16]: \n[(10, 1),\n (10, 2),\n (10, 3),\n (10, 4),\n (20, 1.1),\n (20, 2.2),\n (20, 3.3),\n (30, 1.4),\n (30, 2.4),\n (30, 3.4),\n (40, 1.5),\n (40, 2.8),\n (50, 1.8),\n (50, 2.9),\n (60, 1.9),\n (70, 2.0)]\n</code></pre>\n\n<p>Then use the <code>zip(*)</code> idiom to 'transpose' this into two tuples:</p>\n\n<pre><code>In [17]: x,y = zip(*_) \nIn [18]: x \nOut[18]: (10, 10, 10, 10, 20, 20, 20, 30, 30, 30, 40, 40, 50, 50, 60, 70)\nIn [19]: y \nOut[19]: (1, 2, 3, 4, 1.1, 2.2, 3.3, 1.4, 2.4, 3.4, 1.5, 2.8, 1.8, 2.9, 1.9, 2.0)\n</code></pre>\n\n<p>A <code>numpy</code> version:</p>\n\n<pre><code>In [40]: A = delay.repeat(4).reshape(8,4) \nIn [41]: B = np.array(omega) \nIn [42]: mask = np.frompyfunc(lambda x: x is not None,1,1)(_21).astype(bool) \nIn [43]: A[mask] \nOut[43]: \narray([10, 10, 10, 10, 20, 20, 20, 30, 30, 30, 40, 40, 50, 50, 60, 70],\n dtype=object)\nIn [44]: B[mask] \nOut[44]: \narray([1, 2, 3, 4, 1.1, 2.2, 3.3, 1.4, 2.4, 3.4, 1.5, 2.8, 1.8, 2.9, 1.9,\n 2.0], dtype=object)\n</code></pre>\n\n<p>If <code>omega</code> had <code>np.nan</code> instead of <code>None</code> I could have made the mask without the <code>frompyfunc</code> iteration.</p>\n\n<p>The arrays:</p>\n\n<pre><code>In [45]: A \nOut[45]: \narray([[10, 10, 10, 10],\n [20, 20, 20, 20],\n [30, 30, 30, 30],\n [40, 40, 40, 40],\n [50, 50, 50, 50],\n [60, 60, 60, 60],\n [70, 70, 70, 70],\n [None, None, None, None]], dtype=object)\nIn [46]: B \nOut[46]: \narray([[1, 2, 3, 4],\n [1.1, 2.2, 3.3, None],\n [1.4, 2.4, 3.4, None],\n [1.5, 2.8, None, None],\n [1.8, 2.9, None, None],\n [1.9, None, None, None],\n [2.0, None, None, None],\n [None, None, None, None]], dtype=object)\nIn [47]: mask \nOut[47]: \narray([[ True, True, True, True],\n [ True, True, True, False],\n [ True, True, True, False],\n [ True, True, False, False],\n [ True, True, False, False],\n [ True, False, False, False],\n [ True, False, False, False],\n [False, False, False, False]])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T15:16:12.303",
"Id": "227095",
"ParentId": "227069",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227075",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T10:25:57.870",
"Id": "227069",
"Score": "1",
"Tags": [
"python",
"numpy"
],
"Title": "Is there a way to make reshaping arrays shorter and cleaner?"
}
|
227069
|
<h2>Method</h2>
<p>Frequently input for problems is given as a 1D or 2D array in a text file.</p>
<p>Have knocked out a method to do so, but believe something shorter, clearer and cheaper can be written:</p>
<pre><code>def read_array_from_txt(path, dim, typ, sep):
'''
@time: O(n)
@space: O(n)
'''
txt_file_object = open(path,"r")
text = txt_file_object.readlines()
text = text[0]
if dim == 1:
if typ == "int":
text = [int(num) for num in text.split(sep)]
elif typ == "str":
text = [let for let in text.split(sep)]
else:
raise ValueError("Unknown type.")
elif dim == 2:
if typ == "int":
text = [[int(num) for num in line.split(sep)] for line in text]
if typ == "str":
text = [[let for let in line.split(sep)] for line in text]
else:
raise ValueError("Unknown type.")
else:
raise ValueError("Unknown dimension.")
txt_file_object.close()
return text
</code></pre>
<h2>An Example:</h2>
<p>Input: encrypted_message.txt</p>
<pre><code>36,22,80,0,0,4,23,25,19,17,88,4,4,19
</code></pre>
<p>Output:</p>
<pre><code>>>> read_array_from_txt("./encrypted_message.txt", 1, "int", ",")
[36,22,80,0,0,4,23,25,19,17,88,4,4,19]
</code></pre>
<h2>Some Other Possible Inputs:</h2>
<pre><code>1 37 79 164 155 32 87 39 113 15 18 78 175 140 200 4 160 97 191 100 91 20 69 198 196
2 123 134 10 141 13 12 43 47 3 177 101 179 77 182 117 116 36 103 51 154 162 128 30
3 48 123 134 109 41 17 159 49 136 16 130 141 29 176 2 190 66 153 157 70 114 65 173 104 194 54
</code></pre>
<pre><code>are,in,hello,hi,ok,yes,no,is
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T10:47:25.007",
"Id": "441711",
"Score": "0",
"body": "Could you include an example how you'd use this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T11:00:42.070",
"Id": "441712",
"Score": "0",
"body": "Have you tested this? It seems to me to have at least one obvious bug."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T11:05:54.773",
"Id": "441714",
"Score": "0",
"body": "Tested and have used this on several problems, but could have missed something."
}
] |
[
{
"body": "<p>First of all, let's make use of the <a href=\"https://docs.python.org/3/whatsnew/2.6.html#pep-343-the-with-statement\" rel=\"nofollow noreferrer\"><code>with</code></a> statement so that the file is closed automatically:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>with open(path, 'r') as txt_file_object:\n text = txt_file_object.readlines()\n</code></pre>\n\n<p>With this, you don't have to call <code>close()</code> anymore, as the file will close automatically when you exit the <code>with</code> scope.</p>\n\n<hr>\n\n<p><code>text = text[0]</code></p>\n\n<p>You are only reading the first line of text. Is this really what you want to do?</p>\n\n<hr>\n\n<p>You are using the variable <code>text</code> for two different things: for the input lines and for the output values. This is not very intuitive; in fact, the result can be a list of integers, so why would it be called <code>text</code>? Maybe <code>result</code> would be a better name for it.</p>\n\n<p>BUT since now you don't have to close at the end of the function, you can return the result directly instead of saving it in a variable:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>return [int(num) for num in text.split(sep)]\n</code></pre>\n\n<p>Returning will exit the <code>with</code> scope, so again the file will be closed automatically.</p>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code>[let for let in text.split(sep)]\n</code></pre>\n\n<p>This selects all objects inside <code>text.split(sep)</code>, so we can return the splitted list directly:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>text.split(sep)\n</code></pre>\n\n<p>Similarly, there's a different way of applying a function to every item in a list, which is using <code>map</code>. Maybe the list comprehension feels more natural, so you can keep that if you want; still I'll show you just so you know:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># Creates a list by calling 'int' to every item in the list\nlist(map(int, text.split(sep))\n</code></pre>\n\n<hr>\n\n<p>You are repating a lot of code; you have four different results, but they are very similar, so let's try to provide a more generic way.</p>\n\n<p>My concern here is handling the two possible dimensions. You are parsing the text in the same way (depending if it's int or str), but when it's two dimensions you do it for every line. So we could use Python's <a href=\"https://www.w3schools.com/python/python_lambda.asp\" rel=\"nofollow noreferrer\"><strong>lambdas</strong></a> to decide first what type of parsing (int or str) we are doing, and then just apply it once or multiple times.</p>\n\n<p>The lambda can take parameters; the only parameter we need in our case is the input text. We can't just use <code>text</code> directly because sometimes we want to parse the full text, but sometimes only the line:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if typ == \"int\":\n parse_function = lambda t: list(map(int, t.split(sep)))\nelif typ == \"str\":\n parse_function = lambda t: list(t.split(sep))\nelse:\n raise ValueError(\"Unknown type.\")\n</code></pre>\n\n<p>Now <code>parse_function</code> can be used like any other function, taking the text as input. So we can use it when deciding the dimension:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if dim == 1:\n return parse_function(text)\nelif dim == 2:\n return [parse_function(line) for line in text]\nelse:\n raise ValueError(\"Unknown dimension.\")\n</code></pre>\n\n<hr>\n\n<p>You do well in throwing exceptions for invalid input, but how is the user meant to know what possible values can be used for <code>typ</code> and <code>dim</code>? You could add that to the docstring. You should also say what the function does in the docstring.</p>\n\n<h2>Updated code</h2>\n\n<pre class=\"lang-py prettyprint-override\"><code>def read_array_from_txt(path, dim, typ, sep):\n '''\n Processes a text file as a 1D or 2D array.\n :param path: Path to the input file.\n :param dim: How many dimensions (1 or 2) the array has.\n :param typ: Whether the elements are read as 'int' or 'str'\n :param sep: The text that is used to separate between elements.\n @time: O(n)\n @space: O(n)\n '''\n with open(path,\"r\") as txt_file_object:\n text = txt_file_object.readlines()\n\n if typ == \"int\":\n parse_function = lambda t: list(map(int, t.split(sep)))\n elif typ == \"str\":\n parse_function = lambda t: list(t.split(sep))\n else:\n raise ValueError(\"Unknown type.\")\n\n if dim == 1:\n return parse_function(text)\n elif dim == 2:\n return [parse_function(line) for line in text]\n else:\n raise ValueError(\"Unknown dimension.\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T16:47:03.457",
"Id": "441777",
"Score": "0",
"body": "Like the comment on explaining inputs in doscstring; and removal of redundancy via lambdas. Disinclined to use with; explicitly closing seems clearer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T16:50:45.323",
"Id": "441779",
"Score": "1",
"body": "`str.split` already returns a list, so `list(text.split(sep))` is redundant.\n\n@A.L.Verminburger: The `with` scope gives you more than just calling `close`. It guarantees that the file will be closed (barring the computer instantaneously dying). Even in the event of an exception (which would prevent your `close` from running. It is a well-known and often used Python idiom, which I would recommend getting used to."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T06:34:51.050",
"Id": "441869",
"Score": "0",
"body": "True, I assumed it would return a generator. I will edit the answer now, thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T21:05:13.357",
"Id": "442900",
"Score": "0",
"body": "You didn't remove `list(...)` from all the cases of `list(text.split(sep))`. You missed this one: `parse_function = lambda t: list(t.split(sep))`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T21:07:14.877",
"Id": "442901",
"Score": "0",
"body": "You'll want `return parse_function(text[0])` on the `dim == 1` case, because `text` is a list, not a string."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T12:09:58.600",
"Id": "227082",
"ParentId": "227071",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227082",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T10:35:53.843",
"Id": "227071",
"Score": "2",
"Tags": [
"python",
"programming-challenge",
"io"
],
"Title": "Python Method for Text Input from Project Euler"
}
|
227071
|
<p>I have a list of variables which I need to convert to LIKE statements in SQL. The final query should look like the following:</p>
<pre class="lang-sql prettyprint-override"><code>...
WHERE ([TraceableItem].[IdentificationNo] LIKE N'%015558'
OR [TraceableItem].[IdentificationNo] LIKE N'%123456'
OR [TraceableItem].[IdentificationNo] LIKE N'%654321')
...
</code></pre>
<p>Below is my code to do it, but I feel it is fairly inefficient / redundant. Especially features like having a bool for firstLoop, and constantly checking for items already existing. I would be very grateful for a code review and tips on how to improve - I'm fairly rusty on C#</p>
<pre class="lang-cs prettyprint-override"><code>string queryInsertString = "([TraceableItem].[IdentificationNo] LIKE ";
string lastBatchNo = batchnos.Last();
List<string> alreadyAdded = new List<string>();
bool firstLoop = true;
foreach(string item in batchnos)
{
string splitItem = item.Split('/')[1];
if (!alreadyAdded.Contains(item)){
if (!firstLoop)
{
queryInsertString += " OR [TraceableItem].[IdentificationNo] LIKE N'%" + splitItem + "'";
} else
{
queryInsertString += "N'%" + splitItem + "'";
firstLoop = false;
}
alreadyAdded.Add(item);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T11:31:28.223",
"Id": "441719",
"Score": "3",
"body": "You're lacking some of the context here - when reviewing, we want to see the complete program or function, including the definitions of the identifiers in scope (e.g. `batchnos` in this question)."
}
] |
[
{
"body": "<p>Using <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.string.join?view=netframework-4.8#System_String_Join_System_String_System_Collections_Generic_IEnumerable_System_String__\" rel=\"nofollow noreferrer\">String.Join</a> makes this kind of string operation a breeze:</p>\n\n<pre><code>// DON'T USE THIS - SQL INJECTION\nstring predicates = string.Join(\" OR \", \n batchNos.Select(item => item.Split('/')[1])\n .Distinct()\n .Select(splitItem => $\"[TraceableItem].[IdentificationNo] LIKE N'%{splitItem}'\"));\nstring queryInsertString = \"(\" + predicates + \")\";\n</code></pre>\n\n<p>You'll notice the all capital warning not to use that code. It's not just because I haven't even checked if it compiles/works, it's because this kind of thing introduces a SQL Injection Vulnerability.</p>\n\n<p>What you need to do is read up on using SqlParameters in C#. You'll want to generate SQL that looks more like:</p>\n\n<pre><code>[TraceableItem].[IdentificationNo] LIKE @param1 OR [TraceableItem].[IdentificationNo] LIKE @param2\n</code></pre>\n\n<p>You then need to create a SqlParameter instance for each one and add that to the SqlCommand before you execute it. That's assuming you're using Ado.Net, if you're using a framework you'll have to look up the right way of doing it in the one you're using.</p>\n\n<p>The danger is that if someone passes a batch number of <code>\"a/'); delete from Users; --\"</code>, you'll end up creating a query that looks like: </p>\n\n<pre><code>WHERE ([TraceableItem].[IdentificationNo] LIKE N''); delete from Users; -- ...\n</code></pre>\n\n<p>You do not want a user to be able to do that!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T08:49:18.683",
"Id": "442339",
"Score": "0",
"body": "Thank you very much. SQL Injection wasn't something I'd thought about"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T11:31:28.480",
"Id": "227076",
"ParentId": "227072",
"Score": "5"
}
},
{
"body": "<p>Your SQL query is never going to be efficient because it has wildcard at the start, and is not Sargable (<code>LIKE N'%015558'</code>).</p>\n\n<p>Assuming your database allows it, what you should do in this scenario is to create a <code>PERSISTED</code> computed SQL column which is set to <code>REVERSE(IdentificationNo)</code>, and create an index on that column.</p>\n\n<p>Combine this with the advice from @RobH, and make your query something similar.</p>\n\n<pre><code>WHERE [ReversedIdentificationNo] LIKE + splitItem.Reverse() + '%'\n</code></pre>\n\n<p>This way, your query will use an index seek (instead of an index scan) and potentially be magnitudes faster.</p>\n\n<p>EDIT: \nWith a variable number of <code>IdentificationNo</code> that you intend of searching, you run into a cache pollution issue. For every distinct number of parameters, your SQL engine will <em>not</em> be able to reuse an existing query cache plan. This is very common issue when dynamically generating SQL statements (especially without SQL paramters). </p>\n\n<p>To avoid this, you could use a temp table / table type.</p>\n\n<p><code>CREATE TYPE Ids AS TABLE ( ID varchar(128) PRIMARY KEY )</code></p>\n\n<p>Then, instead of constructing a bunch of <code>OR</code> statements, you just insert all your <code>splitItem</code> into this temp table. Finally, your query looks something like the following.</p>\n\n<pre><code>WHERE EXISTS (\n SELECT 1 \n FROM @Ids\n WHERE [ReversedIdentificationNo] LIKE [Id] + '%'\n)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T17:48:02.490",
"Id": "227114",
"ParentId": "227072",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "227076",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T10:50:51.903",
"Id": "227072",
"Score": "2",
"Tags": [
"c#",
"sql"
],
"Title": "Looping through list to create SQL Query"
}
|
227072
|
<p>I would appreciate som feedback on my fictional product landing page. I am doing the freeCodeCamp curriculum and <a href="https://learn.freecodecamp.org/responsive-web-design/responsive-web-design-projects/build-a-product-landing-page" rel="nofollow noreferrer">Product Landing Page</a> is one of the Responsive Web Design Projects using only HTML/CSS.</p>
<p>I am especially interested in feedback regarding best practice, naming conventions and efficient code.</p>
<hr>
<p>The code is also <a href="https://oyvind-solberg.github.io/fcc-product-landing-page/" rel="nofollow noreferrer">on GitHub</a>.</p>
<h3>HTML file:</h3>
<pre class="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" />
<link rel="stylesheet" href="css/style.css" />
<script src="https://kit.fontawesome.com/4dd9b52bee.js"></script>
<title>Fireworks</title>
</head>
<body>
<header id="header">
<div class="flex-row-center">
<div>
<img
id="header-img"
src="img/Logo.png"
alt="Company logo"
width="1068px"
height="132px"
/>
</div>
<nav id="nav-bar">
<ul class="flex-row">
<li><a href="#showcase" class="nav-link">Home</a></li>
<li><a href="#pricing" class="nav-link">Pricing</a></li>
<li><a href="#newsletter" class="nav-link">Newsletter</a></li>
</ul>
</nav>
<div class="social-icons">
<ul class="flex-row">
<li>
<a href="#"><i class="fab fa-facebook-f"></i></a>
</li>
<li>
<a href="#"><i class="fab fa-twitter"></i></a>
</li>
<li>
<a href="#"><i class="fab fa-instagram"></i></a>
</li>
</ul>
</div>
</div>
</header>
<aside class="social-icons">
<ul>
<li>
<a href="#"><i class="fab fa-facebook-f"></i></a>
</li>
<li>
<a href="#"><i class="fab fa-twitter"></i></a>
</li>
<li>
<a href="#"><i class="fab fa-instagram"></i></a>
</li>
</ul>
</aside>
<main>
<section id="showcase">
<div class="flex-column-center left-align content">
<p class="sub-header">Get ready for</p>
<h1>
<i class="logo-icon fas fa-haykal fa-xs"></i
>Fireworks<br />of flavors
</h1>
</div>
<div class="product-video flex-row-center">
<div class="video-container">
<video id="video" autoplay loop muted>
<source src="video/fireworksHD.mp4" type="video/mp4">
<source src="video/fireworksHD.webm" type="video/webm">
<source src="video/fireworksHD.ogv" type="video/ogv">
</video>
</div>
</div>
<div class="product-img flex-row-center">
<img class="standard_img" src="img/Product.png" alt="Fireworks coffee" />
<img class="mobile_img" src="img/Product_mobile.png" alt="Fireworks coffee" />
</div>
</section>
<section id="pricing">
<div class="flex-row-center content">
<div class="flex-column-center left-align">
<h2>Pricing</h2>
<h3 class="sub-header">Monthly subscription</h3>
</div>
<div class="flex-row container-centered shadow">
<div class="price-tag">
<h3>Personal</h3>
<ul>
<li>&dollar;<strong class="price-strong">10</strong>/mo</li>
<li>10 bags of coffee</li>
<li><a class="btn" href="#">Order Now</a></li>
</ul>
</div>
<div class="price-tag focus-line">
<h3 class="focus">Professional</h3>
<ul>
<li>&dollar;<strong class="price-strong">150</strong>/mo</li>
<li>200 bags of coffee</li>
<li><a class="btn focus-bg" href="#">Order Now</a></li>
</ul>
</div>
<div class="price-tag">
<h3>Corporate</h3>
<ul>
<li>&dollar;<strong class="price-strong">600</strong>/mo</li>
<li>1000 bags of coffee</li>
<li><a class="btn" href="#">Order Now</a></li>
</ul>
</div>
</div>
</div>
</section>
<section id="newsletter">
<div class="flex-row-center content">
<div class="flex-column-center left-align">
<h2>Newsletter</h2>
<h3 class="sub-header">Let's keep in touch</h3>
</div>
<div class="flex-row container-centered shadow">
<form class="flex-column"
action="https://www.freecodecamp.com/email-submit"
method="GET"
id="form"
>
<h3 class="focus">E-mail subscription</h3>
<input
id="email"
type="email"
name="email"
placeholder="Enter your e-mail"
/>
<input class="btn focus-bg" id="submit" type="submit" value="Submit"/>
</form>
</div>
</div>
</section>
</main>
<footer>
<p class="footer-text">
&copy; 2019 Fireworks all rights reserved
</p>
<div class="footer-logo">
<img
id="header-img"
src="img/Logo.png"
alt="Company logo"
width="1068px"
height="132px"
/>
</div>
</footer>
</body>
</html>
</code></pre>
<h3>CSS file:</h3>
<pre class="lang-css prettyprint-override"><code>/* Color scheme */
:root {
--background: #000;
--background-dark: #555;
--text-standard: #ccc;
--text-subtle: #777;
--text-title: #fff;
--focus: #f98836;
--focus-highlight: #e27426;
}
/* Basic Reset */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
/* Setup */
body {
background-color: var(--background);
color: var(--text-standard);
font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
font-size: 1rem;
font-weight: 400;
overflow-x: hidden;
}
img {
width: 100%;
height: auto;
}
a {
text-decoration: none;
color: var(--text-title);
}
ul,
li {
list-style: none;
}
input[type="submit"] {
border: none;
font-size: 1rem;
}
.logo-icon {
color: var(--focus);
margin-right: 0.1em;
transform: translateY(-0.1em);
}
h1 {
font-size: 4rem;
color: var(--text-title);
text-transform: uppercase;
}
h2 {
font-size: 3rem;
color: var(--text-title);
text-transform: uppercase;
}
h3 {
font-size: 1.1rem;
color: var(--text-title);
text-transform: uppercase;
}
.sub-header {
color: var(--focus);
font-size: 1rem;
font-weight: 600;
letter-spacing: 0.3em;
text-transform: uppercase;
margin-top: 1rem;
}
/* Utility classes */
.flex-row-center {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
text-align: center;
}
.flex-column-center {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
}
.flex-row {
display: flex;
}
.flex-column {
display: flex;
flex-direction: column;
}
.container-centered {
margin: auto;
}
.left-align {
align-items: flex-start;
text-align: left;
width: auto;
}
.content {
position: relative;
z-index: 2;
padding: 12rem 10rem 12rem 6rem;
}
.shadow {
box-shadow: 5px 20px 60px rgba(0, 0, 0, 0.7), 5px 5px 100px rgba(255, 255, 255, 0.2)
}
.focus {
color: var(--focus);
}
body .focus-bg {
background-color: var(--focus);
}
.mobile_img {
display: none;
}
/* Buttons */
.btn {
background-color: var(--background-dark);
padding: 0.5rem 1.5rem;
width: 100%;
color: var(--text-title);
}
body .btn:hover {
background-color: var(--focus-highlight);
}
/* Header */
header {
position: fixed;
top: 0;
left: 6rem;
padding-top: 3rem;
z-index: 100;
}
header::before {
content: "";
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 7rem;
background: linear-gradient(to bottom, #0006, #0006 60%, #0000);
z-index: -1;
}
header img {
width: 12rem;
}
header .social-icons {
display: none;
position: fixed;
right: 3rem;
top: 2.5rem;
align-items: flex-end;
}
header .social-icons li {
margin-left: 2rem;
}
/* Nav */
#nav-bar a {
font-size: 1rem;
font-weight: 600;
letter-spacing: 0.5em;
margin-left: 5rem;
text-transform: uppercase;
}
#nav-bar a:hover {
color: var(--focus);
}
/* Aside */
.social-icons {
position: fixed;
top: 50%;
right: 4rem;
transform: translateY(-50%);
z-index: 100;
}
.social-icons a {
color: var(--text-subtle);
}
.social-icons li {
margin: 2rem 0;
}
/* Showcase */
#showcase {
width: 100vw;
height: 100vh;
background: radial-gradient(#ffffff34, #ffffff17);
}
#showcase .product-img {
position: absolute;
top: 0;
left: 10rem;
z-index: 1;
overflow: hidden;
}
#showcase img {
max-width: 1600px;
}
#showcase .product-video {
position: absolute;
top: 0;
left: 10rem;
z-index: -1;
overflow: hidden;
}
#showcase .video-container {
max-width: 1600px;
}
#showcase .product-video video {
width: 100%;
}
#showcase .sub-header {
margin-bottom: 1rem;
}
/* Pricing */
#pricing {
width: 100vw;
height: 100vh;
background: radial-gradient(#ffffff34, #ffffff17);
}
.price-tag {
color: var(--text-subtle);
width: 12rem;
padding: 2rem 1rem 1rem 1rem;
border: 1px solid;
border-color: var(--text-subtle);
justify-content: flex-start;
}
.price-strong {
color: var(--text-title);
font-size: 2em;
margin: 0 0.1em;
}
#pricing li {
display: flex;
align-items: center;
justify-content: center;
margin: 2rem 0 0 0;
}
#pricing li:first-child {
margin-top: 0.3rem;
margin-bottom: 0;
}
#pricing li:last-child {
margin-top: 2rem;
}
.focus-line {
border-color: var(--focus);
border-width: 1.5px;
outline: 2px solid;
outline-color: var(--focus);
z-index: 100;
}
/* Newsletter */
#newsletter {
width: 100vw;
height: 100vh;
background: radial-gradient(#ffffff34, #ffffff17);
}
#newsletter form {
width: 32rem;
border: 1px solid;
border-color: var(--text-subtle);
padding: 2rem 4rem;
}
#newsletter form h3 {
margin-bottom: 1rem;
}
input[type="email"] {
padding: 0.5rem;
margin: 1rem 0;
}
/* Footer */
footer {
position: relative;
z-index: 100;
}
footer::before {
content: "";
position: fixed;
bottom: 0;
left: 0;
width: 100%;
height: 7rem;
background: linear-gradient(to top, #0006, #0006 60%, #0000);
z-index: -1;
}
.footer-text {
position: fixed;
left: 6rem;
bottom: 3rem;
color: var(--text-subtle);
text-transform: uppercase;
}
.footer-logo {
position: fixed;
right: 8rem;
bottom: 3rem;
color: var(--text-subtle);
width: 7rem;
opacity: 0.3;
}
/* Media queries */
@media only screen and (max-width: 1200px) {
#pricing > .flex-row-center,
#newsletter > .flex-row-center {
flex-direction: column;
}
#pricing .left-align,
#newsletter .left-align {
align-items: center;
text-align: center;
justify-content: flex-end;
flex: 0;
}
#pricing .sub-header,
#newsletter .sub-header {
margin-bottom: 4rem;
}
}
@media only screen and (max-width: 1000px) {
aside.social-icons,
#nav-bar {
display: none;
}
header .social-icons {
display: flex;
}
header img {
width: 8rem;
}
.content {
padding: 6rem 3rem 6rem 3rem;
}
#pricing .content,
#newsletter .content {
padding: 10rem 3rem 10rem 3rem;
}
header {
left: 3rem;
padding-top: 2rem;
}
#showcase .left-align {
align-items: center;
text-align: center;
justify-content: flex-start;
}
.footer-text {
left: 3rem;
bottom: 2rem;
}
.footer-logo {
right: 3rem;
bottom: 2rem;
}
#showcase .product-img,
#showcase .product-video {
top: 15%;
left: 0;
}
h1 {
font-size: 3rem;
}
h2 {
font-size: 2.3rem;
}
}
/* Tablet 768px */
@media only screen and (max-width: 768px) {
#showcase .product-img,
#showcase .product-video {
top: 10%;
left: 0;
}
#pricing {
height: auto;
}
#pricing .flex-row {
flex-direction: column;
}
#pricing .flex-row,
.price-tag {
width: 100%;
}
.price-tag {
padding: 2rem;
}
#newsletter .flex-row,
#newsletter form {
width: 100%;
}
#newsletter form {
padding: 2rem 2rem;
}
}
/* Phone 568px */
@media only screen and (max-width: 568px) {
header .social-icons li {
margin-left: 0.8rem;
}
#pricing .content,
#newsletter .content {
padding: 1rem 2rem 5rem 2rem;
}
h1 {
font-size: 2rem;
}
h2 {
font-size: 1.8rem;
}
.footer-logo {
display: none;
}
.footer-text {
left: 0;
width: 100%;
text-align: center;
padding: 0 2rem;
font-size: 0.8rem;
}
#newsletter {
height: auto;
}
#showcase img,
#showcase video {
width: 150%;
left: -25%;
}
#video {
display: none;
}
.standard_img {
display: none;
}
.mobile_img {
display: inline-block;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T11:47:29.203",
"Id": "441724",
"Score": "1",
"body": "Welcome to Code Review! \"this is one of the Responsive Web Design Projects\", which one specifically?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T11:52:27.530",
"Id": "441725",
"Score": "1",
"body": "Thank you! Build a Product Landing Page.\n\n[Link to website](https://learn.freecodecamp.org/responsive-web-design/responsive-web-design-projects/build-a-product-landing-page)"
}
] |
[
{
"body": "\n\n<blockquote>\n<pre class=\"lang-html prettyprint-override\"><code>width=\"1068px\"\nheight=\"132px\"\n</code></pre>\n</blockquote>\n\n<p>The <code>width</code> and <code>height</code> attributes can’t contain \"px\".</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>width=\"1068\"\nheight=\"132\"\n</code></pre>\n\n<hr>\n\n<p>The <code>alt</code> value for the logo should not contain \"logo\", just the company name.</p>\n\n<hr>\n\n<blockquote>\n<pre class=\"lang-html prettyprint-override\"><code><i class=\"fab fa-facebook-f\"></i>\n</code></pre>\n</blockquote>\n\n<p>Don’t use the <code>i</code> element if you just want to display an icon via CSS. The <code>i</code> element has a meaning which isn’t appropriate for this (<a href=\"https://stackoverflow.com/a/22501699/1591669\">details</a>). Use the <code>span</code> element instead.</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><span class=\"fab fa-facebook-f\"></span>\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre class=\"lang-html prettyprint-override\"><code><h1>\n <i class=\"logo-icon fas fa-haykal fa-xs\"></i\n >Fireworks<br />of flavors\n</h1>\n</code></pre>\n</blockquote>\n\n<p>Don’t use the <code>br</code> element if you want to show a line break just because of aesthetic reasons. The <code>br</code> element must only be used for meaningful line breaks (<a href=\"https://stackoverflow.com/a/13221418/1591669\">details</a>). Use a <code>span</code> element and CSS to add the line break.</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><h1>\n <span class=\"logo-icon fas fa-haykal fa-xs\"></span\n >Fireworks <span class=\"separator\">of flavors</span>\n</h1>\n</code></pre>\n\n<hr>\n\n<p>Your use of heading elements is not consistent. Your first <code>section</code> starts with <code>h1</code>, your second <code>section</code> starts with <code>h2</code>. While this is not an error, it’s a good practice to be consistent: either use <code>h1</code> everywhere, or (preferably) use the heading elements of the correct rank, i.e., start with <code>h2</code> in top-level sections.</p>\n\n<hr>\n\n<blockquote>\n<pre class=\"lang-html prettyprint-override\"><code><h2>Pricing</h2>\n<h3 class=\"sub-header\">Monthly subscription</h3>\n</code></pre>\n</blockquote>\n\n<p>Don’t use a heading element for sub-headings (<a href=\"https://stackoverflow.com/a/22451639/1591669\">details</a>). This creates a wrong document outline. Use a <code>p</code> element instead.</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><h2>Pricing</h2>\n<p class=\"sub-header\">Monthly subscription</p>\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre class=\"lang-html prettyprint-override\"><code>/mo\n</code></pre>\n</blockquote>\n\n<p>You can use the <code>abbr</code> element here.</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><abbr title=\"per month\">/mo</abbr>\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre class=\"lang-html prettyprint-override\"><code><p class=\"footer-text\">\n &copy; 2019 Fireworks all rights reserved\n</p>\n</code></pre>\n</blockquote>\n\n<p>You can use the <code>small</code> element here (<a href=\"https://stackoverflow.com/a/21489636/1591669\">details</a>).</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><p class=\"footer-text\">\n <small>&copy; 2019 Fireworks all rights reserved</small>\n</p>\n</code></pre>\n\n<hr>\n\n<p>Both of your logo <code>img</code> element have the same <code>id</code> value. An <code>id</code> value can only be used once per page. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T11:35:28.550",
"Id": "441936",
"Score": "1",
"body": "Thank you for your detailed feedback! Exactly what I was looking for.\n\nRegarding heading elements, I have now wraped a h1 tag around my logo image in the header and changed all my top-level-sections to h2.\nI'm a bit unsure if this is the correct use of the h1 tag, but I see Facebook is doing the same so I guess it is ok."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T12:28:09.487",
"Id": "441942",
"Score": "0",
"body": "@Øyvindsen: I would say having the site name (whether it’s text or a logo) as `h1` is ideal; many people disagree because they have the (outdated, I would say) assumption that `h1` should only be used for the main content, but this would typically lead to a wrong document outline. -- You can check the document outline with https://validator.w3.org/nu/ -- there is a checkbox \"outline\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T14:15:19.217",
"Id": "441964",
"Score": "0",
"body": "Thanks. I'm already familiar with the validator. Guess I need to remember to use it more often. Now the outline looks good. It just takes the `alt` value from the image as the h1 text."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T17:18:20.250",
"Id": "227111",
"ParentId": "227079",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227111",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T11:38:22.107",
"Id": "227079",
"Score": "3",
"Tags": [
"html",
"css"
],
"Title": "Product landing page (freeCodeCamp Responsive Web Design project)"
}
|
227079
|
<p>I have some XML that I want to flatten based on its XPath. The task is to acquire certain nodes that are passed as input. That said, I have to get to parent nodes and look for nodes that might be part of the configuration. I am avoiding lists in a given iteration.</p>
<p>This is my code:</p>
<pre><code>from lxml import etree
tree = etree.parse("sample.xml")
path = "/DATA_DS/G_1"
def getNodesDict(node_element, nodes_to_pick):
some_dict = {}
for element in node_element:
if not isinstance(element, list):
if element.tag in nodes_to_pick:
some_dict[element.tag] = element.text
return some_dict
def fetchNodesListBasedOnXpath(Xpath, tree, selected_nodes):
"""
:param Xpath:
:param tree:
:param selected_nodes:
:return:
"""
temp_list = []
temp_list1 = []
element_split = Xpath.split('/')
for i in range(len(element_split), 1, -1):
path = "/".join(element_split[0:i])
try:
element = tree.xpath(path)
for j, node_element in enumerate(element):
value = getNodesDict(node_element, selected_nodes)
if len(temp_list) > 0 and len(temp_list) - 1 > j:
for k, item in enumerate(temp_list):
dall = {}
dall.update(value)
dall.update(item)
if item:
temp_list1.append(dall)
temp_list = []
else:
temp_list.append(value)
except:
pass
nodes_to_pick = ['SUBSCRIPTION_ID', "PRODUCT_NUMBER", "SUBSCRIPTION_ID1", "SALES_PRODUCT_TYPE1"]
fetchNodesListBasedOnXpath(path, tree, nodes_to_pick)
</code></pre>
<p>This is my sample XML:</p>
<pre class="lang-xml prettyprint-override"><code><DATA_DS>
<SUBSCRIPTION_ID1>300000031070490</SUBSCRIPTION_ID1>
<SALES_PRODUCT_TYPE1>SUBSCRIPTION</SALES_PRODUCT_TYPE1>
<G_1>
<SUBSCRIPTION_ID>300000031070490</SUBSCRIPTION_ID>
<PRODUCT_NUMBER>1</PRODUCT_NUMBER>
<SALES_PRODUCT_TYPE>SUBSCRIPTION</SALES_PRODUCT_TYPE>
<PRODUCT_NAME>Demo4</PRODUCT_NAME>
<STATUS>ORA_EXPIRED</STATUS>
<START_DATE>2019-06-01T00:00:00.000+00:00</START_DATE>
<END_DATE>2019-06-01T00:00:00.000+00:00</END_DATE>
</G_1>
<G_1>
<SUBSCRIPTION_ID>300000031070491</SUBSCRIPTION_ID>
<PRODUCT_NUMBER>4</PRODUCT_NUMBER>
<SALES_PRODUCT_TYPE>SUBSCRIPTION</SALES_PRODUCT_TYPE>
<PRODUCT_NAME>Demo4</PRODUCT_NAME>
<STATUS>ORA_ACTIVE</STATUS>
<START_DATE>2019-06-01T00:00:00.000+00:00</START_DATE>
<END_DATE>2020-05-31T00:00:00.000+00:00</END_DATE>
</G_1>
<G_1>
<SUBSCRIPTION_ID>300000031070492</SUBSCRIPTION_ID>
<PRODUCT_NUMBER>2</PRODUCT_NUMBER>
<SALES_PRODUCT_TYPE>SUBSCRIPTION</SALES_PRODUCT_TYPE>
<PRODUCT_NAME>Demo4</PRODUCT_NAME>
<STATUS>ORA_CLOSED</STATUS>
<START_DATE>2019-06-01T00:00:00.000+00:00</START_DATE>
<END_DATE>2019-06-30T00:00:00.000+00:00</END_DATE>
</G_1>
<G_1>
<SUBSCRIPTION_ID>300000031070493</SUBSCRIPTION_ID>
<PRODUCT_NUMBER>3</PRODUCT_NUMBER>
<SALES_PRODUCT_TYPE>SUBSCRIPTION</SALES_PRODUCT_TYPE>
<PRODUCT_NAME>Demo4</PRODUCT_NAME>
<STATUS>ORA_ACTIVE</STATUS>
<START_DATE>2019-06-01T00:00:00.000+00:00</START_DATE>
<END_DATE>2019-08-31T00:00:00.000+00:00</END_DATE>
</G_1>
</DATA_DS>
</code></pre>
|
[] |
[
{
"body": "<h1>Docstrings</h1>\n\n<p>You should include a <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\"><code>docstring</code></a> at the beginning of every module, class, and function you write. This will allow documentation to identify what your code is supposed to do. Docstrings are great for the understanding the functionality of the larger part of the code, i.e., the general purpose of any class, module or function. Comments are used for code, statement, and expressions which tend to be small.</p>\n\n<h1>Function Naming</h1>\n\n<p>You have these two function names:</p>\n\n<pre><code>fetchNodesListBasedOnXpath\ngetNodesDict\n</code></pre>\n\n<p>According to <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">PEP-8's Guidelines</a> for function names, these function names should be <code>snake_case</code>. </p>\n\n<h1><code>_</code> for unused loop variables</h1>\n\n<p>When you don't use a variable in a loop, like:</p>\n\n<pre><code>for i in range(5):\n print(\"Hi!\")\n</code></pre>\n\n<p>You should use a <code>_</code>. This makes it clear that the variable used for the loop is not needed, and should be ignored.</p>\n\n<h1>Use of <code>if len(...)</code></h1>\n\n<blockquote>\n <p>For sequences, (strings, lists, tuples), use the fact that empty sequences are false.</p>\n\n<pre><code><b>Yes:</b> if not seq:\n if seq:\n\n<b>No:</b> if len(seq):\n if not len(seq):\n</code></pre>\n</blockquote>\n\n<p>Essentially, <code>if seq</code> will return <code>True</code> if it's not empty, and <code>if not seq</code> will return <code>True</code> if it is empty. Since you are checking <code>if len(temp_list) > 0 ...</code>, this should be changed to <code>if temp_list ...</code>.</p>\n\n<h1>Constant Variable Naming</h1>\n\n<p>According to PEP8s rule on <a href=\"https://www.python.org/dev/peps/pep-0008/#naming-conventions\" rel=\"nofollow noreferrer\">constants</a>:</p>\n\n<blockquote>\n <p>Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include <code>MAX_OVERFLOW</code> and <code>TOTAL</code>.</p>\n</blockquote>\n\n<p>Long Version: </p>\n\n<p>In the Python community (as in many other communities) exist conventions about how to write code. This is different from <em>working code</em>: even if you write your constants all lowercase, your code still works. </p>\n\n<p>But there is community consensus (as documented in PEP8) which is \"enforced\" with tools like <em>pylint</em>. If you program for your own happiness, you may neglect the hints pylint gives you. If you want open exchange with the community, aka »someone besides myself should use my code«, you should prepare your code according to PEP8. [<a href=\"https://softwareengineering.stackexchange.com/a/342377\">source</a></p>\n\n<h1>Main Guard</h1>\n\n<p>Having a main guard clause in a module allows you to both run code in the module directly and also use procedures and classes in the module from other modules. Without the main guard clause, the code to start your script would get run when the module is imported. This can cause a plethora of issues if you want to reuse this code. Wrapping it in a main guard (check updated code) protects against this.</p>\n\n<h1>Parameter Naming</h1>\n\n<p>Parameters, variables, and default parameters all follow the same <a href=\"https://www.python.org/dev/peps/pep-0008/#naming-conventions\" rel=\"nofollow noreferrer\">PEP-8 Guidelines</a> for naming. They should all be <code>snake_case</code>. You currently have a parameter named <code>Xpath</code>. A simple change to <code>xpath</code> will do the trick.</p>\n\n<h1>Catching Errors/Exceptions</h1>\n\n<p>Right now, your main function can catch an exception, but doesn't handle it. If your program suddenly fails, a detailed error message would do the trick. You should catch specific errors that you think your code will generate. Since you're dealing with files and paths, catching <code>FileNotFoundError</code> is a good idea. Then, after dealing with all the specific errors, you can use a <code>finally</code>. Since this will always be run, you can put your <code>pass</code> here.</p>\n\n<p><strong><em>Updated Code</em></strong></p>\n\n<pre><code>\"\"\"\nModule Docstring\nA description of your program goes here\n\"\"\"\n\nfrom lxml import etree\n\ndef get_nodes_dict(node_element, nodes_to_pick):\n \"\"\"\n A description of this method should go here\n \"\"\"\n some_dict = {}\n for element in node_element:\n if not isinstance(element, list):\n if element.tag in nodes_to_pick:\n some_dict[element.tag] = element.text\n\n return some_dict\n\n\ndef fetch_nodes_list_based_on_xpath(xpath, tree, selected_nodes):\n \"\"\"\n\n A description of this method should go here\n\n :param xpath:\n :param tree:\n :param selected_nodes:\n :return:\n \"\"\"\n temp_list = []\n temp_list1 = []\n element_split = xpath.split('/')\n for i in range(len(element_split), 1, -1):\n path = \"/\".join(element_split[0:i])\n try:\n element = tree.xpath(path)\n for j, node_element in enumerate(element):\n value = get_nodes_dict(node_element, selected_nodes)\n if temp_list and len(temp_list) - 1 > j:\n for _, item in enumerate(temp_list):\n dall = {}\n dall.update(value)\n dall.update(item)\n if item:\n temp_list1.append(dall)\n temp_list = []\n else:\n temp_list.append(value)\n except FileNotFoundError as _:\n print(f\"The file at [{PATH}] doesn't exist!\")\n finally:\n pass\n\nif __name__ == '__main__':\n\n TREE = etree.parse(\"code/sample.xml\")\n PATH = \"/DATA_DS/G_1\"\n\n NODES_TO_PICK = ['SUBSCRIPTION_ID', \"PRODUCT_NUMBER\", \"SUBSCRIPTION_ID1\", \"SALES_PRODUCT_TYPE1\"]\n\n fetch_nodes_list_based_on_xpath(PATH, TREE, NODES_TO_PICK)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T10:55:12.200",
"Id": "227168",
"ParentId": "227086",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T12:38:12.920",
"Id": "227086",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"xpath",
"lxml"
],
"Title": "Flattening XML and selecting nodes based on input to convert to CSV"
}
|
227086
|
<p>I have to develop a small security management application that relies on a Web API. Based on that API, I have generated the REST client classes (<a href="https://github.com/OpenAPITools/openapi-generator" rel="noreferrer">Open API generator</a>), but I still have to code on top to provide things like retrials and token management (avoid getting a token for each call).</p>
<h3>Code</h3>
<pre><code>///<inheritdoc/>
public class DataLakeSecurityApiTokenService : IDataLakeSecurityApiTokenService
{
private const int TokenRefreshCoolDownPeriod = 3600; // seconds
private static readonly SemaphoreSlim NewTokenMutex = new SemaphoreSlim(1, 1);
private static string Token { get; set; }
private static readonly Stopwatch StopWatch= new Stopwatch();
private IConfigurationService ConfigurationService { get; }
private ILoggingService Logger { get; }
private async Task RefreshToken()
{
var defaultApiClient = new DefaultApi(ConfigurationService.DataLakeBasePath);
var tokenObj = (JObject)await defaultApiClient.LoginTokenPostAsync(
ConfigurationService.DataLakeUser, ConfigurationService.DataLakePassword);
Token = tokenObj["access_token"].ToString();
StopWatch.Restart();
}
///<inheritdoc/>
public DataLakeSecurityApiTokenService(IConfigurationService configurationService, ILoggingService logger)
{
ConfigurationService = configurationService;
Logger = logger;
}
///<inheritdoc/>
public async Task<ValidationResult<string>> GetLoginToken(bool force = false)
{
await NewTokenMutex.WaitAsync();
try
{
bool expired = StopWatch.Elapsed.Seconds > TokenRefreshCoolDownPeriod;
if (expired || force || string.IsNullOrWhiteSpace(Token))
await RefreshToken();
return new ValidationResult<string> {Payload = Token};
}
catch (ApiException exc)
{
Logger.LogError(exc, "Failed to get login token");
return new ValidationResult<string> { IsError = true, Message = exc.Message};
}
finally
{
NewTokenMutex.Release();
}
}
///<inheritdoc/>
public async Task<ValidationResult<TRes>> ExecuteWithTokenRefresh<TApiClient, TRes>(
string context, string functionName, params object[] functionParams)
{
for (int retryIndex = 0; retryIndex < 2; retryIndex++)
{
var tokenRes = await GetLoginToken(retryIndex > 0);
if (tokenRes.IsError)
return ValidationResult<TRes>.Create(tokenRes);
try
{
var defaultConfiguration = GetDefaultConfiguration(tokenRes.Payload);
var apiClient = Activator.CreateInstance(typeof(TApiClient), args: defaultConfiguration);
// ReSharper disable once PossibleNullReferenceException
var apiResponse = await (Task<ApiResponse<TRes>>) typeof(TApiClient).GetMethod(functionName)
?.Invoke(apiClient, functionParams);
// ReSharper disable once PossibleNullReferenceException
return new ValidationResult<TRes> {Payload = apiResponse.Data};
}
catch (ApiException exc)
{
Logger.LogError(exc, $"{context} error, retry index = {retryIndex}");
if (retryIndex > 0)
return new ValidationResult<TRes> { IsError = true, Message = exc.Message };
}
}
// normally it should not ever reach this point
return new ValidationResult<TRes>();
}
//TODO: move to a more appropriate place when a common service is defined
///<inheritdoc/>
public Configuration GetDefaultConfiguration(string token)
{
return new Configuration
{
BasePath = ConfigurationService.DataLakeBasePath,
AccessToken = token
};
}
}
</code></pre>
<p>This code does the following:</p>
<ul>
<li>caches the last valid token for a period</li>
<li>provides a way to quickly execute an API client method without worrying about getting the token, by fetching the token if necessary and also performing a retrial if an error has occurred. Unfortunately the generated code does not allow to discriminate between access denied errors (invalid or expired token) and a real internal server error (500), so I have to retry regardless of the error to be certain I catch access denied errors.</li>
</ul>
<h3>Usage</h3>
<pre><code>///<inheritdoc/>
public async Task<ValidationResult<List<Tag>>> GetTableLevelTagList()
{
var ret = await DataLakeSecurityApiTokenService.ExecuteWithTokenRefresh<SecurityTagsApi, List<Tag>>(
"Get table level tag list",
nameof(SecurityTagsApi.ListTableLevelSecurityTagsTagTableGetAsyncWithHttpInfo));
return ret;
}
</code></pre>
<p>The usage is pretty straightforward, but what I particularly dislike is that I am using dynamic invocation. If the consumer works with <code>nameof</code> it is pretty safe, but it still quite messy when working with methods with parameters which are not validated at compile-time.</p>
<p>I am wondering if there is way to improve this code.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T00:57:35.087",
"Id": "441833",
"Score": "3",
"body": "I think you should build on top of some higher level abstractions, like RX. For one, your implementation uses a fixed retry timeout, which is the worst kind. You should add randomized jitter and exponential back-off (google the terms) to prevent yourself from browning out your servers from an avalanche of retries. Also, the use of reflection here seems completely unnecessary. It would be much better to just take a function object."
}
] |
[
{
"body": "<h2>Inversion-of-control</h2>\n\n<p>I wouldn't use reflection using error-prone member-by-string lookup, when a simple <code>Func</code> provides type-safe behavior. This signature could be used to have the error callback, client factory and operation provided using <em>inversion-of-control</em>.</p>\n\n<pre><code>public async Task<ValidationResult<TRes>> ExecuteWithTokenRefresh<TApiClient, TRes>(\n Action<ApiException, int> errorCallback,\n Func<Configuration, TApiClient> clientFactory,\n Func<TApiClient, Task<ValidationResult<TRes>> operation) { // ..\n</code></pre>\n\n<p>Creating the client:</p>\n\n<pre><code>var apiClient = clientFactory(defaultConfiguration);\n</code></pre>\n\n<p>instead of:</p>\n\n<blockquote>\n<pre><code> var apiClient = Activator.CreateInstance(typeof(TApiClient), \n args: defaultConfiguration);\n</code></pre>\n</blockquote>\n\n<p>Getting the response then becomes:</p>\n\n<pre><code>var apiResponse = await operation(apiClient);\n</code></pre>\n\n<p>instead of:</p>\n\n<blockquote>\n<pre><code>var apiResponse = await (Task<ApiResponse<TRes>>) \n typeof(TApiClient).GetMethod(functionName)\n ?.Invoke(apiClient, functionParams);\n</code></pre>\n</blockquote>\n\n<p>And the error gets handled as:</p>\n\n<pre><code>catch (ApiException exc)\n{\n errorCallback(exc, retryIndex);\n if (retryIndex > 0)\n return new ValidationResult<TRes> { IsError = true, Message = exc.Message }; \n}\n</code></pre>\n\n<p>so you no longer require that <code>context</code> string:</p>\n\n<blockquote>\n<pre><code>Logger.LogError(exc, $\"{context} error, retry index = {retryIndex}\");\n</code></pre>\n</blockquote>\n\n<p>This is only one possible way to refactor the code. Perhaps you would like to have improved error flow management and have the error callback control retry management.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T13:53:20.357",
"Id": "441744",
"Score": "2",
"body": "10k! Say hi to [nobody-cares-spongebob](https://codereview.stackexchange.com/questions/144947/simple-packethandler-class/145695#145695) ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T13:56:36.610",
"Id": "441746",
"Score": "3",
"body": "@t3chb0t You gave me my first bounty and now you get me over 10K, you'ze my bro!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T07:39:02.443",
"Id": "442200",
"Score": "1",
"body": "@dfhwze - indeed this is a much better (safe) way to write the code. My initial code was started with a very \"lazy\" client in mind (provide as little information as possible and let the generic method take of the rest), but it is clearly not a good approach. Thanks."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T13:43:44.477",
"Id": "227089",
"ParentId": "227088",
"Score": "7"
}
},
{
"body": "<p>Definitely agree with <strong>dfhwze</strong>'s suggestion above. A few other minor points to consider:</p>\n\n<ol>\n<li>Define <code>TokenRefreshCoolDownPeriod</code> as a <code>TimeSpan</code> since that is what it represents. This simplifies the stopwatch comparison slightly and improves readability.</li>\n</ol>\n\n<pre><code>private static readonly TimeSpan TokenRefreshCoolDownPeriod = TimeSpan.FromHours(1);\n\n// ...\n\nvar expired = StopWatch.Elapsed > TokenRefreshCoolDownPeriod;\n</code></pre>\n\n<ol start=\"2\">\n<li>The <code>if (retryIndex > 0)</code> statement in your <code>catch</code> block will always match on the second attempt. This is not currently a problem because you're only attempting a maximum of two times, but may introduce a subtle bug if you later decide to increase the maximum retry count. Consider defining a <code>MaxAttemptCount</code> field and using it in the <code>for</code> loop and <code>if</code> statement instead, e.g.</li>\n</ol>\n\n<pre><code>private const int MaxAttemptCount = 2;\n\n// ...\n\n// Note indexing starts from 1 now, i.e. the first attempt is attempt #1, and the\n// final iteration will be when the attempt number equals the maximum defined above.\nfor (int attemptNumber = 1; attemptNumber <= MaxAttemptCount; attemptNumber++)\n{\n // Only force the token refresh on attempts after the first.\n var tokenRes = await GetLoginToken(attemptNumber > 1);\n\n // ...\n\n try\n {\n // ...\n }\n catch (ApiException exc)\n {\n Logger.LogError(exc, $\"{context} error, attempt number = {attemptNumber}\");\n\n // If this is the last attempt, return the error.\n if (attemptNumber == MaxAttemptCount)\n return new ValidationResult<TRes> { IsError = true, Message = exc.Message }; \n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T18:28:08.893",
"Id": "227118",
"ParentId": "227088",
"Score": "4"
}
},
{
"body": "<p><strong>There are dragons in your code</strong> I must say you beat me with this API. I usually build strange things but the way you misuse the <code>ValidationResult</code> here is remarkable. Every single method returns a <code>ValidationResult<T></code> or some kind. I needed a while to figure out that you aren't actually validating anything.</p>\n\n<p><strong>Use a true monad</strong> If you want this kind of monad for results that may fail or not then you should use something that is built for this purpose and doesn't confuse the user. Like the <code>Task</code> that you are already using. In this case you wrapped one of them in another one. You can however create your own like the <a href=\"https://medium.com/@dimpapadim3/either-is-a-common-type-in-functional-languages-94b86eea325c\" rel=\"nofollow noreferrer\">Either Monad</a>.</p>\n\n<p><strong>Read</strong>\nYou can also learn a lot about this topic from this question: <a href=\"https://codereview.stackexchange.com/questions/163171/a-failablet-that-allows-safe-returning-of-exceptions\">A Failable that allows safe returning of exceptions\n</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T13:50:31.430",
"Id": "227175",
"ParentId": "227088",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227089",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T13:19:04.193",
"Id": "227088",
"Score": "6",
"Tags": [
"c#",
"functional-programming",
"rest"
],
"Title": "Generic method to call API functions with simple retrial on errors"
}
|
227088
|
<p>I'm trying to solve <a href="https://www.codewars.com/kata/find-all-the-possible-numbers-multiple-of-3-with-the-digits-of-a-positive-integer" rel="nofollow noreferrer">this problem from codewars</a>.</p>
<blockquote>
<p><strong>Problem</strong></p>
<p>Given a certain number, how many multiples of three could you obtain with its digits? Suppose that you have the number <code>362</code>. The numbers that can be generated from it are: <code>3, 6, 2, 36, 63, 62, 26, 32, 23, 236, 263, 326, 362, 623, 632</code> and among those <code>3, 6, 36, 63</code> are divisible by <code>3</code>. </p>
<p>We need a function that can receive a number ann may output in the following order:</p>
<ul>
<li><p>the amount of multiples(without <code>0</code>)</p></li>
<li><p>the maximum multiple</p></li>
</ul>
</blockquote>
<p><strong>My solution</strong></p>
<p>I have found all possible permutations of the digits of the given number and checked if the number is divisible by <code>3</code>. Here is my code - </p>
<pre><code>from itertools import permutations as perm
from functools import reduce
def to_int(digs): # takes a list of digits of an integer and returns the number
n = reduce(lambda total, d: 10 * total + d, digs, 0)
return n
def find_mult_3(num):
digs = list(map(int, str(num)))
perms = [] # stores all possible permutations with the digits of num
for i in range(1, len(digs)+1):
perms.extend(list(p) for p in set(perm(digs, i)))
count, mx = 0, 0
seen = set() # to keep track of divisors already seen
if 0 in perms:
perms.remove(0)
for p in perms:
n = to_int(p)
if n % 3 == 0 and n not in seen:
if mx < n:
mx = n
count += 1
seen.add(n)
return [count, mx]
</code></pre>
<p>But getting <code>TLE</code>, is there any way to make this program faster or any other clever way to solve this problem? Please ask if there is any need for clarification in any part of the code.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T14:29:19.457",
"Id": "441747",
"Score": "0",
"body": "Can you think of a way to avoid permutating all possibilities before checking the %3 guard?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T14:35:43.927",
"Id": "441749",
"Score": "0",
"body": "@dfhwze Not getting any way"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T15:06:35.977",
"Id": "441759",
"Score": "0",
"body": "Then I need to write own permutation function ig"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T15:12:48.517",
"Id": "441761",
"Score": "2",
"body": "Hello, have you considered that a number is divisible by 3 if sum of its digits is divisible by 3?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T15:23:19.757",
"Id": "441768",
"Score": "0",
"body": "Hello, yeah but will that help here? I need to use the `to_int()` function."
}
] |
[
{
"body": "<p>The algorithm can be improved, so that we do less work:</p>\n\n<p>Use the fact that multiples of 3 have a sum of digits that's also a multiple of 3. That means we can select all the distinct <em>combinations</em> of digits, and discard any that don't sum to a multiple of 3. Only for those sets not discarded, we can compute the number of permutation of the selected digits. (Note that we don't have to actually produce all the numbers, merely count them - so if we have <em>n</em> different digits, we count <em>n</em>! permutations; if <em>p</em> of them are identical, then <em>n</em>!/<em>p</em>!, and so on).</p>\n\n<p>For example, with input <code>5532</code>:</p>\n\n<ul>\n<li>5+5+3+2 is 15, this gives us 4!/2! permutations that are multiples of 3 (and remember 5532 as the largest such multiple).</li>\n<li>5+5+3 is 13, so ignore it.</li>\n<li>5+5+2 is 12, giving us 3!/2! more permutations to add to our count.</li>\n<li>5+3+2 is 10; ignore it.</li>\n<li>5+5 is 10; ignore it.</li>\n<li>5+3 is 8; ignore it.</li>\n<li>5+2 is 7; ignore it.</li>\n<li>2+3 is 5; ignore it.</li>\n<li>5 alone - ignore</li>\n<li>3 alone - add one to the count.</li>\n<li>2 alone - ignore.</li>\n</ul>\n\n<p>And we're done; the total count is 4!/2! + 3!/2! + 1 = 16.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T14:51:31.693",
"Id": "441967",
"Score": "2",
"body": "having 1 or more zeroes in the number complicates this a bit"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T16:00:29.383",
"Id": "227102",
"ParentId": "227091",
"Score": "5"
}
},
{
"body": "<p>From the mathematical point , <strong><em>one number is divisible by 3 if sum of its digits is divisible by 3</em></strong> and it is valid the commutative property, so 3 + 6 + 2 is equal to 6 + 3 + 2 because you can commute elements in every position and still obtain the same result.\nSo if sum of <em>n</em> digits is divisible by 3, the <em>n!</em> permutations of the number including itself are still divisible by 3. Below the execution of algorithm starting from number <code>362</code>:</p>\n\n<ol>\n<li>First step: you start from number <code>362</code> and the sum is <code>11</code> that is\nnot divisible by 3 and so are the commutation of its digits that are\nthe permutation of the number: the amount of multiples is <code>0</code> and the maximum multiple is <code>None</code>.</li>\n<li>Second step: you subtract one digit from number '362' obtaining numbers <code>62, 32, 36</code>; now there is one number <code>36</code> that is divisible by 3 and its permutations are divisible by 3. In this case there is the permutation <code>63</code> that is the maximum multiple. The amount of multiples is now <code>2</code>.</li>\n<li>Third step: you subtract one digit from number <code>36</code> obtaining numbers <code>3</code> and <code>6</code>: both are divisible by <code>3</code> and the final amount of multiples is now <code>4</code>.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T17:34:36.577",
"Id": "441796",
"Score": "1",
"body": "There is a pending edit on your answer: _Third step: you subtract two digit from number 362 obtaining numbers 3 and 6 and 2: 6 and 3 are divisible by 3 and the final amount of multiples is now 4._"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T17:35:34.897",
"Id": "441797",
"Score": "1",
"body": "@Linny why did you vote to approve the edit?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T13:14:30.917",
"Id": "441953",
"Score": "0",
"body": "+1 for your idea, not able to implement it properly till now :("
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T16:01:07.670",
"Id": "227103",
"ParentId": "227091",
"Score": "4"
}
},
{
"body": "<h1>Variable names</h1>\n\n<p>The few keystrokes you save by not having to type digits or permutations in full is not worth it. Just name em <code>digits</code> and <code>permutations</code>. For the import, just import <code>itertools</code> instead of <code>from itertools import permutations as perm</code></p>\n\n<h1>to_int</h1>\n\n<p>To take a sum, <code>reduce</code> is seldom needed. You can explain this logic simpler like :</p>\n\n<p>def to_int(digits):\n return sum(x * 10 ** i for i, x in enumerate(reversed(digits)))</p>\n\n<h1>itertools chain</h1>\n\n<p>instead of having a list and extending it, </p>\n\n<pre><code>perms = [] # stores all possible permutations with the digits of num\nfor i in range(1, len(digs)+1):\n perms.extend(list(p) for p in set(perm(digs, i)))\n</code></pre>\n\n<p>you can use:</p>\n\n<pre><code>permutations = list(\n itertools.chain.from_iterable(\n set(itertools.permutations(digs, i)) for i in range(1, len(digs) + 1)\n )\n)\n</code></pre>\n\n<p>Even better would be to filter as soon as possible, and use:</p>\n\n<pre><code>permutations = itertools.chain.from_iterable(\n set(\n permutation\n for permutation in itertools.permutations(digits, i)\n if (\n sum(permutation)\n and sum(permutation) % 3 == 0\n and permutation[0] != 0\n )\n )\n for i in range(1, len(digits) + 1)\n)\n</code></pre>\n\n<p>You don't even need to instantiate the list. The <code>sum(permutation)</code> test checks for a permutation with only 0s. Then the rest becomes a simple:</p>\n\n<pre><code>count = 0\nrunning_max = 0\nfor permutation in permutations:\n n = to_int(permutation)\n count += 1\n running_max = max(running_max, n)\nreturn count, running_max\n</code></pre>\n\n<p>But it turns out you don't need all the permutations on a list</p>\n\n<h1>not needed operations</h1>\n\n<p>Not all operations need to be done on all numbers:</p>\n\n<p>For a given combination of digits:</p>\n\n<ul>\n<li>if its sum is not divisible by 3, it can be discarded</li>\n<li>it has 1 maximum permutation, which can be easily calculated by <code>sum(x * 10 ** i for i, x in enumerate(sorted(combination)))</code>, so <code>to_int</code> is no longer needed</li>\n<li>if there are no <code>0</code>s in it, the number of permutations can be calculated with <a href=\"https://en.wikipedia.org/wiki/Permutation#Permutations_of_multisets\" rel=\"nofollow noreferrer\">this formula</a></li>\n<li>if there are <code>0</code>s the simplest will be to generate all the combinations not starting with 0 and counting them:</li>\n</ul>\n\n<p>In python, I would do this like this:</p>\n\n<pre><code>import itertools\nfrom collections import Counter\nfrom math import factorial\n\n\ndef powerset(iterable):\n \"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)\"\n s = list(iterable)\n return itertools.chain.from_iterable(\n itertools.combinations(s, r) for r in range(len(s) + 1)\n )\n</code></pre>\n\n<p>This <a href=\"https://docs.python.org/3/library/itertools.html#itertools-recipes\" rel=\"nofollow noreferrer\">itertools recipe</a> gives all of the combinations for all of the subsets</p>\n\n<pre><code>def product(iterable):\n result = 1\n for i in iterable:\n result *= i\n return result\n</code></pre>\n\n<p>helper method to calculate the product of an iterable</p>\n\n<pre><code>def permutation_count(combination):\n total = sum(combination)\n if total == 0: # all digits are 0\n return 0\n if 0 not in combination:\n counter = Counter(combination)\n return int(\n factorial(total) / product(factorial(i) for i in counter.values())\n )\n\n return len(\n {\n permutation\n for permutation in itertools.permutations(combination)\n if permutation[0] != 0\n }\n )\n\ndef multiples(number):\n digits = map(int, str(number))\n running_count = 0\n running_max = 0\n for combination in powerset(digits):\n if sum(combination) == 0 or sum(combination) % 3: # not divisible by 3\n continue\n max_combination = sum(x * 10 ** i for i, x in enumerate(sorted(combination)))\n running_max = max(running_max, max_combination)\n running_count += permutation_count(combination)\n\n return running_count, running_max\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T02:41:55.450",
"Id": "442488",
"Score": "0",
"body": "Thanks for your time :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T09:11:20.740",
"Id": "227308",
"ParentId": "227091",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227102",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T14:26:05.017",
"Id": "227091",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"time-limit-exceeded",
"combinatorics"
],
"Title": "Counting numbers that are divisible by 3 and can be produced from the digits of a given number"
}
|
227091
|
<p>The following code is a solution to <a href="https://github.com/exercism/problem-specifications/issues/1570" rel="nofollow noreferrer">an exercise I've made</a>:</p>
<blockquote>
<p>This exercise idea is based on a story from my current work place: My boss'es Ubuntu had a bug that made his printer, when asked to print <em>N</em> copies of something, instead print <em>N²</em> copies. So for our Thursday status meeting, he'd hope that the number of people who show up, for whom he would bring a copy of his status report, was targetable with as few print requests as possible.</p>
<p>For example, if 13 people would show up to the meeting, he would first ask the printer of 3 copies (yielding 9 copies), and then 2 copies (yielding 4 copies) copies, with a final result of 3² + 2² = 13 copies. For some numbers of employees, this was simply not possible with two print jobs, and he'd need to consult the printer a third time.</p>
<p>The exercise is to write a function that computes the <em>groan factor</em>, being the minimal number of print jobs it takes to print <em>N</em> copies of a status report when the printer gives you back <em>N²</em> copies.</p>
<p>Examples:</p>
<ul>
<li>It takes 1 print job to print 1 copy because 1² = 1.</li>
<li>It takes 2 print jobs to print 5 copies because 2² + 1² = 5.</li>
<li>It takes 3 print jobs to print 11 copies because 3² + 1² + 1² = 11.</li>
</ul>
<p>The suggested exercise name comes from the thought that it must be kafkaesque to hope that a specific number of employees <em>N</em> show up on Thursdays such that ∃ <em>a</em>, <em>b</em> ∈ ℕ₀: <em>a</em>² + <em>b</em>² = <em>N</em>.</p>
</blockquote>
<p>For more background information, see <a href="https://en.wikipedia.org/wiki/Lagrange%27s_four-square_theorem" rel="nofollow noreferrer">Lagrange's four-square theorem</a>.</p>
<p>I am unsure how to improve on my solution below, but among the things I am dissatisfied with are: (1) the repetitiveness inside <code>hasTwo</code> and <code>hasThree</code>, and (2) the use of <code>elemOrd</code> seems a little non-standard, and (3) the constant use of <code>(^ 2)</code> throws a bunch of warnings about <code>2</code> defaulting to <code>Integer</code> when I'm really just using <code>Int</code> here.</p>
<p>Any feedback to the solution below is appreciated.</p>
<p><strong>Refactored 1:</strong></p>
<ul>
<li>Instead of having <code>hasOne, hasTwo, hasThree :: Int -> Bool</code> as top-level definitions, I've introduced a type class <code>SquarePolynomial</code> and wrote a <code>hasSquare :: SquarePolynomial a => Int -> [a] -> Bool</code>. </li>
<li>This eliminates any specialized solutions: for <em>P = 1</em> I can find a solution in constant time, for <em>P = 2</em> I can find a solution by prime factorization, and for <em>P = 3</em> the straight-forward solution using integer modulo that @vnp suggests in a comment.</li>
<li>Because there are three algorithms for different <code>n</code>, this is a bad choice, but I like that the code has one generalised solution strategy, even though it's not the best one in each case. An optimal strategy might first check 1, then 3, then 2, then go with 4.</li>
<li><p>Since I cannot easily generate the list sorted by <code>value</code>, i.e. (2,2) comes before (3,1), which is good because <em>2² + 2² = 8</em> and <em>3² + 1² = 10</em>, but (3,3) also comes before (4,1), which is bad because <em>3² + 3² = 18</em> and <em>4² + 1² = 17</em>. So I can't assume that <code>map value</code> is monotonically increasing. E.g. to find <code>hasSquare 17 twoTerms</code> I end up generating</p>
<pre><code> takeWhile ((isqrt n >=) . maxTerm) twoTerms
= takeWhile ((4 >=) . maxTerm) twoTerms
= takeWhile ((4 >=) . maxTerm) [(1,1),(2,1),...]
= [(1,1),(2,1),(2,2),(3,1),(3,2),(3,3),(4,1),(4,2),(4,3),(4,4)]
</code></pre>
<p>to avoid stopping at <code>value (3,3)</code> being 18 when <code>value (4,1)</code> is 17.</p></li>
</ul>
<p>The code after refactoring (see edit history for previous version):</p>
<pre class="lang-hs prettyprint-override"><code>{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE FlexibleInstances #-}
module KafkaPrinter (groanFactor) where
groanFactor :: Int -> Int
groanFactor 0 = 0
groanFactor n
| n `isSquareWith` oneTerm = 1
| n `isSquareWith` twoTerms = 2 -- http://oeis.org/A000404
| n `isSquareWith` threeTerms = 3 -- https://oeis.org/A000408
| otherwise = 4
-- Find if any candidate polynomial 'a^2 + b^2 + ...' of nonzero squares
-- exists such that 'a^2 + b^2 + ... = n'. Assume that candidates are
-- ordered by their largest term, 'maxTerm', and limit candidates so that
-- 'maxTerm <= isqrt n'.
--
-- This is an upper bound because
-- ⇒ maxTerm^2 + K <= n
-- ⇒ maxTerm <= isqrt (n - K)
-- ⇒ maxTerm <= isqrt n
isSquareWith :: SquarePolynomial a => Int -> [a] -> Bool
isSquareWith n = elem n . map value . takeWhile ((isqrt n >=) . maxTerm)
square :: Num a => a -> a
square = (^ (2 :: Int))
isqrt :: Int -> Int
isqrt = floor @Float . sqrt . fromIntegral
class SquarePolynomial a where
value :: a -> Int
maxTerm :: a -> Int
instance SquarePolynomial Int where
value = square
maxTerm = id
oneTerm :: [Int]
oneTerm = [1..]
instance SquarePolynomial (Int, Int) where
value (i, j) = square i + square j
maxTerm (i, _) = i
-- [(1,1), (2,1), (2,2), (3,1), ...]
twoTerms :: [(Int, Int)]
twoTerms = iterate next (1,1)
where next (i, j) = if i > j then (i, j+1) else (i+1, 1)
instance SquarePolynomial (Int, Int, Int) where
value (i, j, k) = square i + square j + square k
maxTerm (i, _, _) = i
-- [(1,1,1), (2,1,1), (2,2,1), (2,2,2), (3,1,1), ...]
threeTerms :: [(Int, Int, Int)]
threeTerms = iterate next (1,1,1)
where
next (i, j, k)
| j > k = (i, j, k+1)
| i > j = (i, j+1, 1)
| otherwise = (i+1, 1, 1)
</code></pre>
<p>The end.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T17:20:14.440",
"Id": "441789",
"Score": "1",
"body": "You may be also interested in [Legendre's three-square](https://en.wikipedia.org/wiki/Legendre%27s_three-square_theorem) and [Fermat's two-square](https://en.wikipedia.org/wiki/Sum_of_two_squares_theorem) theorems. At least the first one simplifies `hasThree` in a very straightforward way."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T14:42:25.013",
"Id": "227092",
"Score": "3",
"Tags": [
"haskell"
],
"Title": "Finding the least number of terms to satisfy integer square equation"
}
|
227092
|
<p>I implemented <a href="https://github.com/Shpota/github-activity-generator" rel="nofollow noreferrer">a Python script</a> that generates git commits for the last year making one's Contribution Graph look full of changes. It was my first Python program (I work mostly with Java). Although the program is quite useless I want to use it as a learning playground to build my Python competences. That is why I would appreciate <em>any feedback</em> about the code (both constructive and destructive).</p>
<p><strong>Questions:</strong></p>
<ol>
<li>I didn't use types to make the script work with Python 2 and 3. Is it a good practice?</li>
<li>Does the script follow Python style conventions? I didn't manage to find unified Python style guides, I used what was provided by <code>flake8</code>.</li>
<li>Do you usually cover scripts like this with Unit tests? How would you do that?</li>
<li>And generally what would you improve? <strong>Any comments are appreciated</strong>.</li>
</ol>
<p><strong>Code:</strong> (applied the changes <a href="https://codereview.stackexchange.com/a/227110/207526">proposed by Graipher</a>)</p>
<p>You can find <strong><a href="https://github.com/Shpota/github-activity-generator/blob/master/contribute.py" rel="nofollow noreferrer">the full script here</a></strong>.</p>
<pre><code>def main():
args = arguments()
curr_date = datetime.now()
directory = 'repository-' + curr_date.strftime('%Y-%m-%d-%H-%M-%S')
repository = args.repository
if repository is not None:
start = repository.rfind('/') + 1
end = repository.rfind('.')
directory = repository[start:end]
no_weekends = args.no_weekends
frequency = args.frequency
os.mkdir(directory)
os.chdir(directory)
run(['git', 'init'])
start_date = curr_date.replace(hour=20, minute=0) - timedelta(366)
for day in (start_date + timedelta(n) for n in range(366)):
if (not no_weekends or day.weekday() < 5) \
and randint(0, 100) < frequency:
for commit_time in (day + timedelta(minutes=m)
for m in range(contributions_per_day(args))):
contribute(commit_time)
if repository is not None:
run(['git', 'remote', 'add', 'origin', repository])
run(['git', 'push', '-u', 'origin', 'master'])
print('\nRepository generation ' +
'\x1b[6;30;42mcompleted successfully\x1b[0m!')
def contribute(date):
with open(os.path.join(os.getcwd(), 'README.md'), 'a') as file:
file.write(message(date) + '\n\n')
run(['git', 'add', '.'])
run(['git', 'commit', '-m', '"%s"' % message(date),
'--date', date.strftime('"%Y-%m-%d %H:%M:%S"')])
def run(commands):
Popen(commands).wait()
def message(date):
return date.strftime('Contribution: %Y-%m-%d %H:%M')
def contributions_per_day(args):
max_c = args.max_commits
if max_c > 20:
max_c = 20
if max_c < 1:
max_c = 1
return randint(1, max_c)
def arguments():
parser = argparse.ArgumentParser()
parser.add_argument('-nw', '--no_weekends',
required=False, action='store_true', default=False,
help="""do not commit on weekends""")
parser.add_argument('-mc', '--max_commits', type=int, default=10,
required=False, help="""Defines the maximum amount of
commits a day the script can make. Accepts a number
from 1 to 20. If N is specified the script commits
from 1 to N times a day. The exact number of commits
is defined randomly for each day. The default value
is 10.""")
parser.add_argument('-fr', '--frequency', type=int, default=80,
required=False, help="""Percentage of days when the
script performs commits. If N is specified, the script
will commit N%% of days in a year. The default value
is 80.""")
parser.add_argument('-r', '--repository', type=str, required=False,
help="""A link on an empty non-initialized remote git
repository. If specified, the script pushes the changes
to the repository. The link is accepted in SSH or HTTPS
format. For example: git@github.com:user/repo.git or
https://github.com/user/repo.git""")
return parser.parse_args()
if __name__ == "__main__":
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T15:35:54.293",
"Id": "441770",
"Score": "4",
"body": "Welcome to Code Review! This site has a very generous limit on the amount of code you can put in a question. Since [you are ought to have all the code that you want to have reviewed in the question](/help/on-topic) and your script is not super massive, it's likely best to show it in full length."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T20:36:24.800",
"Id": "442016",
"Score": "2",
"body": "@AlexV added the full script"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T14:43:57.607",
"Id": "442401",
"Score": "0",
"body": "You say that you support Python 2 because it's your OS default, but... that's not great. If you write a shebang with python3, your script will use the right thing and your code can be improved."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T04:25:20.713",
"Id": "442725",
"Score": "0",
"body": "To anyone looking at the edit history: I rolled it back after seeing that the OP changed the code, then realizing that they added the full script at the request of @AlexV, I rolled the post back to the updated code."
}
] |
[
{
"body": "<p>Python is actually well-known for having a unified style-guide. It is called <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. It has both general advice as well as specific advice (naming and such). <code>flake8</code> follows the recommendations of PEP8, AFAIK.</p>\n\n<p>Currently your script only runs on UNIX system due to the way you manually handle file paths for the <code>directory</code> variable. If you were consistently using the <code>os.path</code> module instead, it would run also on Windows.</p>\n\n<pre><code>import os\n\nif args.repository is not None:\n directory = os.path.splitext(os.path.basename(args.repository))[0]\nelse:\n directory = 'repository-' + curr_date.strftime('%Y-%m-%d-%H-%M-%S')\n</code></pre>\n\n<p>I would add a <code>os.chdir(directory)</code> somewhere in the beginning. This way you don't need to pass the directory to every call of <code>perform</code>. I would leave it as an argument (in case you do need it), but make it optional. I would also call the function <code>run</code>.</p>\n\n<pre><code>def run(commands, context_dir=None):\n if context_dir is None:\n context_dir = os.getcwd()\n Popen(commands, cwd=context_dir).wait()\n</code></pre>\n\n<p>Actually, that is already the default behaviour of <code>Popen</code>!. So you can just do:</p>\n\n<pre><code>def run(commands, context_dir=None):\n Popen(commands, cwd=context_dir).wait()\n</code></pre>\n\n<hr>\n\n<p>In your argument parsing a few things are superfluous. While \"explicit is better than implicit\", \"simple is better than complex\". All arguments that start with a <code>-</code> or <code>--</code> are automatically optional, so you don't need the <code>required=False</code>. In addition, with <code>action=\"store_true\"</code>, <code>default=False</code> is implied.</p>\n\n<p><code>type=str</code> is also redundant, since that is the default for all arguments.</p>\n\n<p>The repository option should maybe have a <code>nargs=1</code> keyword to ensure an actual argument is passed.</p>\n\n<p>I would pass an optional argument to the parsing, which let's you test the function with a list of strings:</p>\n\n<pre><code>def arguments(args=None):\n ....\n return parser.parse_args(args)\n\nprint(arguments([\"-r\"]))\n</code></pre>\n\n<hr>\n\n<p>If you were not concerned about Python 2 compatibility (it's <a href=\"https://pythonclock.org/\" rel=\"nofollow noreferrer\">time is finally coming to an end</a>, slowly), I would have recommended using the <a href=\"https://docs.python.org/3/library/subprocess.html#using-the-subprocess-module\" rel=\"nofollow noreferrer\">new high-level API <code>subprocess.run</code></a> (Python 3.5+, 3.7+ for some features). With that your function would not even be needed anymore, a simple <code>from subprocess import run</code> would be enough.</p>\n\n<p>In that vain, you could then also use <code>pathlib</code>, as recommended <a href=\"https://codereview.stackexchange.com/questions/227093/a-python-script-that-generates-git-commits-for-the-last-year/227110#comment441793_227110\">in the comments</a> by <a href=\"https://codereview.stackexchange.com/users/104108/grooveplex\">@grooveplex</a>:</p>\n\n<pre><code>from pathlib import Path\n\nif args.repository is not None:\n directory = Path(args.repository).stem\n...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T17:23:17.717",
"Id": "441793",
"Score": "3",
"body": "And if you're not concerned about Python 2 compatibility, you could also use `pathlib`, which is really quite nice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T17:29:36.993",
"Id": "441794",
"Score": "2",
"body": "@grooveplex Added a short part on that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T07:19:52.237",
"Id": "441886",
"Score": "0",
"body": "Thank you for the review (+1)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T20:45:26.360",
"Id": "442021",
"Score": "1",
"body": "@Graipher I applied most of your recommendations and added *the full script* to the question. I kept Python 2 compatibility simply because my latest Ubuntu LTS still defaults to python 2. As for Windows compatibility, I was not clear enough - the `args.repository` is a git repository link (either HTTPS or SSH format). It should also work on Windows (though, I had no chance to test it)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T17:10:43.523",
"Id": "227110",
"ParentId": "227093",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "227110",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T15:03:05.413",
"Id": "227093",
"Score": "7",
"Tags": [
"python",
"git"
],
"Title": "A Python script that generates git commits for the last year"
}
|
227093
|
<p><strong>Objective:</strong> The objective of the program is to create a JIRA ticket using a REST API. It's working perfectly fine without any issue. However I am not sure if it's up to good Scala standards. </p>
<p>I would be delighted if someone could let me know what I can do to improve it. </p>
<pre><code>import org.apache.http.HttpResponse
import org.apache.http.auth.UsernamePasswordCredentials
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.auth.BasicScheme
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils
object JIRAUtil{
private def getJiraID(response: HttpResponse): String ={
val entity = response.getEntity
val content = EntityUtils.toString(entity)
val id = "DPPR-\\d{4}".r
val jiraID = id.findFirstIn(content)
assert(jiraID.isDefined, s"Failed to create JIRA: ${content}")
jiraID.get
}
def createJIRA(project: String, summary: String, description: String, assigneeName: String,
assigneeEmail: String): String = {
val data = s"""{
"fields": {
"project":{
"key": "${project}"
},
"summary": "[Automation] - ${summary}",
"customfield_10118": "DPPR-1109",
"assignee": {
"name": "${assigneeName}",
"emailAddress": "${assigneeEmail}"
},
"description": "${description}",
"issuetype": {
"name": "Bug"
}
}
}"""
val url = "https://acosta-it.atlassian.net/rest/api/latest/issue/"
val post = new HttpPost(url)
val httpClient = HttpClients.createDefault()
val credential = new UsernamePasswordCredentials("gaurang.shah@abc.com", "CoddadEhptnDfU18F")
post.addHeader("Content-type", "application/json")
post.addHeader(new BasicScheme().authenticate(credential, post, null))
post.setEntity(new StringEntity(data))
val response = httpClient.execute(post)
val jiraId = getJiraID(response)
jiraId
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T04:29:42.690",
"Id": "441842",
"Score": "0",
"body": "The variables `response` and `jiraId` don't appear to serve any purpose other than documentation and, in the case of `jiraId`, that's already well served by `getJiraID()`."
}
] |
[
{
"body": "<p>The suggestions I'd make are all around making the code more robust and more explicit in error handling.</p>\n\n<h1>Representing errors</h1>\n\n<p>Your methods return <code>String</code>s. However, I'd say that's not really a good representation of what the methods do. Here's what I mean...</p>\n\n<p><code>getJiraID</code> can fail. You've checked for this in an <code>assert</code>, which is great. That will give an informative message, but will also stop the program. (It's totally possible that's OK for your case, but in general, it's not). What you could do instead is have the methods return perhaps an <code>Either[Error, String]</code> where <code>Error</code> could be a case class that captures the relevant details of what went wrong.</p>\n\n<p>Why is that important? If I'm using your code, the signature says I'll get a <code>String</code> back no matter what I pass in. However, what really happens is that the programme could stop. That would be very surprising to me as a user.</p>\n\n<p>If, instead, I see the signature is <code>Either[Error, String]</code> I know it could fail, and I have to handle that appropriately. </p>\n\n<p>To be clear: I'm making a general point. Your <code>getJiraID</code> is private, and you could say it's an internal helper, and will never fail in reality, but hopefully, you see the point I'm making.</p>\n\n<p>That carries through into <code>createJIRA</code> which also returns a <code>String</code> (no matter what), but clearly this can fail. It can fail in more ways: presumably, the http client you're using could fail due to network error or a server error. This is essentially the same point I made above.</p>\n\n<h1>JSON</h1>\n\n<p>The value <code>data</code> represents JSON. What happens if <code>project</code> contains a quotation mark? You'll have invalid JSON. I'd suggest using a JSON library to construct JSON safely, which will handle the cases of properly encoding String. <a href=\"https://circe.github.io/circe/\" rel=\"nofollow noreferrer\">Circe</a> is a good one, but there are plenty of others.</p>\n\n<h1>Hardcoded credentials</h1>\n\n<p>You have included a username and password in the body of the code. When that password expires (or changes), you'll have to hunt that down. I'd suggest making those parameters. For example:</p>\n\n<pre><code>case class JiraClient(user: String, pass: String) {\n def create(...) = ...\n}\n</code></pre>\n\n<p>... and then creating a <code>JiraClient</code> at the edges of your code (e.g., in a <code>main</code>) and perhaps reading those credentials from the environment (command-line arguments, configuration file, environment variables). You'd then have something anyone could use, and is easy to change without a recompile.</p>\n\n<p>That same suggestion might apply for the <code>url</code>, too. I don't know how often that might change.</p>\n\n<h1>Trivial</h1>\n\n<p>Some of the formatting looks a little odd to my eye. E.g., <code>String ={</code> vs. <code>String = {</code>. Take a look at <a href=\"https://scalameta.org/scalafmt/\" rel=\"nofollow noreferrer\">scalafmt</a> as a way to automatically format your code for consistency.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T08:39:35.360",
"Id": "237130",
"ParentId": "227100",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T15:39:12.763",
"Id": "227100",
"Score": "1",
"Tags": [
"scala"
],
"Title": "Create JIRA ticket using REST API"
}
|
227100
|
<p>I wrote a small rust library <a href="https://github.com/Sauro98/aes_s" rel="nofollow noreferrer">available on github</a> that can encrypt/decrypt a 16 bytes block using either 128, 192 or 256 bit passwords. This implementation is tested with the test data provided in the <a href="https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.197.pdf" rel="nofollow noreferrer">standard description</a>. Since I'm pretty new to rust and this was mainly an exercise to learn to use this language I would love to get feedback regarding code style and best practices. Also, I would be very interested in knowing how I could optimize it or in resources concerning that.</p>
<p>The function I feel could somehow use optimization the most is the mix_column transformation in the AES matrix: </p>
<pre class="lang-rust prettyprint-override"><code>
/**
* Basically the inverse_mix_columns sets the bytes in each column to:
*
* col[0] = (col[0] * 0x02) xor (col[1] * 0x03) xor col[2] xor col[3]
* col[1] = col[0] xor (col[1] * 0x02) xor (col[2] * 0x03) xor col[3]
* col[2] = col[0] xor col[1] xor (col[2] * 0x02) xor (col[3] * 0x03)
* col[3] = (col[0] * 0x03) xor col[1] xor col[2] xor (col[3] * 0x02)
*
* With '*' meaning the multiplication in the GF2 field as described by the AES standard
*/
fn mix_column_8(bytes: &mut [u8; 16], offset: usize) {
let mut column_bytes = [
bytes[offset],
bytes[offset + 1],
bytes[offset + 2],
bytes[offset + 3],
];
for index in 0..4 {
bytes[offset + index] = Math::x_time(column_bytes[0])
^ Math::multiplication_by_03(column_bytes[1])
^ column_bytes[2]
^ column_bytes[3];
let temp = column_bytes[0];
column_bytes[0] = column_bytes[1];
column_bytes[1] = column_bytes[2];
column_bytes[2] = column_bytes[3];
column_bytes[3] = temp;
}
}
</code></pre>
<p>With the two external functions called being: </p>
<pre class="lang-rust prettyprint-override"><code>pub fn x_time(val: u8) -> u8 {
if val > 0x7f {
(val << 1) ^ 0x1b
} else {
val << 1
}
}
pub fn multiplication_by_03(val: u8) -> u8 {
(val ^ Self::x_time(val))
}
</code></pre>
<p>This is my first post on here so I hope that it fits the rules, otherwise I'll be happy to edit it.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T15:49:32.373",
"Id": "227101",
"Score": "1",
"Tags": [
"performance",
"beginner",
"rust",
"aes"
],
"Title": "AES encryption/decryption in rust: performance and best practices"
}
|
227101
|
<p>I am attempting to translate some of my Perl code to Ruby, from <a href="http://rosettacode.org/wiki/Welch%27s_t-test" rel="nofollow noreferrer">http://rosettacode.org/wiki/Welch%27s_t-test</a></p>
<p>I am a very very beginner with Ruby, but I have verified that this is producing the correct answers. Is this "idiomatic" Ruby code? how is this with regard to best practices?</p>
<pre><code> def calculate_Pvalue (array1, array2)
if array1.size <= 1
return 1.0
end
if array2.size <= 1
return 1.0
end
mean1 = array1.sum / array1.size
mean2 = array2.sum / array2.size
if mean1 == mean2
return 1.0
end
variance1 = 0.0
variance2 = 0.0
array1.each do |x|
variance1 += (mean1 - x)**2
end
array2.each do |x|
variance2 += (mean2 - x)**2
end
if variance1 == 0.0 && variance2 == 0.0
return 1.0
end
variance1 = variance1 / (array1.size - 1)
variance2 = variance2 / (array2.size - 1)
welch_t_statistic = (mean1 - mean2) / Math.sqrt(variance1 / array1.size + variance2/array2.size)
degrees_of_freedom = ((variance1/array1.size+variance2/array2.size)**2) / (
(variance1*variance1)/(array1.size*array1.size*(array1.size-1))+
(variance2*variance2)/(array2.size*array2.size*(array2.size-1)));
a = degrees_of_freedom / 2
value = degrees_of_freedom / (welch_t_statistic**2 + degrees_of_freedom)
beta = Math.lgamma(a)[0] + 0.57236494292470009 - Math.lgamma(a + 0.5)[0]
acu = 10**(-15)
if a <= 0
return value
end
if value < 0.0 || 1.0 < value
return value
end
if value == 0 or value == 1.0
return value
end
psq = a + 0.5
cx = 1.0 - value
if a < psq * value
xx = cx
cx = value
pp = 0.5
qq = a
indx = 1
else
xx = value
pp = a
qq = 0.5
indx = 0
end
term = 1.0;
ai = 1.0;
value = 1.0;
ns = (qq + cx * psq).to_i;
#Soper reduction formula
rx = xx / cx
temp = qq - ai
while 1
term = term * temp * rx / ( pp + ai );
value = value + term;
temp = term.abs;
if temp <= acu && temp <= acu * value
#p "pp = #{pp}"
#p "xx = #{xx}"
#p "qq = #{qq}"
#p "cx = #{cx}"
#p "beta = #{beta}"
value = value * Math.exp(pp * Math.log(xx) + (qq - 1.0) * Math.log(cx) - beta) / pp;
#p "value = #{value}"
value = 1.0 - value if indx
if indx == 0
value = 1.0 - value
end
break
end
ai = ai + 1.0
ns = ns - 1
#p "ai = #{ai}"
#p "ns = #{ns}"
if 0 <= ns
temp = qq - ai
rx = xx if ns == 0
else
temp = psq
psq = psq + 1.0
end
end
return value
end
d1 = [27.5,21.0,19.0,23.6,17.0,17.9,16.9,20.1,21.9,22.6,23.1,19.6,19.0,21.7,21.4]
d2 = [27.1,22.0,20.8,23.4,23.4,23.5,25.8,22.0,24.8,20.2,21.9,22.1,22.9,20.5,24.4]
d3 = [17.2,20.9,22.6,18.1,21.7,21.4,23.5,24.2,14.7,21.8]
d4 = [21.5,22.8,21.0,23.0,21.6,23.6,22.5,20.7,23.4,21.8,20.7,21.7,21.5,22.5,23.6,21.5,22.5,23.5,21.5,21.8]
d5 = [19.8,20.4,19.6,17.8,18.5,18.9,18.3,18.9,19.5,22.0]
d6 = [28.2,26.6,20.1,23.3,25.2,22.1,17.7,27.6,20.6,13.7,23.2,17.5,20.6,18.0,23.9,21.6,24.3,20.4,24.0,13.2]
d7 = [30.02,29.99,30.11,29.97,30.01,29.99]
d8 = [29.89,29.93,29.72,29.98,30.02,29.98]
x = [3.0,4.0,1.0,2.1]
y = [490.2,340.0,433.9]
s1 = [1.0/15,10.0/62.0]
s2 = [1.0/10,2/50.0]
v1 = [0.010268,0.000167,0.000167]
v2 = [0.159258,0.136278,0.122389]
z1 = [9/23.0,21/45.0,0/38.0]
z2 = [0/44.0,42/94.0,0/22.0]
CORRECT_ANSWERS = [0.021378001462867, 0.148841696605327, 0.0359722710297968,
0.090773324285671, 0.0107515611497845, 0.00339907162713746, 0.52726574965384, 0.545266866977794]
pvalue = calculate_Pvalue(d1,d2)
error = (pvalue - CORRECT_ANSWERS[0]).abs
printf("Test sets 1 p-value = %.14g\n",pvalue)
pvalue = calculate_Pvalue(d3,d4)
error += (pvalue - CORRECT_ANSWERS[1]).abs
printf("Test sets 2 p-value = %.14g\n",pvalue)
pvalue = calculate_Pvalue(d5,d6)
error += (pvalue - CORRECT_ANSWERS[2]).abs
printf("Test sets 3 p-value = %.14g\n",pvalue)
pvalue = calculate_Pvalue(d7,d8)
error += (pvalue - CORRECT_ANSWERS[3]).abs
printf("Test sets 4 p-value = %.14g\n",pvalue)
pvalue = calculate_Pvalue(x,y)
error += (pvalue - CORRECT_ANSWERS[4]).abs
printf("Test sets 5 p-value = %.14g\n",pvalue)
pvalue = calculate_Pvalue(v1,v2)
error += (pvalue - CORRECT_ANSWERS[5]).abs
printf("Test sets 6 p-value = %.14g\n",pvalue)
pvalue = calculate_Pvalue(s1,s2)
error += (pvalue - CORRECT_ANSWERS[6]).abs
printf("Test sets 7 p-value = %.14g\n",pvalue)
pvalue = calculate_Pvalue(z1,z2)
error += (pvalue - CORRECT_ANSWERS[7]).abs
printf("Test sets z p-value = %.14g\n",pvalue)
printf("the cumulative error is %g\n", error)
</code></pre>
|
[] |
[
{
"body": "<p>Some general guidelines:</p>\n\n<ul>\n<li>Try to keep methods short (+- 10 lines max). Each method should serve a somewhat distinct purpose.</li>\n<li>Use clear variable names</li>\n</ul>\n\n<hr>\n\n<p>Prefer inline if-statements:</p>\n\n<pre><code>return 1.0 if array1.size <= 1\n</code></pre>\n\n<blockquote>\n<pre><code>if array1.size <= 1\n return 1.0\nend\n</code></pre>\n</blockquote>\n\n<p>Another case:</p>\n\n<pre><code>return 1.0 if mean1 == mean2\n</code></pre>\n\n<blockquote>\n<pre><code>if mean1 == mean2\n return 1.0\nend\n</code></pre>\n</blockquote>\n\n<p>A big one:</p>\n\n<pre><code> return value if a <= 0\n return value if value < 0.0 || value > 1.0\n return value if (value == 0) || (value == 1.0)\n</code></pre>\n\n<blockquote>\n<pre><code>if a <= 0\n return value\nend\nif value < 0.0 || 1.0 < value\n return value\nend\nif value == 0 or value == 1.0\n return value\nend\n</code></pre>\n</blockquote>\n\n<p>You get the point.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T17:51:14.433",
"Id": "227115",
"ParentId": "227108",
"Score": "1"
}
},
{
"body": "<h1>Warnings</h1>\n\n<p>You should always turn warnings on during development. Your code generates <strong>6 warnings</strong>, all of which are easy to fix:</p>\n\n<pre><code>test.rb:1: warning: parentheses after method name is interpreted as an argument list, not a decomposed argument\ntest.rb:51: warning: mismatched indentations at 'else' with 'if' at 45\ntest.rb:56: warning: mismatched indentations at 'end' with 'if' at 45\ntest.rb:93: warning: mismatched indentations at 'end' with 'while' at 64\ntest.rb:64: warning: literal in condition\ntest.rb:95: warning: mismatched indentations at 'end' with 'def' at 1\n</code></pre>\n\n<h1>Formatting</h1>\n\n<p>You should use your text editor's auto-format feature.</p>\n\n<h1>Linting</h1>\n\n<p>If you want to make sure that your code is <em>idiomatic</em>, you should use an automated linting tool that checks for violations of Community Coding Style Guidelines, common mistakes, complexity, etc. One popular tool for this is <a href=\"https://docs.rubocop.org/\" rel=\"nofollow noreferrer\">Rubocop</a>. If I run Rubocop with the default settings on your code, I get a whopping <strong>408 violations</strong>. Thankfully, 391 of those can be auto-corrected, leaving only 17, of which 13 are trivially correctable.</p>\n\n<h1>Consistency</h1>\n\n<p>Consistency is <em>very</em> important when writing code. Actually, it is very important when writing anything technical. If there are two different ways to write something, and you use two different ways to write it, people are going to assume that you wanted to express <em>two different things</em>, and thus they will waste time trying to figure out <em>why</em> you expressed the same thing two different ways.</p>\n\n<p>It is important not only to be consistent with yourself within your code, but also with the community as a whole. There are Community Coding Style Guidelines in pretty much every community, and usually, there are also tools that automatically format your code according to those guidelines.</p>\n\n<p>Here are a couple of examples:</p>\n\n<ul>\n<li><p><em>Indentation</em></p>\n\n<ul>\n<li><p><em>Amount</em>: Sometimes, you indent by 1 column, sometimes by 2, sometimes by 4. There does not seem to be any logic whatsoever as to which amount of indentation you choose. <em>Idiomatic</em> would be 2. For example, the first three lines:</p>\n\n<pre><code>def calculate_Pvalue (array1, array2)\n if array1.size <= 1\n return 1.0\n</code></pre></li>\n<li><p><em>When to indent</em>: Sometimes, you indent the body of a loop or a conditional expression, sometimes you don't. Again, there does not seem to be any logic to it. <em>Idiomatic</em> would be to indent. Also, sometimes you indent just randomly in the middle of a sequence of expressions. Also in this case, I can't see any logic to it. <em>Idiomatic</em> would be to <em>not</em> indent.</p></li>\n</ul></li>\n<li><p><em>Whitespace</em></p>\n\n<ul>\n<li><em>Around Operators</em>: Sometimes, you put whitespace around operators, sometimes not. <em>Idiomatic</em> would be to use whitespace. Personally, I sometimes use different amounts of whitespace to emphasize precedence rules, e.g. I would write <code>a*b + c</code>, but I can't find such a logic in your case, for example here: <code>variance1 / array1.size + variance2/array2.size</code></li>\n<li><em>Around Commas</em>: Sometimes, you have no whitespace around commas, sometimes you have whitespace after a comma. <em>Idiomatic</em> would be to have 1 space after a comma.</li>\n<li><em>Within parentheses</em>: Sometimes, you have whitespace after the opening and before the closing parenthesis, sometimes not. <em>Idiomatic</em> would be to have no whitespace.</li>\n</ul></li>\n<li><p><em>Operators</em></p>\n\n<ul>\n<li><p><em>Boolean keyword operators</em>: Sometimes you use the operator symbols (<code>&&</code> / <code>||</code>), sometimes you use the keywords (<code>and</code> / <code>or</code>). I cannot detect any logic as to when you use which. <em>Idiomatic</em> would be to use the symbol versions. Example:</p>\n\n<pre><code>if value < 0.0 || 1.0 < value\n return value\nend\nif value == 0 or value == 1.0\n return value\nend\n</code></pre></li>\n<li><p><em>Compound assignment</em>: Sometimes, you use compound assignment (<code>a += b</code>) and sometimes the long form (<code>a = a + b</code>). <em>Idiomatic</em> would be to use the compound form, unless it severely hinders readability. Examples: <code>variance1 += (mean1 - x)**2</code> and <code>psq = psq + 1.0</code>.</p></li>\n</ul></li>\n<li><p><em>Naming</em>: sometimes, you spell p-value <code>pvalue</code> and sometimes <code>Pvalue</code>. You should be consistent and pick one. <em>Idiomatic</em> would be <code>pvalue</code> or <code>p_value</code>. Example:</p>\n\n<pre><code>pvalue = calculate_Pvalue(d1,d2)\n</code></pre></li>\n</ul>\n\n<h1>Naming</h1>\n\n<ul>\n<li><p><em>Snake Case</em>: Names of methods, parameters, local variables, instance variables, class hierarchy variables, and global variables should be written in <em>snake_case</em>. Constants should be written in <em>SCREAMING_SNAKE_CASE</em>. The exception are constants that refer to modules or classes, and methods that are closely related to classes (E.g. <code>Kernel#Hash</code>, <code>Kernel#Float</code>), which are written in <em>PascalCase</em>. So, <code>calculate_Pvalue</code> should be either <code>calculate_pvalue</code> or <code>calculate_p_value</code>.</p></li>\n<li><p><em>Intention-revealing names</em>: Names should be intention-revealing. There are couple of names in your code that don't really help with understanding, e.g. <code>temp</code> and <code>value</code>.</p></li>\n</ul>\n\n<h1>Layout</h1>\n\n<ul>\n<li><p><em>Whitespace</em>: Your code is all mashed together with no room to breathe. You should break up logical blocks with whitespace to make the flow easier to follow.</p></li>\n<li><p><em>Indentation</em>: You already start your code indented by 1 space. Your code should start with no indentation. Then, blocks should be indented bxy 2 spaces.</p></li>\n<li><p><em>No whitespace after method name</em>: both when sending a message (calling a method) and when defining a method, there should be no whitespace between the name and the opening parenthesis of the argument list / parameter list:</p>\n\n<pre><code>def calculate_Pvalue (array1, array2)\n</code></pre></li>\n</ul>\n\n<h1>Semantics</h1>\n\n<ul>\n<li><p><em>Useless conditional</em>:</p>\n\n<pre><code>value = 1.0 - value if indx\n</code></pre>\n\n<p>There is no way that <code>indx</code> can ever become falsy in your code (it will always be either <code>0</code> or <code>1</code>, both of which are truthy), so this conditional is redundant and should just be:</p>\n\n<pre><code>value = 1.0 - value\n</code></pre></li>\n<li><p><em>Redundant conditionals</em>:</p>\n\n<pre><code>if value < 0.0 || 1.0 < value\n return value\nend\nif value == 0 or value == 1.0\n return value\nend\n</code></pre>\n\n<p>You <code>return</code> the <code>value</code> if it is less than zero and you also <code>return</code> the <code>value</code> if it is equal to zero. That is the same thing as returning the value if it is less than or equal to zero. Same for the other conditional. Replace with</p>\n\n<pre><code>if value <= 0.0 || 1.0 <= value\n return value\nend\n</code></pre></li>\n<li><p><em>Use <code>Range#cover?</code></em>: Actually, the above conditional is even better written as</p>\n\n<pre><code>unless (0.0..1.0).cover?(value)\n return value\nend\n</code></pre></li>\n<li><p><em>Use modifier-<code>if</code> for single-expression conditionals and guard clauses</em>: prefer </p>\n\n<pre><code>return value unless (0.0..1.0).cover?(value)\n</code></pre></li>\n<li><p><em>Useless use of <code>Float</code> literals</em>: In the above and many other places, you could equally well use <code>Integer</code> literals. An explicit <code>Float</code> literal is only required when you specifically need to call a <code>Float</code> method, e.g. for division. So, just use <code>1</code> and <code>0</code> instead.</p></li>\n<li><p><em>Use <code>Numeric#zero?</code> predicate instead of testing for equality with <code>0</code></em>: There are multiple places where you test for equality with <code>0</code>. It would be more idiomatic to use the <code>Numeric#zero?</code> predicate instead:</p>\n\n<pre><code>return 1 if variance1.zero? && variance2.zero?\n</code></pre></li>\n<li><p><em>Avoid loops</em>: In general, you should avoid loops as much as possible. You should prefer high-level iterators such as <code>inject</code>, <code>map</code>, <code>select</code>, etc. Only if that is not possible, use <code>each</code>. In case you need an infinite loop, use <code>Kernel#loop</code>. Don't use <code>while true</code> and <em>most definitely</em> do not use <code>while 1</code>. For example, </p>\n\n<pre><code>variance1 = 0\nvariance2 = 0\narray1.each do |x|\n variance1 += (mean1 - x)**2\nend\narray2.each do |x|\n variance2 += (mean2 - x)**2\nend\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>variance1 = array1.inject(0) {|acc, x| acc + (mean1 - x)**2 }\nvariance2 = array2.inject(0) {|acc, x| acc + (mean2 - x)**2 }\n</code></pre></li>\n<li><p><em>Redundant <code>return</code></em>: In Ruby, the last expression evaluated inside a block, method, module, or class is the return value. So, instead of <code>return value</code>, you can just write <code>value</code>.</p></li>\n<li><p><em>Magic number</em>: What does <code>0.57236494292470009</code> mean? You should give it a name.</p></li>\n<li><p>*Use <code>Array#first</code> instead of <code>[0]</code>: Replace</p>\n\n<pre><code>beta = Math.lgamma(a)[0] + 0.57236494292470009 - Math.lgamma(a + 0.5)[0]\n</code></pre>\n\n<p>with</p>\n\n<pre><code>beta = Math.lgamma(a).first + 0.57236494292470009 - Math.lgamma(a + 0.5).first\n</code></pre></li>\n<li><p><em><code>freeze</code> objects that are not meant to be modified, especially ones that are assigned to constants</em>: </p>\n\n<pre><code>CORRECT_ANSWERS = [0.021378001462867, 0.148841696605327, 0.0359722710297968,\n 0.090773324285671, 0.0107515611497845, 0.00339907162713746, \n 0.52726574965384, 0.545266866977794].freeze\n</code></pre></li>\n<li><p><em>Frozen string literals</em>: In the same vein, you should make a habit of adding the <em>magic comment</em></p>\n\n<pre><code># frozen_string_literal: true\n</code></pre>\n\n<p>to all your files.</p></li>\n<li><p><em>Commented out code</em>: You should not comment out code. That's what a version control system is for.</p></li>\n<li><p><em>Duplication</em>: There is a fair amount of duplication in your code, e.g.</p>\n\n<pre><code>mean1 = array1.sum / array1.size\nmean2 = array2.sum / array2.size\n</code></pre>\n\n<p>or</p>\n\n<pre><code>variance1 = 0.0\nvariance2 = 0.0\narray1.each do |x|\n variance1 += (mean1 - x)**2\nend\narray2.each do |x|\n variance2 += (mean2 - x)**2\nend\n</code></pre>\n\n<p>You could remove this duplication e.g. by extracting the logic into a method.</p></li>\n<li><p><em>Complexity</em>: The method is very complex, according to pretty much any metric (Cyclomatic Complexity, NPath Complexity, ABC, Perceived Complexity, …). You should break it up into multiple methods.</p></li>\n<li><p><em>Documentation</em>: All your methods should have a documentation comment describing their purpose, usage, and pre- and post-conditions. Also, while in general, code should describe itself, in your case, you should document the algorithm and the names of the variables. Presumably, those names come from a well-known paper, in that case, you should cite that paper. (Note: in general, variable names like <code>x</code>, <code>xx</code>, <code>pp</code>, etc. should be avoided because they do not reveal the intent of the code, but here, I assume they actually <em>are</em> intention-revealing names because they are well-known to a reader versed in statistics. Still, you should document where those names come from.)</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T16:49:05.563",
"Id": "444919",
"Score": "0",
"body": "thanks, this code is a translation of C, which in turn is a translation of Fortran, so that's where a lot of the quirkiness comes from. The variable names were given by someone else, like you said, I'm not entirely sure what they represent"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T19:49:40.953",
"Id": "227600",
"ParentId": "227108",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227600",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T16:53:43.530",
"Id": "227108",
"Score": "2",
"Tags": [
"beginner",
"ruby",
"statistics"
],
"Title": "Calculating p-value for Welch's t-test"
}
|
227108
|
<p>I'm doing a larger PyQt5 project which includes loading in large amount of data into a QTableWidget. However filling the table up with the loaded data is extremely slow due to nested for loops. I put there a minimal working example.
The loaded .txt files usually look like this:</p>
<pre><code>...
3.137856026645493124e+00,-1.018072816226149244e-02
3.137333399059442751e+00,2.133285461296379468e-04
3.136810945537534145e+00,6.040261342268495991e-04
3.136288665992822633e+00,6.455403916425843380e-03
3.135766560338420383e+00,3.788118428284327315e-03
3.135244628487498630e+00,3.439159817145511638e-02
3.134722870353285007e+00,-8.456704230609860635e-04
3.134201285849066654e+00,2.062391644217435177e-02
3.133679874888186667e+00,-1.154215762495692556e-02
3.133158637384046763e+00,-3.520437354375163114e-02
3.132637573250105945e+00,4.354430655996290934e-05
...
</code></pre>
<p><strong>main.py</strong></p>
<pre class="lang-py prettyprint-override"><code>from PyQt5.QtWidgets import QFileDialog
from PyQt5 import QtWidgets, QtCore
import numpy as np
from ui import Ui_MainWindow
class MainProgram(QtWidgets.QMainWindow, Ui_MainWindow):
x_val = np.array([])
y_val = np.array([])
def __init__(self, parent = None):
super(MainProgram, self).__init__(parent)
self.setupUi(self)
self.tableWidget.setColumnCount(2)
self.tableWidget.setRowCount(5)
self.tableWidget.setHorizontalHeaderLabels(["Angular frequency", "Intensity"])
self.tableWidget.setSizeAdjustPolicy(
QtWidgets.QAbstractScrollArea.AdjustToContents)
self.btn_load.clicked.connect(self.load_data)
def load_data(self):
options = QFileDialog.Options()
fileName, _ = QFileDialog.getOpenFileName(None,"Title..", "",
"All Files (*);;Text Files (*.txt)", options=options)
try:
if fileName:
self.tableWidget.setRowCount(0)
self.x_val, self.y_val = np.loadtxt(fileName, usecols=(0,1), unpack = True, delimiter =',')
""" as you can see I limit the max lines, but even at max 800
it's slow"""
if len(self.x_val)<800:
for row_number in range(len(self.x_val)):
self.tableWidget.insertRow(row_number)
for item in range(len(self.x_val)):
self.tableWidget.setItem(item, 0, QtWidgets.QTableWidgetItem(str(self.x_val[item])))
for item in range(len(self.y_val)):
self.tableWidget.setItem(item, 1, QtWidgets.QTableWidgetItem(str(self.y_val[item])))
else:
for row_number in range(800):
self.tableWidget.insertRow(row_number)
for item in range(800):
self.tableWidget.setItem(item, 0, QtWidgets.QTableWidgetItem(str(self.x_val[item])))
for item in range(800):
self.tableWidget.setItem(item, 1, QtWidgets.QTableWidgetItem(str(self.y_val[item])))
self.tableWidget.resizeRowsToContents()
self.tableWidget.resizeColumnsToContents()
except Exception as e:
print(e)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
my_interface = MainProgram()
my_interface.show()
sys.exit(app.exec_())
</code></pre>
<p><strong>ui.py</strong></p>
<pre class="lang-py prettyprint-override"><code># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName("verticalLayout")
self.btn_load = QtWidgets.QPushButton(self.centralwidget)
self.btn_load.setObjectName("btn_load")
self.verticalLayout.addWidget(self.btn_load)
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(0)
self.tableWidget.setRowCount(0)
self.verticalLayout.addWidget(self.tableWidget)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 26))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.btn_load.setText(_translate("MainWindow", "Load"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
</code></pre>
<p>My question is: <em>Can this be optimized in any way?</em>
Thank you for answering.</p>
|
[] |
[
{
"body": "<p>Sorry, but I thought you overdid it with loops in the <code>load_data</code> method.</p>\n\n<p>Try your example with the <code>load_data</code> method, which looks like this:</p>\n\n<pre><code># ...\n\ndef load_data(self): \n options = QFileDialog.Options()\n fileName, _ = QFileDialog.getOpenFileName(None,\"Title..\", \"\",\n \"Text Files (*.txt)\", options=options)\n if fileName:\n self.tableWidget.setRowCount(0) \n self.x_val, self.y_val = np.loadtxt(fileName, usecols=(0,1), unpack = True, delimiter =',') \n for row in range(len(self.x_val)):\n self.tableWidget.insertRow(row)\n self.tableWidget.setItem(row, 0, QtWidgets.QTableWidgetItem(str(self.x_val[row])))\n self.tableWidget.setItem(row, 1, QtWidgets.QTableWidgetItem(str(self.y_val[row])))\n self.tableWidget.resizeColumnsToContents()\n\n# ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T22:14:58.423",
"Id": "230193",
"ParentId": "227109",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T16:55:16.263",
"Id": "227109",
"Score": "2",
"Tags": [
"python",
"performance",
"pyqt"
],
"Title": "GUI table widget filling with nested for loops"
}
|
227109
|
<p>Here is my solution for <a href="https://www.codewars.com/kata/57eb8fcdf670e99d9b000272" rel="noreferrer">CodeWars - Highest Scoring Game</a></p>
<blockquote>
<p>Given a string of words, you need to find the highest scoring word.</p>
<p>Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.</p>
<p>You need to return the highest scoring word as a string.</p>
<p>If two words score the same, return the word that appears earliest in the original string.</p>
<p>All letters will be lowercase and all inputs will be valid</p>
<p>Example: </p>
<p>Input: 'man i need a taxi up to ubud'</p>
<p>Output: 'taxi'</p>
</blockquote>
<p>This is my solution:</p>
<pre class="lang-py prettyprint-override"><code>def word_value(input_word):
values = {
'a': 1,
'b': 2,
'c': 3,
'd': 4,
'e': 5,
'f': 6,
'g': 7,
'h': 8,
'i': 9,
'j': 10,
'k': 11,
'l': 12,
'm': 13,
'n': 14,
'o': 15,
'p': 16,
'q': 17,
'r': 18,
's': 19,
't': 20,
'u': 21,
'v': 22,
'w': 23,
'x': 24,
'y': 25,
'z': 26
}
value = 0
for letter in input_word:
value += values[letter]
return value
def high(x):
word_list = x.split(" ")
word_values = []
for word in word_list:
word_values.append(word_value(word))
max_value = max(word_values)
index_of_max = word_values.index(max_value)
return word_list[index_of_max]
</code></pre>
<p>The solution passed the test suite but I think I can improve the part where I store all the letters matched with their value. Is there any suggestions for this and in general the entire code?</p>
<p>Thank you.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T07:47:41.983",
"Id": "441895",
"Score": "0",
"body": "TXR Lisp: `(defun highest-score-word (wordlist) (find-max wordlist : (opip (mapcar (lop - #\\`)) (apply +))))`"
}
] |
[
{
"body": "<p>Indeed, the <code>values</code> dictionary looks unnecessary. Using a built-in function <code>ord</code> you could compute the letter score with <code>ord(letter) - ord('a') + 1</code>. One may argue that it is even faster than a dictionary lookup, but in this case the timing difference is rather marginal.</p>\n\n<hr>\n\n<p>With Python you should avoid rolling explicit loops. For example, collecting the word values is more idiomatically expressed as a comprehension:</p>\n\n<pre><code> word_values = [word_value(word) for word in word_list]\n</code></pre>\n\n<p>Similarly, instead of</p>\n\n<pre><code> for letter in input_word:\n value += values[letter]\n</code></pre>\n\n<p>consider <code>functools.reduce</code>:</p>\n\n<pre><code> value = functools.reduce(lambda x, y: x + ord(y) - ord('a') + 1, input_word, 0)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T08:44:13.700",
"Id": "441903",
"Score": "11",
"body": "Wouldn't using `sum` with a generator expression be more clear than `reduce`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T14:26:33.080",
"Id": "441966",
"Score": "5",
"body": "I fail to see how `reduce` is more clear than the `for` loop, what makes it better?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T19:36:39.480",
"Id": "227120",
"ParentId": "227119",
"Score": "10"
}
},
{
"body": "<p>Welcome to code review, good job as your first program I suppose.</p>\n\n<h1>Style</h1>\n\n<p><strong>Docstrings:</strong> Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. An object's docstring is defined by including a string constant as the first statement in the object's definition.</p>\n\n<pre><code>def word_value(input_word):\ndef high(x):\n</code></pre>\n\n<p>You should include a docstring with your functions indicating what they do specially the names are pretty ambiguous ...</p>\n\n<pre><code>def get_word_value(word):\n \"\"\"Return word letter score.\"\"\"\n\ndef get_highest_scoring_word(word_list):\n \"\"\"Return highest scoring word.\"\"\"\n</code></pre>\n\n<p><strong>Blank lines:</strong> I suggest you check PEP0008 <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0008/</a> the official Python style guide and regarding blank lines, use blank lines sparingly to separate logical sections inside a function (too many blank lines in your high function)</p>\n\n<pre><code>word_values = []\nfor word in word_list:\n word_values.append(word_value(word))\n\nmax_value = max(word_values)\nindex_of_max = word_values.index(max_value)\n\nreturn word_list[index_of_max]\n</code></pre>\n\n<h1>Code</h1>\n\n<p><strong>First function</strong> </p>\n\n<p>can be shortened in the following way:</p>\n\n<pre><code>import string\nvalues = dict(zip(string.ascii_lowercase, range(1, 27)))\n\ndef get_value(word):\n \"\"\"Return word letter score.\"\"\"\n return sum(values[letter] for letter in word)\n</code></pre>\n\n<p><strong>Second function:</strong></p>\n\n<pre><code>word_list = x.split(\" \")\n</code></pre>\n\n<p>split() has a default value of \" \" so no need to specify</p>\n\n<pre><code>word_list = x.split()\n</code></pre>\n\n<p>does the same functionality</p>\n\n<p><strong>Descriptive names:</strong></p>\n\n<p>word_list is extremely confusing, because word_list is not a list so I suggest changing the name to word_sequence</p>\n\n<p><strong>Comprehension syntax:</strong></p>\n\n<pre><code>word_values = []\nfor word in word_list:\n word_values.append(word_value(word))\n</code></pre>\n\n<p>this can be enclosed in a comprehension syntax (it's more efficient and shorter)</p>\n\n<pre><code>word_values = [word_value(word) for word in word_sequence]\n</code></pre>\n\n<p><strong>Code might look like:</strong></p>\n\n<pre><code>import string\nvalues = dict(zip(string.ascii_lowercase, range(1, 27)))\n\n\ndef get_value(word):\n \"\"\"Return word letter score.\"\"\"\n return sum(values[letter] for letter in word)\n\n\ndef get_highest(word_sequence):\n \"\"\"\n Return word with the highest score assuming word_sequence a \n string of words separated by space.\n \"\"\"\n return max(word_sequence.split(), key=get_value)\n\n\nif __name__ == '__main__':\n words = 'abc def ggg'\n print(get_highest(words))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T20:55:18.357",
"Id": "441817",
"Score": "0",
"body": "Thank you for your response. That is some beautiful code you wrote."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T20:57:30.863",
"Id": "441818",
"Score": "0",
"body": "You're welcome man, I'm not an expert though"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T09:54:07.790",
"Id": "441913",
"Score": "0",
"body": "You are however re-creating the values-dict for every word you check. (and you don't need this dict at all if you just use ord(_))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T10:36:43.787",
"Id": "441921",
"Score": "0",
"body": "@ FooBar does not mean this is the wrong answer and unless the word list has a 7 figure length, efficiency is negligible and this is much more readable than the creation of complicated ord() formulas or making the dictionary a global variable which is not the best practice ever."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T11:01:54.633",
"Id": "441924",
"Score": "2",
"body": "If you would like to stick with the dict-version, using `{letter: i for i, letter in enumerate(string.ascii_lowercase, 1)}` could be a more readable approach. To compensate what @FooBar said, you could make it into a global variable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T11:06:45.823",
"Id": "441927",
"Score": "0",
"body": "AlexV I think a global variable will do. But as I said unless the input size is significant, the chosen approach doesn't matter as long it gives a correct answer. What do you think?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T11:15:08.527",
"Id": "441932",
"Score": "0",
"body": "CodeReview is about style. Moving the dict out of the loop even improves the readability (imho) as the reader could try to understand why you recompute it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T11:31:21.603",
"Id": "441935",
"Score": "0",
"body": "I moved it, it's done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T06:00:19.950",
"Id": "442512",
"Score": "0",
"body": "`split() has a default value of \" \" so no need to specify` - not true, the default is `None`. From the docs: `If sep is not specified or is None, a different splitting algorithm is applied`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T06:15:41.877",
"Id": "442514",
"Score": "0",
"body": "x = 'a a a a a a a a' x.split() output: ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'] y = 'a a a a a a a' y.split() output: ['a', 'a', 'a', 'a', 'a', 'a', 'a'] z = 'a a a a a a a' z.split() output: ['a', 'a', 'a', 'a', 'a', 'a', 'a'] so? does he need to specify x.split(' ') in order the what you call 'other algorithm' gets to understand what output he wants? and by the way it's super easy to check whatever editor I or anyone is using for the function default parameters, I'm sorry but you won't get the Nobel prize for the discovery."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T19:52:05.313",
"Id": "227122",
"ParentId": "227119",
"Score": "9"
}
},
{
"body": "<p>If performance isn't your main concern then consider the following approach of looking up the index of each character in an alphabet string. This will be slower than the other methods suggested, but provides greater readability.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def word_value(word):\n alphabet = 'abcdefghijklmnopqrstuvwxyz'\n return sum(alphabet.index(char) + 1 for char in word)\n\ndef highest_valued_word(phrase):\n return max(\n (word for word in phrase.split(' ')),\n # Use the `word_value` function to select the maximum.\n key=word_value\n )\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T22:50:01.350",
"Id": "445710",
"Score": "0",
"body": "The +1 is strictly necessary. Consider the score of `'round'` verses `'around'`. The latter would should be clearly be higher than the former, but without the +1, you treat the letter `'a'` as worthless, and they compare as equal!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T05:01:24.267",
"Id": "445726",
"Score": "0",
"body": "@AJNeufeld Thanks, hadn't considered that case!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T20:06:19.857",
"Id": "227124",
"ParentId": "227119",
"Score": "0"
}
},
{
"body": "<p>If you really want to go for simplicity, you might want to try a one-liner like this:</p>\n\n<pre><code>def highest_scoring_word(words):\n return max(words.split(), key=lambda word: sum(map(ord, word)) - 96*len(word))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T22:40:27.243",
"Id": "445708",
"Score": "0",
"body": "Your \"one-liner\" is far too long. Instead of a for-loop over the word characters, try a mapping: `max(words.split(), key=lambda word: sum(map(ord, word)) - 96*len(word))`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T11:01:00.723",
"Id": "227264",
"ParentId": "227119",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "227120",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T19:04:40.930",
"Id": "227119",
"Score": "7",
"Tags": [
"python",
"programming-challenge"
],
"Title": "Codewars - Highest Scoring Word"
}
|
227119
|
<p>I'm writing a chart.js port for c# blazor (you can find it <a href="https://github.com/Joelius300/ChartJSBlazor" rel="nofollow noreferrer">here</a>) using C# 8.0 with .NET Core 3 (latest preview).<br>
In chart.js there is this thing called <a href="https://www.chartjs.org/docs/latest/general/options.html#indexable-options" rel="nofollow noreferrer">indexable options</a>. It let's you use either a single value or an array and handles it accordingly.<br>
Because I want the port to be as type-safe as possible, I implemented a wrapper which allows you to store a value which either represents a single value or an array of values. </p>
<p>Points that might need (the most) attention: </p>
<h3>Equality</h3>
<p>This is the main thing I'd like feedback on. I've implemented <a href="https://docs.microsoft.com/en-us/dotnet/api/system.iequatable-1?view=netcore-3.0" rel="nofollow noreferrer"><code>IEquatable</code></a> and tried to write "smart" equality checks which use the most appropriate method to compare but since I'm not an expert, I don't expect them to be perfect :)</p>
<h3>Conversion</h3>
<p>Because I have implemented two implicit and two explicit conversions, which are vital for the coding experience when using this struct, it's important to me that those are correct. </p>
<h3>Summaries</h3>
<p>This isn't as important as the other factors but I still think it's nice to write good summaries, especially considering this is a library.<br>
I tried to keep it consistent and mimic the summaries of built-in classes like <code>string</code> where it makes sense. Again, it's not as important but if you see something and think "you don't do that usually", I'd love to hear what you'd do instead.</p>
<h3>Other</h3>
<p>Improving coding style (and other "basic" stuff) is of course always good so don't hold back on that if anything bugs you.</p>
<p>I'd also like to mention my thoughts on a few design choices because maybe I was wrong before I even started coding this class:</p>
<ul>
<li>Use <code>struct</code> instead of <code>class</code> because it has value semantics.</li>
<li>Implement <code>IEquatable</code> because it's a <code>struct</code> and therefore avoid unnecessary boxing.</li>
<li>Keep the <code>Value</code>-property <code>public</code> simply because there's no reason to hide it.</li>
<li>Use an array instead of e.g. an <code>IEnumerable</code> because I want the values to already be present when the instance is serialized. This way there is definitely no downtime wasted on e.g. database access when I try to serialize the instance.</li>
</ul>
<pre><code>/// <summary>
/// Represents an object that can be either a single value or an array of values. This is used for typesafe js-interop.
/// </summary>
/// <typeparam name="T">The type of data this <see cref="IndexableOption{T}"/> is supposed to hold.</typeparam>
public struct IndexableOption<T> : IEquatable<IndexableOption<T>>
{
/// <summary>
/// The compile-time name of the property which stores the wrapped value. This is used internally for serialization.
/// </summary>
internal const string PropertyName = nameof(Value);
/// <summary>
/// The actual value represented by this instance.
/// </summary>
public object Value { get; }
/// <summary>
/// Gets the value indicating whether the option wrapped in this <see cref="IndexableOption{T}"/> is indexed.
/// <para>True if the wrapped value represents an array of <typeparamref name="T"/>, false if it represents a single value of <typeparamref name="T"/>.</para>
/// </summary>
public bool IsIndexed { get; }
/// <summary>
/// Creates a new instance of <see cref="IndexableOption{T}"/> which represents a single value.
/// </summary>
/// <param name="singleValue">The single value this <see cref="IndexableOption{T}"/> should represent.</param>
public IndexableOption(T singleValue)
{
Value = singleValue ?? throw new ArgumentNullException(nameof(singleValue));
IsIndexed = false;
}
/// <summary>
/// Creates a new instance of <see cref="IndexableOption{T}"/> which represents an array of values.
/// </summary>
/// <param name="indexedValues">The array of values this <see cref="IndexableOption{T}"/> should represent.</param>
public IndexableOption(T[] indexedValues)
{
Value = indexedValues ?? throw new ArgumentNullException(nameof(indexedValues));
IsIndexed = true;
}
/// <summary>
/// Implicitly wraps a single value of <typeparamref name="T"/> to a new instance of <see cref="IndexableOption{T}"/>.
/// </summary>
/// <param name="singleValue">The single value to wrap</param>
public static implicit operator IndexableOption<T>(T singleValue) => new IndexableOption<T>(singleValue);
/// <summary>
/// Implicitly wraps an array of values of <typeparamref name="T"/> to a new instance of <see cref="IndexableOption{T}"/>.
/// </summary>
/// <param name="indexedValues">The array of values to wrap</param>
public static implicit operator IndexableOption<T>(T[] indexedValues) => new IndexableOption<T>(indexedValues);
/// <summary>
/// Explicitly unwraps an <see cref="IndexableOption{T}"/> to a single value.
/// <para>If this instance represents an array of values instead of a single value, an <see cref="InvalidCastException"/> will be thrown.</para>
/// </summary>
/// <param name="wrappedValue">The wrapped single value</param>
public static explicit operator T(IndexableOption<T> wrappedValue)
{
if (wrappedValue.IsIndexed)
throw new InvalidCastException("This instance represents an array of values and can't be converted to a single value.");
return (T)wrappedValue.Value;
}
/// <summary>
/// Explicitly unwraps an <see cref="IndexableOption{T}"/> to an array of values.
/// <para>If this instance represents a single value instead of an array of values, an <see cref="InvalidCastException"/> will be thrown.</para>
/// </summary>
/// <param name="wrappedValue">The wrapped array of values</param>
public static explicit operator T[](IndexableOption<T> wrappedValue)
{
if (!wrappedValue.IsIndexed)
throw new InvalidCastException("This instance represents a single value and can't be converted to an array of values.");
return (T[])wrappedValue.Value;
}
/// <summary>
/// Determines whether the specified <see cref="IndexableOption{T}"/> instance is considered equal to the current instance.
/// </summary>
/// <param name="other">The <see cref="IndexableOption{T}"/> to compare with.</param>
/// <returns>true if the objects are considered equal; otherwise, false.</returns>
public bool Equals(IndexableOption<T> other)
{
if (IsIndexed != other.IsIndexed) return false;
if (IsIndexed)
{
return EqualityComparer<T[]>.Default.Equals((T[])Value, (T[])other.Value);
}
else
{
return EqualityComparer<T>.Default.Equals((T)Value, (T)other.Value);
}
}
/// <summary>
/// Determines whether the specified object instance is considered equal to the current instance.
/// </summary>
/// <param name="obj">The object to compare with.</param>
/// <returns>true if the objects are considered equal; otherwise, false.</returns>
public override bool Equals(object obj)
{
// an indexable option cannot store null
if (obj == null) return false;
if (obj is IndexableOption<T> option)
{
return Equals(option);
}
else
{
return Value.Equals(obj);
}
}
/// <summary>
/// Returns the hash of the underlying object.
/// </summary>
/// <returns>The hash of the underlying object.</returns>
public override int GetHashCode()
{
return -1937169414 + Value.GetHashCode();
}
/// <summary>
/// Determines whether two specified <see cref="IndexableOption{T}"/> instances contain the same value.
/// </summary>
/// <param name="a">The first <see cref="IndexableOption{T}"/> to compare</param>
/// <param name="b">The second <see cref="IndexableOption{T}"/> to compare</param>
/// <returns>true if the value of a is the same as the value of b; otherwise, false.</returns>
public static bool operator ==(IndexableOption<T> a, IndexableOption<T> b) => a.Equals(b);
/// <summary>
/// Determines whether two specified <see cref="IndexableOption{T}"/> instances contain different values.
/// </summary>
/// <param name="a">The first <see cref="IndexableOption{T}"/> to compare</param>
/// <param name="b">The second <see cref="IndexableOption{T}"/> to compare</param>
/// <returns>true if the value of a is different from the value of b; otherwise, false.</returns>
public static bool operator !=(IndexableOption<T> a, IndexableOption<T> b) => !(a == b);
}
</code></pre>
|
[] |
[
{
"body": "<p>It's a bit counter intuitive you store <code>Value</code> as <code>Object</code> if the class <code>IndexableOption<T></code> is <em>generic</em>. I understand you are trying to find a common type to store both <code>T</code> as <code>T[]</code>. However, if <code>T : struct</code> then what happens in case <code>Value</code> is <code>T</code> is a thing called <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing\" rel=\"nofollow noreferrer\">boxing</a>*.</p>\n\n<p>From reference source:</p>\n\n<blockquote>\n <p>Performance</p>\n \n <p><em>In relation to simple assignments, boxing and unboxing are computationally expensive processes. When a value type is boxed, a new\n object must be allocated and constructed. To a lesser degree, the cast\n required for unboxing is also expensive computationally.</em></p>\n</blockquote>\n\n<p>For instance, in <code>Equals</code> there is an expensive unboxing:</p>\n\n<blockquote>\n<pre><code>if (IsIndexed)\n{\n return EqualityComparer<T[]>.Default.Equals((T[])Value, (T[])other.Value);\n}\nelse\n{\n // unboxing#1 unboxing#2\n return EqualityComparer<T>.Default.Equals((T)Value, (T)other.Value);\n}\n</code></pre>\n</blockquote>\n\n<p>I don't think it's worth storing both <code>T</code> as <code>T[]</code> in the same property. Why don't you use 2 properties instead and use the one associated with the value of <code>IsIndexed</code>?</p>\n\n<pre><code>public T Value { get; }\npublic T[] IndexedValue { get; }\n</code></pre>\n\n<p>Equals refactored:</p>\n\n<pre><code>if (IsIndexed)\n{\n return EqualityComparer<T[]>.Default.Equals(IndexedValue , other.IndexedValue );\n}\nelse\n{\n return EqualityComparer<T>.Default.Equals(Value, other.Value);\n}\n</code></pre>\n\n<p>One other thing, you may not like that the consumer has to call <code>IsIndexed</code> in order to decide to use <code>Value</code> or <code>IndexedValue</code>. If you really must, you can shield both properties from public access and still decide to use some boxing. But at least, internally, no redundant boxing/unboxing takes place.</p>\n\n<pre><code>protected T Value { get; }\nprotected T[] IndexedValue { get; }\n\npublic object ValueRef => IsIndexed ? IndexedValue : Value;\n</code></pre>\n\n<p>Or you may want to turn the logic around without using boxing:</p>\n\n<pre><code>public T[] ValueRef => IsIndexed ? IndexedValue : new[] { Value };\n</code></pre>\n\n<p>Which makes me wonder, perhaps you should only store <code>T[]</code> and return either the array or its sole element. This should avoid most recurring if-statements as well. I also think you should only use <code>EqualityComparer<T></code>, not <code>EqualityComparer<T[]></code>, but that has to be verified.</p>\n\n<hr>\n\n<p>Footnote:</p>\n\n<ul>\n<li><sup>Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type</sup></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T06:03:55.870",
"Id": "441850",
"Score": "1",
"body": "Good stuff, thanks. As far as my library goes the consumer doesn't actually have to get the stored value, it's just serialized for the js-interop. With that in mind I'm thinking about using the two properties, make them internal and not even exposing any way of getting the value back. Is that a bad idea? I'm thinking it might be bad since it will still be a mutable type because you can still change the value that was stored, even if you can't get it back after creation by storing a reference first (for reference types and the array)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T06:08:58.967",
"Id": "441852",
"Score": "0",
"body": "Also, about only using an array to store the value, I don't think I should do that. The reason is simply that an array with one value and one value alone has to and will be handled differently. What I could do of course is use `IsIndexed` and then decide if I should use an array or only the first element but that seems more confusing for no actual benefits (or is there something I'm missing which is worse about two properties?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T06:10:46.343",
"Id": "441853",
"Score": "0",
"body": "I don't think you are missing something, let's wait and see if other reviewers come up with alternative ideas."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T10:22:46.237",
"Id": "441919",
"Score": "0",
"body": "Okay. About the _`EqualityComparer<T>`, not `EqualityComparer<T[]>`_, you can't actually use `EqualityComparer<T>` for `T[]` because the `Equals` method will only accept two elements of `T`, not `T[]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T12:04:46.163",
"Id": "441938",
"Score": "0",
"body": "Well what I mean with 1 comparer, is to use that one to compare the elements of T[] instances."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T12:14:58.353",
"Id": "441941",
"Score": "0",
"body": "How? With a loop? Why not just use `T[]` instead? Are there benefits to doing the loop yourself and using the `T` version?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T15:45:10.703",
"Id": "441983",
"Score": "0",
"body": "I can't say for sure. I would have to look up best practices."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T16:35:57.007",
"Id": "441992",
"Score": "1",
"body": "I have asked on SO about it (it was a bad question though so I deleted it). The best thing to do probably is to use `a == b` (cheap reference check) and then go for [`Enumerable.SequenceEqual`](https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sequenceequal) which will also use the correct equality comparer as you can see [here](https://github.com/dotnet/corefx/blob/master/src/System.Linq/src/System/Linq/SequenceEqual.cs)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T18:36:54.047",
"Id": "442001",
"Score": "0",
"body": "Yes SequenceEqual seems to be just right :)"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T04:52:31.133",
"Id": "227145",
"ParentId": "227121",
"Score": "3"
}
},
{
"body": "<p><strong>Compiler error</strong> Unless you're using some experimental preview C# version, your code doesn't compile as this line:</p>\n\n<blockquote>\n<pre><code>Value = singleValue ?? throw new ArgumentNullException(nameof(singleValue));\n</code></pre>\n</blockquote>\n\n<p>yields an error</p>\n\n<blockquote>\n <p>CS0019 Operator '??' cannot be applied to operands of type 'T' and ''</p>\n</blockquote>\n\n<p>You would need to add a constraint for that like: <code>where T : class</code></p>\n\n<hr>\n\n<p><strong>Nested options</strong> This operator produces nested <code>IndexableOption</code>s:</p>\n\n<blockquote>\n<pre><code>public static implicit operator IndexableOption<T>(T singleValue) => new IndexableOption<T>(singleValue);\n</code></pre>\n</blockquote>\n\n<p>This means when you do this:</p>\n\n<pre><code>var x = (object)new IndexableOption<object>();\nIndexableOption<object> y = x;\n</code></pre>\n\n<p>you'll end up with <code>x</code> nested inside <code>y</code>. I find this operator should check whether <code>T</code> is already of type <code>IndexableOption<T></code> to prevent nested options.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T05:57:20.137",
"Id": "441849",
"Score": "0",
"body": "My bad I forgot to mention that I'm using C# 8 with .net core 3 (latest preview). Good catch about the nested options, entirely missed that, thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T12:05:59.607",
"Id": "441939",
"Score": "0",
"body": "@t3chb0t I'm just reflecting my edit. Did I invalidate your answer by including the targetted framework in the question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T12:11:56.403",
"Id": "441940",
"Score": "1",
"body": "@dfhwze in a certain way you did, indeed but you're forgiven; let's say it was late :-]"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T05:12:45.443",
"Id": "227146",
"ParentId": "227121",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227145",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T19:50:29.873",
"Id": "227121",
"Score": "4",
"Tags": [
"c#",
"object-oriented",
"generics",
"wrapper"
],
"Title": "Generic wrapper for single value or array of values"
}
|
227121
|
<p>I have been working on this code, which is the part of an economy system that handles the work command. This lets the user pick a role and if they have enough level then they will get it by updating a db.</p>
<p>I know it's inefficient and I am unsure how to reduce the if count and keeping a cyclomatic complexity below 15. I need to add 8 more jobs but I can't add anymore.</p>
<ul>
<li>How can I reduce the if count?</li>
<li>What else have I done wrong?</li>
</ul>
<h2>The code I have been working on</h2>
<pre class="lang-py prettyprint-override"><code> @job.command()
async def apply(self,ctx,*,selection:str):
a = banned(ctx.author.id,self.bot.blacklisted)
if a is True:
return await ctx.send("You are blacklisted from using this command.")
db = client.bot
posts = db.user
for x in posts.find({"guildid":f"{ctx.guild.id}","id":f"{ctx.author.id}"},{ "_id": 0,"job":1,"level":1}):
level = int(x["level"])
if selection.lower() == "garbage collector" and level >= 0:
posts.update_one({"id":f"{ctx.author.id}","guildid":f"{ctx.guild.id}"}, {"$set": { "job": "Garbage Collector","income":50}})#save
elif selection.lower() == "cleaner" and level >= 7:
posts.update_one({"id":f"{ctx.author.id}","guildid":f"{ctx.guild.id}"}, {"$set": { "job": "Cleaner","income":70}})#save
elif selection.lower() == "car washer" and level >= 16:
posts.update_one({"id":f"{ctx.author.id}","guildid":f"{ctx.guild.id}"}, {"$set": { "job": "Car Washer","income":105}})#save
elif selection.lower() == "maid" and level >= 27:
posts.update_one({"id":f"{ctx.author.id}","guildid":f"{ctx.guild.id}"}, {"$set": { "job": "Maid","income":145}})#save
elif selection.lower() == "receptionist" and level >= 36:
posts.update_one({"id":f"{ctx.author.id}","guildid":f"{ctx.guild.id}"}, {"$set": { "job": "Receptionist","income":185}})#save
else:
return await ctx.send(f"You are currently {level}, please go to school using ?learn")
await ctx.send(f"You are now working as a {selection.lower()}")
</code></pre>
<h2>The pymongo document format</h2>
<pre class="lang-py prettyprint-override"><code>"id":f"{message.author.id}"
"name":f"{message.author.name}"
"guildid":f"{message.guild.id}"
"cash":0
"job":"Homeless"
"balance":0
"shares":0
"level":0
"income":0
</code></pre>
|
[] |
[
{
"body": "<h2>Why loop?</h2>\n\n<pre><code>for x in posts.find({\"guildid\":f\"{ctx.guild.id}\",\"id\":f\"{ctx.author.id}\"},{ \"_id\": 0,\"job\":1,\"level\":1}):\n level = int(x[\"level\"])\n</code></pre>\n\n<p>You're looping over the result of <code>posts.find</code> to... convert an element to an integer and then throw it away? Are you sure that this is what you want to be doing?</p>\n\n<p>If you care about <code>level</code>, your current code is overwriting it on every iteration, so you'll only get the last one.</p>\n\n<h2>Don't repeat yourself</h2>\n\n<pre><code>for job_name, level_min, income in (\n ('Garbage Collector', 0, 50),\n ( 'Cleaner', 7, 70),\n ( 'Car Washer', 16, 105),\n ( 'Maid', 27, 145),\n ( 'Receptionist', 36, 185)\n):\n if selection.lower() == job_name.lower() and level >= level_min:\n data = {\n \"id\": f\"{ctx.author.id}\",\n \"guildid\": f\"{ctx.guild.id}\"\n }\n set_stuff = {\n \"$set\": {\n \"job\": job_name,\n \"income\": income\n }\n }\n posts.update_one(data, set_stuff)\n break\nelse:\n return await ctx.send(f\"You are currently {level}, please go to school using ?learn\")\n</code></pre>\n\n<p>If you want to get fancier, you can use a case-insensitive dictionary, but for this, that isn't strictly needed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T06:27:44.717",
"Id": "441865",
"Score": "0",
"body": "Thank you, is there a guide or something to learn how to make code like that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T13:52:54.103",
"Id": "441960",
"Score": "0",
"body": "Making what kind of code, in particular? Yes, there are some online Python guides."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T15:02:59.150",
"Id": "441969",
"Score": "0",
"body": "Really efficient code like yours"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T15:10:45.450",
"Id": "441971",
"Score": "0",
"body": "It basically takes practice and experience. Read books and other peoples' source code, and keep submitting to CodeReview :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T01:30:43.410",
"Id": "227141",
"ParentId": "227123",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227141",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T19:59:35.393",
"Id": "227123",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"cyclomatic-complexity",
"pymongo"
],
"Title": "Work command handler for an economy system"
}
|
227123
|
<p>I'm following a tutorial on Single Linked List (SLL). </p>
<p>There are so many methods in the code, if you had time please feel free to review any part of it and I can work on it and repost it. </p>
<p>I'm especially interested in object-oriented, algorithms, design, logic, exception handling, and other programming side of it. Other developer-oriented issues such as variable namings, documenting, commenting, and such are not really a concern here since it's just for practicing algorithm and data structures, and have to follow the tutorial as much as possible. </p>
<p>Thanks so much for your time!</p>
<pre><code>"""
Single Linked List (SLL):
A simple object-oriented implementation of Single Linked List (SLL)
with some associated methods, such as create list, count nodes, delete nodes, and such.
"""
class Node:
"""
Instantiates a node
"""
def __init__(self, value):
"""
Node class constructor which sets the value and link of the node
"""
self.info = value
self.link = None
class SingleLinkedList:
"""
Instantiates the SLL class
"""
def __init__(self):
"""
SLL class constructor which sets the value and link of the node
"""
self.start = None
def create_single_linked_list(self):
"""
Reads values from stdin and appends them to this list and creates a SLL with integer nodes
"""
try:
number_of_nodes = int(input(" Enter a positive integer between 1-50 for the number of nodes you wish to have in the list: "))
if number_of_nodes <= 0 or number_of_nodes > 51:
print(" The number of nodes though must be an integer between 1 to 50!")
self.create_single_linked_list()
except Exception as e:
print(" Error: ", e)
self.create_single_linked_list()
try:
for _ in range(number_of_nodes):
try:
data = int(input(" Enter an integer for the node to be inserted: "))
self.insert_node_at_end(data)
except Exception as e:
print(" Error: ", e)
except Exception as e:
print(" Error: ", e)
def count_sll_nodes(self):
"""
Counts the nodes of the linked list
"""
try:
p = self.start
n = 0
while p is not None:
n += 1
p = p.link
if n >= 1:
print(f" The number of nodes in the linked list is {n}")
else:
print(f" The SLL does not have a node!")
except Exception as e:
print(" Error: ", e)
def search_sll_nodes(self, x):
"""
Searches the x integer in the linked list
"""
try:
position = 1
p = self.start
while p is not None:
if p.info == x:
print(f" YAAAY! We found {x} at position {position}")
return True
#Increment the position
position += 1
#Assign the next node to the current node
p = p.link
else:
print(f" Sorry! We couldn't find {x} at any position. Maybe, you might want to use option 9 and try again later!")
return False
except Exception as e:
print(" Error: ", e)
def display_sll(self):
"""
Displays the list
"""
try:
if self.start is None:
print(" Single linked list is empty!")
return
display_sll = " Single linked list nodes are: "
p = self.start
while p is not None:
display_sll += str(p.info) + "\t"
p = p.link
print(display_sll)
except Exception as e:
print(" Error: ", e)
def insert_node_in_beginning(self, data):
"""
Inserts an integer in the beginning of the linked list
"""
try:
temp = Node(data)
temp.link = self.start
self.start = temp
except Exception as e:
print(" Error: ", e)
def insert_node_at_end(self, data):
"""
Inserts an integer at the end of the linked list
"""
try:
temp = Node(data)
if self.start is None:
self.start = temp
return
p = self.start
while p.link is not None:
p = p.link
p.link = temp
except Exception as e:
print(" Error: ", e)
def insert_node_after_another(self, data, x):
"""
Inserts an integer after the x node
"""
try:
p = self.start
while p is not None:
if p.info == x:
break
p = p.link
if p is None:
print(f" Sorry! {x} is not in the list.")
else:
temp = Node(data)
temp.link = p.link
p.link = temp
except Exception as e:
print(" Error: ", e)
def insert_node_before_another(self, data, x):
"""
Inserts an integer before the x node
"""
try:
# If list is empty
if self.start is None:
print(" Sorry! The list is empty.")
return
# If x is the first node, and new node should be inserted before the first node
if x == self.start.info:
temp = Node(data)
temp.link = p.link
p.link = temp
# Finding the reference to the prior node containing x
p = self.start
while p.link is not None:
if p.link.info == x:
break
p = p.link
if p.link is not None:
print(f" Sorry! {x} is not in the list.")
else:
temp = Node(data)
temp.link = p.link
p.link = temp
except Exception as e:
print(" Error: ", e)
def insert_node_at_position(self, data, k):
"""
Inserts an integer in k position of the linked list
"""
try:
# if we wish to insert at the first node
if k == 1:
temp = Node(data)
temp.link = self.start
self.start = temp
return
p = self.start
i = 1
while i < k-1 and p is not None:
p = p.link
i += 1
if p is None:
print(f" The max position is {i}")
else:
temp = Node(data)
temp.link = self.start
self.start = temp
except Exception as e:
print(" Error: ", e)
def delete_a_node(self, x):
"""
Deletes a node of a linked list
"""
try:
# If list is empty
if self.start is None:
print(" Sorry! The list is empty.")
return
# If there is only one node
if self.start.info == x:
self.start = self.start.link
# If more than one node exists
p = self.start
while p.link is not None:
if p.link.info == x:
break
p = p.link
if p.link is None:
print(f" Sorry! {x} is not in the list.")
else:
p.link = p.link.link
except Exception as e:
print(" Error: ", e)
def delete_sll_first_node(self):
"""
Deletes the first node of a linked list
"""
try:
if self.start is None:
return
self.start = self.start.link
except Exception as e:
print(" Error: ", e)
def delete_sll_last_node(self):
"""
Deletes the last node of a linked list
"""
try:
# If the list is empty
if self.start is None:
return
# If there is only one node
if self.start.link is None:
self.start = None
return
# If there is more than one node
p = self.start
# Increment until we find the node prior to the last node
while p.link.link is not None:
p = p.link
p.link = None
except Exception as e:
print(" Error: ", e)
def reverse_sll(self):
"""
Reverses the linked list
"""
try:
prev = None
p = self.start
while p is not None:
next = p.link
p.link = prev
prev = p
p = next
self.start = prev
except Exception as e:
print(" Error: ", e)
def bubble_sort_sll_nodes_data(self):
"""
Bubble sorts the linked list on integer values
"""
try:
# If the list is empty or there is only one node
if self.start is None or self.start.link is None:
print(" The list has no or only one node and sorting is not required.")
end = None
while end != self.start.link:
p = self.start
while p.link != end:
q = p.link
if p.info > q.info:
p.info, q.info = q.info, p.info
p = p.link
end = p
except Exception as e:
print(" Error: ", e)
def bubble_sort_sll(self):
"""
Bubble sorts the linked list
"""
try:
# If the list is empty or there is only one node
if self.start is None or self.start.link is None:
print(" The list has no or only one node and sorting is not required.")
end = None
while end != self.start.link:
r = p = self.start
while p.link != end:
q = p.link
if p.info > q.info:
p.link = q.link
q.link = p
if p != self.start:
r.link = q.link
else:
self.start = q
p, q = q, p
r = p
p = p.link
end = p
except Exception as e:
print(" Error: ", e)
def sll_has_cycle(self):
"""
Tests the list for cycles using Tortoise and Hare Algorithm (Floyd's cycle detection algorithm)
"""
try:
if self.find_sll_cycle() is None:
return False
else:
return True
except Exception as e:
print(" Error: ", e)
def find_sll_cycle(self):
"""
Finds cycles in the list, if any
"""
try:
# If there is one node or none, there is no cycle
if self.start is None or self.start.link is None:
return None
# Otherwise,
slowR = self.start
fastR = self.start
while slowR is not None and fastR is not None:
slowR = slowR.link
fastR = fastR.link.link
if slowR == fastR:
return slowR
return None
except Exception as e:
print(" Error: ", e)
def remove_cycle_from_sll(self):
"""
Removes the cycles
"""
try:
c = self.find_sll_cycle()
# If there is no cycle
if c is None:
return
print(f" There is a cycle at node: ", c.info)
p = c
q = c
len_cycles = 0
while True:
len_cycles += 1
q = q.link
if p == q:
break
print(f" The cycle length is {len_cycles}")
len_rem_list = 0
p = self.start
while p != q:
len_rem_list += 1
p = p.link
q = q.link
print(f" The number of nodes not included in the cycle is {len_rem_list}")
length_list = len_rem_list + len_cycles
print(f" The SLL length is {length_list}")
# This for loop goes to the end of the SLL, and set the last node to None and the cycle is removed.
p = self.start
for _ in range(length_list-1):
p = p.link
p.link = None
except Exception as e:
print(" Error: ", e)
def insert_cycle_in_sll(self, x):
"""
Inserts a cycle at a node that contains x
"""
try:
if self.start is None:
return False
p = self.start
px = None
prev = None
while p is not None:
if p.info == x:
px = p
prev = p
p = p.link
if px is not None:
prev.link = px
else:
print(f" Sorry! {x} is not in the list.")
except Exception as e:
print(" Error: ", e)
def merge_using_new_list(self, list2):
"""
Merges two already sorted SLLs by creating new lists
"""
merge_list = SingleLinkedList()
merge_list.start = self._merge_using_new_list(self.start, list2.start)
return merge_list
def _merge_using_new_list(self, p1, p2):
"""
Private method of merge_using_new_list
"""
if p1.info <= p2.info:
Start_merge = Node(p1.info)
p1 = p1.link
else:
Start_merge = Node(p2.info)
p2 = p2.link
pM = Start_merge
while p1 is not None and p2 is not None:
if p1.info <= p2.info:
pM.link = Node(p1.info)
p1 = p1.link
else:
pM.link = Node(p2.info)
p2 = p2.link
pM = pM.link
#If the second list is finished, yet the first list has some nodes
while p1 is not None:
pM.link = Node(p1.info)
p1 = p1.link
pM = pM.link
#If the second list is finished, yet the first list has some nodes
while p2 is not None:
pM.link = Node(p2.info)
p2 = p2.link
pM = pM.link
return Start_merge
def merge_inplace(self, list2):
"""
Merges two already sorted SLLs in place in O(1) of space
"""
merge_list = SingleLinkedList()
merge_list.start = self._merge_inplace(self.start, list2.start)
return merge_list
def _merge_inplace(self, p1, p2):
"""
Merges two already sorted SLLs in place in O(1) of space
"""
if p1.info <= p2.info:
Start_merge = p1
p1 = p1.link
else:
Start_merge = p2
p2 = p2.link
pM = Start_merge
while p1 is not None and p2 is not None:
if p1.info <= p2.info:
pM.link = p1
pM = pM.link
p1 = p1.link
else:
pM.link = p2
pM = pM.link
p2 = p2.link
if p1 is None:
pM.link = p2
else:
pM.link = p1
return Start_merge
def merge_sort_sll(self):
"""
Sorts the linked list using merge sort algorithm
"""
self.start = self._merge_sort_recursive(self.start)
def _merge_sort_recursive(self, list_start):
"""
Recursively calls the merge sort algorithm for two divided lists
"""
# If the list is empty or has only one node
if list_start is None or list_start.link is None:
return list_start
# If the list has two nodes or more
start_one = list_start
start_two = self._divide_list(self_start)
start_one = self._merge_sort_recursive(start_one)
start_two = self._merge_sort_recursive(start_two)
start_merge = self._merge_inplace(start_one, start_two)
return start_merge
def _divide_list(self, p):
"""
Divides the linked list into two almost equally sized lists
"""
# Refers to the third nodes of the list
q = p.link.link
while q is not None and p is not None:
# Increments p one node at the time
p = p.link
# Increments q two nodes at the time
q = q.link.link
start_two = p.link
p.link = None
return start_two
def concat_second_list_to_sll(self, list2):
"""
Concatenates another SLL to an existing SLL
"""
# If the second SLL has no node
if list2.start is None:
return
# If the original SLL has no node
if self.start is None:
self.start = list2.start
return
# Otherwise traverse the original SLL
p = self.start
while p.link is not None:
p = p.link
# Link the last node to the first node of the second SLL
p.link = list2.start
def test_merge_using_new_list_and_inplace(self):
"""
"""
LIST_ONE = SingleLinkedList()
LIST_TWO = SingleLinkedList()
LIST_ONE.create_single_linked_list()
LIST_TWO.create_single_linked_list()
print("1️⃣ The unsorted first list is: ")
LIST_ONE.display_sll()
print("2️⃣ The unsorted second list is: ")
LIST_TWO.display_sll()
LIST_ONE.bubble_sort_sll_nodes_data()
LIST_TWO.bubble_sort_sll_nodes_data()
print("1️⃣ The sorted first list is: ")
LIST_ONE.display_sll()
print("2️⃣ The sorted second list is: ")
LIST_TWO.display_sll()
LIST_THREE = LIST_ONE.merge_using_new_list(LIST_TWO)
print("The merged list by creating a new list is: ")
LIST_THREE.display_sll()
LIST_FOUR = LIST_ONE.merge_inplace(LIST_TWO)
print("The in-place merged list is: ")
LIST_FOUR.display_sll()
def test_all_methods(self):
"""
Tests all methods of the SLL class
"""
OPTIONS_HELP = """
Select a method from 1-19:
ℹ️ (1) Create a single liked list (SLL).
ℹ️ (2) Display the SLL.
ℹ️ (3) Count the nodes of SLL.
ℹ️ (4) Search the SLL.
ℹ️ (5) Insert a node at the beginning of the SLL.
ℹ️ (6) Insert a node at the end of the SLL.
ℹ️ (7) Insert a node after a specified node of the SLL.
ℹ️ (8) Insert a node before a specified node of the SLL.
ℹ️ (9) Delete the first node of SLL.
ℹ️ (10) Delete the last node of the SLL.
ℹ️ (11) Delete a node you wish to remove.
ℹ️ (12) Reverse the SLL.
ℹ️ (13) Bubble sort the SLL by only exchanging the integer values.
ℹ️ (14) Bubble sort the SLL by exchanging links.
ℹ️ (15) Merge sort the SLL.
ℹ️ (16) Insert a cycle in the SLL.
ℹ️ (17) Detect if the SLL has a cycle.
ℹ️ (18) Remove cycle in the SLL.
ℹ️ (19) Test merging two bubble-sorted SLLs.
ℹ️ (20) Concatenate a second list to the SLL.
ℹ️ (21) Exit.
"""
self.create_single_linked_list()
while True:
print(OPTIONS_HELP)
UI_OPTION = int(input(" Enter an integer for the method you wish to run using the above help: "))
if UI_OPTION == 1:
data = int(input(" Enter an integer to be inserted at the end of the list: "))
x = int(input(" Enter an integer to be inserted after that: "))
self.insert_node_after_another(data, x)
elif UI_OPTION == 2:
self.display_sll()
elif UI_OPTION == 3:
self.count_sll_nodes()
elif UI_OPTION == 4:
data = int(input(" Enter an integer to be searched: "))
self.search_sll_nodes(data)
elif UI_OPTION == 5:
data = int(input(" Enter an integer to be inserted at the beginning: "))
self.insert_node_in_beginning(data)
elif UI_OPTION == 6:
data = int(input(" Enter an integer to be inserted at the end: "))
self.insert_node_at_end(data)
elif UI_OPTION == 7:
data = int(input(" Enter an integer to be inserted: "))
x = int(input(" Enter an integer to be inserted before that: "))
self.insert_node_before_another(data, x)
elif UI_OPTION == 8:
data = int(input(" Enter an integer for the node to be inserted: "))
k = int(input(" Enter an integer for the position at which you wish to insert the node: "))
self.insert_node_before_another(data, k)
elif UI_OPTION == 9:
self.delete_sll_first_node()
elif UI_OPTION == 10:
self.delete_sll_last_node()
elif UI_OPTION == 11:
data = int(input(" Enter an integer for the node you wish to remove: "))
self.delete_a_node(data)
elif UI_OPTION == 12:
self.reverse_sll()
elif UI_OPTION == 13:
self.bubble_sort_sll_nodes_data()
elif UI_OPTION == 14:
self.bubble_sort_sll()
elif UI_OPTION == 15:
self.merge_sort_sll()
elif UI_OPTION == 16:
data = int(input(" Enter an integer at which a cycle has to be formed: "))
self.insert_cycle_in_sll(data)
elif UI_OPTION == 17:
if self.sll_has_cycle():
print(" The linked list has a cycle. ")
else:
print(" YAAAY! The linked list does not have a cycle. ")
elif UI_OPTION == 18:
self.remove_cycle_from_sll()
elif UI_OPTION == 19:
self.test_merge_using_new_list_and_inplace()
elif UI_OPTION == 20:
list2 = self.create_single_linked_list()
self.concat_second_list_to_sll(list2)
elif UI_OPTION == 21:
break
else:
print(" Option must be an integer, between 1 to 21.")
print()
if __name__ == '__main__':
# Instantiates a new SLL object
SLL_OBJECT = SingleLinkedList()
SLL_OBJECT.test_all_methods()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-17T07:37:00.010",
"Id": "449991",
"Score": "1",
"body": "Seeing it's been seven weeks, this would be a great time to revise the code and post a follow-on question."
}
] |
[
{
"body": "<blockquote>\n <p>Other developer-oriented issues such as variable namings, documenting, commenting, and such are not really a concern here since it's just for practicing algorithm and data structures, and have to follow the tutorial as much as possible.</p>\n</blockquote>\n\n<p>I feel this is a bad idea, this is as it promotes detrimental core habits.</p>\n\n<p>Myself and a friend used to play a purely skill based game. You had to click circles at specific points in time. My friend had discipline and decided to laboriously focus on improving their accuracy by playing on the easiest levels until they could reasonably 100% any easy level. After this they played harder and harder levels, focusing on building one skill at a time. They became one of the best at this game in the world.</p>\n\n<p>I however found the easy levels boring, and decided to skip to harder levels. I would on average get 80%-90% when we were playing some of the easier levels together. But as my friend progressed this dropped to an average of 60%, it seemed nearly impossible to get higher or lower than this.</p>\n\n<p>This is the same with programming. When you get in <a href=\"https://en.wikipedia.org/wiki/Flow_(psychology)\" rel=\"nofollow noreferrer\">the zone</a> you want to stay in it for the maximum amount of time. However if you don't have core skills then you'll likely trip up and leave it. This can be as simple as hitting a road block where you need to think of a name, and the more it takes to get the name you want the more you've left the zone. And then you have to build up to get in that zone again.</p>\n\n<h1>As for the code</h1>\n\n<p>I think adding hearts is 'cute', and if this were a professional project I'd recommend they go away. Currently however they look like there's no clear standard on what should be green, orange or red.</p>\n\n<blockquote>\n<pre><code>print(\" Single linked list is empty!\")\nprint(\" Error: \", e)\n</code></pre>\n</blockquote>\n\n<p>Personally I'd make a couple of functions <code>info</code>, <code>warn</code> and <code>error</code> that print the message with the correct heart prepended. This could be something simple like:</p>\n\n<pre><code>def info(*args, sep=None, **kwargs):\n print('', *args, **kwargs)\n</code></pre>\n\n<ul>\n<li><code>create_single_linked_list</code> should be a class method. This is as it is <em>creating</em> the linked list, and so you should be initializing the LL in the function.</li>\n<li><code>create_single_linked_list</code> shouldn't have printing in it, and it shouldn't have any reading input from users. This is not what a Linked List does, this is something independent of the linked list.</li>\n<li><p>Don't use recursion unless you know it's reasonably safe. Python limits how deep a function call stack can be, and so this is like creating a bomb. You never know when your code may just break.</p>\n\n<p>There's ways to increase this limit, but I'd advise against them as they don't solve the problem. It's like having bomb defuser hide bombs in the middle of nowheer. Sure it's less likely to kill anybody, but there's still a chance.</p></li>\n<li><p>The lack of magic methods is very alarming. What's the point in making an abstract data type, if you can't even use it via standard means?</p></li>\n<li><p>Adding an <code>__iter__</code> magic method would make the majority of your functions very simple. You could define <code>search_sll_nodes</code> (which is a very poor name) as simply <code>return x in iter(self)</code>. You could make <code>count_sll_nodes</code>, <code>return sum(1 for _ in self)</code>.</p>\n\n<p>This is a large oversight, and makes the code longer and harder to understand for seemingly no reason.</p></li>\n<li><p><code>except Exception as e: print(\" Error: \", e)</code> is really bad form. You shouldn't be ignoring potentially fatal errors in your linked list class. This is just another example on how your code has merged the calling code with the linked list implementation.</p>\n\n<p>Also the pure magnitude of these makes me either think you have the worlds most error prone linked list, in which case you should probably focus on fixing the issues you have. Or that your code is just an example of the boy who cried wolf. Are there actually any errors here, or will the calling code handle the issue if I allow it to propagate?</p>\n\n<p>Either way I'd get rid of most of them.</p></li>\n<li><p>You can implement pretty much everything you need by inheriting <a href=\"https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableSequence\" rel=\"nofollow noreferrer\"><code>collections.abc.MutableSequence</code></a>.</p></li>\n</ul>\n\n<p>I would go through the code in more depth, but I'm only a tenth of the way through and I've come to the conclusion that I'd be rewriting the entire of your code as you've not decoupled your user interactions from your implementation.</p>\n\n<h1>Conclusion</h1>\n\n<p>You should implement the entire linked list again, I'd advise inheriting from <code>MutableSequence</code> to ease the creation of this list.</p>\n\n<p>Your main code should be built in a way that you can test a list and your <code>SingleLinkedList</code>. This has the benefit that you can make a <code>DoubleLinkedList</code> and not have to duplicate nearly a thousand lines, which is long.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T23:54:29.890",
"Id": "227133",
"ParentId": "227125",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "227133",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T21:27:37.623",
"Id": "227125",
"Score": "1",
"Tags": [
"python",
"beginner",
"algorithm",
"object-oriented",
"sorting"
],
"Title": "Single Linked List (Python)"
}
|
227125
|
<p>I was presented with a task to come up with a script that generates a CSV with POSTAL codes via bruteforce (I'm in Brazil, so that means CEP to us).</p>
<p>Points to note:</p>
<ul>
<li>I'm using an external library, but basically consuming a SOAP service provided by the Postal agency;</li>
<li>I have a list of cities I have to get the results for, with variable ranges to be tested;</li>
<li>I have 8 threads available for me, and using 7 to process and 1 to writing (Iw as scared of sincronism);</li>
</ul>
<p>When formulating the solution, I had two paths:</p>
<ol>
<li>Send a city to each thread, and wait for that city to finish processing.</li>
<li>Send the entire list of postal codes available for a city to all threads, and only grab the next city after it is all done.</li>
</ol>
<p>Currently I opted for option 1, since I was thinking the number of requests and processing would be the same, but now it does seem a bit slow (it's been running for around 7 days and not done).</p>
<p>Problems:</p>
<ul>
<li>There're cities with huge ranges to test (like Sao Paulo, with 6.5M), which means a thread stuck processing it;</li>
<li>but on the other hand, it's complicated to manage which cities have completed by going for option 2.</li>
</ul>
<p>My input data is a CSV file, formatted like this (This is in Brazilian Portuguese):</p>
<pre class="lang-none prettyprint-override"><code>Adamantina,17800-000 a 17809-999,Não codificada por logradouros,Total do município
Agudos,17120-001 a 17149-999,Codificado por logradouros,Total do município
</code></pre>
<p>My code is below. Some of the code can be ignored (like the logging statements):</p>
<pre class="lang-py prettyprint-override"><code>import threading
import csv
import queue
import time
from datetime import timedelta
import requests
import pycep_correios
from loguru import logger
from pycep_correios import HOMOLOGACAO, PRODUCAO
from tqdm import tqdm
def read_csv(csv_path: str):
"""Utility function to read CSV files
Arguments:
csv_path {str} -- path to the CSV file
Returns:
list -- a list of lists where each CSV row is a list
"""
with open(csv_path, 'r') as f:
csv_reader = csv.reader(f)
return [list(row) for row in csv_reader]
def recover_range(range_string: str):
"""Utility function to recover the numeric range from string
Given that the string is in a specific format,
we split it and get the numeric range
Arguments:
range_string {str} -- string containing the range, must be in format 'xxxxx-xxx a xxxxx-xxx'
Returns:
list -- list with the numeric range ([from, to])
"""
cep_range = [v.replace('-', '') for v in range_string.split(' ')]
cep_range = [int(v) for v in cep_range if v.isnumeric()]
return cep_range
class DataWriterThread(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
logger.info('Instantiating {} on {}', self.__class__.__name__,
self.name)
self.queue = queue
def write_to_file(self, content: dict):
"""Method to write content to the target CSV
Arguments:
content {dict} -- dictionary where each key is a column for the CSV
"""
with open('output_sp.csv', 'a') as f:
logger.info('{}: writing new register to CSV.', self.name)
writer = csv.DictWriter(f, content.keys())
writer.writerow(content)
def run(self):
while True:
result = self.queue.get()
self.write_to_file(result)
self.queue.task_done()
class RequestThread(threading.Thread):
def __init__(self, in_queue: queue.Queue, out_queue: queue.Queue):
threading.Thread.__init__(self)
logger.info('Instantiating {} on {}', self.__class__.__name__,
self.name)
self.in_queue = in_queue
self.out_queue = out_queue
def run(self):
while True:
record = self.in_queue.get()
for item in record:
result = self.process(item)
if result is not None:
self.out_queue.put(result)
else:
logger.success('{} has finished processing...', result['cidade'])
self.in_queue.task_done()
def process(self, record):
"""Processing method
This method expects a CEP number as input, and will make a request
to the Correios API to check if it exists. In positive cases we
return the data, else None is returned.
Arguments:
record {int} -- CEP number
Returns:
dict -- Dictionary containing the valid CEP data, None if not found
"""
cep = str(record)
if len(cep) < 8:
cep = '0{}'.format(cep)
if pycep_correios.validar_cep(cep):
try:
address = pycep_correios.consultar_cep(cep=cep,
ambiente=HOMOLOGACAO)
if address is not None:
logger.success('{}: {} is a valid CEP, saving...',
self.name, cep)
return address
except pycep_correios.excecoes.ExcecaoPyCEPCorreios as exc:
logger.error('{}: Exception when processing: {} - [{}]',
self.name, cep, exc.message)
return None
except AttributeError as exc:
logger.error('{}: CEP {} has AttributeError {}', self.name,
cep, exc)
except requests.exceptions.ConnectionError:
logger.warning(
'{}: Connection blocked, trying again in 60 seconds...',
self.name)
time.sleep(60) # After some time the SOAP service force disconnects
# Recursive call to reprocess the item
return self.process(cep)
else:
logger.error('{}: Invalid CEP {}', self.name, cep)
return None
def main():
lg = logger.add("events.log",
rotation="25 MB",
compression="zip",
format="{time} {level} {message}",
level="INFO")
cep_list = read_csv('cep_sp.csv') # read and preprocess ranges
cep_list = [
item for item in cep_list
if item[1] and item[2] == 'Codificado por logradouros'
]
cep_queue = queue.Queue() # list of ceps to process
result_queue = queue.Queue() # results acquired
for _ in range(3): # 4 cores = 3 proc threads + 1 writer thread
t = RequestThread(in_queue=cep_queue, out_queue=result_queue)
t.daemon = True
t.start()
# spawn threads to print
t = DataWriterThread(result_queue)
t.daemon = True
t.start()
cep_processing_list = []
for record in cep_list:
cep_ranges = recover_range(record[1])
if not cep_ranges: # dealing with header rows
continue
else:
cep_processing_list.append(
[cep for cep in range(cep_ranges[0], cep_ranges[1])])
# add paths to queue
for record in tqdm(cep_processing_list):
cep_queue.put(record)
start_time = time.time()
logger.info('Starting the script...')
# wait for queue to get empty
cep_queue.join()
result_queue.join()
logger.info('Finished. Done in {}.',
str(timedelta(seconds=(time.time() - start_time))))
logger.remove(lg)
if __name__ == "__main__":
main()
# reference: https://stackoverflow.com/questions/11983938/python-appending-to-same-file-from-multiple-threads
</code></pre>
<p>The goals I want to achieve:</p>
<ul>
<li>Improve efficiency overall;</li>
<li>Improve code to be cleaner and more compliant with Python guidelines (I tried my best);</li>
<li>Get some advice if I should split this code in functions and files more;</li>
<li>If possible, come up with a solution for the huge amount of data implied.</li>
</ul>
<p>If more hardware is the only answer, there's nothing I can do. But I would like to do the best I can with the code. Thanks in advance.</p>
<p><strong>EDIT</strong>: As this question has been around for some time and has not seem much activity besides the initial response I am marking it as solved, but if there're any pointers you would like to comment, you are free to do.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T12:50:36.200",
"Id": "442565",
"Score": "1",
"body": "While unintuitive, you should know that the `threading` package does not actually do proper multithreading, it only simulates asynchronous threads. It's great for doing HTTP requests, and waiting for results. But you probably want to look at the `multiprocessing` package, which actually runs your code in parallel, and offers a speedup."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T13:55:19.320",
"Id": "442832",
"Score": "0",
"body": "That's interesting to know. I am quite new to multithreading in python, thanks for the head up."
}
] |
[
{
"body": "<h2>Type hints for return values</h2>\n\n<p>You add <code>str</code> as a parameter hint, but you're missing a return value hint - for <code>read_csv</code> for instance, it should be <code>list</code>.</p>\n\n<p>You're also missing a type hint for <code>queue</code>.</p>\n\n<h2>Formatting leading zeros</h2>\n\n<p>Don't pre-convert <code>cep</code> to a string. Instead:</p>\n\n<pre><code>cep = '{:08d}'.format(cep)\n</code></pre>\n\n<h2>f-strings</h2>\n\n<pre><code>logger.success(f'{self.name}: {cep} is a valid CEP, saving...')\n</code></pre>\n\n<h2>Recursion for retry</h2>\n\n<p>Don't! There's no need to recurse, and it's needlessly bloating your stack. Rather than recursing, use a simple loop.</p>\n\n<h2><code>continue</code> logic</h2>\n\n<pre><code> if not cep_ranges: # dealing with header rows\n continue\n else:\n cep_processing_list.append(\n [cep for cep in range(cep_ranges[0], cep_ranges[1])])\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>if cep_ranges:\n cep_processing_list.append(\n [cep for cep in range(cep_ranges[0], cep_ranges[1])])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T01:26:54.247",
"Id": "441837",
"Score": "0",
"body": "Thank you for your pointers, I was not aware `loguru` supports f-strings directly. The recursion strategy is a hack, and your suggestion seems pretty much smarter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T01:33:29.167",
"Id": "441838",
"Score": "1",
"body": "An f-string, after formatting, turns into a regular string - so anything that accepts a `str` supports an f-string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T12:51:15.033",
"Id": "441950",
"Score": "0",
"body": "Overall, what do you think of the logic?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T01:13:12.347",
"Id": "227138",
"ParentId": "227128",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227138",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T22:20:26.587",
"Id": "227128",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"multithreading",
"csv"
],
"Title": "Multithreading to process requests and save results in python"
}
|
227128
|
<p>I am generating SQL statements (of MySQL format) and writing into a file to create 10,000 tables. Each table contains 5 columns with 1.5 million rows of data in each column. I generated these data by using regex and faker module. So, I have a loop of 10,000 (one for each <strong>create table</strong> statement) and within this loop, I have another loop of 1.5 million (to <strong>insert</strong> rows of data into each table created).</p>
<p>The code is running properly but is <strong>extremely slow</strong>. Is there any way to make this run considerably faster?</p>
<pre><code>import rstr
import random
from faker import Faker
import time
fake = Faker()
name = ['Name', 'Person_Name', 'Customer_Name', 'Employee_Name', 'Contact_Name', 'CustName', 'EmpName']
ssn = ['SSN', 'Social_Security_Number', 'National_Identification_Number', 'NID', 'US_SSN', 'Social_Number', 'Social_Security_No', 'Social_Security_Num', 'Customer_Social_Security Number', 'Employee_Social_Security_Number']
address = ['Address', 'Customer_Location_Details', 'Employee_Address_Details', 'Address_Det.', 'Add_Line_1', 'Add_Line_2', 'Address_Line_1', 'Address_Line_2']
dob = ['DOB', 'Date_Of_Birth', 'Birth_Date', 'V_VLD_BRTH_DT', 'DAY_OF_BRTH', 'DT_OF_BIRTH']
phone = ['Phone_Number', 'Contact_Number', 'Office_Phone', 'Residential_phone', 'Contact_Phone']
ssn1='(?!000|.+0{4})(?:\d{9})'
ssn2='(?!000|.+0{4})(\d{3}-\d{2}-\d{4})'
sList=[ssn1,ssn2]
db1='^(0[1-9]|[12][0-9]|3[01])[/](0[1-9]|1[012])[/](19)\d\d$'
db2='^(19)\d\d$[.](0[1-9]|1[012])[.](0[1-9]|[12][0-9]|3[01])'
db3='^(19)\d\d$[-](0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])'
db4='^(0[1-9]|[12][0-9]|3[01])[-](0[1-9]|1[012])[-](19)\d\d$'
db5='^(0[1-9]|[12][0-9]|3[01])[.](0[1-9]|1[012])[.]\d\d$'
dbList=[db1,db2, db3, db4, db5]
p1='1[2-9][0-8][0-9][2-9][0-9]{2}[0-9]{4}'
p2='[2-9][0-8][0-9][2-9][0-9]{2}[0-9]{4}'
p3='001[2-9][0-8][0-9][2-9][0-9]{2}[0-9]{4}'
p4='[(][\d]{3}[)][ ]?[\d]{3}-[\d]{4}'
p5='\+1[2-9][0-8][0-9][2-9][0-9]{2}[0-9]{4}'
p6='(\d{3}\d{3}\d{4})'
p7='[2-9][0-8][0-9][-][2-9][0-9]{2}[-][0-9]{4}'
pList=[p1, p2, p3, p4, p5, p6, p7]
tables=10001
rows=1500001
with open("D:\Output.sql", "a") as text_file:
count = 0
for i in range(1,tables):
a=[]
b=[]
j=str(i)
x=f'Tab_{i}'
#a.append(random.choice(name)+'_'+j)
#a.append(random.choice(ssn)+'_'+j)
#a.append(random.choice(address)+'_'+j)
#a.append(random.choice(dob)+'_'+j)
#a.append(random.choice(phone)+'_'+j)
a.extend(f'{random.choice(n)}_{j}' for n in (name, ssn, address, dob, phone))
text_file.write(f"create table Python_test.{x}({a[0]} VARCHAR(255),{a[1]} VARCHAR(255),{a[2]} VARCHAR(255),{a[3]} VARCHAR(255),{a[4]} VARCHAR(255));\n")
start = time.time()
for j in range(1,rows):
text_file.write(f"insert into {x}({a[0]},{a[1]},{a[2]},{a[3]},{a[4]}) values ('{fake.name()}','{rstr.xeger(random.choice(sList))}','{fake.address()}','{rstr.xeger(random.choice(dbList))}','{rstr.xeger(random.choice(pList))}');\n")
print(time.time() - start)
text_file.write('\n')
count+=1
print(count)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T00:25:02.937",
"Id": "441831",
"Score": "2",
"body": "What are `name` `ssn` `address` `dob` `phone` and where are they defined?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T00:47:41.053",
"Id": "441832",
"Score": "8",
"body": "What's the purpose of this exercise? Is it homework? Surely creating 10,000 SQL tables isn't something we'd want to do in real life. What are your concerns - speed? Python style? SQL style?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T07:17:46.060",
"Id": "441883",
"Score": "0",
"body": "@AJNeufeld Sorry for the inconvenience. I have attached the full code. The code is working. But it is taking a huge amount of time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T15:08:53.620",
"Id": "441970",
"Score": "2",
"body": "Please define \"extremely slow\", since that is subjective. It's probably very fast compared to some measures. A rough estimate of the system used and the current execution time would be good."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T15:13:32.010",
"Id": "441973",
"Score": "1",
"body": "It might be faster to create a list, NumPy array or Pandas DataFrame with all the random entries, and only then loop over the contents, so you don't have to call the random functions inside each loop (it'll depend a bit on the memory available)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T15:17:06.067",
"Id": "441974",
"Score": "0",
"body": "There is a fair chance it's largely the random generation of numbers, names and addresses that is causing the slowdown. Do you really want to measure (and improve) the generation of random entries? Or do you want to improve the output writing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T15:32:29.497",
"Id": "441977",
"Score": "1",
"body": "Lets assume 500 bytes per line. 500 bytes/line*15 000 000 lines/table*10 000 tables/file = 75 000 000 000 000 bytes/file. Writing 75 TB takes time and it would surprise me a lot if your program spends a noticable amount of time on anything other than writing to disc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T15:35:06.380",
"Id": "441979",
"Score": "1",
"body": "Also, have you talked to your db administrator about your plan of dumping 15 billion insert statemens into the system in one go?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T16:38:49.663",
"Id": "441993",
"Score": "2",
"body": "Just to add to @Taemyr's comment: the very fastest SSDs today have write speeds of ~3.4GB/s. You would need a parallel RAID-0 of *12* of the fastest SSDs of the planet, just bring the pure time for even *writing the output file* to 30 minutes. This is assuming that *no other* I/O takes place during that time, that the 75 TB file largely fits in cache and that the writes are fully sequential and evenly distributed across the drives."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T09:07:41.693",
"Id": "442345",
"Score": "0",
"body": "@00 I want to reduce the overall time. Be it an improvement on generation of random entries or improvement on output writing. As of now, creation of each table takes around 25 mins each (Each iteration). I need 10,000 tables (10,000 iterations)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T11:07:21.923",
"Id": "442365",
"Score": "0",
"body": "Profile it to find the bottleneck. Easy start: removing *all* random calls, and just write the same line (of roughly the proper length) to file, so you have 1500001 identical lines in each file. If the execution drops by 50% or more, the random calls are a notable culprit. If the execution hardly varies, the disk I/O is very likely your bottleneck."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T11:08:44.840",
"Id": "442366",
"Score": "0",
"body": "To add to JörgWMittag and Taemyr's comments: do you know the type of disk you are using; any specifications that you know about it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T11:32:44.687",
"Id": "442375",
"Score": "0",
"body": "@00 It's an hdd. Also, i will try your method to find the bottleneck."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T12:22:38.667",
"Id": "442380",
"Score": "0",
"body": "HDD does not mean too much without an RPM, but assuming this means a spinning drive, that likely means it will already be slower than an SSD; see also the comments above. Good luck with profiling, and let us know what you find."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T13:47:34.323",
"Id": "442388",
"Score": "0",
"body": "@00 I removed the random calls in the inner loop and wrote a string (of approx same length) 1.5 million times in the file. It took 4 secs (with the random and faker calls it took 21.5mins).\nIn another instance, i removed **just** the random calls and kept everything else as it is ( including the regex function and faker). It took 22.5 minutes to run. \nSo it seems the regex and faker function calls are the bottleneck."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T15:50:49.893",
"Id": "442410",
"Score": "0",
"body": "Ok, that was easy. So, now the question you should be asking yourself: do you *really* need (completely) random entries? Can you do, whatever you are testing, with identical lines? Or can you create a set of, say, 100 different lines, and simply loop through those continuously while writing 1500001 rows?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T15:53:52.410",
"Id": "442412",
"Score": "0",
"body": "Or perhaps you mimick the random data by looping through *parts* of the entries, each a list of different lengths. So you could have 5 first names, 7 last names, 13 dobs, 17 street names, 19 street numbers etc, and then simply loop over them (the prime numbers ensures there'll be few identical lines). `itertools.cycle` could be handy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T16:10:21.570",
"Id": "442417",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/98203/discussion-between-subhadeep-majumder-and-0-0)."
}
] |
[
{
"body": "<h2>Use <code>open</code> in a <code>with</code></h2>\n\n<p>...so that you can be guaranteed of file closure regardless of any potential exceptions.</p>\n\n<h2>Use f-strings</h2>\n\n<p>So that something like this:</p>\n\n<pre><code>x='Tab_'+str(i)\n</code></pre>\n\n<p>turns into</p>\n\n<pre><code>x = f'Tab_{i}'\n</code></pre>\n\n<h2>Computers are good at repetition</h2>\n\n<pre><code>a.append(random.choice(name)+'_'+str(i))\na.append(random.choice(ssn)+'_'+str(i))\na.append(random.choice(address)+'_'+str(i))\na.append(random.choice(dob)+'_'+str(i))\na.append(random.choice(phone)+'_'+str(i))\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>a.extend(f'{random.choice(n)}_{i}' for n in (name, ssn, address, dob, phone))\n</code></pre>\n\n<h2>Injection attacks</h2>\n\n<p>Unless you're <em>really</em> confident about the source, safety and validity of your data, constructing a string and sending it off as executable SQL is enemy number one of database security. This is what prepared statements are for. It's unclear what flavour of SQL you need, so it's unclear which library you'll need for this.</p>\n\n<h2>Combined assignment/increment</h2>\n\n<pre><code>count=count+1\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>count += 1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T07:12:02.297",
"Id": "441877",
"Score": "0",
"body": "Thanks for the advice! I am trying to generate **create** and **insert into** sql statements (for mysql db) through python. It seems Python does not support prepared statements. Any library suggestions for this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T13:53:52.113",
"Id": "441961",
"Score": "3",
"body": "Python definitely does support prepared statements, but you have to use a library - maybe https://dev.mysql.com/doc/connector-python/en/"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T00:54:38.903",
"Id": "227136",
"ParentId": "227129",
"Score": "11"
}
},
{
"body": "<h1>Docstrings</h1>\n\n<p>You should include a <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"noreferrer\"><code>docstring</code></a> at the beginning of every module, class, and function you write. This will allow documentation to identify what your code is supposed to do.</p>\n\n<h1><code>with open</code> vs <code>file = open</code></h1>\n\n<p>Currently, you open the file with <code>text_file = open(\"D:\\Output.sql\", \"a\", encoding=\"utf-8\")</code>, and manually close it with <code>text_file.close()</code>. You can save yourself from having to do this with opening the file using <code>with open(...) as ...:</code>. This lets you work with the file, and once done and out of scope, can continue writing the program. <em>\"But wait. What about closing the file?\"</em>. When you use <code>with</code>, once you are out of the scope of the <code>with</code>, it closes itself automatically.</p>\n\n<h1>Magic Numbers</h1>\n\n<pre><code>for i in range(1,10001): ...\nfor j in range(1,1500001): ...\n</code></pre>\n\n<p>At first look, I had no idea what these numbers were supposed to represent. You should assign these numbers to variables, and use those variables instead. This makes the code cleaner and easier to maintain. What if you wanted to change the number of tables or number of people? You'd need to find every instance of that magic number (should you use it more than once) and change it. Having it assigned to a variables fixes this problem, as you can just change the value of the variable.</p>\n\n<h1>String Formatting <code>f\"\"</code></h1>\n\n<p><code>text_file.write('create table Python_test.'+x+'('+a[0]+' VARCHAR(255),'+a[1]+' VARCHAR(255),'+a[2]+' VARCHAR(255),'+a[3]+' VARCHAR(255),'+a[4]+' VARCHAR(255));\\n')</code> </p>\n\n<p>This hurts to read. All the <code>+</code> split apart the string and makes it really hard to know what the whole string is. My solution is to use <code>f\"...\"</code>. This allows you to directly incorporate variables into your strings, without having to <code>+...+</code>, and also avoiding (if present) <code>+str(...)+</code> which is <em>very</em> ugly to me.</p>\n\n<h1>Objects</h1>\n\n<p>Having a redefined list with fixed positions of properties of people is messy. Instead, you can generate a list with instances of a <code>Person</code>, and you can access their properties when incorporating it in your <code>SQL</code> string.</p>\n\n<h1><code>_</code> for unused loop variables</h1>\n\n<p>When you don't use a variable in a loop, like:</p>\n\n<pre><code>for i in range(5):\n print(\"Hi!\")\n</code></pre>\n\n<p>You should use a <code>_</code>. This makes it clear that the variable used for the loop is not needed, and should be ignored.</p>\n\n<h1>Helper Functions</h1>\n\n<p>I wrote a few helper functions for generating some random values in your code. Using helper functions in your code can really help you, as you don't have to cram everything into one function.</p>\n\n<p><em>Exclaimer: I had no idea what you were trying to do when inserting data into your tables, so I left that blank. It also didn't help that <code>fake</code> and <code>rstr</code> weren't defined / weren't shown in your program.</em></p>\n\n<p><strong><em>Updated Code</em></strong></p>\n\n<pre><code>\"\"\"\nModule Docstring\nA description of your program goes here\n\"\"\"\n\nimport random\n\nclass Person():\n \"\"\"\n Class to store properties of Person\n \"\"\"\n\n def __init__(self, name, ssn, address, dob, phone):\n self.name = name\n self.ssn = ssn\n self.address = address\n self.dob = dob\n self.phone = phone\n\ndef generate_ssn():\n \"\"\"\n Returns a randomly generated SSN\n \"\"\"\n return f\"{random.randint(100, 999)}-{random.randint(10, 99)}-{random.randint(1000, 9999)}\"\n\ndef generate_dob():\n \"\"\"\n Returns a randomly generated address in format MM/DD/YYYY\n \"\"\"\n return f\"{random.randint(1, 12)}/{random.randint(1, 31)}/{random.randint(1919, 2019)}\"\n\ndef generate_phone():\n \"\"\"\n Returns a randomly generated phone number\n \"\"\"\n return f\"{random.randint(100, 999)}-{random.randint(100, 999)}-{random.randint(1000, 9999)}\"\n\ndef generate_sql_script(num_people, num_tables, output_file):\n \"\"\"\n Generates an SQL script for inserting people into tables\n \"\"\"\n with open(output_file, \"a\") as out_file:\n people = []\n count = 0\n for i in range(1, num_people):\n people.append(Person(f\"John_{i}\",\n generate_ssn(),\n f\"123 Main St_{i}\",\n generate_dob(),\n generate_phone())\n )\n random_person = random.choice(people)\n table = f\"Tab_{i}\"\n out_file.write(f'CREATE TABLE Python_test.{table}({random_person.name} VARCHAR(255), {random_person.ssn} VARCHAR(255), {random_person.address} VARCHAR(255), {random_person.dob} VARCHAR(255), {random_person.phone} VARCHAR(255)')\n\n for _ in range(1, num_tables):\n #Couldn't understand what this is doing with `fake` and `rstr`\n pass\n\n out_file.write('\\n')\n count += 1\n print(count)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T07:22:31.913",
"Id": "441888",
"Score": "0",
"body": "Thanks for the suggestions. I have attached the full code in case you wanted to take a look into it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T07:59:14.983",
"Id": "441899",
"Score": "0",
"body": "you can split the string along mutliple lines ([string literal concatenation](https://docs.python.org/3/reference/lexical_analysis.html#string-literal-concatenation)) to reduce the line length and make the long strings better readable"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T01:13:47.880",
"Id": "227139",
"ParentId": "227129",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "18",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T22:26:53.303",
"Id": "227129",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"strings",
"random"
],
"Title": "Writing 1.5 million rows in a file"
}
|
227129
|
<p><strong>What i am trying to do</strong></p>
<p>I have an image of a polygon exemple:
<a href="https://i.stack.imgur.com/H8rtj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/H8rtj.png" alt="County"></a></p>
<p>what i am tring to do is getting all border points, that do not have at least one neighbour with the same color, and ordering them in a way that later i can draw lines</p>
<p><strong>The Code</strong></p>
<pre><code>private Vector2F[] ReorderBorder(Vector2F[] Data) {
List<Vector2F> BorderPixels = new List<Vector2F>();
BorderPixels.AddRange(Data);
List<int> Indexs = new List<int>();
Indexs.Add(0);
bool Working = true;
while (Working)
{
int LastIndex = Indexs.Last();
List<int> Possible = new List<int>();
for (int Index = 0; Index < BorderPixels.Count; Index++)
{
if (!Indexs.Contains(Index))
{
if (new Vector2F(BorderPixels[LastIndex].X + 1, BorderPixels[LastIndex].Y) == BorderPixels[Index])
Possible.Add(Index);
else if (new Vector2F(BorderPixels[LastIndex].X + 1, BorderPixels[LastIndex].Y + 1) == BorderPixels[Index])
Possible.Add(Index);
else if (new Vector2F(BorderPixels[LastIndex].X + 1, BorderPixels[LastIndex].Y - 1) == BorderPixels[Index])
Possible.Add(Index);
else if (new Vector2F(BorderPixels[LastIndex].X, BorderPixels[LastIndex].Y + 1) == BorderPixels[Index])
Possible.Add(Index);
else if (new Vector2F(BorderPixels[LastIndex].X - 1, BorderPixels[LastIndex].Y + 1) == BorderPixels[Index])
Possible.Add(Index);
else if (new Vector2F(BorderPixels[LastIndex].X + 1, BorderPixels[LastIndex].Y + 1) == BorderPixels[Index])
Possible.Add(Index);
else if (new Vector2F(BorderPixels[LastIndex].X - 1, BorderPixels[LastIndex].Y) == BorderPixels[Index])
Possible.Add(Index);
else if (new Vector2F(BorderPixels[LastIndex].X - 1, BorderPixels[LastIndex].Y + 1) == BorderPixels[Index])
Possible.Add(Index);
else if (new Vector2F(BorderPixels[LastIndex].X - 1, BorderPixels[LastIndex].Y - 1) == BorderPixels[Index])
Possible.Add(Index);
else if (new Vector2F(BorderPixels[LastIndex].X, BorderPixels[LastIndex].Y - 1) == BorderPixels[Index])
Possible.Add(Index);
else if (new Vector2F(BorderPixels[LastIndex].X - 1, BorderPixels[LastIndex].Y - 1) == BorderPixels[Index])
Possible.Add(Index);
else if (new Vector2F(BorderPixels[LastIndex].X + 1, BorderPixels[LastIndex].Y - 1) == BorderPixels[Index])
Possible.Add(Index);
}
}
Indexs.Add(GetPreference(BorderPixels[LastIndex], Possible.ToArray(), BorderPixels));
if (BorderPixels.Count == Indexs.Count)
Working = false;
}
List<Vector2F> Vertices = new List<Vector2F>();
for (int Index = 0; Index < Indexs.Count; Index++)
Vertices.Add(BorderPixels[Indexs[Index]]);
return Vertices.ToArray();
}
private int GetPreference(Vector2F Origin, int[] Indices, List<Vector2F> BorderPixels) {
if (Indices.Length == 1)
return Indices[0];
Vector2F[] IndicesTest = new Vector2F[Indices.Length];
///Relativity
/// 0 - Up
/// 1 - Up Right
/// 2 - Right
/// 3 - Down Right
/// 4 - Down
/// 5 - Down Left
/// 6 - Left
/// 7 - Up Left
for (int Index = 0; Index < Indices.Length; Index++) {
if(new Vector2F(Origin.X, Origin.Y - 1) == BorderPixels[Indices[Index]])
IndicesTest[Index] = new Vector2F(Indices[Index], 0);
else if(new Vector2F(Origin.X + 1, Origin.Y - 1) == BorderPixels[Indices[Index]])
IndicesTest[Index] = new Vector2F(Indices[Index], 1);
else if (new Vector2F(Origin.X + 1, Origin.Y) == BorderPixels[Indices[Index]])
IndicesTest[Index] = new Vector2F(Indices[Index], 2);
else if (new Vector2F(Origin.X + 1, Origin.Y + 1) == BorderPixels[Indices[Index]])
IndicesTest[Index] = new Vector2F(Indices[Index], 3);
else if (new Vector2F(Origin.X, Origin.Y + 1) == BorderPixels[Indices[Index]])
IndicesTest[Index] = new Vector2F(Indices[Index], 4);
else if (new Vector2F(Origin.X - 1, Origin.Y + 1) == BorderPixels[Indices[Index]])
IndicesTest[Index] = new Vector2F(Indices[Index], 5);
else if (new Vector2F(Origin.X - 1, Origin.Y) == BorderPixels[Indices[Index]])
IndicesTest[Index] = new Vector2F(Indices[Index], 6);
else if (new Vector2F(Origin.X - 1, Origin.Y - 1) == BorderPixels[Indices[Index]])
IndicesTest[Index] = new Vector2F(Indices[Index], 7);
}
if (IndicesTest.Length != 0) {
Array.Sort(IndicesTest, CompareY);
return (int)IndicesTest[0].X;
}
return 0;
}
private int CompareY(Vector2F Left, Vector2F Right) {
if (Left.Y < Right.Y)
return -1;
else if (Left.Y == Right.Y)
return 0;
else
return 1;
}
</code></pre>
<p><strong>What it does</strong></p>
<pre><code>private Vector2F[] ReorderBorder(Vector2F[] Data)
</code></pre>
<p>This is the main function where i pass the border points, currently orderd by y so 0,0 1,0 2,0 0,1 1,1 etc..</p>
<p>so what it does is starting from the first pixel it get all existing border pixels in 8 directions and add the "preferenced" pixel (see GetPreference function) then after finishing ordering all pixels it sends a orderd array back</p>
<pre><code>private int GetPreference(Vector2F Origin, int[] Indices, List<Vector2F> BorderPixels)
</code></pre>
<p>this functions recives a point and a list of possible neighbours then it returns the index of the perfed one (lowest score see code)</p>
<pre><code>private int CompareY(Vector2F Left, Vector2F Right)
</code></pre>
<p>this function is simply used to sort by the lowest y, for the score on the <code>GetPreference</code> function</p>
<p><strong>What i want to know</strong></p>
<p>All i want to know is if there is any way to optmized the code, or a better alternative, i know that the code as some bugs but this is the most reliable way i could do, since i was not able to find any good alternative online</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T22:50:15.527",
"Id": "441822",
"Score": "0",
"body": "All green points seem to have at least one neighbour with the same color and all transparent points seem to have at least one neighbour being transparent. So, according to your definition there are no points in the result set. Your working example draws black lines that are not on a border. I'm a bit confused."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T22:55:20.923",
"Id": "441823",
"Score": "0",
"body": "@OlivierJacot-Descombes first i dont know what you mean with green points the exemple is yellow second getting the points from the image is not in question, i have everything working i just want to know if the reorganization of the points can be optimized, and final in the exemple we have yellow so the way i get points is if a points is yellow see if any of the neighbours is transparent if yes then add to the border list if does not then do not add and in the point in question is transperent completely ignore"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T23:21:23.577",
"Id": "441825",
"Score": "0",
"body": "Looking at [HTML color codes and names](https://www.computerhope.com/htmcolor.htm) I would say the color is very close to Tea Green."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T23:23:26.770",
"Id": "441826",
"Score": "0",
"body": "@OlivierJacot-Descombes look that as nothing to do with the question so unless you have anything constructive to say please stop comenting"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T23:33:41.480",
"Id": "441827",
"Score": "4",
"body": "@BotWade: don't be rude to people trying to help. The second picture, titled \"working exemple\", doesn't make much sense. The border lines are all over the place. I suggest you either update or remove the picture. Also, arguing over colors is unnecessary. Ever heard of colorblindness?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T23:36:58.757",
"Id": "441828",
"Score": "0",
"body": "@TomG First sorry if i sounded rude it was not my intension, about the working exemple i though that it was easy to understand in that case i will remove it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T13:33:47.363",
"Id": "441957",
"Score": "0",
"body": "I think the confusion comes from the sentence \"... that do not have at least one neighbour with the same color, ...\". It should be \"... that do have at least one neighbour with another color, ...\". The first sentence describes isolated pixels."
}
] |
[
{
"body": "<p>You are making the test <code>!Indexs.Contains(Index)</code>. Since <code>Indexs</code> is a <code>List<int></code> you have a look up time of <code>O(n)</code>. A <code>HashSet<T></code> has an approximate look up time of <code>O(1)</code>. Create a hash set for this test. Since a set is not ordered, you still need the list.</p>\n\n<pre><code>var Indexs = new List<int>();\nvar indexTest = new HashSet<int>();\n\nIndexs.Add(0);\nindexTest.Add(0);\n</code></pre>\n\n<p>and</p>\n\n<pre><code>int i = GetPreference(BorderPixels[LastIndex], Possible.ToArray(), BorderPixels);\nIndexs.Add(i);\nindexTest.Add(i);\n</code></pre>\n\n<p>and of course now test with</p>\n\n<pre><code>if (!indexTest.Contains(Index))\n</code></pre>\n\n<ul>\n<li><p>Another point is the repeated indexed access of border pixels. Store the pixels in a temp. This also makes the code more readable.</p></li>\n<li><p>You can merge all the if-statements into one conditional expression. Because of the <a href=\"https://www.c-sharpcorner.com/article/short-circuit-evaluation-in-c-sharp/\" rel=\"nofollow noreferrer\">Short-Circuit Evaluation In C#</a>, the evaluation will stop at the first term evaluating to <code>true</code>.</p></li>\n<li><p>You have duplicated some cases. You have 12 instead of 8. Reordering the conditions in a logical way makes it easier: x-1, x, x+1 combined with y-1, y, y+1.</p></li>\n<li><p>The Boolean temp <code>Working</code> can be inlined.</p></li>\n<li><p>You can initialize collections in the constructor or with collection initializers.</p></li>\n<li><p>The <a href=\"https://github.com/ktaranov/naming-convention/blob/master/C%23%20Coding%20Standards%20and%20Naming%20Conventions.md\" rel=\"nofollow noreferrer\">C# naming conventions</a> use camelCase for parameter names and local variables.</p></li>\n<li><p>Since neither <code>data</code> nor <code>borderPixels</code> are altered, copying <code>data</code> into <code>borderPixels</code> seems superfluous. I simply renamed <code>data</code> to <code>borderPixels</code>. This change requires the type of the last parameter of <code>GetPreference</code> to be changed from <code>List<Vector2F></code> to <code>Vector2F[]</code> and <code>borderPixels.Count</code> must be changed to <code>borderPixels.Length</code>.</p></li>\n<li><p>If you change the type of the corresponding parameter in <code>GetPreference</code>, the conversion of the <code>possible</code> list to array is not necessary. Since the collection is not altered in <code>GetPreference</code>, we don't need to make this copy. Note that <code>IList<T></code> is compatible to <code>List<T></code> as well as to <code>T[]</code>.</p></li>\n</ul>\n\n<p>The new <code>ReorderBorder</code> method:</p>\n\n<pre><code>private Vector2F[] ReorderBorder(Vector2F[] borderPixels)\n{\n var indexes = new List<int> { 0 };\n var indexTest = new HashSet<int> { 0 };\n\n while (indexes.Count < borderPixels.Length) {\n int lastIndex = indexes.Last();\n Vector2F last = borderPixels[lastIndex];\n\n var possible = new List<int>();\n for (int index = 0; index < borderPixels.Length; index++) {\n if (!indexTest.Contains(index)) {\n Vector2F current = borderPixels[index];\n if (new Vector2F(last.X - 1, last.Y - 1) == current ||\n new Vector2F(last.X - 1, last.Y) == current ||\n new Vector2F(last.X - 1, last.Y + 1) == current ||\n new Vector2F(last.X, last.Y - 1) == current ||\n new Vector2F(last.X, last.Y + 1) == current ||\n new Vector2F(last.X + 1, last.Y - 1) == current ||\n new Vector2F(last.X + 1, last.Y) == current ||\n new Vector2F(last.X + 1, last.Y + 1) == current)\n {\n possible.Add(index);\n }\n }\n }\n\n int preferredIndex = GetPreference(last, possible, borderPixels);\n indexes.Add(preferredIndex);\n indexTest.Add(preferredIndex);\n }\n\n var vertices = new List<Vector2F>();\n for (int index = 0; index < indexes.Count; index++) {\n vertices.Add(borderPixels[indexes[index]]);\n }\n\n return vertices.ToArray();\n}\n</code></pre>\n\n<hr>\n\n<p>Now, to the <code>GetPreference</code> method.</p>\n\n<ul>\n<li><p>We can apply the C# naming conventions.</p></li>\n<li><p>If we change the type of the <code>inidces</code> and <code>borderPixels</code> parameters to <code>IList<T></code>, we will be able to pass arrays or lists. The caller gains some flexibility.</p></li>\n<li><p>The <code>indicesTest</code> array must store two integers but is of <code>Vector2F[]</code> type based on <code>float</code>. We could use a <a href=\"https://blogs.msdn.microsoft.com/mazhou/2017/05/26/c-7-series-part-1-value-tuples/\" rel=\"nofollow noreferrer\">ValueTuple</a> (since C# 7.0) here. If you don't want this, at least use a vector type based on <code>int</code>. I will be using an array of <code>(int index, int relativity)</code>. I rename it to <code>relativeIndices</code>.</p></li>\n<li><p>Instead of describing the relativity numbers in a comment, we can make them constants. This eliminates <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic numbers</a>.</p></li>\n<li><p>We can store the double index lookup <code>borderPixels[Indices[Index]]</code> in temps.</p></li>\n</ul>\n\n\n\n<pre><code>private int GetPreference(Vector2F origin, IList<int> indices, IList<Vector2F> borderPixels)\n{\n /* Relativity */ const int Up = 0, UpRight = 1, Right = 2, DownRight = 3, \n Down = 4, DownLeft = 5, Left = 6, UpLeft = 7;\n\n if (indices.Count == 1) return indices[0];\n\n var relativeIndices = new (int index, int relativity)[indices.Count];\n for (int index = 0; index < indices.Count; index++) {\n int pixelIndex = indices[index];\n Vector2F pixel = borderPixels[pixelIndex];\n if (new Vector2F(origin.X, origin.Y - 1) == pixel)\n relativeIndices[index] = (index: pixelIndex, relativity: Up);\n else if (new Vector2F(origin.X + 1, origin.Y - 1) == pixel)\n relativeIndices[index] = (index: pixelIndex, relativity: UpRight);\n else if (new Vector2F(origin.X + 1, origin.Y) == pixel)\n relativeIndices[index] = (index: pixelIndex, relativity: Right);\n else if (new Vector2F(origin.X + 1, origin.Y + 1) == pixel)\n relativeIndices[index] = (index: pixelIndex, relativity: DownRight);\n else if (new Vector2F(origin.X, origin.Y + 1) == pixel)\n relativeIndices[index] = (index: pixelIndex, relativity: Down);\n else if (new Vector2F(origin.X - 1, origin.Y + 1) == pixel)\n relativeIndices[index] = (index: pixelIndex, relativity: DownLeft);\n else if (new Vector2F(origin.X - 1, origin.Y) == pixel)\n relativeIndices[index] = (index: pixelIndex, relativity: Left);\n else if (new Vector2F(origin.X - 1, origin.Y - 1) == pixel)\n relativeIndices[index] = (index: pixelIndex, relativity: UpLeft);\n }\n\n if (relativeIndices.Length > 0) {\n Array.Sort(relativeIndices, CompareRelativity);\n return relativeIndices[0].index;\n }\n return 0;\n}\n</code></pre>\n\n<ul>\n<li>We must adapt the <code>CompareY</code> method to the new type of the array. I rename it to <code>CompareRelativity</code> and flatten the if-statements. There is no need for else-statements, since we return.</li>\n</ul>\n\n\n\n<pre><code>private int CompareRelativity(\n (int index, int relativity) left,\n (int index, int relativity) right)\n{\n if (left.relativity < right.relativity) return -1;\n if (left.relativity == right.relativity) return 0;\n return 1;\n}\n</code></pre>\n\n<p>I did not question the algorithm. Since your now deleted picture shows borders all over the place, a simple sorting might not be the right approach for finding the preferred pixel.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T00:16:19.127",
"Id": "227135",
"ParentId": "227130",
"Score": "7"
}
},
{
"body": "<h2>DRY Principle</h2>\n\n<p>As a small addendum on Olivier Jacot-Descombes' answer, I would like to add you should go for DRY code.</p>\n\n<p>answer snippet: </p>\n\n<blockquote>\n <p><em>\"You have duplicated some cases. You have 12 instead of 8. Reordering the conditions in a logical way makes it easier: x-1, x, x+1 combined\n with y-1, y, y+1.\"</em></p>\n</blockquote>\n\n<p>This..</p>\n\n<pre><code>var current = BorderPixels[Index];\nvar last = BorderPixels[LastIndex];\nif (Math.Abs(current.X - last.X) <= 1 && Math.Abs(current.Y - last.Y) <= 1)\n{\n Possible.Add(Index);\n}\n</code></pre>\n\n<p>replaces..</p>\n\n<blockquote>\n<pre><code>if (new Vector2F(BorderPixels[LastIndex].X + 1, BorderPixels[LastIndex].Y) == BorderPixels[Index])\n Possible.Add(Index);\nelse if (new Vector2F(BorderPixels[LastIndex].X + 1, BorderPixels[LastIndex].Y + 1) == BorderPixels[Index])\n Possible.Add(Index);\nelse if (new Vector2F(BorderPixels[LastIndex].X + 1, BorderPixels[LastIndex].Y - 1) == BorderPixels[Index])\n Possible.Add(Index);\nelse if (new Vector2F(BorderPixels[LastIndex].X, BorderPixels[LastIndex].Y + 1) == BorderPixels[Index])\n Possible.Add(Index);\nelse if (new Vector2F(BorderPixels[LastIndex].X - 1, BorderPixels[LastIndex].Y + 1) == BorderPixels[Index])\n Possible.Add(Index);\nelse if (new Vector2F(BorderPixels[LastIndex].X + 1, BorderPixels[LastIndex].Y + 1) == BorderPixels[Index])\n Possible.Add(Index);\nelse if (new Vector2F(BorderPixels[LastIndex].X - 1, BorderPixels[LastIndex].Y) == BorderPixels[Index])\n Possible.Add(Index);\nelse if (new Vector2F(BorderPixels[LastIndex].X - 1, BorderPixels[LastIndex].Y + 1) == BorderPixels[Index])\n Possible.Add(Index);\nelse if (new Vector2F(BorderPixels[LastIndex].X - 1, BorderPixels[LastIndex].Y - 1) == BorderPixels[Index])\n Possible.Add(Index);\nelse if (new Vector2F(BorderPixels[LastIndex].X, BorderPixels[LastIndex].Y - 1) == BorderPixels[Index])\n Possible.Add(Index);\nelse if (new Vector2F(BorderPixels[LastIndex].X - 1, BorderPixels[LastIndex].Y - 1) == BorderPixels[Index])\n Possible.Add(Index);\nelse if (new Vector2F(BorderPixels[LastIndex].X + 1, BorderPixels[LastIndex].Y - 1) == BorderPixels[Index])\n Possible.Add(Index);\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T15:28:41.483",
"Id": "442112",
"Score": "0",
"body": "@Olivier Jacot-Descombes It doesn't matter, my point is how to refactor that redundant part to DRY code. If the original code was incorrect, my rewrite would also be."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T05:41:14.767",
"Id": "227150",
"ParentId": "227130",
"Score": "5"
}
},
{
"body": "<p><strong>Use enums</strong> When in the below snippet each index really means what the numbers stand for in the comments then you definitely need at least an <code>enum</code> for that. This is so extremely fragile. Without these comments nobody ever would be able to decipher this logic.</p>\n\n<blockquote>\n<pre><code>///Relativity\n/// 0 - Up\n/// 1 - Up Right\n/// 2 - Right\n/// 3 - Down Right\n/// 4 - Down\n/// 5 - Down Left\n/// 6 - Left\n/// 7 - Up Left\nfor (int Index = 0; Index < Indices.Length; Index++)\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T06:13:41.457",
"Id": "227152",
"ParentId": "227130",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "227135",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T22:37:36.030",
"Id": "227130",
"Score": "6",
"Tags": [
"c#",
"coordinate-system"
],
"Title": "Ordering 2D Border Points"
}
|
227130
|
<p>This is the piece of code I'd like to refactor. Basically, when the credit card option is selected, then do I want the credit card number, zip code, and Cvv inputs to be validated. </p>
<pre><code>validateForm=(e)=> {
Array.from(inputElements).forEach(element=> {
let value=element.value;
let input=element;
if (input===name) {
errorMessage(isValidName, input, value, e)
} else if (element===email) {
errorMessage(isValidEmail, input, value, e);
} else if (element===creditNumber) {
if (creditOptionChecked()) {
errorMessage(isValidCreditCard, input, value, e);
}
} else if (element===zip) {
if (creditOptionChecked()) {
errorMessage(isValidZipCode, input, value, e);
}
} else if (element===cvv) {
if (creditOptionChecked()) {
errorMessage(isValidCvv, input, value, e);
}
} else if (element==fieldSetActivity) {
validateCheckboxes(e)
}
});
}
form.addEventListener('submit', (e)=> {
validateForm(e)
console.log("hello")
})
</code></pre>
<p>I've been at this for a couple hours, but I'm still a bit new to be able to implement something that is modular. Here is a link to my JS fiddle, so you can see the rest of the javascript code: <a href="https://jsfiddle.net/apasric4/4xfL9utv/2/" rel="nofollow noreferrer">https://jsfiddle.net/apasric4/4xfL9utv/2/</a></p>
|
[] |
[
{
"body": "<h2>Incomplete code</h2>\n\n<p>Your question's code is missing so much information there is not much to review.</p>\n\n<p>Because of this I can only review the code in regard to exactly the logic your function performs. </p>\n\n<h2>Style points</h2>\n\n<ul>\n<li><p>Don't add code that is not needed. Eg </p>\n\n<ul>\n<li><p>The variable <code>input</code> is a copy of <code>element</code> having two names for the same reference will lead to confusion, mistakes and bugs.</p></li>\n<li><p>You add a function to form submit, and all it does is call validateForm. Set the listener to <code>validateForm</code> eg <code>form.addEventListener('submit', validateForm)</code> and avoid the middle man.</p></li>\n</ul></li>\n<li><p>Good code does not repeat AKA is DRY (Don't Repeat Yourself). </p>\n\n<p>Examples of repeated code;</p>\n\n<ul>\n<li><p>You call <code>errorMessage</code>, with the same 3 last arguments five times. Create a function and just pass the first argument, let the function call <code>errorMessage</code> with the rest of the arguments.</p></li>\n<li><p>You repeat the same statement <code>if (creditOptionChecked()) {</code> three times. Again hand the repetitive source code to a function..</p></li>\n</ul></li>\n<li><p>Variables that do not change and/or should not change should be declared as constants. eg <code>const value = element.value;</code> rather than <code>let value = element.value;</code></p></li>\n<li><p><code>Array.from</code> requires an array like argument. Array like arguments are all iterable thus you do not need to create an array before you iterate. The line <code>Array.from(inputElements).forEach(element=> {</code> can be written as <code>inputElements.forEach(element => {</code> or <code>for (const element of inputElements) {</code></p>\n\n<p>Array iterators (example <code>Array.forEach</code>) are not as efficient as <code>for</code> or <code>while</code> loops. Using <code>for</code> or <code>while</code> loops when you can also gives you a better sense of the code complexity, while using a little less memory and power.</p></li>\n</ul>\n\n<h2>Example</h2>\n\n<p>Rewriting your function to be compatible with the original under all possible unknown states using the above points.</p>\n\n<pre><code>form.addEventListener(\"submit\", e => {\n var input;\n const error = valid => errorMessage(valid, input, input.value, e);\n const optError = valid => creditOptionChecked() && error(valid);\n for (input of inputElements) {\n if (input === name) { error(isValidName) }\n else if (input === email) { error(isValidEmail) }\n else if (input === creditNumber) { optError(isValidCreditCard) }\n else if (input === zip) { optError(isValidZipCode) }\n else if (input === cvv) { optError(isValidCvv) }\n else if (input == fieldSetActivity) { validateCheckboxes(e) }\n }\n});\n</code></pre>\n\n<p>There are some improvements that can be made depending on the unknowns, maybe needing no <code>if</code> statements at all, but I likely waste both of our times if I speculate.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T22:28:32.293",
"Id": "227240",
"ParentId": "227131",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T22:53:50.887",
"Id": "227131",
"Score": "2",
"Tags": [
"javascript",
"validation"
],
"Title": "Conditional validation for credit card payment information on form submission"
}
|
227131
|
<p>In my project I have a header file which contains only functions which are put into a namespace, the purpose of these functions is to be used from another class of the framework I'm working on, or from client code. </p>
<p>Does this code follow best practices? How can I efficiently just keep such data?</p>
<pre><code>#pragma once
#include <iomanip>
#include <sstream>
#include <chrono>
#include <ctime>
namespace lwlog::datetime
{
std::string get_chrono(std::string format)
{
auto now = std::chrono::system_clock::now();
auto in_time_t = std::chrono::system_clock::to_time_t(now);
std::stringstream ss;
ss << std::put_time(std::localtime(&in_time_t), format.c_str());
return ss.str();
}
std::string get_time() { return get_chrono("%H:%M:%S"); }
std::string get_date() { return get_chrono("%Y-%m-%d"); }
std::string get_date_short() { return get_chrono("%m/%d/%y"); }
std::string get_second() { return get_chrono("%S"); }
std::string get_minute() { return get_chrono("%M"); }
std::string get_hour_24() { return get_chrono("%H"); }
std::string get_hour_12() { return get_chrono("%I"); }
std::string get_weekday() { return get_chrono("%A"); }
std::string get_weekday_abbreviated() { return get_chrono("%a"); }
std::string get_day() { return get_chrono("%d"); }
std::string get_month() { return get_chrono("%m"); }
std::string get_month_name() { return get_chrono("%B"); }
std::string get_month_name_abbreviated() { return get_chrono("%b"); }
std::string get_year() { return get_chrono("%Y"); }
std::string get_year_short() { return get_chrono("%y"); }
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T01:16:02.740",
"Id": "441835",
"Score": "0",
"body": "Have you tried including this header from multiple sources? I suspect that it wouldn't link. `get_chrono` is not a template function, so you'd be double-defining it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T01:17:18.570",
"Id": "441836",
"Score": "0",
"body": "Refer to https://stackoverflow.com/questions/25274312/defining-c-functions-inside-header-files/25274371"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T07:14:14.200",
"Id": "441881",
"Score": "0",
"body": "I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T07:16:33.170",
"Id": "441882",
"Score": "0",
"body": "Are functions like `get_minute()` and `get_second()` of actual use to any code? I've never seen a need for getting single components from a timepoint, without needing one or more other components from the same timepoint (rather than from some future timepont)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T07:28:13.797",
"Id": "441892",
"Score": "0",
"body": "Yes they are needed for a logging framework pattern formatter"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T07:38:25.330",
"Id": "441893",
"Score": "0",
"body": "I fixed the title - since that's not strictly about getting time, it's about the more abstract picture - is it okay to have a header file for globally accessing functions"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T07:50:29.277",
"Id": "441897",
"Score": "0",
"body": "I still don't understand: what use is the \"second\" value without the \"minute\" value?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T07:51:45.280",
"Id": "441898",
"Score": "0",
"body": "Code Review is *never* about the \"abstract picture\" - we specifically ask for *real code, in context*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T08:11:12.590",
"Id": "441901",
"Score": "0",
"body": "I'm well informed, and that's why I have posted a snippet of code which I'm interested in, yet I don't want to give out the impression it's strictly regarded about time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T08:12:05.470",
"Id": "441902",
"Score": "0",
"body": "I need a second because one can use a minute and second in their pattern, or just output time in a more specific way."
}
] |
[
{
"body": "<p>There are many useless functions here, because individual time components aren't much use separately. For example, <code>get_second()</code> is unlikely to be any use to anyone, as users generally want the minutes, too. It won't work to separately call <code>get_minute()</code>, because that returns the \"minute\" component of a <em>different time-point</em> (that of the second call). So the API presented is likely to encourage user errors.</p>\n\n<p>I advise removing all the functions that return individual components.</p>\n\n<p>There exist single formats for time and date - use <code>%T</code> instead of <code>%H:%M:%S</code>, and <code>%F</code> instead of <code>%Y-%m-%d</code>. (Note that <code>%D</code> superficially appears like it might be the short date formate, but it's broken because it puts month first).</p>\n\n<p>If we're to use this for logging, then <code>std::localtime</code> is a poor choice, as this has jumps and ambiguities around daylight savings changes. <code>std::gmtime</code> is more suitable for this purpose, as it's monotonic on a well-administered system.</p>\n\n<p>Oh, and you'll need your functions to have <em>static linkage</em>, so you don't get conflicts when two or more translation units both define the functions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T08:49:20.967",
"Id": "227161",
"ParentId": "227132",
"Score": "2"
}
},
{
"body": "<ul>\n<li><p>As noted by commenters, you will get multiple definition errors if you try to include this header in multiple translation units. The functions must be marked <code>inline</code>, or the header file reduced to the declarations, with the definitions placed in a separate source file.</p></li>\n<li><p>The <code>std::string format</code> argument is copied unnecessarily as it is passed by value. It should be passed by <code>const&</code> instead. (Or replaced with <code>std::string_view</code>).</p></li>\n<li><p>The difference between all these functions is the format string. As such, we don't really need the functions at all. We can define the format strings as constants, and the user can pass the one they need to <code>get_chrono</code>.</p></li>\n<li><p><code>get_chrono</code> is probably not the best name for the function. Maybe <code>format_time_now</code>, or <code>format_time</code>.</p></li>\n<li><p>The function would be much less restrictive if the time were passed as an argument. It can then be used for formatting other times than <code>now</code>.</p></li>\n<li><p>Note also that in the original code, if we wanted to call <code>get_second</code> and <code>get_minute</code> for one point in time (say for some custom output format), we can't! Because <code>now</code> will have changed between the calls, and we might end up with incorrect output.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T09:02:38.887",
"Id": "441905",
"Score": "0",
"body": "How can this problem with now be tackled?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T09:09:52.623",
"Id": "441907",
"Score": "0",
"body": "The user should call `now` themselves and store the time in a local variable, and then they can pass it as an argument to the function as many times as they like."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T08:57:40.073",
"Id": "227162",
"ParentId": "227132",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T23:49:00.630",
"Id": "227132",
"Score": "1",
"Tags": [
"c++",
"design-patterns"
],
"Title": "Header file for accessing components globally in library"
}
|
227132
|
<p>I was wondering about the possibility to create an implementation of <code>IList<T></code> that is faster than <code>List<T></code> using C#, or at least faster at adding elements.<br>
I thought to try to write out one using a technique similar to the binary tree that just came up to my mind. Basically, each item is a pointer to a block of memory (let me call it <em>entry</em>) containing three more pointers:</p>
<ol>
<li>A pointer to the item</li>
<li>A pointer to the previous entry</li>
<li>A pointer to the next entry</li>
</ol>
<p>Here's my implementation, which is not complete yet, though:</p>
<pre><code>public class FastList<T> : IList<T>
{
private static readonly int sPtrSize = IntPtr.Size;
private static readonly int sItemSize = sPtrSize * 3;
private static readonly int sItemOffset = 0;
private static readonly int sPreviousOffset = sItemSize - (sPtrSize << 1);
private static readonly int sNextOffset = sItemSize - sPtrSize;
private static IntPtr CreateItem() => Marshal.AllocHGlobal(sItemSize);
private static GCHandle GetItemHandle(IntPtr ptr)
{
IntPtr itemPtr = Marshal.ReadIntPtr(ptr, sItemOffset);
return GCHandle.FromIntPtr(itemPtr);
}
private static void DeleteItem(IntPtr item)
{
GetItemHandle(item).Free();
Marshal.FreeHGlobal(item);
}
private static T GetItem(IntPtr ptr)
{
GCHandle handle = GetItemHandle(ptr);
return (T)handle.Target;
}
private static void SetItem(IntPtr ptr, T item)
{
GCHandle handle = GCHandle.Alloc(item, GCHandleType.Pinned);
IntPtr itemPtr = GCHandle.ToIntPtr(handle);
Marshal.WriteIntPtr(ptr, sItemOffset, itemPtr);
}
private static IntPtr GetPrevious(IntPtr ptr) => Marshal.ReadIntPtr(ptr, sPreviousOffset);
private static void SetPrevious(IntPtr ptr, IntPtr previous) => Marshal.WriteIntPtr(ptr, sPreviousOffset, previous);
private static IntPtr GetNext(IntPtr ptr) => Marshal.ReadIntPtr(ptr, sNextOffset);
private static void SetNext(IntPtr ptr, IntPtr next) => Marshal.WriteIntPtr(ptr, sNextOffset, next);
private class Enumerator : IEnumerator<T>
{
private readonly FastList<T> mList;
private int mPosition = -1;
private IntPtr mCurrent = IntPtr.Zero;
public Enumerator(FastList<T> list) => mList = list;
public T Current => GetItem(mCurrent);
object IEnumerator.Current => Current;
public bool MoveNext()
{
if (++mPosition >= mList.Count)
return false;
if (mCurrent == IntPtr.Zero)
{
mCurrent = mList.mStart;
return mList.Count != 0;
}
mCurrent = GetNext(mCurrent);
return mCurrent != IntPtr.Zero;
}
public void Reset() => mCurrent = mList.mStart;
public void Dispose()
{
}
}
private readonly IntPtr mStart = CreateItem();
private IntPtr mEnd;
public FastList()
{
SetNext(mStart, IntPtr.Zero);
mEnd = mStart;
}
~FastList() => DeleteItem(mStart);
public T this[int index]
{
get => GetItem(FindItem(index));
set => SetItem(FindItem(index), value);
}
public int Count
{
get;
private set;
}
public bool IsReadOnly
{
get;
} = false;
private IntPtr FindItem(int index)
{
int count = Count;
IntPtr item;
if (index < count >> 1)
{
item = mStart;
for (; index != -1 && (item = GetNext(item)) != IntPtr.Zero; index--) ;
}
else
{
item = mEnd;
index = count - index;
for (; index != -1 && (item = GetPrevious(item)) != IntPtr.Zero; index--) ;
}
return item;
}
public void Add(T item)
{
SetItem(mEnd, item);
IntPtr previous = mEnd;
mEnd = CreateItem();
SetPrevious(mEnd, previous);
SetNext(mEnd, IntPtr.Zero);
SetNext(previous, mEnd);
Count++;
}
public void Clear()
{
SetNext(mStart, IntPtr.Zero);
for (IntPtr item = mStart; (item = GetNext(item)) != IntPtr.Zero;)
DeleteItem(item);
Count = 0;
}
private void RemoveItem(IntPtr item)
{
IntPtr previous = GetPrevious(item);
IntPtr next = GetNext(item);
SetNext(previous, next);
SetPrevious(next, previous);
DeleteItem(item);
}
public bool Contains(T item) => IndexOf(item) != -1;
public void CopyTo(T[] array, int arrayIndex) => throw new NotImplementedException();
public int IndexOf(T item) => throw new NotImplementedException();
public void Insert(int index, T item)
{
IntPtr next = FindItem(index);
IntPtr previous = GetPrevious(next);
IntPtr itemPtr = CreateItem();
SetItem(itemPtr, item);
SetPrevious(itemPtr, previous);
SetNext(itemPtr, next);
SetPrevious(next, itemPtr);
SetNext(previous, itemPtr);
}
public bool Remove(T item) => throw new NotImplementedException();
public void RemoveAt(int index) => RemoveItem(FindItem(index));
public IEnumerator<T> GetEnumerator() => new Enumerator(this);
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
</code></pre>
<p>Unfortunately, however, it turns out that it is roughly 10 times slower than <code>List<T></code>. I couldn't still understand why.<br>
Could someone, please, tell me why it results so slow and suggest me how can I speed this up?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T00:23:46.223",
"Id": "441830",
"Score": "5",
"body": "Can you be more specific about where (what operations) it is slower with?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T04:34:04.390",
"Id": "441843",
"Score": "2",
"body": "_create an implementation of IList<T> that is faster than List<T>_ faster for lookup or manipulation of items?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T04:54:34.123",
"Id": "441846",
"Score": "7",
"body": "This is ironic, `FastList` is slower than `List` :-) How did you measure and compare them?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T07:38:26.530",
"Id": "441894",
"Score": "2",
"body": "SortedList is a built in list using a red black tree under the hood, https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.sortedset-1?redirectedfrom=MSDN&view=netframework-4.8"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T07:50:23.117",
"Id": "441896",
"Score": "0",
"body": "Sorry, my above comment should be SortedSet not SortedList"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T09:35:12.630",
"Id": "441911",
"Score": "1",
"body": "@t3chb0t, of course, FastList<T> is named after my purpose, even if I couldn't fulfill it yet. Regarding measurements, I used the System.Diagnostics.Stopwatch to perform measurements with different count of items to add to both FastList<T> and List<T> and I've taken the average of those measurements for either my list and the standard one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T11:04:29.880",
"Id": "441925",
"Score": "3",
"body": "On a more fundamental level, before you attempt to create \"something like X, but faster\", you should make sure you can answer these questions: 1) How does X work? 2) What does my thing do differently? 3) Why is that a faster way? Implicit in these questions is that you have some knowledge of what kind of code is fast in a modern computer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T12:30:21.167",
"Id": "441943",
"Score": "1",
"body": "Indeed, @Sebastian Redl, I'm aware how List<T> works in every detail, and I opted to use unmanaged memory instead of arrays, so I don't have to resize them (it would be slow as it is impossible to resize arrays, and so you'll end up allocating a brand new array and copy the data from the previous one to the latter). Rather, I have just to allocate more memory and update the next pointer of the previous entry to one that points out to this one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T12:31:59.883",
"Id": "441944",
"Score": "0",
"body": "Also, @Sebastian Redl, my method IS faster, the problem is, how it is to be implemented in C#, being it an interpreted language whose memory is fully managed by CLR, so that every attempt to work at a lower level would inevitably slow down the memory access. Talk to inexpert people, not those ones who know almost everything about CLR and how .NET languages work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T12:42:21.733",
"Id": "441948",
"Score": "1",
"body": "\"my method IS faster\" - For what? Appends? Inserts in the middle? Access? Iteration? The answer is actually *none of them*, unless your lists are quite large. Random pointer chasing is just that slow compared to simple sequential memory like `List` uses."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T12:50:35.620",
"Id": "441949",
"Score": "0",
"body": "This time you're right, @Sebastian Redl. I should have specified. My method is faster at adding elements. Operations that have to do with indexes will result way slower. But at adding elements it is faster for sure!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T13:16:45.487",
"Id": "441956",
"Score": "1",
"body": "@1201ProgramAlarm, it is slower both at adding elements and iterating through them. Not sure about everything else, as I just tested those two operations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T15:34:23.650",
"Id": "441978",
"Score": "0",
"body": "`List<T>.Add` is already as fast as it can possibly be, as it's basically just doing `_array[_count] = item; _count++;`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T15:42:38.057",
"Id": "441982",
"Score": "1",
"body": "You're allocating memory in `Add` so it's no surprise it's slower than `List<T>.Add` which has no allocation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T15:52:23.470",
"Id": "441985",
"Score": "1",
"body": "@Flavien, you're absolutely wrong. The step you're pointing out to is not the whole thing. If the array is too small to get a new element added, then it will be created a new, larger array; then the whole previous array will be copied into the newer one, and finally the item will be added to the newer array, which will replace the older one. Also, it's not even so simple: the actual List<T> implementation does something more I can't actually recall that would be needed if all elements are too many to be stored in any array. It does alot of things, though. It's not nearly as simple as you state"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T16:04:21.157",
"Id": "441987",
"Score": "2",
"body": "*(1)* The reallocation of the array is rare as the array doubles in size every time, so if you add 1000 items to a list, there will only be 8 memory allocations - versus 1000 in your case. *(2)* It can be avoided (or mitigated) most of the time by setting the capacity to a sensible value at creation, especially in performance critical code. *(3)* The reallocation is a single allocation and block copy and will be only maginally slower than the allocation you do in your `Add` on *every single call*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T16:20:15.623",
"Id": "441989",
"Score": "0",
"body": "I know, @Flavien. But List<T> memory allocations also require the previous array to be copied into the newer one. So, if, as you said, you have a List<T> and you add 1000 items to that, there are 8 memory allocations and 8 times that the list if fully iterated and copied: 1) 4 items being copied; 2) 8 items being copied; 3) 16 items being copied; and so on. Finally, you'll have copied 1020 items, which is even more than the number of items itself!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T16:25:52.387",
"Id": "441990",
"Score": "1",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/98090/discussion-between-davide-cannizzo-and-flavien)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T16:32:17.440",
"Id": "441991",
"Score": "1",
"body": "That's not how the copy is done. Iterating the list would be terribly slow and would cause allocations. It's done using a block copy which is a native operation and will copy the entire array in (more or less) one CPU operation. The size of the array being copied practically doesn't matter. It will be almost as fast copying 10,000 items as copying 10 items. And certainly many orders of magnitude faster than iterating the array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T16:45:07.663",
"Id": "441994",
"Score": "0",
"body": "Block copy has anyway its overhead. An efficient way (of course, mine isn't) that avoids copying arrays would be much faster!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T07:50:59.737",
"Id": "442327",
"Score": "0",
"body": "I guess the biggest improvement is going to be in your iterations when using unsafe as you can eliminate bounds checking."
}
] |
[
{
"body": "<p>This is called a doubly linked list. <code>List<T></code> is basically a wrapper around an array. The only operations where you can hope to be faster are insertions and deletions from the middle of the list.</p>\n\n<hr>\n\n<p>Using <code>Marshal</code> unless you absolutely have to is a bad idea, if not a plain crazy one. This code has memory leaks (how is that destructor meant to release all of the memory allocated for the list? See also the next subsection). And because you're fighting the GC and the JIT, you can't expect high performance.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public void Clear()\n {\n SetNext(mStart, IntPtr.Zero);\n for (IntPtr item = mStart; (item = GetNext(item)) != IntPtr.Zero;)\n DeleteItem(item);\n Count = 0;\n }\n</code></pre>\n</blockquote>\n\n<p>Expand that <code>for</code> as a <code>while</code> and see whether you can spot the problems:</p>\n\n<pre><code> SetNext(mStart, IntPtr.Zero);\n IntPtr item = mStart;\n while ((item = GetNext(item)) != IntPtr.Zero)\n DeleteItem(item);\n</code></pre>\n\n<blockquote class=\"spoiler\">\n <p> 1. <code>SetNext(mStart, IntPtr.Zero)</code> guarantees that the loop body never executes.<br>\n 2. <code>DeleteItem(item)</code> before <code>GetNext(item)</code> is a use-after-free bug. </p>\n</blockquote>\n\n<hr>\n\n<p>I can't figure out whether <code>mStart</code> is a sentinel or an actual element of the list. It seems to do both in different places. Comments!</p>\n\n<hr>\n\n<p>What happens if I modify the list while iterating through it with the enumerator? Is this desirable?</p>\n\n<hr>\n\n<p>I can't think of any good reason to implement <code>IList<T></code> and not also implement <code>IReadOnlyList<T></code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T07:42:26.343",
"Id": "227157",
"ParentId": "227134",
"Score": "20"
}
},
{
"body": "<p>You've essentially built a doubly-linked list that also performs its own memory management.</p>\n\n<p>Regarding linked lists:</p>\n\n<ul>\n<li>This makes indexing is an <span class=\"math-container\">\\$O(n)\\$</span> operation, compared to <span class=\"math-container\">\\$O(1)\\$</span> for <code>List<T></code>. Searching from the end for indexes beyond the center helps, but it does not fundamentally change this performance characteristic.</li>\n<li>Adding is an <span class=\"math-container\">\\$O(1)\\$</span> operation, similar to <code>List<T></code> (which is <span class=\"math-container\">\\$O(1)\\$</span> on average).</li>\n<li>Inserting and removing-at can also be <span class=\"math-container\">\\$O(1)\\$</span>, but only if you provide the right API (for an example, see <code>LinkedList<T></code>'s <code>AddAfter/Before/First/Last</code> methods). Your current implementation is <span class=\"math-container\">\\$O(n)\\$</span>, similar to <code>List<T></code>.</li>\n<li>Like <code>List<T></code>, iterating is <span class=\"math-container\">\\$O(n)\\$</span>, but having to follow a chain of pointers will make it slower than <code>List<T></code>, which stores its items in a contiguous block of memory. Pointer-chasing is also less cache-friendly.</li>\n</ul>\n\n<hr>\n\n<p>Regarding custom memory management, GCHandles allow you to access managed objects from unmanaged code, but you don't have any unmanaged code here. This only introduces problems:</p>\n\n<ul>\n<li>It limits your list to only types that do not contain reference fields (<code>Add</code> will throw an <code>ArgumentException</code> (Object contains non-primitive or non-blittable data.) for all but the most basic types).</li>\n<li>It involves extra allocations, which take additional time and memory.</li>\n<li>It introduces the risk of leaking memory/handles.</li>\n<li>Pinning objects can make the garbage collector less efficient - it'll hinder memory compaction.</li>\n<li>Unexpected program terminations.</li>\n</ul>\n\n<p>Creating a small <code>LinkedListNode<T></code> class instead would be a much better idea.</p>\n\n<hr>\n\n<p>There are also other problems with your code:</p>\n\n<ul>\n<li>Indexing is broken: <code>list[0]</code> returns the second item, while the first item is located at <code>list[-1]</code>... and around the center, a higher index might actually give you an earlier item.</li>\n<li>There's no bounds-checking: <code>list[-2]</code> and <code>list[list.Count + 2]</code> result in an <code>AccessViolationException</code> (if you're lucky) rather than an <code>OutOfRangeException</code>.</li>\n<li><code>RemoveAt</code> seems to be implemented, but it fails with an <code>InvalidOperationException</code> (if it doesn't cause the program to terminate instead).</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T08:08:14.673",
"Id": "441900",
"Score": "2",
"body": "Also a LinkedListNode can be pooled (externally offcourse, just like the built in LinkedList) and result in zero strain on the GC which is important in real time systems."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T07:59:01.733",
"Id": "227159",
"ParentId": "227134",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "227157",
"CommentCount": "21",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T00:03:50.907",
"Id": "227134",
"Score": "10",
"Tags": [
"c#",
"performance",
"linked-list",
"collections"
],
"Title": "IList<T> implementation"
}
|
227134
|
<p>I'm wondering what I could do to improve the function that handles initializing the UI. I think it looks disgusting. Any ideas on what I could do besides splitting the code up into multiple functions to make it look better?</p>
<pre><code>def init_ui(window, root_dir):
window.title('ACFA Save Editor')
tk.Label(window, text='Pilot name: ').grid(row=0)
tk.Label(window, text='AC name: ').grid(row=1)
tk.Label(window, text='COAM (money): ').grid(row=2)
tk.Label(window, text='FRS Memory: ').grid(row=3)
e_p_name = tk.Entry(window)
e_p_name.grid(row=0, column=1)
e_ac_name = tk.Entry(window)
e_ac_name.grid(row=1, column=1)
e_coam = tk.Entry(window)
e_coam.grid(row=2, column=1)
e_frs_memory = tk.Entry(window)
e_frs_memory.grid(row=3, column=1)
messagebox.showinfo('Open Save Folder', 'Ex: GAMEDATXXXX')
directory = askdirectory(initialdir=root_dir)
APGD = directory + '/APGD.dat'
GAMEDAT = directory + '/' + directory.split('/')[-1] + '_CONTENT'
p, a, c, f = read_data(APGD)
e_p_name.insert(0, p)
e_ac_name.insert(0, a)
e_coam.insert(0, c)
e_frs_memory.insert(0, f)
b_apply = tk.Button(window, text='Apply', width=10, command=lambda:
apply(e_p_name.get(), e_ac_name.get(), e_coam.get(),
e_frs_memory.get(),
APGD, GAMEDAT)).grid(row=4, column=0)
b_quit = tk.Button(window, text='Quit', width=10,
command=window.destroy).grid(row=4, column=1)
return window
</code></pre>
<p>The rest of the code can be found <a href="https://github.com/Confettimaker/AC-For-Answer-Save-Editor" rel="nofollow noreferrer">here</a>.</p>
|
[] |
[
{
"body": "<p>It depends what direction you want to go with your program, but my suggestion would be to make small factories for components you use the most often. Here it seems you are building a common UI feature: a form with several fields. Since you only have a single form you don't really benefit from abstracting the form for now, except for clarity, but you benefit from abstracting the fields as you use 4 of them.</p>\n\n<p>So this code separates better generic UI components and data although it's not perfect; but UI code rarely is. Since you usually only have a handfew windows in the average app it's often OK to hardcode some values and components. It's a matter of making compromises between genericity, features, and verbosity.</p>\n\n<p>(Disclaimer: I haven't tested it, please let me know if it needs fixing)</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class FormField:\n def __init__(self, window, row, label, placeholder=None):\n tk.Label(window, text=label).grid(row=row)\n self.entry = tk.Entry(window)\n self.entry.grid(row, column=1)\n if placeholder:\n self.entry.insert(0, placeholder)\n\n def get(self):\n return self.entry.get()\n\nclass Form:\n def __init__ (self, window, row, field_keywords, callback, button_text):\n self.fields = []\n for i, field_keyword in enumerate(field_keywords):\n self.fields.append(window, row=row + i, **field_keyword)\n self.callback = callback\n # This '10' is hardcoded, but you could compute it from button_text length\n b_apply = tk.Button(window, text=button_text, width=10, command=self.submit))\n\n def submit(self):\n self.callback(*[field.get() for field in self.fields])\n\ndef init_ui(window, root_dir):\n # Below is code that is tricky to make any more generic and can be left as is\n # Making UI abstractions for single use components can be complexity you don't need\n window.title('ACFA Save Editor')\n messagebox.showinfo('Open Save Folder', 'Ex: GAMEDATXXXX')\n directory = askdirectory(initialdir=root_dir)\n APGD = directory + '/APGD.dat'\n GAMEDAT = directory + '/' + directory.split('/')[-1] + '_CONTENT'\n p, a, c, f = read_data(APGD)\n fields_kws = [{'label':'Pilot name: ', 'placeholder':p},\n {'label':'AC name: ', 'placeholder':a},\n {'label':'COAM (money): ', 'placeholder':c},\n {'label':'FRS Memory: ', 'placeholder':f}]\n ui_form = Form(window, 1, field_kws, lambda p, a, c, f: apply(p, a, c, f, APGD, GAMEDAT), 'Apply')\n\n b_quit = tk.Button(window, text='Quit', width=10, \n command=window.destroy).grid(row=4, column=1)\n return window\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T17:11:59.347",
"Id": "442127",
"Score": "0",
"body": "I’ll be able to test this code out tomorrow, thanks for answering."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T18:22:23.450",
"Id": "227190",
"ParentId": "227142",
"Score": "2"
}
},
{
"body": "<p>Loops are your friend. Much of your function can be replaced with:</p>\n\n<pre><code>\n for row, (name, data) in enumerate(zip((\n 'Pilot name',\n 'AC name',\n 'COAM (money)',\n 'FRS Memory'\n ), read_data(APGD))):\n tk.Label(window, text=f'{name}: ').grid(row=row)\n e = tk.Entry(window)\n e.grid(row=row, column=1)\n e.insert(0, data)\n</code></pre>\n\n<p>I'm unable to test this, so YMMV.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T17:11:09.990",
"Id": "442126",
"Score": "0",
"body": "I’ll have some time to test this code out tomorrow and then I’ll go from there, thanks for your answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T18:53:27.597",
"Id": "227192",
"ParentId": "227142",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227192",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T03:22:50.787",
"Id": "227142",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"tkinter",
"user-interface"
],
"Title": "UI code for save editor"
}
|
227142
|
<p>I am writing a function to decode a string, which means performing a string transformation like <code>3e4f2e</code> --> <code>eeeffffee</code>.</p>
<p>I have two versions of codes which are very similar but slightly different. In version1,</p>
<pre><code>def decoding(s):
res = []
curr = 0
curr_val = 0
while curr < len(s):
if not s[curr].isdigit():
res.append(curr_val * s[curr])
curr_val = 0
else:
curr_val = curr_val * 10 + int(s[curr])
curr += 1
return ''.join(res)
</code></pre>
<p>I keep in track of <code>curr_val</code> and keep accumulating the value until I see a non-digit string. </p>
<p>In version2, I keep in track of the first position of the digit string and slice the string just to represent the digit string.</p>
<pre><code>def decoding(s):
digit_start, res = 0, []
curr = 0
while curr < len(s):
if not s[curr].isdigit():
res.append(int(s[digit_start:curr]) * s[curr])
digit_start = curr + 1
curr += 1
return ''.join(res)
</code></pre>
<p>I just keep in track of the right index and multiply the <code>int</code> of that string with the current non-digit string (e.g. <code>10a --> aaaaaaaaaa</code>)</p>
<p>I wonder if the first version has a way better time complexity or if they have the same time complexity in big-O. I assumed that both of them are <span class="math-container">\$O(n)\$</span> where <span class="math-container">\$n\$</span> is the length of the input string, but I wonder if slicing inside a loop would significantly increase the time-complexity of the code.</p>
<p>Please note that this is an interview practice, so I care about time-complexity, not the real-world style.</p>
|
[] |
[
{
"body": "<p>They both look like they are <span class=\"math-container\">\\$O(n)\\$</span>.</p>\n\n<p>A quick check with timeit show they both take essentially the same amount of time, and the time grows linearly with the length of the input string.</p>\n\n<p>It would be better to iterate over the characters in the string rather use an explicit index over the length of the string (<code>while curr < len(s)</code> is often a smell).</p>\n\n<pre><code>def decoding(s):\n result = []\n repeat = 0\n\n for c in s:\n if c.isdigit():\n repeat = 10 * repeat + int(c)\n\n else:\n result.append(repeat * c)\n repeat = 0\n\n return ''.join(result)\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>def decoding(s):\n result = []\n prev_index = 0\n\n for index,c in enumerate(s):\n if not c.isdigit():\n result.append(int(s[prev_index:index]) * c)\n prev_index = index + 1\n\n return ''.join(result)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T06:46:36.160",
"Id": "441875",
"Score": "0",
"body": "Doesn't slicing take O(j - i) in `S[i:j]`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T20:22:23.470",
"Id": "442010",
"Score": "0",
"body": "@Dawn17, yes it does. However, in the worst case each character gets handled twice (e.g. consider a string that has an enormous number of digits and then one letter). O(2n) is still O(n)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T06:43:57.190",
"Id": "227155",
"ParentId": "227147",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "227155",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T05:16:42.973",
"Id": "227147",
"Score": "3",
"Tags": [
"python",
"interview-questions",
"comparative-review"
],
"Title": "Comparing algorithms to decode a String"
}
|
227147
|
<p>I am fairly new to C++ and have been trying to make a doubly-linked-list class that imitates std::list (though not all of it). I'd appreciate if someone can look at my code and let me know if I have missed anything important, and if everything seems to be implemented correctly.</p>
<p>Note:the end node is implemented as one past the last element.</p>
<p>Here is the interface:</p>
<pre><code>#ifndef my_list_h
#define my_list_h
#include <cstdlib>
// forward declarations
template<class T> class my_list;
template<class Value,class Pointer,class Reference> class
my_bidirectional_iterator;
template<class T> class my_list_iterator;
template<class T> class my_list_const_iterator;
template<class T> class node {
node(const T& t = T()):data(t),next(0),prev(0) {}
T data;
node* next;
node* prev;
friend class my_list<T>;
friend class my_bidirectional_iterator<node<T>,T*,T&>;
friend class my_bidirectional_iterator<node<T>,const T*,const T&>;
};
template<class Value,class Pointer,class Reference> class my_bidirectional_iterator {
public:
// increment and decrement operators
my_bidirectional_iterator operator++();
my_bidirectional_iterator operator++(int);
my_bidirectional_iterator operator--();
my_bidirectional_iterator operator--(int);
// bool comparison iterators
bool operator==(const my_bidirectional_iterator& other) const {return pos_==other.pos_;}
bool operator!=(const my_bidirectional_iterator& other) const {return pos_!=other.pos_;}
// member access
Reference operator*() const {return pos_->data;}
Pointer operator->() const {return &(pos_->data);}
private:
explicit my_bidirectional_iterator(Value* p=0):pos_(p) {}
Value* pos_;
template<class U> friend class my_list_iterator;
template<class U> friend class my_const_list_iterator;
template<class U> friend class my_list;
};
template<class T> class my_list_iterator: public my_bidirectional_iterator<node<T>,T*,T&> {
using my_bidirectional_iterator<node<T>,T*,T&>::my_bidirectional_iterator;
friend class my_list_const_iterator<T>;
public:
operator my_list_const_iterator<T>() {return my_list_const_iterator<T>(this->pos_);}
};
template<class T> class my_list_const_iterator: public my_bidirectional_iterator<node<T>,const T*,const T&>
{
friend class my_list_iterator<T>;
using my_bidirectional_iterator<node<T>,const T*,const T&>::my_bidirectional_iterator;
};
template<class T> class my_list {
public:
typedef my_list_iterator<T> iterator;
typedef my_list_const_iterator<T> const_iterator;
typedef T value_type;
typedef std::size_t size_type;
// constructors
my_list() {create();}
explicit my_list(size_type n,const T& t=T()) {create(n,t);}
// copy constructor
my_list(const my_list& rhs) {create(rhs.begin(),rhs.end());}
// assignment operator
my_list& operator=(const my_list&);
// destructor
~my_list() {clear();}
// element access
T& front() {return head_->data;}
const T& front() const {return head_->data;}
T& back() {return tail_->prev->data;}
const T& back() const {return tail_->prev->data;}
// iterators
iterator begin() {return iterator(head_);}
const_iterator begin() const {return const_iterator(head_);}
iterator end() {return iterator(tail_);}
const_iterator end() const {return const_iterator(tail_);}
// capacity
bool size() const {return size_;}
bool empty() const {return size_==0;}
// modifiers
void clear();
iterator insert(iterator,const T&);
iterator erase(iterator);
void push_back(const T& t) {insert(end(),t);}
void push_front(const T& t) {insert(begin(),t);}
void pop_back() {erase(iterator(tail_->prev));}
void pop_front() {erase(iterator(head_));}
void resize(size_type);
private:
node<T> *head_,*tail_;
size_type size_;
void create();
void create(size_type, const T& t = T());
void create(const_iterator,const_iterator);
void insertInternal(node<T>*,const T&);
friend class my_list_iterator<T>;
friend class my_list_const_iterator<T>;
};
#include "my_list.hpp"
#endif
</code></pre>
<p>And the implementation:</p>
<pre><code>template<class Value,class Pointer,class Reference>
my_bidirectional_iterator<Value,Pointer,Reference> my_bidirectional_iterator<Value,Pointer,Reference>::operator++()
{
pos_ = pos_->next;
return *this;
}
template<class Value,class Pointer,class Reference>
my_bidirectional_iterator<Value,Pointer,Reference>
my_bidirectional_iterator<Value,Pointer,Reference>::operator++(int)
{
Value* prev= pos_;
pos_ = pos_->next;
return my_bidirectional_iterator(prev);
}
template<class Value,class Pointer,class Reference>
my_bidirectional_iterator<Value,Pointer,Reference>
my_bidirectional_iterator<Value,Pointer,Reference>::operator--()
{
pos_ = pos_->prev;
return *this;
}
template<class Value,class Pointer,class Reference>
my_bidirectional_iterator<Value,Pointer,Reference>
my_bidirectional_iterator<Value,Pointer,Reference>::operator--(int)
{
Value* next= pos_;
pos_ = pos_->prev;
return my_bidirectional_iterator(next);
}
template<class T> my_list<T>& my_list<T>::operator=(const my_list& rhs)
{
if (this!=&rhs)
{
clear();
create(rhs.begin(),rhs.end());
}
return *this;
}
template<class T> void my_list<T>::clear()
{
if (size_!=0)
{
node<T>* first = head_;
while (first!=0)
{
node<T>* next = first->next;
delete first;
first = next;
}
}
head_=tail_=0;
size_=0;
}
template<class T> typename my_list<T>::iterator
my_list<T>::insert(iterator pos,const T& t)
{
// create new node holding the value t
node<T>* new_node = new node<T>(t);
// pointer to node before which t is inserted
// if node doesn't exist make it on the fly
node<T>* p = (pos.pos_)?(pos.pos_):(new node<T>());
// make sure new_node is before p
new_node->next = p;
if (p->prev){
new_node->prev = p->prev;
new_node->prev->next = new_node;
} else
head_ = new_node;
p->prev = new_node;
// make sure that tail_ is set properly if we started with empty list
if (size_==0)
tail_ = p;
// increase size
++size_;
// return iterator pointng to new node
return iterator(new_node);
}
template<class T> typename my_list<T>::iterator my_list<T>::erase(iterator pos)
{
node<T> *p = pos.pos_;
if (p->next!=0)
p->next->prev = p->prev;
else
tail_ = p->prev;
if (p->prev!=0)
p->prev->next = p->next;
else
head_ = p->next;
node<T>* n = p->next;
delete p;
--size_;
return iterator(n);
}
template<class T> void my_list<T>::resize(size_type n)
{
while (n<size_)
pop_back();
while (n>size)
push_back(T());
}
template<class T> void my_list<T>::create()
{
head_=tail_=0;
size_ = 0;
}
template<class T> void my_list<T>::create(size_type n,const T& t)
{
create();
for (size_type i=0;i!=n;++i)
push_back(t);
}
template<class T> void my_list<T>::create(const_iterator b,const_iterator e)
{
create();
while (b!=e)
push_back(*b++);
}
</code></pre>
<p>I am using GCC 8.3.0 which, if I checked correctly, implements C++14 by default. In any case, I tried compiling with <code>-std=c++11</code> and it compiles fine.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T09:44:27.603",
"Id": "441912",
"Score": "2",
"body": "Which standard of C++ are you using? Is it C++17?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T09:55:11.977",
"Id": "441914",
"Score": "0",
"body": "Also, it would be nice if you add some test cases so we can verify."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T11:19:03.527",
"Id": "441934",
"Score": "0",
"body": "@ L.F. I am using GCC 8.3.0 which, if I checked correctly, implements C++14 by default. In any case, I tried compiling with -std=c++11 and it compiles fine. This probably seems like a dumb question, but how can I find good test cases?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T11:42:36.093",
"Id": "441937",
"Score": "3",
"body": "That's not a dumb question. In fact, finding good test cases is extremely nontrivial. First of all, make sure all members appear in the test. (This should help you find some typos like `bool size()`.) And always test for edge cases (zero, min/max value, even/odd numbers, etc.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T16:02:10.213",
"Id": "441986",
"Score": "1",
"body": "Welcome to Code Review! Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 8 → 5"
}
] |
[
{
"body": "<p>(Note: Martin York posted an answer when this answer is halfway done. The already written part will be left as is, but I try to avoid duplicating content after that. Make sure you read that answer as well!)</p>\n\n<h1>General</h1>\n\n<p>These are general suggestions:</p>\n\n<ol>\n<li><p>First of all, please write the declaration of a template class on two lines and use more spaces — rather than:</p>\n\n<pre><code>template<class T> class my_list;\n</code></pre>\n\n<p>this is more readble:</p>\n\n<pre><code>template <class T>\nclass my_list;\n</code></pre></li>\n<li><p><code>public:</code> and <code>private:</code> labels usually go one indentation level left, e.g.:</p>\n\n<pre><code>template <class T>\nclass my_list {\n using Foo = T*;\npublic:\n Foo foo();\nprivate:\n Foo bar();\n};\n</code></pre></li>\n<li><p>Do not use <code>0</code> as a null pointer constant. Use <code>nullptr</code> instead. See <a href=\"https://stackoverflow.com/q/1282295\">What exactly is nullptr?</a>.</p></li>\n<li><p>Use alias-declarations rather than <code>typedef</code>. For example, instead of</p>\n\n<pre><code>typedef my_list_iterator<T> iterator;\ntypedef my_list_const_iterator<T> const_iterator;\ntypedef T value_type;\ntypedef std::size_t size_type;\n</code></pre>\n\n<p>we prefer</p>\n\n<pre><code>using iterator = my_list_iterator<T>;\nusing const_iterator = my_list_const_iterator<T>;\nusing value_type = T;\nusing size_type = std::size_t;\n</code></pre>\n\n<p>in modern C++. They are <a href=\"https://stackoverflow.com/q/10747810\">semantically equivalent</a>, but the second form is more readable, especially with complex types (e.g., <code>typedef void (&MyFunc)(int,int);</code> vs. <code>using MyFunc = void(&)(int,int);</code>).</p></li>\n<li><p>Don't squash everything together like this:</p>\n\n<pre><code>my_list(const my_list& rhs) {create(rhs.begin(),rhs.end());}\n</code></pre>\n\n<p>At least use spaces:</p>\n\n<pre><code>my_list(const my_list& rhs) { create(rhs.begin(), rhs.end()); }\n</code></pre>\n\n<p>If I were you, I would probably make it even more readable:</p>\n\n<pre><code>my_list(const my_list& rhs)\n{\n create(rhs.begin(), rhs.end());\n}\n</code></pre></li>\n<li><p>I'm pretty sure the functionality you want to expose is <code>my_list</code> — all the rest is implementation detail and should not be accessed directly. You can put everything in a namespace and use a conventional \"detail\" namespace:</p>\n\n<pre><code>// replace \"unicorn9378\" with your own name for the namespace\nnamespace unicorn9378 {\n\n namespace detail {\n // implementation detail\n }\n\n // public interface\n\n}\n</code></pre>\n\n<p>and then drop <code>my_</code> because \"me\" can be anyone. Namespaces will help you with ADL (argument dependent lookup), so don't hesitate to use them even for small projects.</p></li>\n<li><p>Since you are trying to imitate the standard <code>std::list</code>, there is some missing functionality. I suggest that you check against a <a href=\"https://en.cppreference.com/w/cpp/container/list\" rel=\"nofollow noreferrer\">reference</a>. Some features are nontrivial to implement (e.g., allocator support) but some of them really should be implemented (e.g., move operations).</p></li>\n</ol>\n\n<h1>Code</h1>\n\n<p>So let's go through the code and find something else to improve:</p>\n\n<hr>\n\n<blockquote>\n<pre><code>#ifndef my_list_h\n#define my_list_h\n</code></pre>\n</blockquote>\n\n<p>Macros are usually ALL_CAPS — use <code>MY_LIST_H</code>. Also, this name is short and will cause name clash. My solution is to add a <a href=\"https://www.random.org/strings/?num=1&len=10&digits=on&upperalpha=on&loweralpha=on\" rel=\"nofollow noreferrer\">random string</a> after it — for example, <code>MY_LIST_H_RwxhY7ucBR</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>#include <cstdlib>\n</code></pre>\n</blockquote>\n\n<p>If you include this header for <code>std::size_t</code>, use <code>#include <cstddef></code> instead. It is much cheaper and everyone knows that <code><cstddef></code> defines <code>std::size_t</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>// forward declarations\ntemplate<class T> class my_list;\ntemplate<class Value,class Pointer,class Reference> class \nmy_bidirectional_iterator;\ntemplate<class T> class my_list_iterator;\ntemplate<class T> class my_list_const_iterator;\n</code></pre>\n</blockquote>\n\n<p>This really hurts my eyes. As I mentioned before, use spaces and newlines.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>template<class T> class node {\n node(const T& t = T()):data(t),next(0),prev(0) {}\n T data;\n node* next;\n node* prev;\n\n friend class my_list<T>;\n friend class my_bidirectional_iterator<node<T>,T*,T&>;\n friend class my_bidirectional_iterator<node<T>,const T*,const T&>;\n};\n</code></pre>\n</blockquote>\n\n<p>Rather than making everything private and friend everyone, just make things public — this is already implementation detail, after all. The constructor is unnecessary and introduces an unneeded copy — just leave it out. Like this:</p>\n\n<pre><code>template <class T>\nstruct node {\n T data;\n node* next{nullptr};\n node* prev{nullptr};\n};\n</code></pre>\n\n<p>Then this class will be an <a href=\"https://stackoverflow.com/q/4178175\">aggregate</a> and you will be using <a href=\"https://en.cppreference.com/w/cpp/language/aggregate_initialization\" rel=\"nofollow noreferrer\">aggregate initialization</a> to create nodes like this:</p>\n\n<pre><code>node<T>{value, next_ptr, prev_ptr}\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>template<class Value,class Pointer,class Reference> class my_bidirectional_iterator {\n public:\n // increment and decrement operators\n my_bidirectional_iterator operator++();\n my_bidirectional_iterator operator++(int);\n my_bidirectional_iterator operator--();\n my_bidirectional_iterator operator--(int);\n\n // bool comparison iterators\n bool operator==(const my_bidirectional_iterator& other) const {return pos_==other.pos_;}\n bool operator!=(const my_bidirectional_iterator& other) const {return pos_!=other.pos_;}\n\n // member access\n Reference operator*() const {return pos_->data;}\n Pointer operator->() const {return &(pos_->data);}\n\n private:\n explicit my_bidirectional_iterator(Value* p=0):pos_(p) {}\n Value* pos_;\n template<class U> friend class my_list_iterator;\n template<class U> friend class my_const_list_iterator;\n template<class U> friend class my_list;\n};\n\ntemplate<class T> class my_list_iterator: public my_bidirectional_iterator<node<T>,T*,T&> {\n using my_bidirectional_iterator<node<T>,T*,T&>::my_bidirectional_iterator;\n friend class my_list_const_iterator<T>;\n public:\n operator my_list_const_iterator<T>() {return my_list_const_iterator<T>(this->pos_);}\n};\n\ntemplate<class T> class my_list_const_iterator: public my_bidirectional_iterator<node<T>,const T*,const T&>\n{\n friend class my_list_iterator<T>;\n using my_bidirectional_iterator<node<T>,const T*,const T&>::my_bidirectional_iterator;\n};\n</code></pre>\n</blockquote>\n\n<p>Prefix <code>++</code> and <code>--</code> should return a <em>reference</em> to <code>*this</code>.</p>\n\n<p>I don't really think you need the <code>bidirectional_iterator</code> class — just implement the two iterator types separately, there isn't very much boilerplate code. If you insist to reduce duplicate code by extracting the common part into a base class, things will quickly get complicated — you need to use the CRTP (curiously recurring template pattern). You will have to pass the derived classes as a template parameter to the base class for the base class to return the correct types.</p>\n\n<p>Also, you forgot the required types: <code>value_type</code>, <code>iterator_category</code>, etc. You can either supply them directly in the iterator classes:</p>\n\n<pre><code>template <class T>\nclass list_iterator {\npublic:\n using value_type = T;\n using reference = T&;\n using pointer = T*;\n using difference_type = std::ptrdiff_t;\n using iterator_category = std::bidirectional_iterator_tag;\n\n explicit list_iterator(node<T>* p = nullptr)\n :pos{p}\n {\n }\n\n list_iterator& operator++();\n list_iterator& operator--();\n list_iterator operator++(int);\n list_iterator operator--(int);\n\n bool operator==(const my_bidirectional_iterator& other) const\n {\n return pos == other.pos;\n }\n bool operator!=(const my_bidirectional_iterator& other) const\n {\n return pos != other.pos;\n }\n\n reference operator*() const\n {\n return pos->data;\n }\n pointer operator->() const\n {\n return &pos->data;\n }\n\nprivate:\n node<T>* pos;\n};\n\n// list_const_iterator similar\n</code></pre>\n\n<p>or you can specialize <code>std::iterator_traits</code>. Note that this is a requirement of an <a href=\"https://en.cppreference.com/w/cpp/named_req/Iterator\" rel=\"nofollow noreferrer\">iterator</a>; if you don't implement these types, yours does not qualify as a real \"iterator\" and it will be undefined behavior to use it with the, say, standard algorithms. </p>\n\n<p>(<code>iterator_category</code> is one of <code>input_iterator_tag</code>, <code>output_iterator_tag</code>, <code>forward_iterator_tag</code>, <code>bidirectional_iterator_tag</code>, and <code>random_access_iterator_tag</code>, and represents the iterator category of the iterator. The algorithms can usually provide better performance for more advanced iterators, and this information is not easily available otherwise. For example, <code>lower_bound</code> will perform much better on random access iterators.)</p>\n\n<hr>\n\n<blockquote>\n<pre><code>typedef my_list_iterator<T> iterator;\ntypedef my_list_const_iterator<T> const_iterator;\ntypedef T value_type;\ntypedef std::size_t size_type;\n</code></pre>\n</blockquote>\n\n<p>Missing some of them.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>// constructors\nmy_list() {create();}\nexplicit my_list(size_type n,const T& t=T()) {create(n,t);}\n</code></pre>\n</blockquote>\n\n<p>The <code>create</code> function is a bit unidiomatic in C++. Use member initializers (later) and make the default constructor <code>= default</code>. Also, the size constructor is C++03 style — elements are default constructed (i.e., value initialized) instead of copy constructed from a default constructed element since C++11:</p>\n\n<pre><code>my_list() = default; // requires member initializers\nexplicit my_list(size_type n)\n{\n insert(end(), n); // I'll talk about this later\n}\n</code></pre>\n\n<p>And there are <a href=\"https://en.cppreference.com/w/cpp/container/list/list\" rel=\"nofollow noreferrer\">many more constructors</a>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>// copy constructor\nmy_list(const my_list& rhs) {create(rhs.begin(),rhs.end());}\n// assignment operator\nmy_list& operator=(const my_list&);\n// destructor\n~my_list() {clear();}\n</code></pre>\n</blockquote>\n\n<p>Make a general iterator overload for <code>insert</code>. No need for a special <code>create</code> function.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>// element access\nT& front() {return head_->data;}\nconst T& front() const {return head_->data;}\nT& back() {return tail_->prev->data;}\nconst T& back() const {return tail_->prev->data;}\n</code></pre>\n</blockquote>\n\n<p>Good.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>// iterators\niterator begin() {return iterator(head_);}\nconst_iterator begin() const {return const_iterator(head_);}\niterator end() {return iterator(tail_);}\nconst_iterator end() const {return const_iterator(tail_);}\n</code></pre>\n</blockquote>\n\n<p>Good. Better if you add <code>cbegin</code>, <code>cend</code>, <code>rbegin</code>, etc.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>// capacity\nbool size() const {return size_;}\nbool empty() const {return size_==0;}\n</code></pre>\n</blockquote>\n\n<p>There's a blatant typo here, can you find it?</p>\n\n<hr>\n\n<blockquote>\n<pre><code>// modifiers\nvoid clear();\niterator insert(iterator,const T&);\niterator erase(iterator);\n</code></pre>\n</blockquote>\n\n<p>You are missing a lot of overloads — see <a href=\"https://en.cppreference.com/w/cpp/container/list/insert\" rel=\"nofollow noreferrer\"><code>insert</code></a> and <a href=\"https://en.cppreference.com/w/cpp/container/list/erase\" rel=\"nofollow noreferrer\"><code>erase</code></a>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>void push_back(const T& t) {insert(end(),t);}\nvoid push_front(const T& t) {insert(begin(),t);}\nvoid pop_back() {erase(iterator(tail_->prev));}\nvoid pop_front() {erase(iterator(head_));}\n</code></pre>\n</blockquote>\n\n<p>Good. Also, <code>back</code> before <code>front</code>? A little weird to me.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>void resize(size_type);\n</code></pre>\n</blockquote>\n\n<p>There's another overload <code>resize(n, value)</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>private:\n node<T> *head_,*tail_;\n size_type size_;\n</code></pre>\n</blockquote>\n\n<p><em>Don't declare multiple entities in one declaration like this.</em> It's easy to go wrong, both for the reader and the writer. Declare one entity on one line and use member initializers:</p>\n\n<pre><code>node<T>* head_{nullptr};\nnode<T>* tail_{nullptr};\nsize_type size_{0};\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>void create();\nvoid create(size_type, const T& t = T());\nvoid create(const_iterator,const_iterator);\nvoid insertInternal(node<T>*,const T&);\nfriend class my_list_iterator<T>;\nfriend class my_list_const_iterator<T>;\n</code></pre>\n</blockquote>\n\n<p>As I said before, these <code>create</code> functions do not appear to be necessary — just use <code>insert</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>template<class Value,class Pointer,class Reference> \nmy_bidirectional_iterator<Value,Pointer,Reference> my_bidirectional_iterator<Value,Pointer,Reference>::operator++()\n{\n pos_ = pos_->next;\n return *this;\n}\n</code></pre>\n</blockquote>\n\n<p>As I said before, this should return a reference. Also, use a trailing return type to save some typing. And I would implement it in the class definition directly.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>template<class Value,class Pointer,class Reference> \nmy_bidirectional_iterator<Value,Pointer,Reference> \nmy_bidirectional_iterator<Value,Pointer,Reference>::operator++(int)\n{\n Value* prev= pos_;\n pos_ = pos_->next;\n return my_bidirectional_iterator(prev);\n}\n</code></pre>\n</blockquote>\n\n<p>You can use <code>std::exchange</code> for such things:</p>\n\n<pre><code>template <class T>\nlist_iterator<T>& list_iterator<T>::operator++(int)\n{\n return list_iterator{std::exchange(pos, pos->next)};\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>template<class Value,class Pointer,class Reference> \nmy_bidirectional_iterator<Value,Pointer,Reference> \nmy_bidirectional_iterator<Value,Pointer,Reference>::operator--()\n{\n pos_ = pos_->prev;\n return *this;\n}\n\ntemplate<class Value,class Pointer,class Reference> \nmy_bidirectional_iterator<Value,Pointer,Reference> \nmy_bidirectional_iterator<Value,Pointer,Reference>::operator--(int)\n{\n Value* next= pos_;\n pos_ = pos_->prev;\n return my_bidirectional_iterator(next);\n}\n</code></pre>\n</blockquote>\n\n<p>See above.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>template<class T> my_list<T>& my_list<T>::operator=(const my_list& rhs)\n{\n if (this!=&rhs)\n {\n clear();\n create(rhs.begin(),rhs.end());\n }\n return *this;\n}\n</code></pre>\n</blockquote>\n\n<p>No, no, no. Don't reinvent it. Use the <a href=\"https://stackoverflow.com/q/3279543\">copy and swap idiom</a>:</p>\n\n<pre><code>template <class T>\nlist<T>& list<T>::operator=(list other) // pass by value\n{\n swap(other);\n return *this;\n}\n</code></pre>\n\n<p>(You need to implement <code>swap</code>.)</p>\n\n<hr>\n\n<blockquote>\n<pre><code>template<class T> void my_list<T>::clear()\n{\n if (size_!=0)\n {\n node<T>* first = head_;\n while (first!=0)\n {\n node<T>* next = first->next;\n delete first;\n first = next;\n }\n }\n head_=tail_=0;\n size_=0;\n}\n</code></pre>\n</blockquote>\n\n<p>As Martin York mentioned, the <code>size != 0</code> check is redundant. And you can avoid reimplementing the iterator:</p>\n\n<pre><code>for (auto it = begin(); it != end();)\n delete (it++).pos;\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>(The code for <code>insert</code> and <code>erase</code>)</p>\n</blockquote>\n\n<p>The <code>insert</code> and <code>erase</code> functions are too complex because you have to consider a lot of edge cases. They have bugs, so fix them first. If you redesign the list to use a sentinel, these functions will be simpler.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>template<class T> void my_list<T>::resize(size_type n)\n{\n while (n<size_)\n pop_back();\n while (n>size)\n push_back(T());\n}\n</code></pre>\n</blockquote>\n\n<p><code>size</code> is the name of a function and cannot be compared to a variable of type <code>size_type</code>. Typo?</p>\n\n<h1>Conclusion</h1>\n\n<p>This may seem like a lot of problems, but since you are fairly new to C++, I think this is good enough. I'd say your code is quite nice in general. In the future, remember that you have to instantiate all template functions (including member functions of class templates) to test them because of two-phase lookup, so make sure that every function is included your tests. This should avoid the typo problems. Also, since this is a linked list, an obvious edge case is zero, so test every function on an empty list to see if they work correctly. Good work!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T15:40:43.660",
"Id": "441981",
"Score": "0",
"body": "Wow thanks. I implemented most of the changes but I have a couple of questions:\n1)Why should I use aliases instead of typedef? Is it just a convention or is there a deeper reason?\n2)Will look into the namespace idea. However note this is not to be used as a library, it's more for me to understand better linked lists and to code in C++."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T15:49:15.990",
"Id": "441984",
"Score": "0",
"body": "3)I'm not sure I understand what's the issue with the constructor of node<T>. I need to create a node holding T when I implement push_back anyway. What's the difference with just creating an empty node and then editing the value of data?\n\n4)I don't see why I should implement two classes when I can make a more general template and inherit from both?\n\n5)I didn't use the value_type that's why I didn't implement it. I'm not sure what the iterator_category does. I mean I can sort of imagine but I don't fully understand how it works that's why I left it out..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T02:03:41.243",
"Id": "442035",
"Score": "0",
"body": "@John You are welcome. Re 1) Aliases are preferred to typedef because they are more general (support templates) and they are more easily comprehensible (assignment syntax). [They are equivalent.](https://stackoverflow.com/q/10747810) 2) A namespace can help you avoid name clash, so don't hesitate to use it even in small projects!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T02:05:28.933",
"Id": "442036",
"Score": "0",
"body": "@John 3) You will be using [*aggregate initialization*](https://en.cppreference.com/w/cpp/language/aggregate_initialization). 4) In more complex cases, that's a good idea, but in this case it will cause a ton of conversion problems. If you insist, you need to look up CRTP (curiously recurring template pattern). You need to pass the derived class as a template parameter so that the base class can return the correct type. I'd say that's more work than just implementing them separately :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T02:07:25.763",
"Id": "442037",
"Score": "0",
"body": "@John 5) If you didn't use value_type, other users of the iterator will do. If you don't implement it, your iterator doesn't meet the full requirements of an \"iterator.\" And `iterator_category` see https://en.cppreference.com/w/cpp/iterator#Iterator_categories. I will update my answer to include some of these clarifications :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T14:23:34.127",
"Id": "442106",
"Score": "0",
"body": "I fixed the typo with declaration of `size()`. I have a question about CRTP though. Is this the reason why my compiler throws an error if I do something like `++l.begin();` where `l` is an instance of `my_list(int)`? I should mention I also fixed the pre-increment version of `++` and `--`. The error in question is a conversion error from `my_bidirectional_iterator(int,int&,int&);` to `my_list_iterator(int)`. In general is there a way to add methods to a template class only for specific instances of the type without deriving the whole class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T14:50:17.387",
"Id": "442107",
"Score": "0",
"body": "I meant `l.insert(++l.begin(),4);` throws an error..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T02:57:03.580",
"Id": "442177",
"Score": "0",
"body": "@John Because in your current design, `++` returns the base class, which cannot be automatically converted to the derived class (it doesn't know which derived class)"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T14:19:19.523",
"Id": "227180",
"ParentId": "227148",
"Score": "6"
}
},
{
"body": "<h2>General things</h2>\n\n<p>Please use two lines for template class declarations:</p>\n\n<pre><code>template<class T> class my_list {\n// Do this\ntemplate<class T>\nclass my_list\n{ // In nearly all other cases I am fine with the\n // { being on the same line. But class and function\n // declarations you just need the little bit of extra\n // white space.\n</code></pre>\n\n<p>I worry about you not using braces <code>{}</code> after <code>if/while/for</code> expressions. </p>\n\n<h2>Code Review</h2>\n\n<p>I would make the <code>node</code> class a private member of the list.</p>\n\n<pre><code>template<class T> class node {\n</code></pre>\n\n<p>There is no need to create a globally accessable type that must be maintained if you don't need to. Hide implementation details so they don't need to be maintained. </p>\n\n<hr>\n\n<p>If you put it (<code>node</code>) inside list and also <code>iterator</code> is a class inside list. Then you can simply make <code>node</code> a structure. Then all this friendship becomes redundant.</p>\n\n<pre><code> friend class my_list<T>;\n friend class my_bidirectional_iterator<node<T>,T*,T&>;\n friend class my_bidirectional_iterator<node<T>,const T*,const T&>;\n</code></pre>\n\n<hr>\n\n<p>Pre-(Increment/Decrement) usually return references.</p>\n\n<pre><code> my_bidirectional_iterator operator++();\n my_bidirectional_iterator operator--();\n\n // I would have done this.\n my_bidirectional_iterator& operator++();\n my_bidirectional_iterator& operator--();\n</code></pre>\n\n<hr>\n\n<p>It is a requirement of bi-directional iterators that they are default constructible. </p>\n\n<pre><code> private:\n explicit my_bidirectional_iterator(Value* p=0):pos_(p) {}\n</code></pre>\n\n<p>Making this private and not having a default constructor does not allow this. As this becomes your default constructor.</p>\n\n<hr>\n\n<p>This is old school</p>\n\n<pre><code> typedef my_list_iterator<T> iterator;\n</code></pre>\n\n<p>More modern:</p>\n\n<pre><code> using iterator = my_list_iterator<T>;\n</code></pre>\n\n<hr>\n\n<pre><code> // constructors\n // copy constructor\n // assignment operator\n // destructor\n</code></pre>\n\n<p>No move <code>Move Constructor</code> or <code>Move Assignemtn</code>?</p>\n\n<pre><code> my_list(my_list&& move);\n my_list& operator=(my_list&& move);\n</code></pre>\n\n<hr>\n\n<pre><code> // iterators\n iterator begin();\n iterator end();\n const_iterator begin() const; // These can be marked cost.\n const_iterator end() const; // So they can be used from a const context.\n</code></pre>\n\n<p>There are a couple more you are missing.</p>\n\n<pre><code> // Ability to force const_iterators even in a non const context.\n const_iterator cbegin() const;\n const_iterator cend() const;\n\n // The reverse versions of all the above.\n std::reverse<iterator> rbegin();\n std::reverse<iterator> rend();\n std::reverse<const_iterator> rbegin() const;\n std::reverse<const_iterator> rend() const;\n std::reverse<const_iterator> crbegin() const;\n std::reverse<const_iterator> crend() const;\n</code></pre>\n\n<hr>\n\n<p>Similar to move construction of the list. You should be able to move data into the list.</p>\n\n<pre><code> iterator insert(iterator,T const&);\n iterator insert(iterator,T&&); // The move version.\n // if you are brave you can also try the emplace\n template<typename... Args>\n iterator emplace(Args...&& val);\n</code></pre>\n\n<hr>\n\n<p>Some for <code>push_X()</code> as for insert.</p>\n\n<pre><code> void push_back(const T& t) {insert(end(),t);}\n void push_front(const T& t) {insert(begin(),t);}\n</code></pre>\n\n<hr>\n\n<p>The check for <code>(this!=&rhs)</code> is a false optimization. Its actually a pesimization of the normal path.</p>\n\n<p>First Note. Yes we should handle self assignment. But we should note it is exceedingly rare and barely ever happens. In most normal code this will never happen. So you are effectively making the normal path slightly less effecient.</p>\n\n<pre><code>template<class T> my_list<T>& my_list<T>::operator=(const my_list& rhs)\n{\n if (this!=&rhs)\n {\n clear();\n create(rhs.begin(),rhs.end());\n }\n return *this;\n}\n</code></pre>\n\n<p>This is so common that this is a C++ <code>idiom</code>. It is called the <code>Copy and Swap Idiom</code> (it will turn up when you google it).</p>\n\n<pre><code>my_list<T>& my_list<T>::operator=(my_list const& rhs)\n{\n my_list copy(rhs);\n copy.swap(*this);\n return *this;\n}\n</code></pre>\n\n<p>In this case we always make a copy. Which you have to do anyway in normal circumstances. But there is no branch (so no CPU pipeline stalls) and no expression test. It also defines the copy assignment in terms of the copy constructor so you only need to get that correct.</p>\n\n<hr>\n\n<p>Uneeded test for zero size. It just makes the code more complicated and achieves nothing.</p>\n\n<pre><code>template<class T> void my_list<T>::clear()\n{\n if (size_!=0)\n {\n node<T>* first = head_;\n while (first!=0)\n {\n node<T>* next = first->next;\n delete first;\n first = next;\n }\n }\n head_=tail_=0;\n size_=0;\n}\n</code></pre>\n\n<p>Also you should not use <code>0</code> as a pointer value. Use <code>nullptr</code> it is type safe and makes the code easier to read as you are being explicit about using pointers.</p>\n\n<hr>\n\n<p>Yes there is a bug in this.</p>\n\n<pre><code>my_list<T>::insert(iterator pos,const T& t)\n</code></pre>\n\n<p>There are potentially two calls to <code>new</code> but only one element is added to the list so you are leaking <code>p</code> sometimes.</p>\n\n<p>Also if <code>pos</code> does not have a node is it not the end of the list so you should be adding it to the `tail not the head?</p>\n\n<p>You also need a special case for the empty list.</p>\n\n<hr>\n\n<p>Comment inline</p>\n\n<pre><code>template<class T> typename my_list<T>::iterator my_list<T>::erase(iterator pos)\n{\n node<T> *p = pos.pos_;\n // I suppose it is illegal to erase the end iterator.\n\n if (p->next!=0)\n p->next->prev = p->prev;\n else {\n tail_ = p->prev;\n // Don't we also need to remove the next item from the list.\n tail->next = nullptr\n }\n\n if (p->prev!=0)\n p->prev->next = p->next;\n else\n head_ = p->next;\n // If you delete the last node don't you have to reset tail as well?\n</code></pre>\n\n<hr>\n\n<p>I am not sure I would have a create.</p>\n\n<pre><code>template<class T> void my_list<T>::create()\n{\n head_=tail_=0;\n size_ = 0;\n}\n</code></pre>\n\n<p>I would have a default constructor set these to <code>nullptr</code> and <code>0</code> respectively. Then you can chain the default constructor from the copy/move constructor.</p>\n\n<pre><code> my_list()\n : head(nullptr)\n , tail(nullptr)\n , size(0)\n {}\n\n explicit my_list(size_type n,const T& t=T())\n : my_list()\n {\n resize(n, T);\n }\n\n my_list(const my_list& rhs)\n :mylist()\n {\n for (size_type i=0;i!=n;++i)\n push_back(t);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T02:19:33.473",
"Id": "442038",
"Score": "0",
"body": "I don't really like the idea of making `node`, `iterator`, etc. member classes. I would also implement them as free classes. In particular, this will cause template instantiation problems if you add, say, allocator support."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T03:26:53.320",
"Id": "442041",
"Score": "0",
"body": "@L.F. Can you explain more (maybe a gist) I am not sure why adding allocator support would make private classes would be a problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T03:29:00.700",
"Id": "442042",
"Score": "0",
"body": "For example, list<T, A> and list<T, B> will instantiate two node classes. This can be a problem if you use many different kinds of allocators"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T04:27:18.040",
"Id": "442045",
"Score": "0",
"body": "@L.F. Ahh as you mean you can splice the list together? Hold I don't think that matters. Unless the allocaters are the same you can't splice list (nodes internal or external)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T04:30:24.047",
"Id": "442046",
"Score": "0",
"body": "No, I mean that would cause unnecessary template instantiation. We don't want to instantiate `list<T, A>::node` and `list<T, B>::node` separately."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T05:22:49.497",
"Id": "442048",
"Score": "0",
"body": "@L.F. I don't see how that's a problem. Are you saying that you are worried about the extra code being generated because of it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T05:36:36.183",
"Id": "442049",
"Score": "0",
"body": "Yes, it's not necessary, so why not avoid it :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T14:13:30.390",
"Id": "442105",
"Score": "0",
"body": "The design was so that `tail_` actually models a sentinel node that corresponds to `end()` i.e. one past the last element in the container. In an empty list, there would be no need for sentinel since it has no first element either, otherwise the list would always have at least two elements. In particular note that the `tail_` node has an actual position, but `tail_->next` points to nothing. So the call to `erase()` in that case will actually delete the extra node created when the first element was pushed into the list. I'm not sure how to otherwise model the end of list node effectively..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T15:16:14.830",
"Id": "442108",
"Score": "0",
"body": "@John You should look at this answer I have done previously. https://codereview.stackexchange.com/a/126007/507 (scroll to the bottom) It shows the use of a sentinel in a doubly linked list. The list is circular so the sentinel (is end) and next points to head and head prev points to the head. When the list is empty the sentinel is the only element in the list and links to itself. By doing it this way you remove any need to check for nullptr ever. Note: in my design the sentinel is always there (so part of the class and never dynamically allocated)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T15:17:09.427",
"Id": "442109",
"Score": "0",
"body": "@L.F. Because it makes the design simpler and the amount of extra code generated is insignificant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T15:18:58.247",
"Id": "442110",
"Score": "0",
"body": "@John I will relook at the code now I understand you are using a sentinel. But I belive you have added another mistake because your sentinel is a normal node you are constructing an extra `T` object that you don't need and you are limiting your self to types `T` that can be default constructed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T19:57:19.357",
"Id": "442154",
"Score": "0",
"body": "@Martin the reason I didn't implement cbegin() etc is because I already have implemented an implicit conversion operator from iterator to const_iterator, so I don't see where cbegin() is needed. Is it ever actually used in STL which has a similar conversion?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T21:37:15.380",
"Id": "442164",
"Score": "0",
"body": "@John Actually its `cbegin()` quite important. In a non const context where you want to iterate over the container calling `begin()` returns you a normal iterator. You want to be able to get an explicitly const iterator if you don't plan on mutating the container. You don't need to convert `iterator` to `const_iterator` The definition of is simply `const_iterator cbegin() const {return const_iterator(head_);}`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T23:16:41.193",
"Id": "442166",
"Score": "0",
"body": "I'm not sure I understand. With my code I can currently write `my_list<T>::const_iterator = l.begin()` where `l` is an instance of `my_list`. How is this mutating the container?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T03:01:43.183",
"Id": "442178",
"Score": "0",
"body": "@John `my_list<T>::const_iterator{l.begin()}` is way more verbose than `l.cbegin()`. And if you don't implement `cbegin`, your container does not qualify as a real \"container\" IIRC."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T05:16:16.707",
"Id": "442183",
"Score": "0",
"body": "@John `auto iter = cont.cbegin();` or `my_list<T>::const_iterator iter = cont.begin();` No contest. But **MORE** importantly it conveys contextual information to the reader to tell them you are deliberately only using the const version of the iterator. **AND** its a requirement of containers."
}
],
"meta_data": {
"CommentCount": "16",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T22:54:47.590",
"Id": "227197",
"ParentId": "227148",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T05:25:00.420",
"Id": "227148",
"Score": "8",
"Tags": [
"c++",
"beginner",
"linked-list",
"iterator"
],
"Title": "Doubly-linked-list implementation in C++"
}
|
227148
|
<p>This code yet is not really optimize and I know that . But for now this is all I have.</p>
<p>What this code does is that it computes the expiration date of an account.</p>
<p>By the way I need to do the swapping workaround because the date that the server gives to me are inverted so I need to do a lil workaround about that.</p>
<pre class="lang-cs prettyprint-override"><code>
/// <summary>
/// Add revalidation text and how many days the agents account will expire
/// </summary>
public async void RevalidateAccount()
{
//Get Stored Persistent Data of Date
string _expDateFromPersistent = await SecureStorage.GetAsync("ExpirationDate");
//Check if empty or not
//because if it is empty we need to hide the validation text first
//then show it after relogging in
if (!string.IsNullOrEmpty(_expDateFromPersistent))
{
IsVisibleValidationText = true;
//Convert string date to DateTime
DateTime expDate = Convert.ToDateTime(_expDateFromPersistent);
DateTime todayDate = DateTime.Now;
//Change Format
string _dateToday = todayDate.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);
//Swap workaround
string day = expDate.Day.ToString();
string month = expDate.Month.ToString();
string year = expDate.Year.ToString();
string _expirationDate = year + "/" + day + "/" + month;
//Calculation
TimeSpan expirationDate = DateTime.Parse(_expirationDate) - DateTime.Parse(_dateToday);
//Business Rule: 7 days prior to 30 days show the revalidation text
if (expirationDate.Days <= 7)
{
if (IsVisibleValidationText)
{
//Formatted Text for validation text
Revalidate = new FormattedString();
Revalidate.Spans.Add(new Span { Text = "You have ", ForegroundColor = Color.FromHex(_textColor), FontSize = 15 });
Revalidate.Spans.Add(new Span { Text = $"{expirationDate.Days} days", ForegroundColor = Color.FromHex(_textColor), FontSize = 15, FontAttributes = FontAttributes.Bold });
Revalidate.Spans.Add(new Span { Text = " left before you need \n to re-validate your login credentials.", ForegroundColor = Color.FromHex(_textColor), FontSize = 15 });
await _pageDialogService.DisplayAlertAsync("NOTICE", "You have " + expirationDate.Days + " days left before you need to re-validate your login credentials.", "OK");
}
}
}
else
{
IsVisibleValidationText = false;
}
}
</code></pre>
<p>What my code does is that it gets the data(Expiration Date) from the server then I just need to differ the <code>DateTime.Now</code> and the date(expiration date) from the server to have an expiration date.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T07:26:09.337",
"Id": "441889",
"Score": "2",
"body": "ok, I think the question is fixed now ;-)"
}
] |
[
{
"body": "<p>General naming guidelines suggest that an async method should end its name with \"Async\", so the method name should be <code>RevalidateAccountAsync</code>.</p>\n\n<p>Some would argue that a underscore prefix should never be used for naming of any variables. For those that do allow underscore prefixes, it should only be for class-level variables and never used for variables local to a given method.</p>\n\n<p>When comparing or manipulating 2 <code>DateTime</code> objects, the proper way to do that is to be sure that both have the same <code>Kind</code>. Oddly enough, your code does that since you jump through so many hoops to create new <code>DateTime</code> objects with <code>Kind</code> of <code>Unspecified</code>.</p>\n\n<p><code>expirationDate</code> is a misleading name since it is not a date. It is a <code>TimeSpan</code>.</p>\n\n<p>After checking <code>expirationDate.Days <= 7</code>, there is no need to check <code>IsVisibleValidateText</code> since it will always be true at that point.</p>\n\n<p>Your code looks to be twice as long as it needs to be because of all the manipulation of <code>DateTime</code> and <code>string</code>. For example, to get today's date should only be 1 line:</p>\n\n<p><code>DateTime todayDate = DateTime.Today; \\\\Kind is Local</code></p>\n\n<p><code>expDate</code> could use <code>DateTime.Parse</code> or <code>Convert.ToDateTime</code>. However, you should also set it's Kind because as it is it will be <code>Unspecified</code> unless the string contains any time zone offset. Example setting it to Local:</p>\n\n<p><code>DateTime expDate = DateTime.SpecifyKind(Convert.ToDateTime(_expDateFromPersistent), DateTimeKind.Local);</code></p>\n\n<p>The alternative would be to keep <code>expDate</code> as <code>Unspecified</code> but then make <code>todayDate</code> also <code>Unspecified</code>.</p>\n\n<p><code>DateTime todayDate = DateTime.SpecifyKind(DateTime.Today, DateTimeKind.Unspecified);</code></p>\n\n<p>Since it looks like you are interested in dates starting a midnight, skip the slower string manipulation and instead use the <code>DateTime.Date</code> property. See help at <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.datetime.date?view=netframework-4.8\" rel=\"nofollow noreferrer\">this link</a>. Example:</p>\n\n<p><code>TimeSpan expirationDate = expDate.Date - todayDate;</code></p>\n\n<p>Which gets rid of all the slower and unneeded string variables, both dates above have the same <code>Kind</code>, and both are set to midnight.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T11:25:39.437",
"Id": "227170",
"ParentId": "227151",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T05:50:33.377",
"Id": "227151",
"Score": "4",
"Tags": [
"c#",
"xamarin"
],
"Title": "Calculate expiration date based on server data"
}
|
227151
|
<p>I have a requirement which I posted in SO. However, I have already written code and works fine. I request your review to know whether it is fool proof/elegant and efficient. Please find the details here in SO post <a href="https://stackoverflow.com/questions/57703423/how-to-get-minimum-of-each-group-for-each-day-based-on-hour-criteria">Question in SO</a></p>
<p><strong>my code</strong> </p>
<pre><code>df['time_1']= pd.to_datetime(df['time_1'])
s=pd.to_timedelta(24,unit='h')-(df.time_1-df.time_1.dt.normalize())
df['tdiff'] = df.groupby(df.time_1.dt.date).time_1.diff().shift(-1).fillna(s)
df['t_d'] = df['tdiff'].dt.total_seconds()/3600
df['hr'] = df['time_1'].dt.hour
df['date'] = df['time_1'].dt.date
df['day'] = pd.DatetimeIndex(df['time_1']).day
# here I get the freq and cumsum of each val for each day and each hour.Since sort = 'False', timeorder is retained as is
temp_1 = pd.DataFrame(df.groupby(['subject_id','date','hr','val'], sort=False)['t_d'].agg({'cumduration':sum,'freq':'count'}).reset_index())
# here i remove the `hour` component and sum the value duration in same day but different hours (for example `5` was in 12th hour and 13th hour. we sum them)
temp_2 = pd.DataFrame(temp_1.groupby(['subject_id','date','val'], sort=False)['cumduration'].agg({'sum_of_cumduration':sum,'freq':'count'}).reset_index())
# Later, I create a mask for `> 1` hr criteria
mask = temp_2.groupby(['subject_id','date'])['sum_of_cumduration'].apply(lambda x: x > 1)
output_1 = pd.DataFrame(temp_2[mask].groupby(['subject_id','date'])['val'].min()).reset_index()
# I check for `< 1 ` hr records here
output_2 = pd.DataFrame(temp_2[~mask].groupby(['subject_id','date'])['val'].min()).reset_index()
# I finally check for `subject_id` and `date` and then append
output = output_1.append(output_2[~output_2['subject_id'].isin(output_1['subject_id'])])
output
</code></pre>
<p><a href="https://i.stack.imgur.com/TbANZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TbANZ.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/IjvAC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IjvAC.png" alt="enter image description here"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T09:26:32.897",
"Id": "441908",
"Score": "0",
"body": "Welcome to Code Review! Your indendation seems off in the lines following comments. Could you verify that this code works as posted?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T09:32:59.983",
"Id": "441909",
"Score": "0",
"body": "@AlexV - I fixed the alignment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T09:33:25.273",
"Id": "441910",
"Score": "0",
"body": "I pasted the code from here to jupyter and it works after fixing the alignment"
}
] |
[
{
"body": "<h1>leave the original data intact</h1>\n\n<p>Since <code>df</code> is the original data, adding columns to it can have a strange side effect in another part of the calculation. Best is not to touch the original data, and do all the calculations etc in separate series or copied DataFrames</p>\n\n<h1>pd.grouper</h1>\n\n<p>You can use <code>pd.Grouper</code> to group per day and hour</p>\n\n<p>You can group the date per subject and hour with:</p>\n\n<pre><code>df.groupby([\"subject_id\", pd.Grouper(key=\"time_1\", freq=\"h\"), \"val\"])\n</code></pre>\n\n<p>Then you don't need all those extra columns \"hr\", \"date\" and \"day\" anymore.\nThere is no reason for the column \"t_d\" either. since <code>timedelta</code>'s can be counted, summed etc as well.</p>\n\n<h1>aggregation function</h1>\n\n<p>Apart from that, you can design a specific function to get the requested minimum from one such group.</p>\n\n<p>If you supply it data grouped per subject and date, dropping rows with the same <code>val</code> and checking whether more than 1hr has passed is a lot easier</p>\n\n<pre><code>def day_grouper(group):\n \"\"\"\n Returns the minimum in `val` that lasted more than 1 hour\n \"\"\"\n # drop consecutive same values.\n # The first value is retained because it becomes NaN and `NaN != 0`\n group = group.loc[group[\"val\"].diff() != 0]\n # drop those that take less than 1hr\n more_than_1h = group[\"time_1\"].diff().shift(-1) > pd.Timedelta(\"1h\")\n # Check whether the last value started before 23:00\n more_than_1h.iloc[-1] = group[\"time_1\"].iloc[-1].time() < datetime.time(23)\n return group.loc[more_than_1h, \"val\"].min()\n</code></pre>\n\n<p>This can then be called like this:</p>\n\n<pre><code>(\n df.groupby([\"subject_id\", pd.Grouper(key=\"time_1\", freq=\"d\")])\n .apply(day_grouper)\n .rename(\"val\")\n .reset_index()\n)\n</code></pre>\n\n<p>The 2 last rows are to get the format you want</p>\n\n<h1>code formatting</h1>\n\n<p>Try to follow Pep-8.</p>\n\n<p>£some of your lines are really long, and convention is a space after a comma.</p>\n\n<p>I use <a href=\"https://github.com/psf/black\" rel=\"nofollow noreferrer\">black</a> to format my source code, so I don't have to worry about long lines, spaces, etc any more</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T10:00:36.847",
"Id": "441916",
"Score": "0",
"body": "Thank you. Upvoted. Will incorporate your suggestions. Is my logic foolproof?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T09:40:49.187",
"Id": "227163",
"ParentId": "227156",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "227163",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T07:13:40.107",
"Id": "227156",
"Score": "4",
"Tags": [
"python",
"pandas"
],
"Title": "Get minimum of each group based on hour criteria using pandas"
}
|
227156
|
<p>I've just written some code in an online compiler, and since I'm very new to C#, I wanted to ask what could be improved about the code.</p>
<p>The task of the program is simply to add up the numbers the user entered before and then calculate the average.</p>
<pre class="lang-cs prettyprint-override"><code>public static void Main()
{
int input;
int sum = 0;
bool error = false;
int[] numbers = new int[5];
for(int i = 0; i < numbers.Length; i++)
{
if (!error)
Console.WriteLine("Please write a number:");
if(Int32.TryParse(Console.ReadLine(), out input))
{
numbers[i] = input;
sum += numbers[i];
error = false;
}
else
{
Console.WriteLine("An error occured, please try again:");
error = true;
i--;
continue;
}
}
Console.WriteLine("");
Console.WriteLine("Your typed in values:");
for(int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
Console.WriteLine("");
Console.WriteLine("The result of your numbers:");
Console.WriteLine(sum);
Console.WriteLine("The average of your numbers:");
Console.WriteLine((double)sum / (double)numbers.Length);
}
</code></pre>
<p>The code works fine, but maybe I could do some things more effectively.<br>
Would be glad to get some help :) </p>
<p>Just to sum things up here is the console-output: </p>
<pre><code>Please write a number:
> 4
Please write a number:
> 2
Please write a number:
> a
An error occured, please try again:
> 6
Please write a number:
> 4
Please write a number:
> 8
Your typed in values:
4
2
6
4
8
The sum of your numbers:
24
The average of your numbers:
4.8
</code></pre>
<p><em>('>' = User input)</em></p>
|
[] |
[
{
"body": "<p>The code works, and it seems that you're take care of invalid input. But the logic of the workflow is not - well - that logic.</p>\n\n<blockquote>\n <p><code>int[] numbers = new int[5];</code></p>\n</blockquote>\n\n<p>Here <code>5</code> is a magic number. Why five? Why not four or six or 20?</p>\n\n<p>You should announce the number of input before asking for it (and maybe why).</p>\n\n<p>Alternatively you could let the user enter a number of numbers to be calculated.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>int sum = 0;\n</code></pre>\n</blockquote>\n\n<p>You probably have the <code>sum</code> variable for optimization reasons. Alternatively you could let the built in extension <code>Sum()</code> handle that:</p>\n\n<pre><code>numbers.Sum();\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p><code>if (!error)</code></p>\n</blockquote>\n\n<p>You have this negation of a \"negative\" variable. Why not be positive and call it <code>success</code>:</p>\n\n<pre><code>if (success)\n Console.Write(\"Enter Number: \");\n</code></pre>\n\n<hr>\n\n<p>Instead of: </p>\n\n<blockquote>\n<pre><code> if (Int32.TryParse(Console.ReadLine(), out input))\n {\n numbers[i] = input;\n sum += numbers[i];\n</code></pre>\n</blockquote>\n\n<p>you could write:</p>\n\n<pre><code> success = Int32.TryParse(Console.ReadLine(), out input);\n\n if (success)\n {\n ...\n }\n else\n {\n ...\n }\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> continue;\n</code></pre>\n</blockquote>\n\n<p>I don't see any reason for calling <code>continue</code> in your loop? You use <code>continue</code> to step over the rest of the loop and reenter it - if the condition is still true, but here it is the last expression in the loop, so there is nothing to skip.</p>\n\n<hr>\n\n<p>According to the overall design you should always split your code into meaningful methods in order to accommodate to principles like DRY and Single Responsibility:</p>\n\n<p>For instance:</p>\n\n<pre><code>void Main()\n{\n if (!GetCountOfNumbers(out int numCount))\n return;\n\n if (!GetUserInput(numCount, out int[] numbers, out int sum))\n return;\n\n PrintValues(numbers);\n Console.WriteLine(\"\");\n PrintResult(sum, numbers.Length);\n Console.WriteLine(\"\");\n}\n</code></pre>\n\n<p>Where:</p>\n\n<pre><code>private bool GetCountOfNumbers(out int numCount)\n{\n if (!GetIntInput(\"Enter count of Numbers\", \"Must be a positive number\", x => x > 0, out numCount))\n {\n Console.WriteLine(\"User aborted the calculation\");\n return false;\n }\n\n return true;\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>private bool GetUserInput(int numCount, out int[] numbers, out int sum)\n{\n numbers = new int[numCount];\n sum = 0;\n int input;\n\n for (int i = 0; i < numCount; i++)\n {\n if (!GetIntInput($\"Enter number {i + 1}\", \"Enter any valid integer (32 bit) value\", x => true, out input))\n {\n Console.WriteLine(\"User aborted the calculation\");\n return false;\n }\n\n numbers[i] = input;\n sum += input;\n }\n\n return true;\n}\n</code></pre>\n\n<p>Both methods are calling <code>GetIntInput()</code> which could be defined as follows:</p>\n\n<pre><code>private bool GetIntInput(string message, string errorMessage, Predicate<int> predicate, out int result)\n{\n result = default;\n\n while (true)\n {\n Console.Write($\"{message} ['q' to Exit]: \");\n string input = Console.ReadLine();\n if (input == \"q\" || input == \"Q\")\n return false;\n\n if (int.TryParse(input, out int number) && predicate(number))\n {\n result = number;\n return true;\n }\n Console.WriteLine($\"Invalid input: {errorMessage}\");\n }\n}\n</code></pre>\n\n<p>It takes a message to the user, a predicate to validate the input against and an error message if the predicate returns false on the input, and it returns the result in an <code>out</code> variable (<code>result</code>). Further it allows the user to exit the input loop and then returns true or false accordingly.</p>\n\n<p>In this design everything is counted for through descriptive method names and the logic in the workflow is easily understood and separately maintainable.</p>\n\n<p>It could surely be done in more sophisticated ways, but as a simple user input driven console application like this, the above is a simple way to structure the code properly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T16:44:04.320",
"Id": "227186",
"ParentId": "227172",
"Score": "11"
}
},
{
"body": "<p>In the loop, you're trying to modify the iterator at 2 places. One here <code>for(int i = 0; i < numbers.Length; i++)</code> and the other inside the loop in the else block <code>i--;</code>. Reason I'm not inclined to do that is because not only <code>for</code> is maintaining the status of the iterator but the code as well. The question that needs to be asked is <code>for</code> as a looping construct suited for this problem. This is my take </p>\n\n<pre><code>while (i < 5) {\n Console.WriteLine(\"Please write a number:\");\n if(Int32.TryParse(Console.ReadLine(), out input))\n {\n numbers[i++] = input;\n sum += input;\n }\n else\n {\n Console.WriteLine(\"An error occured, please try again\"); \n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T17:01:36.527",
"Id": "227188",
"ParentId": "227172",
"Score": "6"
}
},
{
"body": "<p>Henkrik's answer is very good. However, there are some things I feel should be addressed as you are a beginner. Some of this answer will address things introduced in his answer.</p>\n\n<p>First, <code>out</code> parameters should generally be avoided. They are used to force the method to initialize them before it returns; essentially, they are are saying \"I have this value, but I need you to update it before you finish running so I can read the updated value.\" Normally you would use a return type for that. In special cases (as in <code>int.TryParse</code>) you need two values, but those are rare, and are mainly for external-facing APIs when you don't want to introduce and maintain a full type for two values to be used in one place. For internal methods, you should consider a tuple type with named members (introduced in C# 7). Having more than 1 <code>out</code> parameter typically is a sign that a more structured response (i.e. a type) is needed.</p>\n\n<p>Henrik is right that you should pull your logic into multiple methods. However, each method should only perform one piece of work. One method, for example, could take input and return an <code>int[]</code>. Then you should have another function for performing the <code>Sum</code> and another the <code>Average</code> of these numbers. Then you can reuse your work. Performance will be slightly less due to calculating <code>Sum</code> twice, but until you hit the scale of millions of numbers, it won't be a serious problem. As an example implementation (using <code>Linq</code>s <code>Sum</code> method):</p>\n\n<pre><code>private int Sum(int[] args)\n{\n return args.Sum();\n}\n\nprivate double Average(int[] args)\n{\n return Sum(args) / args.Length;\n}\n</code></pre>\n\n<p>You can define other methods, such as one to input a single number, one that calls that function several times to input a series of numbers, etc. Then we can call these methods all together and find the data we need.</p>\n\n<p>As mentioned in a comment, I could have used Linq's <code>Average</code> feature: <code>args.Average()</code>. However, I left it with the call to <code>Sum</code> to show how it's good to make functions reusable.</p>\n\n<hr>\n\n<p><code>Console.WriteLine(\"\");</code> doesn't need the argument. If you want just a newline character fed into the output stream, you can do <code>Console.WriteLine()</code>.</p>\n\n<p>If you want output without a trailing newline, you can use <code>Console.Write</code>.</p>\n\n<hr>\n\n<p>In a <code>for</code> loop, you almost never want to step back (<code>i--</code>). I would have used a <code>for</code> loop to get each number, and a <code>while</code> loop within it to get a valid number and keep retrying after invalid numbers were entered. Because you need to run the code at least once, a <code>do/while</code> loop would be a good choice, since it clearly expresses that the loop will run one time before the condition is checked. Something like:</p>\n\n<pre><code>for (var i = 0; i < 5; i++)\n{\n var hasValidInput = false;\n do {\n // read input\n // set hasValidInput\n } while (!hasValidInput);\n}\n</code></pre>\n\n<hr>\n\n<p>What you did right:</p>\n\n<p>You had error handling if the user didn't input a number. That's a common issue for new programmers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T18:08:31.853",
"Id": "441998",
"Score": "1",
"body": "just one remark: http://www.csharp-examples.net/linq-average/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T19:47:36.397",
"Id": "442006",
"Score": "1",
"body": "Isn't your \"`out`-quote\" what a `ref`-parameter would say? A `ref`-parameter is perfect for creating side effects. I would never use an `out`-parameter to update an existing value but only for providing a result from the method. As I understand it, I think your arguments are valid in a functional programming paradigme with pure functions, but not necessarily in a object oriented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T19:49:14.800",
"Id": "442007",
"Score": "1",
"body": "The thing is, `out` is for providing a value--but it's still a side-effect to an existing variable. It's basically a special case of `ref`, like a square is a special case of a rectangle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T20:07:48.103",
"Id": "442008",
"Score": "1",
"body": "Yes, but where a `ref` may or may not be updated, you know that an `out` will always be, so after the method returns you know the variable provided as an `out` parameter is changed (which - admitted - could be to it's existing value) - but you should handle it as changed, hence it acts just as a return value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T21:34:32.517",
"Id": "442028",
"Score": "2",
"body": "You beat me to the punch. My mind immediately jumped to the functions in the Linq namespace."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T18:06:15.577",
"Id": "227189",
"ParentId": "227172",
"Score": "7"
}
},
{
"body": "<p>I’m not a C# guy, but I <strong>can</strong> suggest that an error message should say something <strong>about</strong> the error. “Error” says as much as “an error occurred.” Since you tried to read an integer, perhaps “Integer only, please.”</p>\n\n<p>Speaking of which, since you are only accepting integers, perhaps the prompt should say “integer” instead of “number.”</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T03:09:11.367",
"Id": "227206",
"ParentId": "227172",
"Score": "3"
}
},
{
"body": "<h2>Consistency</h2>\n\n<p>You are evaluating the <code>sum</code> in a single pass by simply adding each <code>input</code> to the current sum. But you don't do the same for the average.</p>\n\n<blockquote>\n<pre><code>if(Int32.TryParse(Console.ReadLine(), out input))\n{\n numbers[i] = input;\n sum += numbers[i];\n}\n\n// ..\n\nConsole.WriteLine(\"The result of your numbers:\");\nConsole.WriteLine(sum);\nConsole.WriteLine(\"The average of your numbers:\");\nConsole.WriteLine((double)sum / (double)numbers.Length);\n</code></pre>\n</blockquote>\n\n<p>As others have pointed out, you should just store the numbers in a single pass <code>numbers[i] = input;</code> and then evaluate the <code>sum</code> and <code>average</code> each in their own pass as:</p>\n\n<pre><code>var sum = numbers.Sum();\nvar average = numbers.Average();\n</code></pre>\n\n<h3>Cumulative Moving Average</h3>\n\n<p>There is another way to be consistent, while keeping everything in a single pass. You'd have the build a <a href=\"https://en.wikipedia.org/wiki/Moving_average#Cumulative_moving_average\" rel=\"nofollow noreferrer\">cumulative moving average</a> together with the sum:</p>\n\n<pre><code>if(Int32.TryParse(Console.ReadLine(), out input))\n{\n numbers[i] = input;\n sum += numbers[i];\n average += ((decimal)input - average) / (i + 1);\n}\n</code></pre>\n\n<p>I would use a decimal to mitigate rounding and truncation errors.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T05:14:07.083",
"Id": "442182",
"Score": "1",
"body": "Just a thought, instead of computing average on each pass can't we just do `sum/numbers.Length`. Reason I'm mentioning that is though the above idea you mentioned above about cumulative moving average is very good, but my questions are as you mentioned we need to mitigate rounding errors, and the other will be by just doing `sum/numbers.Length` will be doing only one computation as compared to calculating average on every iteration."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T07:06:08.117",
"Id": "442196",
"Score": "0",
"body": "Sure that could also work. My point was only that used a one-pass _sum_, and a two pass _average_. The way you implement this is up to you of course :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T22:10:16.030",
"Id": "227239",
"ParentId": "227172",
"Score": "3"
}
},
{
"body": "<p>I'm wondering why are you using an array to store your input in, this a bit of overkill if you only need to have the sum and the average, you can store this in 3 variables.\nHave a look at this. </p>\n\n<p>It shows how to handle the user canceling the console as well as eliminating the need for an array or list. You can still break when it has reached 5 entries by limiting the tries or limiting the successful conversions. </p>\n\n<p>If the user makes a mistake it is normally a good idea to show him what he typed else he is confused and was sure what he typed was \"correct ish\"</p>\n\n<pre><code>public static void Main()\n\n{\n\n int sum = 0;\n bool error = false;\n int count = 0;\n bool canceled = false;\n var track = new StringBuilder();\n track.Append(\"Your typed in values: \");\n Console.CancelKeyPress += (s, e) => canceled = true;\n\n (int left, int top) = (Console.CursorLeft, Console.CursorTop);\n Console.WriteLine(\"Please write a number, press CTL + C to cancel:\");\n\n do\n {\n var userData = Console.ReadLine();\n Console.SetCursorPosition(left, top);\n if (!canceled && int.TryParse(userData, out int input))\n {\n count++;\n sum += input; \n if(count>1)\n Console.WriteLine(track.Append(\",\"));\n\n //clear as the user can endless type values\n Console.Clear();\n Console.WriteLine(\"Please write a number, press CTL + C to cancel:\");\n Console.WriteLine(track.Append(userData));\n }\n else\n {\n\n Console.WriteLine($\"Sorry could not convert {userData} to an integer press CTL + C to cancel to cancel or try again\".PadRight(Console.BufferWidth,' '));\n\n }\n\n } while (!canceled && !error);\n\n\n\n Console.WriteLine(\"\");\n\n Console.WriteLine(\"The result of your numbers:\");\n Console.WriteLine(sum);\n\n Console.WriteLine(\"The average of your numbers:\");\n Console.WriteLine((double)sum / (double)count);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T07:47:14.380",
"Id": "227300",
"ParentId": "227172",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227186",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T12:21:44.707",
"Id": "227172",
"Score": "9",
"Tags": [
"c#",
"beginner",
"console",
"calculator"
],
"Title": "Sum and average calculator"
}
|
227172
|
<p>I have written a Python programme that takes data from Excel sheets and adds this data to new .DAT files.<br>
I use <code>win32com.client</code> because the Excel sheets will already be opened and other modules need to open a file before they can process it.</p>
<p>As the <code>win32com.client</code> outputs the range as a Component Object Model, it changes the content in some minor but destructive ways. Numbers, such as <code>2</code>, are outputted as <code>2.0</code>. Moreover, empty cells are outputted as <code>None</code>.<br>
For this reason I cannot immediately put the cells' values into a file, and instead I use a loop to fill a list during which I edit the data.</p>
<p>This loop, however, is relatively very slow. I'd like a faster method, but I am unsure how to achieve this.</p>
<pre><code>from win32com.client import GetObject
def convertdata(r, l):
newr = []
for c in r:
# Some codes start with leading zeroes and need to be left as-is
# The try...except clause would convert this code into integers, stripping
# the leading zeroes. str(c) == '0.0' makes sure single 0 values do get
# processed.
if str(c) == '0.0' or not str(c)[:1] == '0':
try:
float(str(c))
newr.append(str(int(c)))
except ValueError:
if str(c) == 'None':
newr.append('')
else:
newr.append(str(c))
else:
newr.append(str(c))
if c.Column == l and not c.Row - 1 == r.Rows.Count:
newr.append('\n')
else:
newr.append('\t')
return newr
# ... Code omitted
exl = GetObject(None, "Excel.Application")
exl_wbs = exl.Workbooks
sht = exlwbs[0].Worksheets(2)
rng = sht.Range(sht.Cells(2, 1), sht.Cells(lrow, lcol))
newrng = convertdata(rng, lcol)
dataf = ''.join(newrng)
with open(fpath, "w") as newfile:
newfile.write(dataf)
</code></pre>
<p><code>lrow</code> and <code>lcol</code> are integers. <code>fpath</code> is a string to the new file. <code>sht</code> is a Worksheet object.</p>
<p><strong>Input example</strong><br>
<a href="https://i.stack.imgur.com/cbjvX.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cbjvX.jpg" alt="enter image description here"></a>
<strong>Output example</strong> (not the same data as the input, but you get the gist of it)</p>
<pre class="lang-none prettyprint-override"><code>I 08.5070 Plate assembly Plate assembly 5 5070 VIRTUAL 1 1 1 0
I 0070_01.01 Plate D10 (SA) Plate D10 (SA) 08.58070 101 VIRTUAL 1 1 1 0
I 001170 Support Support 6 1170 VIRTUAL 1 1 1 0
I 0010.1170_01.01 conveyor (SA) conveyor (SA) 0090.1170 101 VIRTUAL
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T12:36:49.000",
"Id": "441945",
"Score": "0",
"body": "Please could you include what `lcol`/`l` is"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T12:37:57.213",
"Id": "441946",
"Score": "0",
"body": "Just the last column in the range, just like how lrow is the last row in the range. They're integers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T12:40:31.080",
"Id": "441947",
"Score": "0",
"body": "Thank you, if you could include that they are integers somewhere in you question. (maybe at the bottom) Then it should prevent people from closing this as lacking code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T13:07:36.340",
"Id": "441951",
"Score": "0",
"body": "Please don't omit code. Include your imports as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T13:13:05.900",
"Id": "441952",
"Score": "1",
"body": "@Mast Why are the imports needed?! That'll just cause more reasons to complain and VTC LCC. \"Why are you importing things and not using them, add more code.\" The only undefined thing is `sht`, and the imports won't help define it. Unless there's some magic `from win32com.client import sht` that pick the sheet OP wants magically."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T13:16:01.007",
"Id": "441955",
"Score": "0",
"body": "I've omitted code that's not necessary to the question. `sht` is just a variable that holds a `Worksheet` object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T14:13:16.940",
"Id": "441963",
"Score": "3",
"body": "As you can see people ask a lot of questions because there is no unnecessary code and since your code is incomplete we cannot tell how it works. Just copy/paste what you've got and we're good."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T19:19:24.810",
"Id": "442003",
"Score": "0",
"body": "@Peilonrayz What can I say, I'm a sucker for bonus context."
}
] |
[
{
"body": "<h1>variable names</h1>\n\n<p>1-letter variable names are difficult to understand. Correct names for variables, functions and classes goes already a long way to comment the intent of the code.\n<code>r</code> is a data range, <code>c</code> is a cell, <code>l</code> is the last row in the range, then call em thus</p>\n\n<h1>functions</h1>\n\n<p>I would extract the code that is needed to parse 1 cell:</p>\n\n<pre><code>def convert_cell(data):\n \"\"\"converts a single cell\"\"\"\n data_string = str(data)\n if data_string == \"0.0\":\n return \"0\"\n if data_string[0] == 0:\n return data_string\n if data_string == \"None\":\n return \"\"\n try:\n float(data_string)\n return str(int(data))\n except ValueError:\n return data_string\n</code></pre>\n\n<p>The advantage is that you cal skip some levels of nesting, and it is really clear what each type of input get transformed to. I also refactored the multiple calls to <code>str(c)</code> to a variable</p>\n\n<h1>generator</h1>\n\n<p>Instead of starting a list, and appending to it, you can better <code>yield</code> the results.</p>\n\n<pre><code>def convertdata(data_range, last_column):\n for cell in data_range:\n yield convert_cell(cell)\n is_last_column = cell.Column == last_column\n is_last_row = cell.Row - 1 == data_range.Rows.Count\n yield \"\\n\" if is_last_column and not is_last_row else \"\\t\"\n\ndata_range = sheet.Range(sheet.Cells(2, 1), sheet.Cells(lrow, lcol))\ndataf = ''.join(convertdata(data_range, lcol))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T14:01:29.317",
"Id": "227176",
"ParentId": "227173",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "227176",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T12:31:47.013",
"Id": "227173",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"excel"
],
"Title": "Populate list with Excel range and keep formatting"
}
|
227173
|
<p>I'm making a small program to benchmark Rust's performance compared to some other languages. The idea I came up with, was to take a file (with the numbers 1 to 10000000 written to it in separate lines) as a command line argument:</p>
<pre class="lang-none prettyprint-override"><code>1
2
3
...
9999999
10000000
</code></pre>
<p>read the file, and then multiple every line in that file by two and write those back to the same file, so the end result would look like this:</p>
<pre class="lang-none prettyprint-override"><code>2
4
6
...
19999998
20000000
</code></pre>
<p>My code works, and does exactly what it should do. I am especially looking for ways how I could make the code cleaner while also making it run faster. I'm currently running it with:</p>
<pre><code>$ cargo run --release numbers.txt
</code></pre>
<p>The program:</p>
<pre class="lang-rust prettyprint-override"><code>use std::env;
use std::fs::OpenOptions;
use std::io::Read;
use std::io::Write;
fn main() {
let args: Vec<String> = env::args().collect();
let file_path = &args[1];
let mut file = OpenOptions::new().read(true).open(file_path).unwrap();
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
let vec: Vec<i32> = contents.lines()
.map(|line| line.trim().parse::<i32>().unwrap() * 2)
.collect();
let mut file = OpenOptions::new().write(true).open(file_path).unwrap();
for line in vec {
write!(file, "{}\n", line).unwrap();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>This is my first post here, but I thought I might give this one a shot. </p>\n\n<ul>\n<li><p>Your code could be made more user friendly by providing custom error messages.</p>\n\n<ul>\n<li>When you get the filename from the command line arguments, you assume that the user will provide at least one command line argument. You could provide a helpful error message if they don't. </li>\n<li>If opening a file fails for some reason (probably that the file doesn't exist at all), you could provide a custom print-out. </li>\n<li>My example uses <code>expect()</code> as an example, but in code where user-friendliness is actually a goal, you would probably want to use <code>eprintln!(\"error message here\")</code> and <code>std::process::exit(1)</code> to quit the program. That way, you don't get rust's extra panic messages which a user shouldn't have to understand. </li>\n</ul></li>\n<li><p>You don't actually have to allocate a <code>Vec</code> to read the command line arguments, you can use the <code>.nth</code> method on the <code>Args</code> iterator. </p></li>\n<li><p>You don't need the <code>trim()</code> call, because the <code>lines()</code> iterator already removes the newlines. </p></li>\n<li><p>If you are looking to make the code cleaner, you could open the file for reading with <code>File::open</code>, and open it for writing with <code>File::create</code>.</p></li>\n<li><p>I don't know how to significantly improve the performance of your code.</p>\n\n<ul>\n<li>The biggest thing that I notice is that when you write the processed sequence of numbers to the file, you call <code>write!</code> on every line. This means that you talk to the OS every time you write a number. This could be made faster by using BufWriter, which would let you talk to the file only once. Alternatively, you could construct your output string while you are <em>reading</em> the file.</li>\n</ul></li>\n</ul>\n\n<pre><code>use std::env;\nuse std::fs::File;\nuse std::io::{BufReader, BufRead};\nuse std::io::Write;\n\nfn main() {\n let file_path = &env::args().nth(1).expect(\"must provide an input file\");\n\n let file = File::open(file_path).expect(\"failed to open input file\");\n\n let doubled_contents: String = BufReader::new(file).lines()\n .map(|line| {\n let number = line.unwrap().parse::<i32>().expect(\"failed to parse file\");\n format!(\"{}\\n\", number*2)\n })\n .collect();\n\n let mut output_file = File::create(file_path).expect(\"failed to open output file\");\n write!(output_file, \"{}\", doubled_contents).expect(\"could not write output\");\n}\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T02:08:26.397",
"Id": "227203",
"ParentId": "227177",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227203",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T14:05:38.490",
"Id": "227177",
"Score": "1",
"Tags": [
"performance",
"file",
"io",
"rust"
],
"Title": "Rust program, which reads, processes, and writes a file"
}
|
227177
|
<p>This isn't meant to be a fully-featured anything, isn't meant to involve any sort of api interactions. It's just meant to be a proof-of-concept of how I could implement nested reddit-style comments.</p>
<p>Every comment is either a top level comment or a reply to another comment. Each level of nesting is indented and is color coded. The color-coding wraps back in on itself (eg if there are 5 defined files, then the 6th layer of nesting should have the same color code as the 1st layer of nesting).</p>
<pre><code>import * as React from 'react';
export class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
comments : [
{
'user': 'user1',
'text': 'text1',
comments: [{
'user': 'user3',
'text': 'responding to text1',
comments: [
{
'user': 'user1',
'text': 'responding to user3'
}
]
}]
},
{
'user': 'user2',
'text': 'text2'
}
]
}
}
render() {
return <div>
{
this.state.comments.map(comment => (
<Comment comment={comment}/>
))
}
</div>;
}
}
class Comment extends React.Component {
renderSidebar(level) {
const colors = ['green','orange','red'];
const index = level % colors.length;
return {'border-left':'solid 3px ' + colors[index]};
}
render() {
const comment = this.props.comment;
const subComments = comment.comments || [];
const level = this.props.level || 0;
return (
<div className="comment">
<div className="main-comment" style={this.renderSidebar(level)}>
<p className="user" style={{'margin-bottom':'0','opacity':'0.3'}}>{comment.user}</p>
<p className="text">{comment.text}</p>
</div>
<div className="subcomments" style={{'padding-left':'2em'}}>
{subComments.map(comment => (
<Comment comment={comment} level={level + 1}/>
))}
</div>
</div>
)
}
}
</code></pre>
<p>jsfiddle here: <a href="https://jsfiddle.net/z318wsq6/" rel="nofollow noreferrer">https://jsfiddle.net/z318wsq6/</a></p>
|
[] |
[
{
"body": "<h1><code>Test</code> class</h1>\n\n<ol>\n<li>In the scope of code you provided, the <code>div</code> is useless and may be omitted:</li>\n</ol>\n\n<pre><code>render() {\n return this.state.comments.map((comment, index) => (\n <Comment key={index} comment={comment}/>\n ))\n}\n</code></pre>\n\n<ol start=\"2\">\n<li>However, as React warns you in the console, don't forget to <a href=\"https://reactjs.org/docs/lists-and-keys.html\" rel=\"nofollow noreferrer\">pass a <code>key</code> prop to your array items</a> (added in the snippet above).</li>\n</ol>\n\n<h1><code>Comment</code> class</h1>\n\n<ol>\n<li>The method name <code>renderSidebar</code> suggest to me that it will return something that React can render, but it returns an object of CSS styles instead. For that reason, I'd rename it to <code>getSidebarStyle</code>.</li>\n<li>Since the method <code>renderSidebar</code> doesn't depend on anything except its parameters and doesn't alter any instance variables (it's a <a href=\"https://en.wikipedia.org/wiki/Pure_function\" rel=\"nofollow noreferrer\">pure function</a>), you can move it outside the class.</li>\n<li>The array of <code>colors</code> has nothing to do with the logic of selecting a color depending on the intendation level. Depending on your coding style preferences, you could move it to outside the method and capitalize it.</li>\n<li>When rendering the subcomments, set a <code>key</code> prop on your array items as above.</li>\n<li><a href=\"https://reactjs.org/docs/introducing-jsx.html\" rel=\"nofollow noreferrer\">JSX is camel-cased</a> and that's why React warns you in the console to change your CSS property names (e.g. <code>border-left</code> to <code>borderLeft</code>), also allowing you to omit the quotes.</li>\n</ol>\n\n<p>Generally, your code is in good shape & all of the comments above are more or less only improvements. To help you move faster, I suggest always checking the console for helpful warnings and using tools such as <a href=\"https://prettier.io/\" rel=\"nofollow noreferrer\">Prettier</a> and a linter for your JS dialect to help you while programming.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T13:52:30.727",
"Id": "227400",
"ParentId": "227179",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227400",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T14:18:45.263",
"Id": "227179",
"Score": "4",
"Tags": [
"react.js",
"jsx"
],
"Title": "Reddit style comment chains in React"
}
|
227179
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.